diff --git a/.gitignore b/.gitignore index 7e7ca472..740e5266 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ target/ +build/local.sh + *.bak bin/ *.iml diff --git a/.gitmodules b/.gitmodules index e69de29b..6c974aa8 100644 --- a/.gitmodules +++ b/.gitmodules @@ -0,0 +1,21 @@ +[submodule "explorer"] + path = explorer + url = git@github.com:blockchain-jd-com/explorer.git +[submodule "libs/bft-smart"] + path = libs/bft-smart + url = git@github.com:blockchain-jd-com/bftsmart.git +[submodule "project"] + path = project + url = git@github.com:blockchain-jd-com/jdchain-project.git +[submodule "framework"] + path = framework + url = git@github.com:blockchain-jd-com/jdchain-framework.git +[submodule "core"] + path = core + url = git@github.com:blockchain-jd-com/jdchain-core.git +[submodule "test"] + path = test + url = git@github.com:blockchain-jd-com/jdchain-test.git +[submodule "kvdb"] + path = kvdb + url = git@github.com:blockchain-jd-com/jdchain-kvdb.git diff --git a/README.md b/README.md index 675472d0..e3d7ced6 100644 --- a/README.md +++ b/README.md @@ -52,69 +52,77 @@ JD Chain 主要部署组件包括以下几种: ![](docs/images/deployment.jpg) -## 三、编译源代码 +## 三、构建源代码 - 1. 安装 Maven 环境 +1. 安装 Maven 环境 JD Chain 当前版本以 Java 语言开发,需要安装配置 JVM 和 Maven,JDK 版本不低于1.8 。(没有特殊要求,请按标准方法安装,此处不赘述) - 2. 安装 Git 工具 +2. 安装 Git 工具 为了能够执行 git clone 命令获取代码仓库。 (没有特殊要求,请按标准方法安装,此处不赘述) - 3. 工程代码 +3. 项目库说明 + +JD Chain 源代码包括 3 个代码仓库 + +- jdchain 项目库: + - URL:git@github.com:blockchain-jd-com/jdchain.git + - 说明:主项目库,包含说明文档、示例代码,用于集成构建和打包; + + #### `主项目库包含以下 6 个子模块仓库,通过执行脚本 <主项目库根目录>/build/build.sh 便可以一键完成子模块的下载和整体的编译、测试和打包操作.` + +- project 项目库: + - URL:git@github.com:blockchain-jd-com/jdchain-project.git + - 说明:公共的父项目,定义公共的依赖; +- framework 项目库: + - URL:git@github.com:blockchain-jd-com/jdchain-framework.git + - 说明:框架源码库,定义公共数据类型、框架、模块组件接口、SDK、SPI、工具; +- core 项目库: + - URL:git@github.com:blockchain-jd-com/jdchain-core.git + - 说明:模块组件实现的源码库; +- explorer 项目库: + - URL:git@github.com:blockchain-jd-com/explorer.git + - 说明:相关产品的前端模块的源码库; +- libs/bft-smart 项目库: + - URL:git@github.com:blockchain-jd-com/bftsmart.git + - 说明:BFT-SMaRT 共识算法的源码库; +- test 项目库: + - URL:git@github.com:blockchain-jd-com/jdchain-test.git + - 说明:集成测试用例的源码库; + + +4. 构建操作 - JD Chain 源代码包括 3 个代码仓库 - - jdchain - - 这是当前仓库,也是核心仓库,包含了共识节点、网关节点、SDK等一切部署组件。依赖于 explorer 和 bftsmart 这两个仓库先进行编译安装; - - - explorer - - 这是区块链浏览器的前端Web页面的工程,需要编译成静态资源包,由网关节点集成到一起部署。 - - 地址:git@github.com:blockchain-jd-com/explorer.git - - - bftsmart - - 这是bftsmart共识协议的工程,需要先编译安装到本地 maven 仓库; - - -4. 命令操作 - -- 编译安装 explorer 到本地 maven 仓库; ```sh - $ git clone git@github.com:blockchain-jd-com/explorer.git explorer +$ git clone git@github.com:blockchain-jd-com/jdchain.git jdchain - $ cd explorer +$ cd jdchain - $ git checkout master +$ git checkout develop - $ mvn clean install - -``` -- 编译安装 bftsmart 到本地 maven 仓库; - - 需要手动先安装一个第三方包,位于仓库根目录下 lib/core-0.1.4.jar -```sh - $ git clone git@github.com:blockchain-jd-com/bftsmart.git bftsmart +$ chmod +x build/*.sh - $ cd bftsmart +# 执行完整的构建,包括执行”集成测试“和”打包“两部分;提供两个参数: +# --skipTests :跳过集成测试部分; +# --update :从远程仓库更新子模块。注意,采用此参数会导致子模块本地仓库丢失尚未 commit 的代码。 +# 不附带此参数的情况下不会更新子模块仓库。 +$ build/build.sh --update - $ git checkout master - - $ mvn install:install-file -Dfile=lib/core-0.1.4.jar -DgroupId=com.yahoo.ycsb -DartifactId=core -Dversion=0.1.4 -Dpackaging=jar +# 跳过集成测试,直接编译和打包; +$ build/build.sh --skipTests - $ mvn clean install +# 只执行集成测试; +$ build/test.sh ``` -- 编译 jdchain 工程; - - 当编译完成后,共识节点的安装包位于 "仓库根目录"/source/deployment/deployment-peer/target/jdchain-peer-1.0.1.RELEASE.zip - - 当编译完成后,网关节点的安装包位于 "仓库根目录"/source/deployment/deployment-gateway/target/jdchain-gateway-1.0.1.RELEASE.zip - -```sh - $ git clone git@github.com:blockchain-jd-com/jdchain.git jdchain - $ cd jdchain/source +5. jdchain 的安装包 - $ git checkout master +当编译完成后,安装包位于主项目库的 deploy 目录中: - $ mvn clean package - -``` +- 共识节点的安装包: + - <主项目库根目录>/deploy/deploy-peer/target/jdchain-peer-**.zip +- 网关节点的安装包: + - <主项目库根目录>/deploy/deploy-gateway/target/jdchain-gateway-**.zip \ No newline at end of file diff --git a/build/build.sh b/build/build.sh new file mode 100755 index 00000000..d5babc33 --- /dev/null +++ b/build/build.sh @@ -0,0 +1,47 @@ + +#定义子脚本的错误返回命令 +RTN="return" + + +#调用当前脚本目录下 env.sh 脚本,设置环境变量,处理当前传入参数; +source `dirname $0`/env.sh "$*" + +echo "主目录:$BASE_DIR" + +#判断是否忽略测试; +if [ $SKIP_TESTS == 1 ] +then + echo "跳过测试。。。" +else + #执行测试; + source $TEST_SHELL + + #检查执行结果是否正常 + ERR=$? + if [ $ERR != 0 ] + then + echo "构建过程中发生了集成测试错误[$ERR]!!终止构建!!" + exit $ERR + fi + #结束集成测试错误检查; +fi + +#如果执行了测试,并且测试已经通过,那么在打包的过程中可以跳过执行单元测试; +if [ $SKIP_TESTS == 0 ] +then + # 可选值:1,2; + # 值为1时附加编译参数 -DskipTests=true; + # 值为2时附加编译参数 -Dmaven.test.skip=true + SKIP_TESTS=2 +fi + +#执行打包构建; +source $PACK_SHELL + +#检查执行结果是否正常 +ERR=$? +if [ $ERR != 0 ] +then + echo "构建过程中发生了打包错误[$ERR]!!终止构建!!" + exit $ERR +fi \ No newline at end of file diff --git a/build/env.sh b/build/env.sh new file mode 100755 index 00000000..cc240384 --- /dev/null +++ b/build/env.sh @@ -0,0 +1,82 @@ + +#定义默认的子脚本错误退出命令; +if [ ! $RTN ] +then + #当以 source 命令调用子脚本时,只能用 return 命令终止子脚本的执行; + #当直接在 shell 中调用脚本或者 fork 等其它命令执行子脚本时,用 exit 命令终止脚本执行; + RTN="exit" +fi + +if [ $ENV_SHELL ] +then + #如果已经设置过环境变量,则不再重复执行; + echo "略过初始化环境变量。。。" + ${RTN} +fi + +echo "---------------- 初始化环境变量 ----------------" + +#主代码库的根目录 +BASE_DIR=$(cd `dirname $0`/..; pwd) + +#标记环境变量脚本; +ENV_SHELL=$BASE_DIR/build/env.sh + +#执行代码库更新的脚本; +UPDATE_SHELL=$BASE_DIR/build/repo.sh + +#执行测试的脚本; +TEST_SHELL=$BASE_DIR/build/test.sh + +#执行构建打包产品的脚本; +PACK_SHELL=$BASE_DIR/build/pack.sh + +#框架工程的Git仓库的根目录 +FRAMEWORK_DIR=$BASE_DIR/framework + +#核心实现工程的Git仓库的根目录 +CORE_DIR=$BASE_DIR/core + +#打包工程的Git仓库的根目录 +DEPLOY_DIR=$BASE_DIR/deploy + +#测试工程的Git仓库的根目录 +TEST_DIR=$BASE_DIR/test + +#初始化参数:是否略过测试步骤; +SKIP_TESTS=0 + +#初始化参数:是否略过子模块的更新;默认值:1-忽略; +SKIP_SUBMODULES_UPDATE=1 + +#初始化参数:是否将仓库采用公开配置(即覆盖本地化配置); +CONFIG_REPO_PUBLIC=0 + +#检查输入参数 +for i in $*; do + case $i in + "--skipTests") + #跳过测试; + echo "收到参数 --skipTests 指示跳过测试环节。。。" + + SKIP_TESTS=1 + ;; + "--update") + #跳过更新子模块; + echo "收到参数 --update 指示跳过子模块源码更新环节。。。" + + SKIP_SUBMODULES_UPDATE=0 + ;; + "--public") + #仓库采用公开配置; + echo "收到参数 --public 指示仓库采用公开配置。。。" + + CONFIG_REPO_PUBLIC=1 + ;; + + esac +done + +echo "---------------- 完成环境变量初始化 ----------------" + + diff --git a/build/pack.sh b/build/pack.sh new file mode 100755 index 00000000..34d87ff8 --- /dev/null +++ b/build/pack.sh @@ -0,0 +1,56 @@ + + +#调用当前脚本目录下 env.sh 脚本,设置环境变量,处理当前传入参数; +if [ ! $ENV_SHELL ] +then + source `dirname $0`/env.sh "$*" +fi + +# 更新代码库; +source $UPDATE_SHELL + +#检查执行结果是否正常 +ERR=$? +if [ $ERR != 0 ] +then + echo "更新代码库时发生了错误[$ERR]!!终止打包!!" + ${RTN} $ERR +fi + + +echo "--------------- 开始编译打包 ---------------" + +cd $DEPLOY_DIR +echo "当前目录:`pwd`" + +#初始化变量 SKIP_TESTS; +if [ ! $SKIP_TESTS ] +then + SKIP_TESTS=0 +fi + +CMD="mvn clean package" + +if [ $SKIP_TESTS == 1 ] +then + echo "编译参数:-DskipTests=true" + CMD="$CMD -DskipTests=true" +fi +if [ $SKIP_TESTS == 2 ] +then + echo "编译参数:-Dmaven.test.skip=true" + CMD="$CMD -Dmaven.test.skip=true" +fi + +echo "执行命令:$CMD" +${CMD} + +#检查执行结果是否正常 +ERR=$? +if [ $ERR != 0 ] +then + echo "编译打包过程中发生了错误[$ERR]!!终止打包!!" + ${RTN} $ERR +fi + +echo "--------------- 完成编译打包 ---------------" diff --git a/build/repo.sh b/build/repo.sh new file mode 100755 index 00000000..56aac1d5 --- /dev/null +++ b/build/repo.sh @@ -0,0 +1,144 @@ + +#调用当前脚本目录下 env.sh 脚本,设置环境变量,处理当前传入参数; +if [ ! $ENV_SHELL ] +then + source `dirname $0`/env.sh "$*" +fi + +echo "" + +echo "切换到主库根目录。。。" +cd $BASE_DIR +pwd + +#先执行初始化; 注:此命令只在 .git/config 文件中没有相应子模块的配置时才生效,重复执行并不会更改已有的配置; +git submodule init + +echo "" + +#根据本地仓库的 .git 目录下是否存在 local.sh 脚本判断是否在更新子模块的代码库之前执行本地化配置; +echo "检查是否执行子模块的本地化配置。。。" +#判断本地化配置脚本是否存在; +LOCAL_CONFIG="$BASE_DIR/.git/local.config" + +LOCALIZED=0 +if [ -f $LOCAL_CONFIG -a $CONFIG_REPO_PUBLIC == 0 ] +then + #执行子模块的本地化配置,将子模块的远程仓库地址指向本地; + echo "---------------- 执行仓库的本地化配置 ----------------" + #解析本地配置 + KEYS=($(cat $LOCAL_CONFIG | awk -F '=' 'length($1)>0 { print $1}')) + VALUES=($(cat $LOCAL_CONFIG | awk -F '=' 'length($2)>0 { print $2}')) + + #匹配子模块 URL 配置名称的正则表达式 + # REG="submodule[\.].*[\.]url" + + #判断本地配置是否为空; + echo "共有 ${#KEYS[@]} 项本地配置。。。" + if [ ${#KEYS[@]} -gt 0 ] + then + for ((i=0; i<${#KEYS[@]}; i++)); + do + #执行本地化配置; + echo "[$i]: git config ${KEYS[i]} ${VALUES[i]}" + git config ${KEYS[i]} ${VALUES[i]} + + #检查执行结果是否正常 + ERR=$? + if [ $ERR != 0 ] + then + echo "执行仓库的本地化配置的过程中发生了错误[$ERR]!!终止构建!!" + ${RTN} $ERR + fi + done + + LOCALIZED=1 + fi + + echo "---------------- 完成执行仓库的本地化配置 ----------------" + echo "" +fi + + +# 如果没有进行仓库的本地化配置,则将仓库设置为公开配置; +cd $BASE_DIR + +if [ $LOCALIZED == 0 ] +then + echo "---------------- 执行仓库的公共配置 ----------------" + + echo "同步子模块的公共配置。。。" + git submodule sync + + # 更新远程仓库地址; + git config remote.origin.url git@github.com:blockchain-jd-com/jdchain.git + + echo "---------------- 完成执行仓库的公共配置 ----------------" + echo "" +fi + + +#同步主库的远程仓库 origin 的推送地址; +REMOTE_ORIGIN_URL=$(git config --get remote.origin.url) +git config remote.origin.pushurl $REMOTE_ORIGIN_URL + +echo "远程仓库的地址更新为:"$REMOTE_ORIGIN_URL +echo "" + +#同步更新子模块的远程仓库 origin 的地址; +echo "---------------- 更新子模块的远程仓库地址 ----------------" +# 子模块名称列表; + +SUBMODULES=$(git submodule | awk '{print $2}') +for m in $SUBMODULES; +do + SUBMODULE_URL=$(git config --get submodule.$m.url) + echo "模块[$m].URL="$SUBMODULE_URL + + cd $BASE_DIR/$m + + git config remote.origin.url $SUBMODULE_URL + git config remote.origin.pushurl $SUBMODULE_URL + + cd $BASE_DIR +done + +#检查是否要跳过子模块更新环节; +if [ $SKIP_SUBMODULES_UPDATE == 1 ] +then + echo "跳过子模块代码更新操作。。。[$RTN]" + ${RTN} +fi + +#初始化变量 SUBMODULES_UPDATED +if [ ! $SUBMODULES_UPDATED ] +then + SUBMODULES_UPDATED=0 +fi + +if [ $SUBMODULES_UPDATED == 1 ] +then + echo "代码库已经最新,跳过更新操作。。。" + ${RTN} +fi + +# 更新子模块代码库 +echo "---------------- 更新子模块代码库 ----------------" +cd $BASE_DIR +echo "git submodule update --recursive --progress --jobs 6" +git submodule update --recursive --progress --jobs 6 + +#检查执行结果是否正常 +ERR=$? +if [ $ERR != 0 ] +then + echo "更新子模块代码库时发生了错误!!返回错误码:$ERR" + ${RTN} $ERR +fi + +#标记代码已经更新; +SUBMODULES_UPDATED=1 + +echo "---------------- 完成子模块代码库更新 ----------------" + +echo "" diff --git a/build/test.sh b/build/test.sh new file mode 100755 index 00000000..5991af7c --- /dev/null +++ b/build/test.sh @@ -0,0 +1,38 @@ +#定义子脚本的错误返回命令 +RTN="return" + +#调用当前脚本目录下 env.sh 脚本,设置环境变量,处理当前传入参数; +if [ ! $ENV_SHELL ] +then + source `dirname $0`/env.sh "$*" +fi + +# 更新代码库; +source $UPDATE_SHELL + +#检查执行结果是否正常 +ERR=$? +if [ $ERR != 0 ] +then + echo "更新代码库时发生了错误[$ERR]!!终止测试!! [$RTN]" + ${RTN} $ERR +fi + + +echo "---------------- 开始集成测试 ----------------" + +cd $TEST_DIR +echo "当前目录:`pwd`" + +echo "执行命令:mvn clean package" +mvn clean package + +#检查执行结果是否正常 +ERR=$? +if [ $ERR != 0 ] +then + echo "集成测试过程中发生了错误[$ERR]!!终止测试!! [$RTN]" + ${RTN} $ERR +fi + +echo "---------------- 完成集成测试 ----------------" \ No newline at end of file diff --git a/core b/core new file mode 160000 index 00000000..5afafb53 --- /dev/null +++ b/core @@ -0,0 +1 @@ +Subproject commit 5afafb536796160f0f6644c7955e0dc56632d141 diff --git a/source/deployment/deployment-gateway/conf/application-gw.properties b/deploy/deploy-gateway/conf/application-gw.properties similarity index 100% rename from source/deployment/deployment-gateway/conf/application-gw.properties rename to deploy/deploy-gateway/conf/application-gw.properties diff --git a/source/deployment/deployment-gateway/pom.xml b/deploy/deploy-gateway/pom.xml similarity index 89% rename from source/deployment/deployment-gateway/pom.xml rename to deploy/deploy-gateway/pom.xml index acb96008..fa321ac1 100644 --- a/source/deployment/deployment-gateway/pom.xml +++ b/deploy/deploy-gateway/pom.xml @@ -4,30 +4,31 @@ 4.0.0 com.jd.blockchain - deployment - 1.1.4.RELEASE + deploy-root + 1.2.0.RELEASE - deployment-gateway + deploy-gateway + com.jd.blockchain gateway - ${project.version} + ${core.version} com.jd.blockchain consensus-bftsmart - ${project.version} + ${core.version} com.jd.blockchain consensus-mq - ${project.version} + ${core.version} - + diff --git a/source/deployment/deployment-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java b/deploy/deploy-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java similarity index 100% rename from source/deployment/deployment-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java rename to deploy/deploy-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java diff --git a/source/deployment/deployment-gateway/src/main/resources/assembly.xml b/deploy/deploy-gateway/src/main/resources/assembly.xml similarity index 94% rename from source/deployment/deployment-gateway/src/main/resources/assembly.xml rename to deploy/deploy-gateway/src/main/resources/assembly.xml index 861990d0..b28d5436 100644 --- a/source/deployment/deployment-gateway/src/main/resources/assembly.xml +++ b/deploy/deploy-gateway/src/main/resources/assembly.xml @@ -31,7 +31,7 @@ true lib - com.jd.blockchain:deployment-gateway + com.jd.blockchain:deploy-gateway diff --git a/source/deployment/deployment-gateway/src/main/resources/config/gateway.conf b/deploy/deploy-gateway/src/main/resources/config/gateway.conf similarity index 100% rename from source/deployment/deployment-gateway/src/main/resources/config/gateway.conf rename to deploy/deploy-gateway/src/main/resources/config/gateway.conf diff --git a/source/deployment/deployment-gateway/src/main/resources/docs/api_doc_cn_1.3.MD b/deploy/deploy-gateway/src/main/resources/docs/api_doc_cn_1.3.MD similarity index 100% rename from source/deployment/deployment-gateway/src/main/resources/docs/api_doc_cn_1.3.MD rename to deploy/deploy-gateway/src/main/resources/docs/api_doc_cn_1.3.MD diff --git a/source/deployment/deployment-gateway/src/main/resources/docs/api_doc_cn_1.3.html b/deploy/deploy-gateway/src/main/resources/docs/api_doc_cn_1.3.html similarity index 100% rename from source/deployment/deployment-gateway/src/main/resources/docs/api_doc_cn_1.3.html rename to deploy/deploy-gateway/src/main/resources/docs/api_doc_cn_1.3.html diff --git a/source/deployment/deployment-gateway/src/main/resources/docs/api_doc_cn_1.4.MD b/deploy/deploy-gateway/src/main/resources/docs/api_doc_cn_1.4.MD similarity index 100% rename from source/deployment/deployment-gateway/src/main/resources/docs/api_doc_cn_1.4.MD rename to deploy/deploy-gateway/src/main/resources/docs/api_doc_cn_1.4.MD diff --git a/source/deployment/deployment-gateway/src/main/resources/scripts/shutdown.sh b/deploy/deploy-gateway/src/main/resources/scripts/shutdown.sh similarity index 80% rename from source/deployment/deployment-gateway/src/main/resources/scripts/shutdown.sh rename to deploy/deploy-gateway/src/main/resources/scripts/shutdown.sh index 7418f49a..0491e963 100644 --- a/source/deployment/deployment-gateway/src/main/resources/scripts/shutdown.sh +++ b/deploy/deploy-gateway/src/main/resources/scripts/shutdown.sh @@ -15,11 +15,11 @@ if [ -f "$PID_LOG" ]; then if [[ $PID_LINE == *GW_BOOT_PID* ]]; then LOG_PID=$(echo $PID_LINE | cut -d "=" -f 2 | cut -d "[" -f 2 | cut -d "]" -f 1) echo "Last Gateway Boot PID = $LOG_PID ..." - PID=`ps -ef | grep deployment-gateway | grep $LOG_PID | grep -v grep | awk '{print $2}'` + PID=`ps -ef | grep deploy-gateway- | grep $LOG_PID | grep -v grep | awk '{print $2}'` fi #启动文件不存在则直接通过PS进行过滤 else - PID=`ps -ef | grep $BOOT_HOME/lib/deployment-gateway | grep -v grep | awk '{print $2}'` + PID=`ps -ef | grep $BOOT_HOME/lib/deploy-gateway- | grep -v grep | awk '{print $2}'` fi #通过Kill命令将进程杀死 diff --git a/source/deployment/deployment-gateway/src/main/resources/scripts/startup.sh b/deploy/deploy-gateway/src/main/resources/scripts/startup.sh similarity index 90% rename from source/deployment/deployment-gateway/src/main/resources/scripts/startup.sh rename to deploy/deploy-gateway/src/main/resources/scripts/startup.sh index 62272d19..01c86077 100644 --- a/source/deployment/deployment-gateway/src/main/resources/scripts/startup.sh +++ b/deploy/deploy-gateway/src/main/resources/scripts/startup.sh @@ -1,7 +1,7 @@ #!/bin/bash HOME=$(cd `dirname $0`;cd ../; pwd) -GATEWAY=$(ls $HOME/lib | grep deployment-gateway-) +GATEWAY=$(ls $HOME/lib | grep deploy-gateway-) PROC_INFO=$HOME/lib/$GATEWAY" -c "$HOME/config/gateway.conf #echo $PROC_INFO #get PID diff --git a/deploy/deploy-kvdb/pom.xml b/deploy/deploy-kvdb/pom.xml new file mode 100644 index 00000000..a1e02938 --- /dev/null +++ b/deploy/deploy-kvdb/pom.xml @@ -0,0 +1,99 @@ + + + + deploy-root + com.jd.blockchain + 1.2.0.RELEASE + + 4.0.0 + + deploy-kvdb + 1.0.0.RELEASE + + + + + com.jd.blockchain + kvdb-protocol + ${version} + + + + com.jd.blockchain + kvdb-engine + ${version} + + + + com.jd.blockchain + kvdb-server + ${version} + + + + com.jd.blockchain + kvdb-cli + ${version} + + + + com.jd.blockchain + kvdb-benchmark + ${version} + + + + com.jd.blockchain + kvdb-client + ${version} + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + package + + single + + + kvdb + + src/main/resources/assembly.xml + + + + + + + + + net.nicoulaj.maven.plugins + checksum-maven-plugin + 1.8 + + + + artifacts + + + + + + SHA-256 + + ${project.basedir}/target/deployment-kvdb-${project.version}.zip + true + ${project.basedir}/target/SHA-256.xml + + + + + \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/assembly.xml b/deploy/deploy-kvdb/src/main/resources/assembly.xml new file mode 100644 index 00000000..34a09ee3 --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/assembly.xml @@ -0,0 +1,54 @@ + + + ${project.version} + + zip + + false + + + src/main/resources/script + bin + unix + + + src/main/resources/config + config + unix + + + src/main/resources/system + system + unix + + + + + false + true + libs + + + + + + true + + com.jd.blockchain:kvdb-engine + com.jd.blockchain:kvdb-benchmark + com.jd.blockchain:kvdb-client + com.jd.blockchain:kvdb-protocol + com.jd.blockchain:kvdb-cli + com.jd.blockchain:kvdb-server + + + libs + false + + + + + \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/config/cluster.conf b/deploy/deploy-kvdb/src/main/resources/config/cluster.conf new file mode 100644 index 00000000..9801c753 --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/config/cluster.conf @@ -0,0 +1,11 @@ +# 数据库集群的分片数,每一个分片都赋予唯一的编号,分片编号最小为 0,所有分片的编号必须连续递增 +#cluster.test1.partitions=2 +# 数据库集群 ‘’ 的第 1 个分片的数据库实例地址(URL格式); +#cluster.test1.0=kvdb://localhost:7078/test1 +# 数据库集群 ‘’ 的第 2 个分片的数据库实例地址(URL格式); +#cluster.test1.1=kvdb://localhost:7079/test1 + +# 指定多个不同的集群 +#cluster.test2.partitions=2 +#cluster.test2.0=kvdb://localhost:7078/test2 +#cluster.test2.1=kvdb://localhost:7079/test2 \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/config/kvdb.conf b/deploy/deploy-kvdb/src/main/resources/config/kvdb.conf new file mode 100644 index 00000000..1b47c61a --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/config/kvdb.conf @@ -0,0 +1,15 @@ +# 数据库服务的本机监听地址; +server.host=0.0.0.0 + +# 数据库服务的本机监听端口; +server.port=7078 + +# 管理控制台的端口; +# 注:管理控制台总是绑定到环回地址 127.0.0.1,只允许本机访问; +manager.port=7060 + +# 数据库实例默认的根目录 +dbs.rootdir=../dbs + +# 数据库实例默认的本地分区数 +dbs.partitions=4 \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/script/kvdb-benchmark.sh b/deploy/deploy-kvdb/src/main/resources/script/kvdb-benchmark.sh new file mode 100644 index 00000000..b2180397 --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/script/kvdb-benchmark.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +HOME=$(cd `dirname $0`;cd ../; pwd) +KVDB=$(ls $HOME/libs | grep kvdb-benchmark) +JVM_SET="-Xmx2g -Xms2g" +LOG_SET="-Dlogging.path="$HOME/logs" -Dlogging.level=error" +PROC_INFO=$HOME/libs/$KVDB +if [ ! -n "$KVDB" ]; then + echo "Can not find kvdb-benchmark !!!" +else + java -jar $LOG_SET $JVM_SET $PROC_INFO $* +fi \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/script/kvdb-cli.sh b/deploy/deploy-kvdb/src/main/resources/script/kvdb-cli.sh new file mode 100644 index 00000000..fd6474a8 --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/script/kvdb-cli.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +HOME=$(cd `dirname $0`;cd ../; pwd) +KVDB=$(ls $HOME/libs | grep kvdb-cli) +JVM_SET="-Xmx2g -Xms2g" +LOG_SET="-Dlogging.path="$HOME/logs" -Dlogging.level.root=error" +PROC_INFO=$HOME/libs/$KVDB +if [ ! -n "$KVDB" ]; then + echo "Can not find kvdb-cli !!!" +else + java -jar $LOG_SET $JVM_SET $PROC_INFO $* +fi \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/script/start.sh b/deploy/deploy-kvdb/src/main/resources/script/start.sh new file mode 100644 index 00000000..18fdc9c6 --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/script/start.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +HOME=$(cd `dirname $0`;cd ../; pwd) +KVDB=$(ls $HOME/libs | grep kvdb-server) +JVM_SET="-Xmx2g -Xms2g" +PROC_INFO=$HOME/libs/$KVDB" -home "$HOME +LOG_SET="-Dlogging.path="$HOME/logs" -Dlogging.level=error" +#echo $PROC_INFO +#get PID +PID=`ps -ef | grep "$PROC_INFO" | grep -v grep | awk '{print $2}'` +#echo $PID +if [[ ! -z $PID ]] +then + echo "process already exists,please check... If necessary, you should kill the process first." + exit +fi +if [ ! -n "$KVDB" ]; then + echo "Can not find kvdb-server !!!" +else + nohup java -jar $LOG_SET $JVM_SET $PROC_INFO $* >/dev/null 2>&1 & + + echo $! > $HOME/system/pid +fi \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/script/stop.sh b/deploy/deploy-kvdb/src/main/resources/script/stop.sh new file mode 100644 index 00000000..5b654ff7 --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/script/stop.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +#启动Home路径 +HOME=$(cd `dirname $0`;cd ../; pwd) + +#进程启动后PID.log所在路径 +PID_LOG=$HOME/system/pid + +#从启动文件中读取PID +if [ -f "$PID_LOG" ]; then + # File exist + echo "Read PID From File:[$PID_LOG] ..." + PID=`sed -n '$p' $PID_LOG` +#启动文件不存在则直接通过PS进行过滤 +else + PID=`ps -ef | grep $HOME/libs/kvdb-server | grep -v grep | awk '{print $2}'` +fi + +#通过Kill命令将进程杀死 +if [ -z "$PID" ]; then + echo "Unable to find kvdb PID. stop aborted." +else + echo "Start to kill PID = $PID ..." + kill -9 $PID + echo "kvdb has been stopped ..." + echo "" > $PID_LOG +fi \ No newline at end of file diff --git a/deploy/deploy-kvdb/src/main/resources/system/dblist b/deploy/deploy-kvdb/src/main/resources/system/dblist new file mode 100644 index 00000000..0d45040c --- /dev/null +++ b/deploy/deploy-kvdb/src/main/resources/system/dblist @@ -0,0 +1,2 @@ +#通过配置enable为true可以在kvdb-server启动时创建或加载指定数据库 +#db.test1.enable=true \ No newline at end of file diff --git a/source/deployment/deployment-peer/pom.xml b/deploy/deploy-peer/pom.xml similarity index 82% rename from source/deployment/deployment-peer/pom.xml rename to deploy/deploy-peer/pom.xml index c25a4ae5..ed269000 100644 --- a/source/deployment/deployment-peer/pom.xml +++ b/deploy/deploy-peer/pom.xml @@ -4,33 +4,33 @@ 4.0.0 com.jd.blockchain - deployment - 1.1.4.RELEASE + deploy-root + 1.2.0.RELEASE - deployment-peer + deploy-peer com.jd.blockchain peer - ${project.version} + ${core.version} com.jd.blockchain runtime-modular - ${project.version} + ${core.version} com.jd.blockchain runtime-modular-booter - ${project.version} + ${core.version} com.jd.blockchain manager-booter - ${project.version} + ${core.version} - + com.jd.blockchain storage-redis - ${project.version} + ${core.version} com.jd.blockchain storage-rocksdb - ${project.version} + ${core.version} + + + com.jd.blockchain + storage-kvdb + ${core.version} + + + + com.jd.blockchain + tools-initializer-booter + ${core.version} + + + + com.jd.blockchain + storage-service + ${core.version} com.jd.blockchain:storage-rocksdb com.jd.blockchain:storage-redis + com.jd.blockchain:storage-kvdb com.jd.blockchain:storage-composite com.jd.blockchain:runtime-modular com.jd.blockchain:runtime-modular-booter com.jd.blockchain:peer - com.jd.blockchain:deployment-peer + com.jd.blockchain:deploy-peer @@ -60,9 +61,10 @@ libs com.jd.blockchain:ledger-core - com.jd.blockchain:storage-service + com.jd.blockchain:storage-rocksdb com.jd.blockchain:storage-redis + com.jd.blockchain:storage-kvdb com.jd.blockchain:storage-composite com.jd.blockchain:runtime-modular com.jd.blockchain:runtime-modular-booter diff --git a/source/deployment/deployment-peer/src/main/resources/config/init/bftsmart.config b/deploy/deploy-peer/src/main/resources/config/init/bftsmart.config similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/config/init/bftsmart.config rename to deploy/deploy-peer/src/main/resources/config/init/bftsmart.config diff --git a/source/deployment/deployment-peer/src/main/resources/config/init/ledger.init b/deploy/deploy-peer/src/main/resources/config/init/ledger.init similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/config/init/ledger.init rename to deploy/deploy-peer/src/main/resources/config/init/ledger.init diff --git a/source/deployment/deployment-peer/src/main/resources/config/init/local.conf b/deploy/deploy-peer/src/main/resources/config/init/local.conf similarity index 89% rename from source/deployment/deployment-peer/src/main/resources/config/init/local.conf rename to deploy/deploy-peer/src/main/resources/config/init/local.conf index 31518046..46ae5b35 100644 --- a/source/deployment/deployment-peer/src/main/resources/config/init/local.conf +++ b/deploy/deploy-peer/src/main/resources/config/init/local.conf @@ -17,6 +17,7 @@ ledger.binding.out=../ #账本数据库的连接字符 #rocksdb数据库连接格式:rocksdb://{path},例如:rocksdb:///export/App08/peer/rocks.db/rocksdb0.db #redis数据库连接格式:redis://{ip}:{prot}/{db},例如:redis://127.0.0.1:6379/0 +#kvdb数据库连接格式:kvdb://{ip}:{prot}/{db},例如:kvdb://127.0.0.1:7078/test ledger.db.uri= #账本数据库的连接口令 diff --git a/source/deployment/deployment-peer/src/main/resources/config/init/mq/ledger.init b/deploy/deploy-peer/src/main/resources/config/init/mq/ledger.init similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/config/init/mq/ledger.init rename to deploy/deploy-peer/src/main/resources/config/init/mq/ledger.init diff --git a/source/deployment/deployment-peer/src/main/resources/config/init/mq/local.conf b/deploy/deploy-peer/src/main/resources/config/init/mq/local.conf similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/config/init/mq/local.conf rename to deploy/deploy-peer/src/main/resources/config/init/mq/local.conf diff --git a/source/deployment/deployment-peer/src/main/resources/config/init/mq/mq.config b/deploy/deploy-peer/src/main/resources/config/init/mq/mq.config similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/config/init/mq/mq.config rename to deploy/deploy-peer/src/main/resources/config/init/mq/mq.config diff --git a/source/deployment/deployment-peer/src/main/resources/docs/imgs/browser.jpeg b/deploy/deploy-peer/src/main/resources/docs/imgs/browser.jpeg similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/docs/imgs/browser.jpeg rename to deploy/deploy-peer/src/main/resources/docs/imgs/browser.jpeg diff --git a/source/deployment/deployment-peer/src/main/resources/docs/imgs/keys.jpeg b/deploy/deploy-peer/src/main/resources/docs/imgs/keys.jpeg similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/docs/imgs/keys.jpeg rename to deploy/deploy-peer/src/main/resources/docs/imgs/keys.jpeg diff --git a/source/deployment/deployment-peer/src/main/resources/docs/imgs/structure.png b/deploy/deploy-peer/src/main/resources/docs/imgs/structure.png similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/docs/imgs/structure.png rename to deploy/deploy-peer/src/main/resources/docs/imgs/structure.png diff --git a/source/deployment/deployment-peer/src/main/resources/docs/安装部署.MD b/deploy/deploy-peer/src/main/resources/docs/安装部署.MD similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/docs/安装部署.MD rename to deploy/deploy-peer/src/main/resources/docs/安装部署.MD diff --git a/source/deployment/deployment-peer/src/main/resources/docs/安装部署.html b/deploy/deploy-peer/src/main/resources/docs/安装部署.html similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/docs/安装部署.html rename to deploy/deploy-peer/src/main/resources/docs/安装部署.html diff --git a/source/deployment/deployment-peer/src/main/resources/scripts/keygen.sh b/deploy/deploy-peer/src/main/resources/scripts/keygen.sh similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/scripts/keygen.sh rename to deploy/deploy-peer/src/main/resources/scripts/keygen.sh diff --git a/source/deployment/deployment-peer/src/main/resources/scripts/ledger-init.sh b/deploy/deploy-peer/src/main/resources/scripts/ledger-init.sh similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/scripts/ledger-init.sh rename to deploy/deploy-peer/src/main/resources/scripts/ledger-init.sh diff --git a/source/deployment/deployment-peer/src/main/resources/scripts/manager-shutdown.sh b/deploy/deploy-peer/src/main/resources/scripts/manager-shutdown.sh similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/scripts/manager-shutdown.sh rename to deploy/deploy-peer/src/main/resources/scripts/manager-shutdown.sh diff --git a/source/deployment/deployment-peer/src/main/resources/scripts/manager-startup.sh b/deploy/deploy-peer/src/main/resources/scripts/manager-startup.sh similarity index 100% rename from source/deployment/deployment-peer/src/main/resources/scripts/manager-startup.sh rename to deploy/deploy-peer/src/main/resources/scripts/manager-startup.sh diff --git a/source/deployment/deployment-peer/src/main/resources/scripts/peer-shutdown.sh b/deploy/deploy-peer/src/main/resources/scripts/peer-shutdown.sh similarity index 80% rename from source/deployment/deployment-peer/src/main/resources/scripts/peer-shutdown.sh rename to deploy/deploy-peer/src/main/resources/scripts/peer-shutdown.sh index da76d093..4df77fb5 100644 --- a/source/deployment/deployment-peer/src/main/resources/scripts/peer-shutdown.sh +++ b/deploy/deploy-peer/src/main/resources/scripts/peer-shutdown.sh @@ -15,11 +15,11 @@ if [ -f "$PID_LOG" ]; then if [[ $PID_LINE == *PEER_BOOT_PID* ]]; then LOG_PID=$(echo $PID_LINE | cut -d "=" -f 2 | cut -d "[" -f 2 | cut -d "]" -f 1) echo "Last Peer Boot PID = $LOG_PID ..." - PID=`ps -ef | grep deployment-peer | grep $LOG_PID | grep -v grep | awk '{print $2}'` + PID=`ps -ef | grep deploy-peer- | grep $LOG_PID | grep -v grep | awk '{print $2}'` fi #启动文件不存在则直接通过PS进行过滤 else - PID=`ps -ef | grep $BOOT_HOME/system/deployment-peer | grep -v grep | awk '{print $2}'` + PID=`ps -ef | grep $BOOT_HOME/system/deploy-peer- | grep -v grep | awk '{print $2}'` fi #通过Kill命令将进程杀死 diff --git a/source/deployment/deployment-peer/src/main/resources/scripts/peer-startup.sh b/deploy/deploy-peer/src/main/resources/scripts/peer-startup.sh similarity index 71% rename from source/deployment/deployment-peer/src/main/resources/scripts/peer-startup.sh rename to deploy/deploy-peer/src/main/resources/scripts/peer-startup.sh index 5c4183c2..3367c3fc 100644 --- a/source/deployment/deployment-peer/src/main/resources/scripts/peer-startup.sh +++ b/deploy/deploy-peer/src/main/resources/scripts/peer-startup.sh @@ -1,8 +1,7 @@ #!/bin/bash HOME=$(cd `dirname $0`;cd ../; pwd) -PEER=$(ls $HOME/system | grep deployment-peer-) -JVM_SET="-server -Xmx2g -Xms1g" +PEER=$(ls $HOME/system | grep deploy-peer-) PROC_INFO=$HOME/system/$PEER" -home="$HOME" -c "$HOME/config/ledger-binding.conf" -p 7080" #echo $PROC_INFO #get PID @@ -16,5 +15,5 @@ fi if [ ! -n "$PEER" ]; then echo "Peer Is Null !!!" else - nohup java -jar $JVM_SET -Djdchain.log=$HOME $PROC_INFO $* >$HOME/bin/peer.out 2>&1 & + nohup java -jar -server -Xmx1g -Xms1g -Djdchain.log=$HOME $PROC_INFO $* >$HOME/bin/peer.out 2>&1 & fi \ No newline at end of file diff --git a/deploy/pom.xml b/deploy/pom.xml new file mode 100644 index 00000000..e3bdb271 --- /dev/null +++ b/deploy/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + com.jd.blockchain + jdchain-parent + 1.1.4.RELEASE + ../project/parent + + deploy-root + 1.2.0.RELEASE + pom + + + 1.2.0.RELEASE + + + + ../core + deploy-gateway + deploy-peer + deploy-kvdb + + + \ No newline at end of file diff --git a/explorer b/explorer new file mode 160000 index 00000000..da3b9c92 --- /dev/null +++ b/explorer @@ -0,0 +1 @@ +Subproject commit da3b9c925d7bc263474baf2c72ff0cee5c8308e1 diff --git a/framework b/framework new file mode 160000 index 00000000..7260fab6 --- /dev/null +++ b/framework @@ -0,0 +1 @@ +Subproject commit 7260fab6ee0336e2a197ddef7bebf2daf9363844 diff --git a/kvdb b/kvdb new file mode 160000 index 00000000..6e541d84 --- /dev/null +++ b/kvdb @@ -0,0 +1 @@ +Subproject commit 6e541d84081362c86430a89806c7dfcbb5fd8a71 diff --git a/libs/bft-smart b/libs/bft-smart new file mode 160000 index 00000000..1a3c32c4 --- /dev/null +++ b/libs/bft-smart @@ -0,0 +1 @@ +Subproject commit 1a3c32c4090e3cf7551998366a4d26a0160451ec diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..deda2b35 --- /dev/null +++ b/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + + com.jd.blockchain + jdchain-root + 1.2.0.RELEASE + pom + jdchain root project + + + project + framework + core + kvdb + deploy + test + samples + + + + diff --git a/project b/project new file mode 160000 index 00000000..ec38eec4 --- /dev/null +++ b/project @@ -0,0 +1 @@ +Subproject commit ec38eec4a6269e7abd35d9ea1b67417a97815bf9 diff --git a/source/contract/contract-samples/pom.xml b/samples/contract-samples/pom.xml similarity index 80% rename from source/contract/contract-samples/pom.xml rename to samples/contract-samples/pom.xml index 1a30c49a..e6fccc42 100644 --- a/source/contract/contract-samples/pom.xml +++ b/samples/contract-samples/pom.xml @@ -2,12 +2,12 @@ - - contract - com.jd.blockchain - 1.1.4.RELEASE - 4.0.0 + + com.jd.blockchain + jdchain-samples + 1.2.0.RELEASE + contract-samples @@ -17,14 +17,12 @@ com.jd.blockchain ledger-model - ${project.version} provided com.jd.blockchain crypto-framework - ${project.version} provided @@ -70,14 +68,6 @@ true - - org.sonatype.plugins - nexus-staging-maven-plugin - - true - - - diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContract.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContract.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContract.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContract.java diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContractImpl.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContractImpl.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContractImpl.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/ComplexContractImpl.java diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContract.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContract.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContract.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContract.java diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContractImpl.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContractImpl.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContractImpl.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/RandomContractImpl.java diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContract.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContract.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContract.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContract.java diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContractImpl.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContractImpl.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContractImpl.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/ReadContractImpl.java diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContract.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContract.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContract.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContract.java diff --git a/source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContractImpl.java b/samples/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContractImpl.java similarity index 100% rename from source/contract/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContractImpl.java rename to samples/contract-samples/src/main/java/com/jd/blockchain/contract/TransferContractImpl.java diff --git a/samples/pom.xml b/samples/pom.xml new file mode 100644 index 00000000..ba6abb2e --- /dev/null +++ b/samples/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + + com.jd.blockchain + jdchain-parent + 1.1.4.RELEASE + ../project/parent + + + com.jd.blockchain + jdchain-samples + 1.2.0.RELEASE + pom + + + 1.2.0.RELEASE + + + + ../framework + sdk-samples + contract-samples + + + + + + + com.jd.blockchain + sdk-client + ${framework.version} + + + com.jd.blockchain + ledger-model + ${framework.version} + + + com.jd.blockchain + crypto-framework + ${framework.version} + + + + + + + diff --git a/source/sdk/sdk-samples/pom.xml b/samples/sdk-samples/pom.xml similarity index 69% rename from source/sdk/sdk-samples/pom.xml rename to samples/sdk-samples/pom.xml index 84a136bf..3d58af03 100644 --- a/source/sdk/sdk-samples/pom.xml +++ b/samples/sdk-samples/pom.xml @@ -1,62 +1,46 @@ - - 4.0.0 - - com.jd.blockchain - sdk - 1.1.4.RELEASE - - sdk-samples - - - - com.jd.blockchain - sdk-client - ${project.version} - - - com.jd.blockchain - ledger-model - ${project.version} - - - com.jd.blockchain - tools-initializer - ${project.version} - - - com.jd.blockchain - contract-samples - ${project.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - true - - - - org.sonatype.plugins - nexus-staging-maven-plugin - - true - - - - - - - - - - - - - + + 4.0.0 + + com.jd.blockchain + jdchain-samples + 1.2.0.RELEASE + + sdk-samples + + + + com.jd.blockchain + sdk-client + + + com.jd.blockchain + ledger-model + + + com.jd.blockchain + contract-samples + ${project.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + + + + \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/ContractConfigure.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/contract/ContractConfigure.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/ContractConfigure.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/contract/ContractConfigure.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract2.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract2.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract2.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract2.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_ConfigureSecurity.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_ConfigureSecurity.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_ConfigureSecurity.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_ConfigureSecurity.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Constant.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Constant.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Constant.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Constant.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Tx_Persistance.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Tx_Persistance.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Tx_Persistance.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Tx_Persistance.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Check_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Check_Demo.java similarity index 88% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Check_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Check_Demo.java index 7d521776..c99b9a6b 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Check_Demo.java +++ b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Check_Demo.java @@ -1,14 +1,17 @@ package com.jd.blockchain.sdk.samples; -import com.jd.blockchain.contract.TransferContract; -import com.jd.blockchain.ledger.*; +import static com.jd.blockchain.sdk.samples.SDKDemo_Constant.readChainCodes; +import static com.jd.blockchain.transaction.ContractReturnValue.decode; + +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.transaction.GenericValueHolder; import com.jd.blockchain.utils.Bytes; import com.jd.chain.contracts.ContractTestInf; -import static com.jd.blockchain.sdk.samples.SDKDemo_Constant.readChainCodes; -import static com.jd.blockchain.transaction.ContractReturnValue.decode; - public class SDK_Contract_Check_Demo extends SDK_Base_Demo { public static void main(String[] args) { diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Demo.java index caae0d6d..0574cf51 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Demo.java +++ b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Demo.java @@ -6,12 +6,12 @@ import static com.jd.blockchain.transaction.ContractReturnValue.decode; import com.jd.blockchain.contract.TransferContract; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.TypedKVEntry; import com.jd.blockchain.ledger.PreparedTransaction; import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.TransactionTemplate; -import com.jd.blockchain.transaction.LongValueHolder; +import com.jd.blockchain.ledger.TypedKVEntry; import com.jd.blockchain.transaction.GenericValueHolder; +import com.jd.blockchain.transaction.LongValueHolder; import com.jd.blockchain.utils.Bytes; public class SDK_Contract_Demo extends SDK_Base_Demo { diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Random_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Random_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Random_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Contract_Random_Demo.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_DataAccount_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_DataAccount_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_DataAccount_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_DataAccount_Demo.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_InsertData_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_InsertData_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_InsertData_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_InsertData_Demo.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_RoleConfig_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_RoleConfig_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_RoleConfig_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_RoleConfig_Demo.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Threads_KvInsert_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Threads_KvInsert_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Threads_KvInsert_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Threads_KvInsert_Demo.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_User2Role_Demo.java b/samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_User2Role_Demo.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_User2Role_Demo.java rename to samples/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_User2Role_Demo.java diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/chain/contracts/ContractTestInf.java b/samples/sdk-samples/src/main/java/com/jd/chain/contracts/ContractTestInf.java similarity index 100% rename from source/sdk/sdk-samples/src/main/java/com/jd/chain/contracts/ContractTestInf.java rename to samples/sdk-samples/src/main/java/com/jd/chain/contracts/ContractTestInf.java diff --git a/source/sdk/sdk-samples/src/main/resources/contract-jdchain.jar b/samples/sdk-samples/src/main/resources/contract-jdchain.jar similarity index 100% rename from source/sdk/sdk-samples/src/main/resources/contract-jdchain.jar rename to samples/sdk-samples/src/main/resources/contract-jdchain.jar diff --git a/source/sdk/sdk-samples/src/main/resources/transfer.jar b/samples/sdk-samples/src/main/resources/transfer.jar similarity index 100% rename from source/sdk/sdk-samples/src/main/resources/transfer.jar rename to samples/sdk-samples/src/main/resources/transfer.jar diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_Contract_Test.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_Contract_Test.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_Contract_Test.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_Contract_Test.java diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_Regist_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_Regist_Test_.java similarity index 79% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_Regist_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_Regist_Test_.java index 77157f0d..77c1e62e 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_Regist_Test_.java +++ b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_Regist_Test_.java @@ -1,17 +1,32 @@ package test.com.jd.blockchain.sdk.test; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.crypto.AddressEncoding; +import com.jd.blockchain.crypto.AsymmetricKeypair; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.ParticipantRegisterOperation; +import com.jd.blockchain.ledger.ParticipantStateUpdateOperation; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.sdk.samples.SDKDemo_Constant; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.net.NetworkAddress; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; /** * 注册参与方测试 diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_State_Update_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_State_Update_Test_.java similarity index 78% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_State_Update_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_State_Update_Test_.java index 4fb229ce..d1ffb9e6 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_State_Update_Test_.java +++ b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Participant_State_Update_Test_.java @@ -1,17 +1,33 @@ package test.com.jd.blockchain.sdk.test; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.crypto.AddressEncoding; +import com.jd.blockchain.crypto.AsymmetricKeypair; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.ParticipantNodeState; +import com.jd.blockchain.ledger.ParticipantRegisterOperation; +import com.jd.blockchain.ledger.ParticipantStateUpdateOperation; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.sdk.samples.SDKDemo_Constant; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.net.NetworkAddress; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; /** * 参与方状态更新测试 diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java b/samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java similarity index 100% rename from source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java rename to samples/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java diff --git a/source/sdk/sdk-samples/src/test/resources/contract.jar b/samples/sdk-samples/src/test/resources/contract.jar similarity index 100% rename from source/sdk/sdk-samples/src/test/resources/contract.jar rename to samples/sdk-samples/src/test/resources/contract.jar diff --git a/source/sdk/sdk-samples/src/test/resources/sys-contract.properties b/samples/sdk-samples/src/test/resources/sys-contract.properties similarity index 100% rename from source/sdk/sdk-samples/src/test/resources/sys-contract.properties rename to samples/sdk-samples/src/test/resources/sys-contract.properties diff --git a/source/sdk/sdk-samples/src/test/resources/transfer.jar b/samples/sdk-samples/src/test/resources/transfer.jar similarity index 100% rename from source/sdk/sdk-samples/src/test/resources/transfer.jar rename to samples/sdk-samples/src/test/resources/transfer.jar diff --git a/tools/compile-latest.sh b/scripts/compile-latest.sh similarity index 100% rename from tools/compile-latest.sh rename to scripts/compile-latest.sh diff --git a/tools/start.sh b/scripts/start.sh similarity index 100% rename from tools/start.sh rename to scripts/start.sh diff --git a/tools/stop.sh b/scripts/stop.sh similarity index 100% rename from tools/stop.sh rename to scripts/stop.sh diff --git a/tools/sync-to-all.sh b/scripts/sync-to-all.sh similarity index 100% rename from tools/sync-to-all.sh rename to scripts/sync-to-all.sh diff --git a/tools/sync-to-remote.sh b/scripts/sync-to-remote.sh similarity index 100% rename from tools/sync-to-remote.sh rename to scripts/sync-to-remote.sh diff --git a/source/base/src/main/java/com/jd/blockchain/consts/DataCodes.java b/source/base/src/main/java/com/jd/blockchain/consts/DataCodes.java deleted file mode 100644 index cd1da3d5..00000000 --- a/source/base/src/main/java/com/jd/blockchain/consts/DataCodes.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.jd.blockchain.consts; - -/** - * A const registeration of codes of all data contracts in ledger model; - * - * @author huanghaiquan - * - */ -public interface DataCodes { - - public static final int MERKLE_SNAPSHOT = 0x070; - - public static final int BYTES_VALUE = 0x080; - - public static final int BYTES_VALUE_LIST = 0x081; - - public static final int BLOCK_CHAIN_IDENTITY = 0x090; - - public static final int BLOCK = 0x100; - - public static final int BLOCK_BODY = 0x110; - - public static final int BLOCK_GENESIS = 0x120; - - public static final int DATA_SNAPSHOT = 0x130; - - public static final int LEDGER_ADMIN_INFO = 0x131; - - public static final int TX = 0x200; - - public static final int TX_LEDGER = 0x201; - - public static final int TX_CONTENT = 0x210; - - public static final int TX_CONTENT_BODY = 0x220; - - public static final int TX_RETURN_MESSAGE = 0x230; - - public static final int TX_OP = 0x300; - - public static final int TX_OP_LEDGER_INIT = 0x301; - - public static final int TX_OP_USER_REG = 0x310; - public static final int TX_OP_USER_INFO_SET = 0x311; - public static final int TX_OP_USER_INFO_SET_KV = 0x312; - - public static final int TX_OP_DATA_ACC_REG = 0x320; - public static final int TX_OP_DATA_ACC_SET = 0x321; - public static final int TX_OP_DATA_ACC_SET_KV = 0x322; - - public static final int TX_OP_CONTRACT_DEPLOY = 0x330; - public static final int TX_OP_CONTRACT_UPDATE = 0x331; - - public static final int TX_OP_CONTRACT_EVENT_SEND = 0x340; - - public static final int TX_OP_PARTICIPANT_REG = 0x350; - public static final int TX_OP_PARTICIPANT_STATE_UPDATE = 0x351; - - public static final int TX_RESPONSE = 0x360; - - public static final int TX_OP_RESULT = 0x370; - - public static final int TX_OP_ROLE_CONFIGURE = 0x371; - - public static final int TX_OP_ROLE_CONFIGURE_ENTRY = 0x372; - - public static final int TX_OP_USER_ROLES_AUTHORIZE = 0x373; - - public static final int TX_OP_USER_ROLE_AUTHORIZE_ENTRY = 0x374; - - // enum types of permissions; - public static final int ENUM_TX_PERMISSION = 0x401; - public static final int ENUM_LEDGER_PERMISSION = 0x402; - public static final int ENUM_MULTI_ROLES_POLICY = 0x403; - - public static final int PRIVILEGE_SET = 0x410; - - public static final int ROLE_SET = 0x411; - - public static final int SECURITY_INIT_SETTING = 0x420; - - public static final int SECURITY_ROLE_INIT_SETTING = 0x421; - - public static final int SECURITY_USER_AUTH_INIT_SETTING = 0x422; - - // contract types of metadata; - public static final int METADATA = 0x600; - public static final int METADATA_V2 = 0x601; - - public static final int METADATA_INIT_SETTING = 0x610; - - public static final int METADATA_INIT_PROPOSAL = 0x611; - - public static final int METADATA_INIT_DECISION = 0x612; - - public static final int METADATA_LEDGER_SETTING = 0x620; - - public static final int METADATA_CONSENSUS_PARTICIPANT = 0x621; - -// public static final int METADATA_CONSENSUS_NODE = 0x630; -// -// public static final int METADATA_CONSENSUS_SETTING = 0x631; -// -// public static final int METADATA_PARTICIPANT_INFO = 0x640; -// -// public static final int METADATA_CRYPTO_SETTING = 0x642; - - // public static final int METADATA_CONSENSUS_NODE = 0x630; - - public static final int METADATA_CONSENSUS_SETTING = 0x631; - - public static final int METADATA_PARTICIPANT_INFO = 0x640; - - public static final int METADATA_PARTICIPANT_STATE_INFO = 0x641; - - public static final int METADATA_CRYPTO_SETTING = 0x642; - - public static final int METADATA_CRYPTO_SETTING_PROVIDER = 0x643; - -// public static final int ACCOUNT = 0x700; - - public static final int ACCOUNT_HEADER = 0x710; - - public static final int USER_ACCOUNT_HEADER = 0x800; - - public static final int USER_INFO = 0x801; - - public static final int DATA = 0x900; - - // contract related; - public static final int CONTRACT_ACCOUNT_HEADER = 0xA00; - - public static final int CONTRACT_INFO = 0xA01; - - // ...0xA19 - public static final int HASH = 0xB00; - - public static final int HASH_OBJECT = 0xB10; - - public static final int ENUM_TYPE = 0xB20; - - public static final int CRYPTO_ALGORITHM = 0xB21; - - public static final int ENUM_TYPE_TRANSACTION_STATE = 0xB22; - - public static final int ENUM_TYPE_BYTES_VALUE_TYPE = 0xB23; - - public static final int ENUM_TYPE_PARTICIPANT_NODE_STATE = 0xB24; - - public static final int DIGITALSIGNATURE = 0xB30; - - public static final int DIGITALSIGNATURE_BODY = 0xB31; - - public static final int CLIENT_IDENTIFICATION = 0xC00; - - public static final int CLIENT_IDENTIFICATIONS = 0xC10; - - public static final int REQUEST = 0xD00; - - public static final int REQUEST_NODE = 0xD10; - - public static final int REQUEST_ENDPOINT = 0xD20; - - // ------------------ 共识相关 ---------------- - - public static final int CONSENSUS = 0x1000; - - public static final int CONSENSUS_ACTION_REQUEST = CONSENSUS | 0x01; - - public static final int CONSENSUS_ACTION_RESPONSE = CONSENSUS | 0x02; - - public static final int CONSENSUS_SETTINGS = CONSENSUS | 0x03; - - public static final int CONSENSUS_NODE_SETTINGS = CONSENSUS | 0x04; - - public static final int CONSENSUS_CLI_INCOMING_SETTINGS = CONSENSUS | 0x05; - - // ------------------ 共识相关(BFTSMART) ---------------- - public static final int CONSENSUS_BFTSMART = 0x1100; - - public static final int CONSENSUS_BFTSMART_SETTINGS = CONSENSUS_BFTSMART | 0x01; - - public static final int CONSENSUS_BFTSMART_NODE_SETTINGS = CONSENSUS_BFTSMART | 0x02; - - public static final int CONSENSUS_BFTSMART_CLI_INCOMING_SETTINGS = CONSENSUS_BFTSMART | 0x03; - - public static final int CONSENSUS_BFTSMART_BLOCK_SETTINGS = CONSENSUS_BFTSMART | 0x04; - - // ------------------ 共识相关(MSGQUEUE) ---------------- - public static final int CONSENSUS_MSGQUEUE = 0x1200; - - public static final int CONSENSUS_MSGQUEUE_SETTINGS = CONSENSUS_MSGQUEUE | 0x01; - - public static final int CONSENSUS_MSGQUEUE_NODE_SETTINGS = CONSENSUS_MSGQUEUE | 0x02; - - public static final int CONSENSUS_MSGQUEUE_CLI_INCOMING_SETTINGS = CONSENSUS_MSGQUEUE | 0x03; - - public static final int CONSENSUS_MSGQUEUE_NETWORK_SETTINGS = CONSENSUS_MSGQUEUE | 0x04; - - public static final int CONSENSUS_MSGQUEUE_BLOCK_SETTINGS = CONSENSUS_MSGQUEUE | 0x05; - -} diff --git a/source/base/src/main/java/com/jd/blockchain/consts/Global.java b/source/base/src/main/java/com/jd/blockchain/consts/Global.java deleted file mode 100644 index b508e833..00000000 --- a/source/base/src/main/java/com/jd/blockchain/consts/Global.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jd.blockchain.consts; - -import java.util.TimeZone; - -public class Global { - - public static final String DEFAULT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSZ"; - - public static final String DEFAULT_TIME_ZONE = "GMT+08:00"; - - static { - initialize(); - } - - public static void initialize() { - TimeZone.setDefault(TimeZone.getTimeZone(DEFAULT_TIME_ZONE)); - } - -} diff --git a/source/base/src/main/java/com/jd/blockchain/provider/NamedProvider.java b/source/base/src/main/java/com/jd/blockchain/provider/NamedProvider.java deleted file mode 100644 index a1e08b27..00000000 --- a/source/base/src/main/java/com/jd/blockchain/provider/NamedProvider.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.provider; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Mark a class as a named service provider; - * - * @author huanghaiquan - * - */ -@Target({ ElementType.TYPE }) -@Retention(RetentionPolicy.RUNTIME) -public @interface NamedProvider { - - String value() default ""; - -} diff --git a/source/base/src/main/java/com/jd/blockchain/provider/Provider.java b/source/base/src/main/java/com/jd/blockchain/provider/Provider.java deleted file mode 100644 index 6843a1a6..00000000 --- a/source/base/src/main/java/com/jd/blockchain/provider/Provider.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.provider; - -public interface Provider { - - String getShortName(); - - String getFullName(); - - S getService(); - -} diff --git a/source/base/src/main/java/com/jd/blockchain/provider/ProviderException.java b/source/base/src/main/java/com/jd/blockchain/provider/ProviderException.java deleted file mode 100644 index 68840e59..00000000 --- a/source/base/src/main/java/com/jd/blockchain/provider/ProviderException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.provider; - -public class ProviderException extends RuntimeException { - - private static final long serialVersionUID = 6422628637835262811L; - - public ProviderException(String message) { - super(message); - } - -} diff --git a/source/base/src/main/java/com/jd/blockchain/provider/ProviderManager.java b/source/base/src/main/java/com/jd/blockchain/provider/ProviderManager.java deleted file mode 100644 index 98584de4..00000000 --- a/source/base/src/main/java/com/jd/blockchain/provider/ProviderManager.java +++ /dev/null @@ -1,272 +0,0 @@ -package com.jd.blockchain.provider; - -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.concurrent.ConcurrentHashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The ProviderManager manages all serivce providers in the system. - *

- * - * The service is represented by an interface, and the provider is - * implementation class of the service. - *

- * - * One service can have multiple providers in the system. - *

- * - * A provider must have a name, and implementor can use the annotation - * {@link NamedProvider} to specify a short name, otherwise the system defaults - * to the full name of the implementation class. - * - * - * @author huanghaiquan - * - */ -public final class ProviderManager { - - private final Logger LOGGER = LoggerFactory.getLogger(ProviderManager.class); - - private final Object mutex = new Object(); - - private ConcurrentHashMap, NamedProviders> serviceProviders = new ConcurrentHashMap<>(); - - /** - * 返回指定提供者的服务; - * - * @param serviceClazz - * @param providerName - * @return - */ - public S getService(Class serviceClazz, String providerName) { - NamedProviders providers = getNamedProviders(serviceClazz); - return providers.getService(providerName); - } - - public Provider getProvider(Class serviceClazz, String providerName) { - @SuppressWarnings("unchecked") - NamedProviders providers = (NamedProviders) serviceProviders.get(serviceClazz); - if (providers == null) { - return null; - } - return providers.getProvider(providerName); - } - - public Collection> getAllProviders(Class serviceClazz) { - @SuppressWarnings("unchecked") - NamedProviders providers = (NamedProviders) serviceProviders.get(serviceClazz); - if (providers == null) { - return Collections.emptyList(); - } - return providers.getProviders(); - } - - public S installProvider(Class serviceClazz, String providerFullName) { - NamedProviders providers = getNamedProviders(serviceClazz); - return providers.install(providerFullName); - } - - public S installProvider(Class service, String providerFullName, ClassLoader classLoader) { - NamedProviders providers = getNamedProviders(service); - return providers.install(providerFullName, classLoader); - } - - public void installAllProviders(Class serviceClazz, ClassLoader classLoader) { - NamedProviders providers = getNamedProviders(serviceClazz); - providers.installAll(classLoader); - } - - @SuppressWarnings("unchecked") - private NamedProviders getNamedProviders(Class serviceClazz) { - NamedProviders providers = (NamedProviders) serviceProviders.get(serviceClazz); - if (providers == null) { - synchronized (mutex) { - providers = (NamedProviders) serviceProviders.get(serviceClazz); - if (providers == null) { - providers = new NamedProviders(serviceClazz); - serviceProviders.put(serviceClazz, providers); - } - } - } - return providers; - } - - /** - * @author huanghaiquan - * - * @param - * Type of Service - */ - private class NamedProviders { - - private Class serviceClazz; - - private Map shortNames = new HashMap<>(); - private Map> namedProviders = new LinkedHashMap<>(); - - private AccessControlContext acc; - - public NamedProviders(Class serviceClazz) { - this.serviceClazz = serviceClazz; - this.acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null; - installAll(); - } - - public void installAll(ClassLoader classLoader) { - ServiceLoader sl = ServiceLoader.load(serviceClazz, classLoader); - installAll(sl); - } - - public void installAll() { - // 默认采用线程上下文的类加载器;避免直接采用系统的类加载器: ClassLoader.getSystemClassLoader() ; - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - installAll(classLoader); - } - - private synchronized void installAll(ServiceLoader sl) { - for (S provider : sl) { - install(provider); - } - } - - /** - * 安装指定的服务提供者;
- * - * 如果同名的服务提供者已经存在(包括ShortName和FullName任意之一存在),则返回 false;
- * - * 如果同名的服务提供者不存在,则返回 false; - * - * @param service - * 提供者的服务实现; - * @return - */ - private synchronized boolean install(S service) { - String fullName = service.getClass().getName(); - if (namedProviders.containsKey(fullName)) { - LOGGER.warn(String.format("The provider[%s] already exists.", fullName)); - return false; - } - String shortName = null; - NamedProvider annoNP = service.getClass().getAnnotation(NamedProvider.class); - if (annoNP != null && annoNP.value() != null) { - String n = annoNP.value().trim(); - if (n.length() > 0) { - shortName = n; - } - } - if (shortName != null && shortNames.containsKey(shortName)) { - return false; - } - ProviderInfo provider = new ProviderInfo<>(shortName, fullName, service); - if (shortName != null) { - shortNames.put(shortName, fullName); - } - namedProviders.put(fullName, provider); - return true; - } - - public S install(String providerFullName) { - return install(providerFullName, null); - } - - public S install(String providerFullName, ClassLoader classLoader) { - // 默认采用线程上下文的类加载器;避免直接采用系统的类加载器: ClassLoader.getSystemClassLoader() ; - ClassLoader cl = (classLoader == null) ? Thread.currentThread().getContextClassLoader() : classLoader; - S p = null; - if (acc == null) { - p = instantiate(providerFullName, cl); - } else { - PrivilegedAction action = new PrivilegedAction() { - public S run() { - return instantiate(providerFullName, cl); - } - }; - p = AccessController.doPrivileged(action, acc); - } - if (!install(p)) { - throw new ProviderException( - "[" + serviceClazz.getName() + "] Provider " + providerFullName + " already exist!"); - } - return p; - } - - public Collection> getProviders() { - return namedProviders.values(); - } - - - public Provider getProvider(String providerFullName) { - return namedProviders.get(providerFullName); - } - - public S getService(String name) { - String fullName = shortNames.get(name); - if (fullName == null) { - fullName = name; - } - Provider pd = namedProviders.get(fullName); - return pd == null ? null : pd.getService(); - } - - private S instantiate(String className, ClassLoader classLoader) { - Class c = null; - try { - c = Class.forName(className, false, classLoader); - } catch (ClassNotFoundException x) { - throw new ProviderException("[" + serviceClazz.getName() + "] Provider " + className + " not found"); - } - if (!serviceClazz.isAssignableFrom(c)) { - throw new ProviderException( - "[" + serviceClazz.getName() + "] Provider " + className + " not a subtype"); - } - try { - S provider = serviceClazz.cast(c.newInstance()); - return provider; - } catch (Throwable e) { - throw new ProviderException("[" + serviceClazz.getName() + "] Provider " + className - + " could not be instantiated! --" + e.getMessage()); - } - } - } - - private static class ProviderInfo implements Provider { - - private final String shortName; - - private final String fullName; - - private final S service; - - public ProviderInfo(String shortName, String fullName, S service) { - this.shortName = shortName; - this.fullName = fullName; - this.service = service; - } - - @Override - public String getShortName() { - return shortName; - } - - @Override - public String getFullName() { - return fullName; - } - - @Override - public S getService() { - return service; - } - - } -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BaseType.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BaseType.java deleted file mode 100644 index f649171e..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BaseType.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jd.blockchain.binaryproto; - -/** - * 基础类型标志; - * - * @author huanghaiquan - * - */ -public interface BaseType { - - /** - * 空值; - */ - public static final byte NIL = (byte) 0x00; - - /** - * 布尔; - */ - public static final byte BOOLEAN = (byte) 0x01; - - /** - * 整数; - */ - public static final byte INTEGER = (byte) 0x10; - - /** - * 8位整数; - */ - public static final byte INT8 = (byte) (INTEGER | 0x01); - - /** - * 16位整数; - */ - public static final byte INT16 = (byte) (INTEGER | 0x02); - - /** - * 32位整数; - */ - public static final byte INT32 = (byte) (INTEGER | 0x03); - - /** - * 64位整数; - */ - public static final byte INT64 = (byte) (INTEGER | 0x04); - - /** - * 文本 - */ - public static final byte TEXT = (byte) 0x20; - - /** - * 字节序列; - */ - public static final byte BYTES = (byte) 0x40; - - /** - * 扩展类型;
- * - * 最高位为1,用作保留字段; - */ - public static final byte EXT = (byte) 0x80; - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BinarySegmentHeader.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BinarySegmentHeader.java deleted file mode 100644 index 82eba875..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BinarySegmentHeader.java +++ /dev/null @@ -1,80 +0,0 @@ -//package com.jd.blockchain.binaryproto; -// -//import java.io.ByteArrayOutputStream; -//import java.io.InputStream; -//import java.io.OutputStream; -//import java.util.Arrays; -//import java.util.Collections; -//import java.util.List; -// -//import my.utils.io.BytesUtils; -// -///** -// * 二进制数据段的头部; -// * -// * @author huanghaiquan -// * -// */ -//public class BinarySegmentHeader { -// -// public static final BinarySliceSpec CODE_SLICE_SPEC = new BinarySliceSpec(4, false, "Code", "Data Contract Code"); -// -// public static final BinarySliceSpec VERSION_SLICE_SPEC = new BinarySliceSpec(8, false, "Version", "Data Contract Version"); -// -// public static final List HEADER_SLICES = Collections.unmodifiableList(Arrays.asList(CODE_SLICE_SPEC, VERSION_SLICE_SPEC)); -// -// private int code; -// -// private long version; -// -// public int getCode() { -// return code; -// } -// -// public long getVersion() { -// return version; -// } -// -// public BinarySegmentHeader(int code, long version) { -// this.code = code; -// this.version = version; -// } -// -// public static int resolveCode(InputStream in) { -// return BytesUtils.readInt(in); -// } -// -// -// public static long resolveVersion(InputStream in) { -// return BytesUtils.readLong(in); -// } -// -// public static BinarySegmentHeader resolveFrom(InputStream in) { -// int code = resolveCode(in); -// long version = resolveVersion(in); -// return new BinarySegmentHeader(code, version); -// } -// -// public static void writeCode(int code, OutputStream out) { -// BytesUtils.writeInt(code, out); -// } -// -// public static void writeVersion(long version, OutputStream out) { -// BytesUtils.writeLong(version, out); -// } -// -// public void writeTo(OutputStream out) { -// writeCode(code, out); -// writeVersion(version, out); -// } -// -// -// public byte[] toBytes() { -// ByteArrayOutputStream out =new ByteArrayOutputStream(); -// writeTo(out); -// return out.toByteArray(); -// } -// -// -// -//} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BinarySliceSpec.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BinarySliceSpec.java deleted file mode 100644 index c98ffcc8..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/BinarySliceSpec.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.jd.blockchain.binaryproto; - -/** - * 表示一个二进制数据片段的格式标准; - *

- * - * 一个数据契约的实例输出生成的二进制数据段{@link BinarySegmentHeader}是由一系列小的标准化的数据片段组成; - * - * @author huanghaiquan - * - */ -public class BinarySliceSpec { - - private boolean repeatable; - - private int length; - - private boolean dynamic; - - private String name; - - private String description; - - /** - * 是否重复多次;true 表示以一个头部表示接下来的片段将重复的次数; - * - * @return - */ - public boolean isRepeatable() { - return repeatable; - } - - /** - * 字节长度; - * - * @return - */ - public int getLength() { - return length; - } - - /** - * 长度是动态扩展的; - * - * @return - */ - public boolean isDynamic() { - return dynamic; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - private BinarySliceSpec(String name, String description, boolean repeatable, int length, boolean dynamic) { - this.name = name; - this.description = description; - this.repeatable = repeatable; - this.length = length; - this.dynamic = dynamic; - } - - public static BinarySliceSpec newFixedSlice(int length, String name, String description) { - return new BinarySliceSpec(name, description, false, length, false); - } - - public static BinarySliceSpec newRepeatableFixedSlice(int length, String name, String description) { - return new BinarySliceSpec(name, description, true, length, false); - } - - public static BinarySliceSpec newDynamicSlice(String name, String description) { - return new BinarySliceSpec(name, description, false, -1, true); - } - - public static BinarySliceSpec newRepeatableDynamicSlice(String name, String description) { - return new BinarySliceSpec(name, description, true, -1, true); - } -} \ No newline at end of file diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContract.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContract.java deleted file mode 100644 index 6c0fc8e2..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContract.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jd.blockchain.binaryproto; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * {@link DataContract} 表示数据契约,用于把一个接口类型声明为一份标准化“数据契约”; - *

- * “数据契约”的定义由类型编码({@link #code()})和属性列表(由标注 - * {@link DataField}定义)构成,其中属性列表中有唯一一个“主键字段”, 主键字段的值用于标识数据契约实例的唯一性; - *

- * “数据契约”通过属性可以引用其它的“数据契约”(由 {@link DataField#refContract()} = true - * 定义),这样便构成了“数据契约”嵌套定义的关系图; - *

- * 当对一个“数据契约”进行二进制序列化输出时,从根对象出发,对关系图中的每一个“数据契约”实例都输出为一个单独的二进制数据段{@link BinarySegmentHeader}, - * - * 父的数据段中会将子数据段的内容合并输出到对应字段的位置; - * - *

- * 在序列化输出数据段时,将按顺序先后输出类型编号({@link #code()})、版本标识、属性值列表;

- * 其中,“版本标识”是根据类型编号和属性列表(由 {@link DataField} 顺序和类型决定,与名称无关) 进行 SHA256 哈希后映射到 64 - * 位值空间的值,占用 8 字节空间; - * “版本标识” 用于在反序列化时校验数据格式的版本是否匹配,并允许数据契约升级后多版本数据并存; - * - * @author huanghaiquan - * - */ -@Target({ ElementType.TYPE, ElementType.PARAMETER }) -@Retention(RetentionPolicy.RUNTIME) -public @interface DataContract { - - /** - * 类型编号; - *

- * 不同类型不能声明相同的编号; - *

- * - * @return - */ - int code(); - - String name() default ""; - - String description() default ""; - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractEncoder.java deleted file mode 100644 index 179f7d76..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractEncoder.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jd.blockchain.binaryproto; - -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; - -/** - * 二进制编码器; - * - * @author huanghaiquan - * - */ -public interface DataContractEncoder { - - /** - * 数据契约的格式标准; - * - * @return - */ - DataSpecification getSepcification(); - - /** - * 数据契约的接口类型; - * - * @return - */ - Class getContractType(); - - /** - * 按照数据格式标准序列化输出指定的数据对象; - * - * @param dataContract - * 数据对象; - * @param buffer - * 要写入的缓冲区; - * @return 返回写入的字节数; - */ - int encode(Object dataContract, BytesOutputBuffer buffer); - - /** - * 按照数据格式标准将指定的二进制输入流反序列化生成数据对象; - * - * @param bytesStream - * @return - */ - T decode(BytesInputStream bytesStream); -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractException.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractException.java deleted file mode 100644 index ae7e57c3..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.binaryproto; - -public class DataContractException extends RuntimeException { - - private static final long serialVersionUID = 5069307301932155810L; - - public DataContractException(String message) { - super(message); - } - public DataContractException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractRegistry.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractRegistry.java deleted file mode 100644 index 08dcc76f..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataContractRegistry.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.impl.DataContractContext; - -/** - * 数据实体注册表; - * - * @author huanghaiquan - * - */ -public class DataContractRegistry { - - private DataContractRegistry() { - } - - - //TODO: Refactor contract type registering in service provider mode; - - public static DataContractEncoder register(Class contractType) { - DataContractEncoder encoder = DataContractContext.resolve(contractType); - return encoder; - } - - public static DataContractEncoder getEncoder(Class contractType) { - return DataContractContext.ENCODER_LOOKUP.lookup(contractType); - } - - public static DataContractEncoder getEncoder(int contractCode, long version) { - return DataContractContext.ENCODER_LOOKUP.lookup(contractCode, version); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataField.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataField.java deleted file mode 100644 index 1829eed6..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataField.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.jd.blockchain.binaryproto; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * 标记一个接口的字段作为数据契约的字段; - *

- * - * 字段的数据类型需要需要显式通过 - * {@link #primitiveType()}、{@link #refEnum()}、{@link #refContract()} - * 3个属性之一标注(只能标记一种); - * - * @author huanghaiquan - * - */ -@Target({ ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -public @interface DataField { - - /** - * 字段顺序; - *

- * - * 顺序编号实际并不会输出,仅用于对字段进行升序排列; - *

- * - * 注:对于已经发布使用的数据契约,都不应该调整顺序,否则会导致无法正确解析已有数据; - * - * @return - */ - int order(); - - /** - * 基本数据类型; - *

- * - * 如果字段的类型属于 {@link PrimitiveType} 枚举中的基本数据类型,则需要显式指定一种具体的类型; - * - * @return - */ - PrimitiveType primitiveType() default PrimitiveType.NIL; - - /** - * 是否是枚举类型; - *

- * 如果为 true,则属性的声明类型必须是枚举类型,且该枚举类型已经标记 {@link EnumContract}; - * - * @return - */ - boolean refEnum() default false; - - /** - * 嵌套的数据契约类型; - * - * 如果为 true,则属性的声明类型必须是接口类型,且该类型已经标记了 {@link DataContract}; - * - * @return - */ - boolean refContract() default false; - - /** - * 嵌套的契约类型是否根据实际的对象实现的契约接口动态写入; - * - * @return - */ - boolean genericContract() default false; - - /** - * 列表; - * - * @return - */ - boolean list() default false; - - /** - * 最大长度,单位为“byte” - *

- * 仅对于文本、字节数组、大整数等相关的数据类型有效(即:{@link PrimitiveType} 枚举中编码大于等于 0x20 - * {@link PrimitiveType#TEXT}的数据类型); - * - * @return - */ - int maxSize() default -1; - - /** - * 名称; - *

- * 默认为属性的名称; - * - * @return - */ - String name() default ""; - - /** - * 关于字段的说明; - *

- * - * 说明内容将输出到数据段的数据结构描述文件; - * - * @return - */ - String decription() default ""; - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataSpecification.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataSpecification.java deleted file mode 100644 index 9577d69e..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/DataSpecification.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jd.blockchain.binaryproto; - -import java.util.List; - -/** - * {@link DataSpecification} 表示数据契约的格式标准; - *

- * {@link DataSpecification} 提供了数据契约的格式描述(通过属性 {@link #getCode()}、 - * {@link #getVersion()}、 - * {@link #getFields()}),以及二进制数据片段序列的格式描述({@link #getSlices()}); - * - *

- * 其中,数据片段列表({@link #getSlices()})反映了数据契约实际输出的二进制序列:
- * 1、首个数据片段是数据契约的类型编码({@link #getCode()});
- * 2、接下来是数据契约的版本({@link #getVersion()});
- * 3、再接下来是与字段列表({@link #getFields()})一一对应的数据分片;

- * - *

- * - * - * @author huanghaiquan - * - */ -public interface DataSpecification { - - /** - * 数据契约的类型编码; - * - * @return - */ - int getCode(); - - /** - * 数据契约的版本; - *

- * - * 由类型编码{@link #getCode()}和字段列表{@link #getFields()} 进行哈希生成的 64 位整数; - * - * @return - */ - long getVersion(); - - String getName(); - - String getDescription(); - - /** - * 按定义顺序排列的字段格式标准的列表; - *

- * 字段的顺序由 {@link DataField#order()} 定义; - * - * @return - */ - List getFields(); - - /** - * 按顺序定义的二进制数据片段的格式标准的列表; - * - * @return - */ - List getSlices(); - - String toHtml(); - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumContract.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumContract.java deleted file mode 100644 index d8e8c452..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumContract.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.binaryproto; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target({ ElementType.TYPE }) -@Retention(RetentionPolicy.RUNTIME) -public @interface EnumContract { - - /** - * 类型编号; - *

- * - * 而且,不同类型不能声明相同的编号;

- * - * @return - */ - int code() ; - - String name() default ""; - - String decription() default ""; - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumField.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumField.java deleted file mode 100644 index f7c588f1..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumField.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.binaryproto; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target({ ElementType.FIELD, ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -public @interface EnumField { - - /** - * 枚举值的类型; - * - *

- * 注:只支持 {@link PrimitiveType#INT8} ~ {@link PrimitiveType#INT32} 这几种类型; - * - * - * @return - */ - PrimitiveType type(); - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumSpecification.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumSpecification.java deleted file mode 100644 index 6c4e73ce..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/EnumSpecification.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.binaryproto; - -public interface EnumSpecification { - - int getCode(); - - String getName(); - - String getDescription(); - - long getVersion(); - - PrimitiveType getValueType(); - - int[] getItemValues(); - - String[] getItemNames(); - - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/FieldSpec.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/FieldSpec.java deleted file mode 100644 index 315e6580..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/FieldSpec.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.jd.blockchain.binaryproto; - -/** - * 表示数据契约字段的格式标准; - * - * @author huanghaiquan - * - */ -public interface FieldSpec { - -// /** -// * 字段值的类型编码; -// *

-// * -// * 该编码是对{@link #getPrimitiveType()}、{@link #getRefEnum()}、{@link #getRefContract()} -// * 3个属性的联合编码,通过首字节标识出类型为这3中类型中的一种;
-// * 其中:
-// * 1、首字节为 0 表示为基本类型 {@link #getPrimitiveType()};
-// * 2、首字节为 1 表示为枚举类型 {@link #getRefEnum()},紧接其后是枚举类型的编码
-// * 3、首字节为 2 表示为数据契约类型 {@link #getRefContract()};
-// * 4、首字节为 3 表示为基本类型的数组类型 {@link #isRepeatable()} ()};
-// * 5、首字节为 4 表示为PubKey类型 {@link #isRefPubKey()};
-// * 6、首字节为 5 表示为PrivKey类型 {@link #isRefPrivKey()};
-// * 7、首字节为 6 表示为HashDigest类型 {@link #isRefHashDigest()};
-// * 8、首字节为 7 表示为数据契约类型数组 {@link #isList(), @link #getRefContract()};
-// * 9、首字节为 8 表示为BlockChainIdentity数据类型 {@link #isRefIdentity()} -// * 10、首字节为9 表示为NetworkAddress数据类型 {@link #isRefNetworkAddr()};
-// * @return -// */ -// long getTypeCode(); - - /** - * 字段的值的类型; - *

- * 如果不是字段的值不是基本类型,则返回 null(即: {@link DataField#primitiveType()} 设置为 - * {@link PrimitiveType#NIL}); - * - * @return - */ - PrimitiveType getPrimitiveType(); - - /** - * 字段的值引用的枚举契约; - *

- * 如果字段的值不是枚举契约类型,则返回 null; - * - * @return - */ - EnumSpecification getRefEnum(); - - /** - * 字段的值引用的数据契约; - *

- * 如果字段的值不是数据契约类型,则返回 null; - * - * @return - */ - DataSpecification getRefContract(); - - boolean isRepeatable(); - -// /** -// * 字段的值引用的PubKey; -// *

-// * 如果字段的值不是PubKey,则返回 false; -// * -// * @return -// */ -// boolean isRefPubKey(); -// /** -// * 字段的值引用的PrivKey; -// *

-// * 如果字段的值不是PrivKey,则返回 false; -// * -// * @return -// */ -// boolean isRefPrivKey(); -// /** -// * 字段的值引用的HashDigest; -// *

-// * 如果字段的值不是HashDigest,则返回 false; -// * -// * @return -// */ -// boolean isRefHashDigest(); -// /** -// * 字段的值引用的SignatureDigest; -// *

-// * 如果字段的值不是SignatureDigest,则返回 false; -// * -// * @return -// */ -// boolean isRefSignatureDigest(); -// /** -// * 字段的值引用的BlockChainIdentity; -// *

-// * 如果字段的值不是HashDigest,则返回 false; -// * -// * @return -// */ -// boolean isRefIdentity(); -// /** -// * 字段的值引用的NetworkAddress; -// *

-// * 如果字段的值不是NetworkAddress,则返回 false; -// * -// * @return -// */ -// boolean isRefNetworkAddr(); - /** - * 最大长度;单位为“byte”; - * - * @return - * @see {@link DataField#maxSize()} - */ - int getMaxSize(); - - String getName(); - - String getDescription(); - - /** - * 是否引用了一个通用数据契约类型,实际的类型需要根据实际的对象实例来定; - * @return - */ - boolean isGenericContract(); -// Class getContractTypeResolver(); -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/AbstractDynamicValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/AbstractDynamicValueConverter.java deleted file mode 100644 index 53c8161e..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/AbstractDynamicValueConverter.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.NumberMask; - -public abstract class AbstractDynamicValueConverter implements DynamicValueConverter { - - protected Class valueType; - - private static final NumberMask SIZE_HEAD = NumberMask.NORMAL; - - private static final byte[] NULL_HEAD = new byte[1]; - - static { - SIZE_HEAD.writeMask(0, NULL_HEAD, 0); - } - - public AbstractDynamicValueConverter(Class valueType) { - this.valueType = valueType; - } - - @Override - public Class getValueType() { - return valueType; - } - - @Override - public Object getDefaultValue() { - return null; - } - - protected int writeSize(int size, BytesOutputBuffer buffer) { - int len = SIZE_HEAD.getMaskLength(size); - byte[] headerBytes = new byte[len]; - SIZE_HEAD.writeMask(size, headerBytes, 0); - buffer.write(headerBytes); - return len; - } - - protected int readSize(BytesInputStream bytesStream) { - return SIZE_HEAD.resolveMaskedNumber(bytesStream); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/AbstractFieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/AbstractFieldEncoder.java deleted file mode 100644 index 597d3e2e..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/AbstractFieldEncoder.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.binaryproto.FieldSpec; - -public abstract class AbstractFieldEncoder implements FieldEncoder { - - protected BinarySliceSpec sliceSpec; - - protected FieldSpec fieldSpec; - - protected Method reader; - - public AbstractFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader) { - this.sliceSpec = sliceSpec; - this.fieldSpec = fieldSpec; - this.reader = reader; - } - - @Override - public BinarySliceSpec getSliceSpecification() { - return sliceSpec; - } - - @Override - public FieldSpec getFieldSpecification() { - return fieldSpec; - } - - @Override - public Method getReader() { - return reader; - } - - - protected Object readValue(Object dataContract) { - try { - return reader.invoke(dataContract); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - protected Object[] readArrayValue(Object dataContract) { - return (Object[]) readValue(dataContract); - } -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BoolConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BoolConverter.java deleted file mode 100644 index c6c9c0f6..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BoolConverter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; - -public class BoolConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return boolean.class; - } - - @Override - public Object getDefaultValue() { - return false; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - buffer[offset] = ((Boolean)value).booleanValue() ? (byte)1 : (byte)0; - return 1; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getByte() == 1 ? Boolean.TRUE : Boolean.FALSE; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BoolWrapperConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BoolWrapperConverter.java deleted file mode 100644 index f4eff751..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BoolWrapperConverter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; - -public class BoolWrapperConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return Boolean.class; - } - - @Override - public Object getDefaultValue() { - return null; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - buffer[offset] = ((Boolean)value).booleanValue() ? (byte)1 : (byte)0; - return 1; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getByte() == 1 ? Boolean.TRUE : Boolean.FALSE; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BytesSerializableValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BytesSerializableValueConverter.java deleted file mode 100644 index 6ac29b9b..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BytesSerializableValueConverter.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import com.jd.blockchain.binaryproto.DataContractException; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSerializable; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class BytesSerializableValueConverter extends AbstractDynamicValueConverter { - - private Constructor constructor; - - public BytesSerializableValueConverter(Class valueType) { - super(valueType); - if (!BytesSerializable.class.isAssignableFrom(valueType)) { - throw new IllegalArgumentException("The specified type cann't be assigned as BytesSerializable!"); - } - // 检查是否存在以 byte[] 为参数的构造器; - try { - constructor = valueType.getConstructor(byte[].class); - constructor.setAccessible(true); - } catch (NoSuchMethodException e) { - throw new DataContractException("No constructor with byte's array argument! --" + e.getMessage(), e); - } catch (SecurityException e) { - throw new DataContractException(e.getMessage(), e); - } - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - if (dataSlice.getSize() == 0) { - return null; - } - byte[] bytes = dataSlice.getBytesCopy(); - try { - return constructor.newInstance(bytes); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - throw new DataContractException(e.getMessage(), e); - } - } - - @Override - public int encodeDynamicValue(Object value, BytesOutputBuffer buffer) { - byte[] bytes = value == null ? BytesUtils.EMPTY_BYTES : ((BytesSerializable) value).toBytes(); - int size = bytes.length; - size += writeSize(size, buffer); - buffer.write(bytes); - return size; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BytesValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BytesValueConverter.java deleted file mode 100644 index 071fdeaa..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/BytesValueConverter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class BytesValueConverter extends AbstractDynamicValueConverter { - - public BytesValueConverter() { - super(byte[].class); - } - - @Override - public int encodeDynamicValue(Object value, BytesOutputBuffer buffer) { - byte[] bytes =value == null ? BytesUtils.EMPTY_BYTES : (byte[]) value; - int size = bytes.length; - size += writeSize(size, buffer); - - buffer.write(bytes); - return size; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getBytesCopy(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractContext.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractContext.java deleted file mode 100644 index ae923b4e..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractContext.java +++ /dev/null @@ -1,790 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataContractEncoder; -import com.jd.blockchain.binaryproto.DataContractException; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.DataSpecification; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; -import com.jd.blockchain.binaryproto.EnumSpecification; -import com.jd.blockchain.binaryproto.FieldSpec; -import com.jd.blockchain.binaryproto.impl.EnumSpecificationInfo.EnumConstant; -import com.jd.blockchain.utils.io.BytesSerializable; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.security.SHA256Hash; -import com.jd.blockchain.utils.security.ShaUtils; - -public class DataContractContext { - - public static DataContractEncoderLookup ENCODER_LOOKUP; - - private static final Object MUTEX = new Object(); - - private static final BinarySliceSpec HEAD_SLICE = BinarySliceSpec.newFixedSlice(HeaderEncoder.HEAD_BYTES, "HEAD", - "The code and version of data contract."); - - private static final byte SINGLE_TYPE = 0; - private static final byte REPEATABLE_TYPE = 1; - - /** - * 基本类型的字段; - */ - private static final byte PRIMITIVE_TYPE_FIELD = 0; - - /** - * 枚举类型的字段; - */ - private static final byte ENUM_CONTRACT_FIELD = 1; - - /** - * 引用一个具体的数据契约类型的字段; - */ - private static final byte DATA_CONTRACT_FIELD = 2; - - /** - * 动态的数据契约类型的字段; - */ - private static final byte DYNAMIC_CONTRACT_FIELD = 3; - - private static Map codeMap = new ConcurrentHashMap<>(); - private static Map, DataContractEncoder> typeMap = new ConcurrentHashMap<>(); - - private static Map, EnumSpecification> enumContractSpecMap = new ConcurrentHashMap<>(); - - private static Map, ValueConverter>> primitiveTypeConverters = new HashMap<>(); - - static { - addConverterMapping(PrimitiveType.BOOLEAN, boolean.class, new BoolConverter()); - addConverterMapping(PrimitiveType.BOOLEAN, Boolean.class, new BoolWrapperConverter()); - addConverterMapping(PrimitiveType.INT8, byte.class, new Int8ByteConverter()); - addConverterMapping(PrimitiveType.INT8, Byte.class, new Int8ByteWrapperConverter()); - addConverterMapping(PrimitiveType.INT16, short.class, new Int16ShortConverter()); - addConverterMapping(PrimitiveType.INT16, Short.class, new Int16ShortWrapperConverter()); - addConverterMapping(PrimitiveType.INT16, char.class, new Int16CharConverter()); - addConverterMapping(PrimitiveType.INT16, Character.class, new Int16CharWrapperConverter()); - addConverterMapping(PrimitiveType.INT32, int.class, new Int32IntConverter()); - addConverterMapping(PrimitiveType.INT32, Integer.class, new Int32IntWrapperConverter()); - addConverterMapping(PrimitiveType.INT64, long.class, new Int64LongConverter()); - addConverterMapping(PrimitiveType.INT64, Long.class, new Int64LongWrapperConverter()); - addConverterMapping(PrimitiveType.TEXT, String.class, new StringValueConverter()); - addConverterMapping(PrimitiveType.BYTES, byte[].class, new BytesValueConverter()); - - ENCODER_LOOKUP = new DataContractEncoderLookup() { - @Override - public DataContractEncoder lookup(int code, long version) { - ContractTypeVersionContext ctx = codeMap.get(code); - if (ctx == null) { - return null; - } - // TODO: 未实现多个版本的处理; - return ctx.contractEncoder; - } - - @Override - public DataContractEncoder lookup(Class contractType) { - return typeMap.get(contractType); - } - }; - } - - private static void addConverterMapping(PrimitiveType protocalType, Class javaType, ValueConverter converter) { - Map, ValueConverter> converterMap = primitiveTypeConverters.get(protocalType); - if (converterMap == null) { - converterMap = new HashMap<>(); - primitiveTypeConverters.put(protocalType, converterMap); - } - converterMap.put(javaType, converter); - } - - private static ValueConverter getPrimitiveTypeConverter(PrimitiveType protocalType, Class javaType) { - Map, ValueConverter> converterMap = primitiveTypeConverters.get(protocalType); - if (converterMap != null) { - ValueConverter converter = converterMap.get(javaType); - if (converter != null) { - return converter; - } - if (PrimitiveType.BYTES == protocalType && BytesSerializable.class.isAssignableFrom(javaType)) { - converter = new BytesSerializableValueConverter(javaType); - converterMap.put(javaType, converter); - return converter; - } - } - throw new IllegalArgumentException(String.format("Unsupport types mapping: [PrimitiveType=%s]-[JavaType=%s]", - protocalType.toString(), javaType.toString())); - } - - public static DataContractEncoder resolve(Class contractType) { - DataContractEncoder encoder = typeMap.get(contractType); - if (encoder != null) { - return encoder; - } - synchronized (MUTEX) { - encoder = typeMap.get(contractType); - if (encoder != null) { - return encoder; - } - ContractTypeVersionContext ctx = resolveContract(contractType); - encoder = ctx.contractEncoder; - } - - return encoder; - } - - /** - * 解析数据契约;
- * - * @param contractType - * @return - */ - private static ContractTypeVersionContext resolveContract(Class contractType) { - // TODO: 未处理可能存在的循环依赖问题,这会导致解析方法陷入死循环; - if (!contractType.isInterface()) { - throw new IllegalArgumentException( - "The specified contractType [" + contractType.toString() + "] is not a interface!"); - } - DataContract annoContract = contractType.getAnnotation(DataContract.class); - if (annoContract == null) { - throw new IllegalArgumentException( - "Class[" + contractType.toString() + "] isn't annotated as DataContract!"); - } - int contractCode = annoContract.code(); - ContractTypeVersionContext ctx = codeMap.get(contractCode); - if (ctx != null) { - if (ctx.contractType == contractType) { - return ctx; - } else { - throw new IllegalStateException(String.format( - "Contract Code[%s] has been registered by type[%s]! Cann't register again with type[%s]!", - contractCode, ctx.contractType.getName(), contractType.getName())); - } - } - - DataContractEncoder contractEncoder = resolveEncoder(contractType, annoContract); - - ctx = new ContractTypeVersionContext(contractType, contractEncoder); - - codeMap.put(contractCode, ctx); - typeMap.put(contractType, contractEncoder); - - return ctx; - } - - /** - * @param contractType - * @param annoContract - * @return - */ - private static DataContractEncoder resolveEncoder(Class contractType, DataContract annoContract) { - DataContractEncoder encoder = typeMap.get(contractType); - if (encoder != null) { - return encoder; - } - - if (!contractType.isInterface()) { - throw new IllegalArgumentException( - "The registering contract type is not a interface! --" + contractType.getName()); - } - - // 解析获得数据契约的有序的字段列表; - List allFields = resolveContractFields(contractType, annoContract); - - // 解析每一个字段,生成字段的编码器和二进制片段描述符; - FieldSpecInfo[] fieldSpecs = new FieldSpecInfo[allFields.size()]; - BinarySliceSpec[] dataSliceSpecs = new BinarySliceSpec[allFields.size() + 1]; - FieldEncoder[] fieldEncoders = new FieldEncoder[allFields.size()]; - - dataSliceSpecs[0] = HEAD_SLICE; - - SHA256Hash versionHash = ShaUtils.hash_256();// 用于计算 DataContract 的版本号的哈希生成器; - int i = 0; - for (FieldDeclaredInfo fieldInfo : allFields) { - fieldSpecs[i] = fieldInfo.fieldSpec; - - // 构建二进制片段; - dataSliceSpecs[i + 1] = buildSlice(fieldInfo.fieldSpec); - - fieldEncoders[i] = buildFieldEncoder(fieldInfo, dataSliceSpecs[i + 1]); - - // 按顺序计算字段类型, - byte[] fieldType = generateFieldTypeCode(fieldInfo.fieldSpec); - versionHash.update(fieldType); - - i++; - } - - // 数据契约的版本号取自对所有字段的数据类型的哈希前 8 位; - byte[] allFieldTypesHash = versionHash.complete(); - long version = BytesUtils.toLong(allFieldTypesHash); - - HeaderEncoder headerEncoder = new HeaderEncoder(HEAD_SLICE, annoContract.code(), version, annoContract.name(), - annoContract.description()); - - DataContractSpecification spec = new DataContractSpecification(annoContract.code(), version, - annoContract.name(), annoContract.description(), dataSliceSpecs, fieldSpecs); - - DataContractEncoderImpl contractEncoder = new DataContractEncoderImpl(contractType, spec, headerEncoder, - fieldEncoders); - - return contractEncoder; - } - - /** - * 解析获得数据契约的有序的字段列表; - * - * @param contractType - * @param annoContract - * @return - */ - private static List resolveContractFields(Class contractType, DataContract annoContract) { - // 解析每一个方法,获得标注的合约字段,并按照声明的合约类型进行分组; - Map, DeclaredFieldGroup> declaredFielGroups = new HashMap<>(); - Method[] methods = contractType.getMethods(); - for (Method method : methods) { - DataField annoField = method.getAnnotation(DataField.class); - if (annoField == null) { - continue; - } - Class declaredType = method.getDeclaringClass(); - DeclaredFieldGroup group = declaredFielGroups.get(declaredType); - if (group != null) { - FieldSpecInfo fieldSpec = resolveFieldSpec(method, annoField); - group.addField(method, annoField, fieldSpec); - continue; - } - if (declaredType == contractType) { - // 字段是由当前的数据契约类型所声明; - FieldSpecInfo fieldSpec = resolveFieldSpec(method, annoField); - group = new DeclaredFieldGroup(contractType, annoContract, method, annoField, fieldSpec); - declaredFielGroups.put(contractType, group); - continue; - } - // 字段由父接口声明,所以取父接口上的标注定义进行解析; - DataContract declaredContractAnnotation = declaredType.getAnnotation(DataContract.class); - if (declaredContractAnnotation == null) { - throw new DataContractException("Declare data contract field in a non-data-contract type! --[Type=" - + declaredType.getName() + "]"); - } - - FieldSpecInfo fieldSpec = resolveFieldSpec(method, annoField); - group = new DeclaredFieldGroup(declaredType, declaredContractAnnotation, method, annoField, fieldSpec); - declaredFielGroups.put(declaredType, group); - } - - DeclaredFieldGroup[] groups = declaredFielGroups.values() - .toArray(new DeclaredFieldGroup[declaredFielGroups.size()]); - for (DeclaredFieldGroup group : groups) { - // 计算继承距离; - int extendsionDistance = computeExtendsionDistance(contractType, group.declaredContractType); - if (extendsionDistance < 0) { - // 实际不会进入此分支; - throw new IllegalStateException("Illegal state that isn't expected to occur!"); - } - group.setExtendsionDistance(extendsionDistance); - } - - // 按继承距离和数据契约的编码进行倒序排序,如果继承距离相同,则编码小的在前; - // 达到的效果:父接口声明的字段在前,子接口声明的字段在后;同一个继承级别,则编码小的在前; - Arrays.sort(groups, - (g1, g2) -> (g2.extendsionDistance == g1.extendsionDistance - ? g1.declaredContractAnnotation.code() - g2.declaredContractAnnotation.code() - : g2.extendsionDistance - g1.extendsionDistance)); - - List allFields = new ArrayList<>(); - for (DeclaredFieldGroup grp : groups) { - allFields.addAll(grp.getFields()); - } - - return allFields; - } - - /** - * 创建字段的编码器; - * - * @param fieldInfo - * @param sliceSpec - * @return - */ - private static FieldEncoder buildFieldEncoder(FieldDeclaredInfo fieldInfo, BinarySliceSpec sliceSpec) { - FieldSpecInfo fieldSpec = fieldInfo.fieldSpec; - if (fieldSpec.getPrimitiveType() != null) { - return buildPrimitiveFieldEncoder(fieldInfo, sliceSpec); - } else if (fieldSpec.getRefEnum() != null) { - return buildEnumFieldEncoder(fieldInfo, sliceSpec); - } else if (fieldSpec.getRefContract() != null) { - return buildContractFieldEncoder(fieldInfo, sliceSpec); - } else { - throw new IllegalStateException("Illegal states that has no type definition for field! --[ReadMethod=" - + fieldInfo.reader.toString() + ""); - } - } - - /** - * 创建数据契约引用字段的编码器; - * - * @param fieldInfo - * @param sliceSpec - * @return - */ - private static FieldEncoder buildContractFieldEncoder(FieldDeclaredInfo fieldInfo, BinarySliceSpec sliceSpec) { - ValueConverter valueConverter; - if (fieldInfo.fieldSpec.isGenericContract()) { - Class contractType = fieldInfo.fieldSpec.getDataType(); - valueConverter = new DataContractGenericRefConverter(contractType, ENCODER_LOOKUP); - } else { - Class contractType = fieldInfo.fieldSpec.getDataType(); - DataContractEncoder encoder = typeMap.get(contractType); - valueConverter = new DataContractValueConverter(encoder); - } - - return createFieldEncoder(sliceSpec, fieldInfo.fieldSpec, fieldInfo.reader, valueConverter); - } - - /** - * 创建枚举类型的字段编码器; - * - * @param fieldInfo - * @param sliceSpec - * @return - */ - private static FieldEncoder buildEnumFieldEncoder(FieldDeclaredInfo fieldInfo, BinarySliceSpec sliceSpec) { - // 枚举类型的值转换器是由枚举值的范围检查加上一个基本类型的值转换器组成; - Class enumType = fieldInfo.fieldSpec.getDataType(); - EnumSpecificationInfo enumSpec = (EnumSpecificationInfo) fieldInfo.fieldSpec.getRefEnum(); - int[] values = enumSpec.getItemValues(); - Object[] constants = enumSpec.getConstants(); - PrimitiveType codeType = enumSpec.getValueType(); - - ValueConverter baseConverter = getPrimitiveTypeConverter(codeType, enumSpec.getDataType()); - - EnumValueConverter valueConverter = new EnumValueConverter(enumType, codeType, values, constants, - (FixedValueConverter) baseConverter); - - return createFieldEncoder(sliceSpec, fieldInfo.fieldSpec, fieldInfo.reader, valueConverter); - } - - /** - * 创建基本类型字段的编码器; - * - * @param fieldInfo - * @param sliceSpec - * @return - */ - private static FieldEncoder buildPrimitiveFieldEncoder(FieldDeclaredInfo fieldInfo, BinarySliceSpec sliceSpec) { - ValueConverter valueConverter = getPrimitiveTypeConverter(fieldInfo.fieldSpec.getPrimitiveType(), - fieldInfo.fieldSpec.getDataType()); - return createFieldEncoder(sliceSpec, fieldInfo.fieldSpec, fieldInfo.reader, valueConverter); - } - - private static FieldEncoder createFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader, - ValueConverter valueConverter) { - if (sliceSpec.isRepeatable()) { - if (sliceSpec.isDynamic()) { - return new DynamicArrayFieldEncoder(sliceSpec, fieldSpec, reader, - (DynamicValueConverter) valueConverter); - } else { - return new FixedArrayFieldEncoder(sliceSpec, fieldSpec, reader, (FixedValueConverter) valueConverter); - } - } else { - if (sliceSpec.isDynamic()) { - return new DynamicFieldEncoder(sliceSpec, fieldSpec, reader, (DynamicValueConverter) valueConverter); - } else { - return new FixedFieldEncoder(sliceSpec, fieldSpec, reader, (FixedValueConverter) valueConverter); - } - } - } - - private static BinarySliceSpec buildSlice(FieldSpecInfo fieldSpec) { - boolean fixed = false; - int len = -1; - PrimitiveType fixedValueType = null; - if (fieldSpec.getPrimitiveType() != null && fieldSpec.getPrimitiveType() != PrimitiveType.NIL) { - fixedValueType = fieldSpec.getPrimitiveType(); - } else if (fieldSpec.getRefEnum() != null) { - fixedValueType = fieldSpec.getRefEnum().getValueType(); - } - - if (fixedValueType != null) { - switch (fixedValueType) { - case BOOLEAN: - fixed = true; - len = 1; - break; - case INT8: - fixed = true; - len = 1; - break; - case INT16: - fixed = true; - len = 2; - break; - case INT32: - fixed = true; - len = 4; - break; - case INT64: - fixed = true; - len = 8; - break; - default: - break; - } - } - if (fieldSpec.isRepeatable()) { - if (fixed) { - return BinarySliceSpec.newRepeatableFixedSlice(len, fieldSpec.getName(), fieldSpec.getDescription()); - } else { - return BinarySliceSpec.newRepeatableDynamicSlice(fieldSpec.getName(), fieldSpec.getDescription()); - } - } else { - if (fixed) { - return BinarySliceSpec.newFixedSlice(len, fieldSpec.getName(), fieldSpec.getDescription()); - } else { - return BinarySliceSpec.newDynamicSlice(fieldSpec.getName(), fieldSpec.getDescription()); - } - } - } - - private static byte[] generateFieldTypeCode(FieldSpecInfo fieldSpec) { - byte repeatable = fieldSpec.isRepeatable() ? REPEATABLE_TYPE : SINGLE_TYPE; - byte[] codeBytes; - if (fieldSpec.getPrimitiveType() != null) { - // repeatable + type indicator + code of primitive type; - // 1 + 1 + 4; - codeBytes = new byte[6]; - codeBytes[0] = repeatable; - codeBytes[1] = PRIMITIVE_TYPE_FIELD; - BytesUtils.toBytes(fieldSpec.getPrimitiveType().CODE, codeBytes, 2); - } else if (fieldSpec.getRefEnum() != null) { - // repeatable + type indicator + code of enum contract + version of enum - // contract; - // 1+ 1 + 4 + 8; - codeBytes = new byte[14]; - codeBytes[0] = repeatable; - codeBytes[1] = ENUM_CONTRACT_FIELD; - EnumSpecification enumSpec = fieldSpec.getRefEnum(); - BytesUtils.toBytes(enumSpec.getCode(), codeBytes, 2); - BytesUtils.toBytes(enumSpec.getVersion(), codeBytes, 6); - } else if (fieldSpec.getRefContract() != null) { - // repeatable + type indicator + code of enum contract + version of enum - // contract; - // 1+ 1 + 4 + 8; - DataSpecification dataSpec = fieldSpec.getRefContract(); - codeBytes = new byte[14]; - codeBytes[0] = repeatable; - if (fieldSpec.isGenericContract()) { - codeBytes[1] = DYNAMIC_CONTRACT_FIELD; - } else { - codeBytes[1] = DATA_CONTRACT_FIELD; - } - BytesUtils.toBytes(dataSpec.getCode(), codeBytes, 2); - BytesUtils.toBytes(dataSpec.getVersion(), codeBytes, 6); - } else { - throw new DataContractException("Unknow field type!"); - } - return codeBytes; - } - - /** - * 计算指定两个接口类型之间的继承距离;
- * - * 如果不具有继承关系,则返回 -1; - * - * @param subsTypes - * 子类型; - * @param superType - * 父类型; - * @return - */ - private static int computeExtendsionDistance(Class subsTypes, Class superType) { - if (subsTypes == superType) { - return 0; - } - Class[] superIntfs = subsTypes.getInterfaces(); - for (Class si : superIntfs) { - int dis = computeExtendsionDistance(si, superType); - if (dis > -1) { - return dis + 1; - } - } - return -1; - } - - private static FieldSpecInfo resolveFieldSpec(Method accessor, DataField annoField) { - String name = annoField.name(); - name = name == null ? null : name.trim(); - if (name == null || name.length() > 0) { - name = accessor.getName(); - } - String desc = annoField.decription(); - desc = desc == null ? null : desc.trim(); - - int order = annoField.order(); - - boolean repeatable = annoField.list(); - Class dataType = accessor.getReturnType(); - - if (repeatable) { - if (!dataType.isArray()) { - throw new DataContractException("The annotated repeatable type mismatch non-array type[" - + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - dataType = dataType.getComponentType(); - } - - int maxSize = annoField.maxSize(); - PrimitiveType primitiveType = annoField.primitiveType(); - if (primitiveType != null) { - primitiveType = verifyPrimitiveType(primitiveType, dataType, accessor); - } - - boolean refEnum = annoField.refEnum(); - EnumSpecification enumSpecification = null; - if (refEnum) { - EnumContract annoEnumContract = dataType.getAnnotation(EnumContract.class); - if (annoEnumContract == null) { - throw new DataContractException("The data type of annotated enum field is not a EnumContract! --[Field=" - + accessor.toString() + "]"); - } - enumSpecification = resolveEnumContract(dataType, annoEnumContract); - } - - boolean refContract = annoField.refContract(); - DataSpecification contractSpecification = null; - // Class contractTypeResolverClazz = null; - if (refContract) { - // DataContract annoContract = dataType.getAnnotation(DataContract.class); - // if (annoContract == null) { - // throw new DataContractException( - // "The data type of annotated contract field is not a DataContract! --[Field=" - // + accessor.toString() + "]"); - // } - - ContractTypeVersionContext contractContext = resolveContract(dataType); - DataContractEncoder encoder = contractContext.contractEncoder; - contractSpecification = encoder.getSepcification(); - // contractTypeResolverClazz = annoField.contractTypeResolver(); - // if (contractTypeResolverClazz != null - // && (!ContractTypeResolver.class.isAssignableFrom(contractTypeResolverClazz))) - // { - // throw new DataContractException( - // "The contract type resolver of contract field doesn't implement - // ContractTypeResolver interface! --[Field=" - // + accessor.toString() + "]"); - // } - } - - if (primitiveType == null && enumSpecification == null && contractSpecification == null) { - throw new DataContractException( - "Miss data type definition of field! --[Field=" + accessor.toString() + "]"); - } - - FieldSpecInfo fieldSpec = null; - if (primitiveType != null) { - fieldSpec = new FieldSpecInfo(order, name, desc, primitiveType, repeatable, maxSize, dataType); - } else if (enumSpecification != null) { - fieldSpec = new FieldSpecInfo(order, name, desc, enumSpecification, repeatable, dataType); - } else { - fieldSpec = new FieldSpecInfo(order, name, desc, contractSpecification, repeatable, dataType, - annoField.genericContract()); - } - return fieldSpec; - } - - private static EnumSpecification resolveEnumContract(Class dataType, EnumContract annoEnumContract) { - EnumSpecificationInfo enumSpec = (EnumSpecificationInfo) enumContractSpecMap.get(dataType); - if (enumSpec != null) { - return enumSpec; - } - try { - if (!dataType.isEnum()) { - throw new DataContractException("Field's type is not a enum type! --[" + dataType.toString() + "]"); - } - // TODO:暂时硬编码检索 code 字段; - Field codeField = dataType.getField("CODE"); - if (codeField == null) { - throw new DataContractException("Enum type miss the 'CODE' field! --[" + dataType.toString() + "]"); - } - EnumField fieldAnno = codeField.getAnnotation(EnumField.class); - if (fieldAnno == null) { - throw new DataContractException("Enum's 'CODE' field is not annotated with @EnumField !"); - } - // TODO: 暂时未实现枚举契约的版本号计算; - long version = 0; - enumSpec = new EnumSpecificationInfo(fieldAnno.type(), annoEnumContract.code(), version, - annoEnumContract.name(), annoEnumContract.decription(), codeField.getType()); - // get enum constants and CODE - Object[] enumItems = dataType.getEnumConstants(); - for (Object item : enumItems) { - int code = codeField.getInt(item); - EnumConstant constant = new EnumConstant(code, item.toString(), item); - enumSpec.addConstant(constant); - // enumSpec.setVersion(); if need - } - enumContractSpecMap.put(dataType, enumSpec); - return enumSpec; - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new DataContractException(e.getMessage(), e); - } - } - - /** - * 解析指定的类型是否匹配;
- * - * 要求必须是显式地声明类型,因此不会根据 Java 语言的声明类型做自动转换; - * - * @param primitiveType - * @param dataType - * @return - */ - private static PrimitiveType verifyPrimitiveType(PrimitiveType primitiveType, Class dataType, Method accessor) { - switch (primitiveType) { - case NIL: - return null; - case BOOLEAN: - if (dataType != Boolean.class && dataType != boolean.class) { - throw new DataContractException("The annotated primitive type[" + primitiveType.toString() - + "] mismatch java type[" + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - break; - case INT8: - if (dataType != Byte.class && dataType != byte.class) { - throw new DataContractException("The annotated primitive type[" + primitiveType.toString() - + "] mismatch java type[" + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - break; - case INT16: - if (dataType != Character.class && dataType != char.class && dataType != short.class) { - throw new DataContractException("The annotated primitive type[" + primitiveType.toString() - + "] mismatch java type[" + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - break; - case INT32: - if (dataType != Integer.class && dataType != int.class) { - throw new DataContractException("The annotated primitive type[" + primitiveType.toString() - + "] mismatch java type[" + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - break; - case INT64: - if (dataType != Long.class && dataType != long.class) { - throw new DataContractException("The annotated primitive type[" + primitiveType.toString() - + "] mismatch java type[" + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - break; - case TEXT: - if (dataType != String.class) { - throw new DataContractException("The annotated primitive type[" + primitiveType.toString() - + "] mismatch java type[" + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - break; - case BYTES: - if (dataType != byte[].class && (!BytesSerializable.class.isAssignableFrom(dataType))) { - throw new DataContractException("The annotated primitive type[" + primitiveType.toString() - + "] mismatch java type[" + dataType.getName() + "]! --[Field=" + accessor.toString() + "]"); - } - break; - default: - throw new DataContractException("Unsupported primitive type[" + primitiveType.toString() + "] ! --[Field=" - + accessor.toString() + "]"); - } - - return primitiveType; - } - - private static class DeclaredFieldGroup { - - /** - * 声明的合约类型; - */ - public Class declaredContractType; - - /** - * - */ - public DataContract declaredContractAnnotation; - - /** - * 声明类型距离要解析的类型的继承距离;直接继承的父接口的距离为 1,父接口的父接口为 2,以此类推; - */ - private int extendsionDistance; - - private TreeMap orderedFields = new TreeMap<>(); - - public Collection getFields() { - return orderedFields.values(); - } - - public DeclaredFieldGroup(Class declaredContractType, DataContract declaredContractAnnotation, - Method accessor, DataField fieldAnnotation, FieldSpecInfo fieldSpec) { - this.declaredContractType = declaredContractType; - this.declaredContractAnnotation = declaredContractAnnotation; - - addField(accessor, fieldAnnotation, fieldSpec); - } - - private void addField(Method accessor, DataField fieldAnnotation, FieldSpecInfo fieldSpec) { - // 检查字段的是否有重复序号; - FieldDeclaredInfo fieldInfo = new FieldDeclaredInfo(accessor, fieldAnnotation, fieldSpec); - FieldDeclaredInfo conflictedField = orderedFields.put(fieldSpec.getOrder(), fieldInfo); - if (conflictedField != null) { - // 有两个字段都声明了相同的序号,这容易导致无序状态; - throw new DataContractException(String.format("Declare two fields with the same order! --[%s][%s]", - fieldInfo.reader.toString(), conflictedField.reader.toString())); - } - } - - @SuppressWarnings("unused") - public int getExtendsionDistance() { - return extendsionDistance; - } - - public void setExtendsionDistance(int extendsionDistance) { - this.extendsionDistance = extendsionDistance; - } - - } - - private static class FieldDeclaredInfo { - public FieldSpecInfo fieldSpec; - - public Method reader; - - @SuppressWarnings("unused") - public DataField annoField; - - public FieldDeclaredInfo(Method accessor, DataField annoField, FieldSpecInfo fieldSpec) { - this.reader = accessor; - this.annoField = annoField; - this.fieldSpec = fieldSpec; - } - } - - private static class ContractTypeVersionContext { - - public Class contractType; - - public DataContractEncoder contractEncoder; - - // TODO:未实现多版本; - // private HashMap versionMap = new HashMap<>(); - - public ContractTypeVersionContext(Class contractType, DataContractEncoder encoder) { - this.contractType = contractType; - this.contractEncoder = encoder; - } - - } -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractEncoderImpl.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractEncoderImpl.java deleted file mode 100644 index f8989cfc..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractEncoderImpl.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -import com.jd.blockchain.binaryproto.DataContractEncoder; -import com.jd.blockchain.binaryproto.DataSpecification; -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; - -public class DataContractEncoderImpl implements DataContractEncoder { - - private Class[] contractTypeArray; - - private Class contractType; - - private DataSpecification specification; - - private HeaderEncoder headEncoder; - - private FieldEncoder[] fieldEncoders; - - // 字段的 Get 方法与编码器的映射表; - private Map fieldIndexMap; - - /** - * @param contractType - * @param specification - * @param headEncoder - * 头部编码器; - * @param fieldEncoders - * 按顺序排列的字段编码器列表; - */ - public DataContractEncoderImpl(Class contractType, DataSpecification specification, HeaderEncoder headEncoder, - FieldEncoder[] fieldEncoders) { - this.contractType = contractType; - this.contractTypeArray = new Class[] { contractType }; - this.specification = specification; - this.headEncoder = headEncoder; - this.fieldEncoders = fieldEncoders; - this.fieldIndexMap = new HashMap<>(); - int i = 0; - for (FieldEncoder fieldEncoder : fieldEncoders) { - fieldIndexMap.put(fieldEncoder.getReader(), i); - i++; - } - } - - HeaderEncoder getHeaderEncoder() { - return headEncoder; - } - - Class[] getContractTypeAsArray() { - return contractTypeArray; - } - - int getFieldCount() { - return fieldEncoders.length; - } - - FieldEncoder getFieldEncoder(int id) { - return fieldEncoders[id]; - } - - /** - * 通过字段的声明方法返回字段的序号; - * - * @param declaredMethod - * 声明并标注为数据契约字段的方法;注:不能是覆盖的非标注方法,也不能是实现方法; - * @return 字段序号; 如果不存在,则返回 -1; - */ - int getFieldId(Method declaredMethod) { - Integer id = fieldIndexMap.get(declaredMethod); - return id == null ? -1 : id.intValue(); - } - - /** - * 通过字段的声明方法返回字段的编码器; - * - * @param declaredMethod - * 声明并标注为数据契约字段的方法;注:不能是覆盖的非标注方法,也不能是实现方法; - * @return - */ - FieldEncoder getFieldEncoder(Method declaredMethod) { - Integer idx = fieldIndexMap.get(declaredMethod); - if (idx == null) { - return null; - } - return fieldEncoders[idx.intValue()]; - } - - @Override - public DataSpecification getSepcification() { - return specification; - } - - @Override - public Class getContractType() { - return contractType; - } - - @Override - public int encode(Object dataContract, BytesOutputBuffer buffer) { - int size = 0; - size += headEncoder.encode(dataContract, buffer); - if (dataContract != null) { - for (SliceEncoder sliceEncoder : fieldEncoders) { - size += sliceEncoder.encode(dataContract, buffer); - } - } - return size; - } - - @SuppressWarnings("unchecked") - @Override - public T decode(BytesInputStream bytesStream) { - BytesSlice headerSlice = bytesStream.getSlice(HeaderEncoder.HEAD_BYTES); - if (!headEncoder.verifyHeaders(headerSlice)) { - throw new IllegalArgumentException(String.format( - "The code and version resolved from bytes stream is not match this data contract encoder! --[expected=%s, %s][actual=%s, %s].", - headEncoder.getCode(), headEncoder.getVersion(), HeaderEncoder.resolveCode(headerSlice), - HeaderEncoder.resolveVersion(headerSlice))); - } - if (bytesStream.getSize() == HeaderEncoder.HEAD_BYTES) { - // 只有头部,没有值,表示空值; - return null; - } - return (T) DynamicDataContract.createContract(bytesStream, this); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractEncoderLookup.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractEncoderLookup.java deleted file mode 100644 index 37f77e32..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractEncoderLookup.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.binaryproto.DataContractEncoder; - -public interface DataContractEncoderLookup { - - /** - * 检索指定类型的编码器; - * - * @param contractType - * @return - */ - DataContractEncoder lookup(Class contractType); - - /** - * 检索指定 code 和 version 的编码器; - * - * @param contractType - * @return - */ - DataContractEncoder lookup(int code, long version); - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractGenericRefConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractGenericRefConverter.java deleted file mode 100644 index 9b926463..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractGenericRefConverter.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataContractEncoder; -import com.jd.blockchain.binaryproto.DataContractException; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; - -public class DataContractGenericRefConverter extends AbstractDynamicValueConverter { - - private final Object mutex = new Object(); - - private DataContractEncoderLookup encoderLookup; - - private Map, DataContractEncoder> encoderCache; - - public DataContractGenericRefConverter(Class baseType, DataContractEncoderLookup encoderLookup) { - super(baseType); - this.encoderLookup = encoderLookup; - this.encoderCache = new ConcurrentHashMap<>(); - } - - private DataContractEncoder lookupEncoder(Class dataObjectType) { - DataContractEncoder encoder = encoderCache.get(dataObjectType); - if (encoder != null) { - return encoder; - } - synchronized (mutex) { - encoder = encoderCache.get(dataObjectType); - if (encoder != null) { - return encoder; - } - Class[] intfs = dataObjectType.getInterfaces(); - Class contractType = null; - DataContract anno = null; - for (Class itf : intfs) { - anno = itf.getAnnotation(DataContract.class); - if (anno != null) { - if (contractType == null) { - contractType = itf; - } else { - throw new DataContractException(String.format( - "Data object implements more than one DataContract interface! --[DataObject=%s]", - dataObjectType.toString())); - } - } - } - if (contractType == null) { - throw new DataContractException( - String.format("Data object doesn't implement any DataContract interface! --[DataObject=%s]", - dataObjectType.toString())); - } - - encoder = encoderLookup.lookup(contractType); - if (encoder == null) { - throw new DataContractException(String.format( - "DataContract of the specified data object hasn't been registered! --[DataContract=%s][DataObject=%s]", - contractType.toString(), dataObjectType.toString())); - } - encoderCache.put(dataObjectType, encoder); - } - - return encoder; - } - - @Override - public int encodeDynamicValue(Object value, BytesOutputBuffer buffer) { - DataContractEncoder contractEncoder = lookupEncoder(value.getClass()); - - BytesOutputBuffer contractBuffer = new BytesOutputBuffer(); - int size = contractEncoder.encode(value, contractBuffer); - - size += writeSize(size, buffer); - - buffer.write(contractBuffer); - return size; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - int code = HeaderEncoder.resolveCode(dataSlice); - long version = HeaderEncoder.resolveVersion(dataSlice); - DataContractEncoder contractEncoder = encoderLookup.lookup(code, version); - if (contractEncoder == null) { - throw new DataContractException( - String.format("No data contract was registered with code[%s] and version[%s]!", code, version)); - } - return contractEncoder.decode(dataSlice.getInputStream()); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractHeader.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractHeader.java deleted file mode 100644 index 13eea96c..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractHeader.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; -//package com.jd.blockchain.binaryproto.impl2; -// -//public class DataContractHeader { -// -// private int code; -// -// private int version; -// -// private String name; -// -// private String description; -// -// public DataContractHeader(int contractCode, int contractVersion, String name, String description) { -// this.code = contractCode; -// this.version = contractVersion; -// this.name = name ; -// this.description = description; -// } -// -// public int getContractVersion() { -// return version; -// } -// -// public int getContractCode() { -// return code; -// } -// -//} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractSpecification.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractSpecification.java deleted file mode 100644 index d13e3242..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractSpecification.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.binaryproto.DataSpecification; -import com.jd.blockchain.binaryproto.FieldSpec; - -public class DataContractSpecification implements DataSpecification { - - private int code; - private long version; - private String name; - private String description; - - private List fieldList; - private List sliceList; - - public DataContractSpecification(int code, long version, String name, String description, BinarySliceSpec[] slices, FieldSpec[] fields) { - this.code = code; - this.version = version; - this.name = name; - this.description = description; - this.fieldList = Collections.unmodifiableList(Arrays.asList(fields)); - this.sliceList = Collections.unmodifiableList(Arrays.asList(slices)); - } - - @Override - public int getCode() { - return code; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public List getFields() { - return fieldList; - } - - @Override - public List getSlices() { - return sliceList; - } - - @Override - public String toHtml() { - throw new IllegalStateException("Not implemented!"); - } -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractValueConverter.java deleted file mode 100644 index 75b52095..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DataContractValueConverter.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.binaryproto.DataContractEncoder; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; - -public class DataContractValueConverter extends AbstractDynamicValueConverter { - - private DataContractEncoder contractEncoder; - - public DataContractValueConverter(DataContractEncoder contractEncoder) { - super(contractEncoder.getContractType()); - this.contractEncoder =contractEncoder; - } - - @Override - public int encodeDynamicValue(Object value, BytesOutputBuffer buffer) { - BytesOutputBuffer contractBuffer = new BytesOutputBuffer(); - int size = contractEncoder.encode(value, contractBuffer); - - size += writeSize(size, buffer); - - buffer.write(contractBuffer); - return size; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return contractEncoder.decode(dataSlice.getInputStream()); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicArrayFieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicArrayFieldEncoder.java deleted file mode 100644 index 0c76d4c3..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicArrayFieldEncoder.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Array; -import java.lang.reflect.Method; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.binaryproto.FieldSpec; -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesSlices; -import com.jd.blockchain.utils.io.DynamicBytesSliceArray; -import com.jd.blockchain.utils.io.NumberMask; - -public class DynamicArrayFieldEncoder extends AbstractFieldEncoder { - - private DynamicValueConverter valueConverter; - - public DynamicArrayFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader, - DynamicValueConverter valueConverter) { - super(sliceSpec, fieldSpec, reader); - this.valueConverter = valueConverter; - } - - @Override - public int encode(Object dataContract, BytesOutputBuffer buffer) { - int size = 0; - Object[] values = readArrayValue(dataContract); - size += encodeArrayDynamic(values, buffer); - - return size; - } - - /** - * 对数组类型的值进行非固定长度的编码; - * - * @param values - * @param buffer - * @return - */ - private int encodeArrayDynamic(Object[] values, BytesOutputBuffer buffer) { - int size = 0; - - int count = values == null ? 0 : values.length; - byte[] countBytes = NumberMask.NORMAL.generateMask(count); - buffer.write(countBytes); - size += countBytes.length; - - for (int i = 0; i < count; i++) { - size += valueConverter.encodeDynamicValue(values[i], buffer); - } - - return size; - } - - @Override - public BytesSlices decode(BytesInputStream bytesStream) { - return DynamicBytesSliceArray.resolve(bytesStream); - } - - @Override - public Object decodeField(BytesSlices fieldBytes) { - Object[] values = (Object[]) Array.newInstance(valueConverter.getValueType(), fieldBytes.getCount()); - BytesSlice itemSlice; - for (int i = 0; i < values.length; i++) { - itemSlice = fieldBytes.getDataSlice(i); - if (itemSlice.getSize() == 0) { - values[i] = valueConverter.getDefaultValue(); - } else { - values[i] = valueConverter.decodeValue(itemSlice); - } - } - return values; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicDataContract.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicDataContract.java deleted file mode 100644 index 58b94e25..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicDataContract.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesSlices; - -class DynamicDataContract implements InvocationHandler { - - public static Method METHOD_GET_CLASS; - - static { - try { - METHOD_GET_CLASS = Object.class.getMethod("getClass"); - } catch (NoSuchMethodException | SecurityException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private DataContractEncoderImpl contractEncoder; - - // 字段的数据片段列表,首个是 HeaderSlice,其次是按字段顺序排列的数据片段; - private BytesSlices[] dataSlices; - - private DynamicDataContract(BytesInputStream bytesStream, DataContractEncoderImpl contractEncoder) { - this.contractEncoder = contractEncoder; - - init(bytesStream); - } - - private void init(BytesInputStream bytesStream) { - // 解析出所有的数据片段; - dataSlices = new BytesSlices[contractEncoder.getFieldCount() + 1]; - - dataSlices[0] = contractEncoder.getHeaderEncoder().decode(bytesStream); - - for (int i = 1; i < dataSlices.length; i++) { - dataSlices[i] = contractEncoder.getFieldEncoder(i - 1).decode(bytesStream); - } - } - - @SuppressWarnings("unchecked") - public static T createContract(BytesInputStream bytesStream, DataContractEncoderImpl contractEncoder) { - return (T) Proxy.newProxyInstance(contractEncoder.getContractType().getClassLoader(), - contractEncoder.getContractTypeAsArray(), new DynamicDataContract(bytesStream, contractEncoder)); - } - - @SuppressWarnings("unchecked") - public static T createContract(byte[] contractBytes, DataContractEncoderImpl contractEncoder) { - return (T) Proxy.newProxyInstance(contractEncoder.getContractType().getClassLoader(), - contractEncoder.getContractTypeAsArray(), - new DynamicDataContract(new BytesInputStream(contractBytes, 0, contractBytes.length), contractEncoder)); - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - int fieldId = contractEncoder.getFieldId(method); - if (fieldId > -1) { - FieldEncoder encoder = contractEncoder.getFieldEncoder(fieldId); - return encoder.decodeField(dataSlices[fieldId + 1]); - } - if (METHOD_GET_CLASS == method) { - return contractEncoder.getContractType(); - } - // invoke method declared in type Object; - Object result; - try { - //for some special case, interface's method without annotation - result = method.invoke(this, args); - } catch (Exception e) { - if (method.getReturnType().isPrimitive()) { - result = 0; - } - else { - result = null; - } - e.printStackTrace(); - } - return result; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicFieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicFieldEncoder.java deleted file mode 100644 index b49a5238..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicFieldEncoder.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Method; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.binaryproto.FieldSpec; -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlices; -import com.jd.blockchain.utils.io.SingleBytesSliceArray; - -public class DynamicFieldEncoder extends AbstractFieldEncoder { - - private DynamicValueConverter valueConverter; - - public DynamicFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader, - DynamicValueConverter valueConverter) { - super(sliceSpec, fieldSpec, reader); - this.valueConverter = valueConverter; - } - - @Override - public int encode(Object dataContract, BytesOutputBuffer buffer) { - int size = 0; - Object value = readValue(dataContract); - size += valueConverter.encodeDynamicValue(value, buffer); - - return size; - } - - @Override - public BytesSlices decode(BytesInputStream bytesStream) { - return SingleBytesSliceArray.resolveDynamic(bytesStream); - } - - @Override - public Object decodeField(BytesSlices fieldBytes) { - // 非数组的字段,最多只有一个数据片段; - if (fieldBytes.getCount() == 0) { - return valueConverter.getDefaultValue(); - } - return valueConverter.decodeValue(fieldBytes.getDataSlice(0)); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicValueConverter.java deleted file mode 100644 index d4c225e5..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/DynamicValueConverter.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; - -public interface DynamicValueConverter extends ValueConverter { - - /** - * 写入一个动态长度的值;以一个头部的长度字节开始 - * @param value - * @param buffer - * @return - */ - int encodeDynamicValue(Object value, BytesOutputBuffer buffer); - - Object decodeValue(BytesSlice dataSlice); - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/EnumSpecificationInfo.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/EnumSpecificationInfo.java deleted file mode 100644 index 3a67a022..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/EnumSpecificationInfo.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.util.LinkedHashSet; -import java.util.Set; - -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.binaryproto.EnumSpecification; - -/** - * Created by zhangshuang3 on 2018/6/21. - */ -public class EnumSpecificationInfo implements EnumSpecification { - - private PrimitiveType valueType; - - private Class dataType; - - private int code; - private long version; - private String name; - private String description; - - private Set items = new LinkedHashSet<>(); - // private Map itemCodeMapping = new HashMap<>(); - // private Map codeItemMapping = new HashMap<>(); - - public EnumSpecificationInfo(PrimitiveType valueType, int code, long version, String name, String description, Class dataType) { - this.valueType = valueType; - this.code = code; - this.version = version; - this.name = name; - this.description = description; - this.dataType = dataType; - } - - @Override - public int getCode() { - return this.code; - } - - @Override - public long getVersion() { - return this.version; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getDescription() { - return this.description; - } - - @Override - public PrimitiveType getValueType() { - return this.valueType; - } - - @Override - public int[] getItemValues() { - int[] values = new int[items.size()]; - int i = 0; - for (EnumConstant it : items) { - values[i] = it.code; - i++; - } - return values; - } - - @Override - public String[] getItemNames() { - String[] names = new String[items.size()]; - int i = 0; - for (EnumConstant it : items) { - names[i] = it.name; - i++; - } - return names; - } - - public Class getDataType() { - return dataType; - } - - public Object[] getConstants() { - Object[] constants = new Object[items.size()]; - int i = 0; - for (EnumConstant it : items) { - constants[i] = it.constant; - i++; - } - return constants; - } - - public void addConstant(EnumConstant item) { - items.add(item); - } - - public static class EnumConstant { - - private int code; - - private String name; - - private Object constant; - - public int getCode() { - return code; - } - - public String getName() { - return name; - } - - public Object getConstant() { - return constant; - } - - public EnumConstant(int code, String name, Object constant) { - this.code = code; - this.name = name; - this.constant = constant; - } - } -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/EnumValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/EnumValueConverter.java deleted file mode 100644 index 34e3cdf2..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/EnumValueConverter.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.binaryproto.DataContractException; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.utils.io.BytesSlice; - -public class EnumValueConverter implements FixedValueConverter { - - private Class enumType; - - private PrimitiveType codeType; - - private int[] values; - - private Object[] constants; - - private FixedValueConverter valueConverter; - - public EnumValueConverter(Class enumType, PrimitiveType codeType, int[] values, Object[] constants, FixedValueConverter valueConverter) { - this.enumType = enumType; - this.values = values; - this.constants = constants; - this.valueConverter = valueConverter; - this.codeType = codeType; - - } - - @Override - public Class getValueType() { - return enumType; - } - - @Override - public Object getDefaultValue() { - return null; - } - - //lookup CODE value - private Object getEnumCode(Object value, int[] codes, Object[] constants) { - int codeIndex = 0; - - for (int i = 0; i < constants.length; i++) { - if (value.toString().equals(constants[i].toString())) { - codeIndex = i; - break; - } - } - switch (codeType) { - case INT8: - return (byte)codes[codeIndex]; - case INT16: - return (short)codes[codeIndex]; - case INT32: - return codes[codeIndex]; - default: - throw new DataContractException(String.format("Enum code error!")); - } - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - // 注:由于是通过反射调用的,已经在外围做了检查,此处不需要重复检查枚举值的范围; - //首先把枚举常量转换成对应的CODE - Object code = getEnumCode(value, values, constants); - return valueConverter.encodeValue(code, buffer, offset); - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - - Object v = valueConverter.decodeValue(dataSlice); - switch (codeType) { - case INT8: - for (int i = 0; i < values.length; i++) { - if ((byte)values[i] == (byte)v) { - return constants[i]; - } - } - throw new DataContractException(String.format( - "The decoding value is out of all enum constants! --[value=%s][enum type=%s]", v, enumType.toString())); - case INT16: - for (int i = 0; i < values.length; i++) { - if ((short)values[i] == (short)v) { - return constants[i]; - } - } - throw new DataContractException(String.format( - "The decoding value is out of all enum constants! --[value=%s][enum type=%s]", v, enumType.toString())); - case INT32: - for (int i = 0; i < values.length; i++) { - if ((int)values[i] == (int)v) { - return constants[i]; - } - } - throw new DataContractException(String.format( - "The decoding value is out of all enum constants! --[value=%s][enum type=%s]", v, enumType.toString())); - default: - throw new DataContractException(String.format("Enum code error!")); - - } - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FieldEncoder.java deleted file mode 100644 index 0541c5f0..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FieldEncoder.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Method; - -import com.jd.blockchain.binaryproto.FieldSpec; -import com.jd.blockchain.utils.io.BytesSlices; - -public interface FieldEncoder extends SliceEncoder { - - Method getReader(); - - FieldSpec getFieldSpecification(); - - Object decodeField(BytesSlices fieldBytes); - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FieldSpecInfo.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FieldSpecInfo.java deleted file mode 100644 index 5a9c7c6d..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FieldSpecInfo.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.binaryproto.DataSpecification; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.binaryproto.EnumSpecification; -import com.jd.blockchain.binaryproto.FieldSpec; - -public class FieldSpecInfo implements FieldSpec { - - private int order; - - private String name; - - private String description; - - private boolean repeatable; - - private PrimitiveType primitiveType; - - private EnumSpecification enumSpec; - - private DataSpecification contractTypeSpec; - - private int maxSize; - - private Class dataType; - - private boolean isGenericContract = false; - - public FieldSpecInfo(int order, String name, String decription, PrimitiveType primitiveType, boolean repeatable, - int maxSize, Class dataType) { - if (primitiveType == null) { - throw new IllegalArgumentException("primitiveType is null!"); - } - this.order = order; - this.name = name; - this.description = decription; - this.primitiveType = primitiveType; - this.repeatable = repeatable; - this.maxSize = maxSize; - this.dataType = dataType; - } - - public FieldSpecInfo(int order, String name, String decription, EnumSpecification enumSpec, boolean repeatable, - Class enumType) { - if (enumSpec == null) { - throw new IllegalArgumentException("enum specification is null!"); - } - this.order = order; - this.name = name; - this.description = decription; - this.enumSpec = enumSpec; - this.repeatable = repeatable; - this.maxSize = -1; - this.dataType = enumType; - } - - public FieldSpecInfo(int order, String name, String decription, DataSpecification contractTypeSpec, - boolean repeatable, Class contractType, boolean isGenericContract) { - if (contractTypeSpec == null) { - throw new IllegalArgumentException("contractType is null!"); - } - this.order = order; - this.name = name; - this.description = decription; - this.contractTypeSpec = contractTypeSpec; - this.repeatable = repeatable; - this.maxSize = -1; - this.dataType = contractType; - this.isGenericContract = isGenericContract; - } - - @Override - public PrimitiveType getPrimitiveType() { - return primitiveType; - } - - @Override - public EnumSpecification getRefEnum() { - return enumSpec; - } - - @Override - public DataSpecification getRefContract() { - return contractTypeSpec; - } - - @Override - public boolean isRepeatable() { - return repeatable; - } - - @Override - public int getMaxSize() { - return maxSize; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public boolean isGenericContract() { - return isGenericContract; - } - - public int getOrder() { - return order; - } - - public Class getDataType() { - return dataType; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedArrayFieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedArrayFieldEncoder.java deleted file mode 100644 index f61ac22e..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedArrayFieldEncoder.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Array; -import java.lang.reflect.Method; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.binaryproto.FieldSpec; -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesSlices; -import com.jd.blockchain.utils.io.FixedBytesSliceArray; -import com.jd.blockchain.utils.io.NumberMask; - -public class FixedArrayFieldEncoder extends AbstractFieldEncoder { - - private FixedValueConverter valueConverter; - - public FixedArrayFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader, FixedValueConverter valueConverter) { - super(sliceSpec, fieldSpec, reader); - this.valueConverter = valueConverter; - } - - @Override - public int encode(Object dataContract, BytesOutputBuffer buffer) { - int size = 0; - - Object[] values = readArrayValue(dataContract); - size += encodeArray(values, buffer); - - return size; - } - - /** - * 对数组类型的值进行固定长度的编码; - * - * @param values - * @param buffer - * @return - */ - private int encodeArray(Object[] values, BytesOutputBuffer buffer) { - int count = values == null ? 0 : values.length; - - int counterSize = NumberMask.NORMAL.getMaskLength(count); - int elementSize = sliceSpec.getLength(); - - int size = counterSize + elementSize * count; - byte[] outbuff = new byte[size]; - NumberMask.NORMAL.writeMask(count, outbuff, 0); - - for (int i = 0; i < count; i++) { - valueConverter.encodeValue(values[i], outbuff, counterSize + elementSize * i); - } - - buffer.write(outbuff); - return size; - } - - @Override - public BytesSlices decode(BytesInputStream bytesStream) { - return FixedBytesSliceArray.resolve(bytesStream, sliceSpec.getLength()); - } - - @Override - public Object decodeField(BytesSlices fieldBytes) { - Object[] values = (Object[]) Array.newInstance(valueConverter.getValueType(), fieldBytes.getCount()); - BytesSlice itemSlice; - for (int i = 0; i < values.length; i++) { - itemSlice = fieldBytes.getDataSlice(i); - if (itemSlice.getSize() == 0) { - values[i] = valueConverter.getDefaultValue(); - } else { - values[i] = valueConverter.decodeValue(itemSlice); - } - } - return values; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedFieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedFieldEncoder.java deleted file mode 100644 index ba9c09d1..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedFieldEncoder.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import java.lang.reflect.Method; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.binaryproto.FieldSpec; -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlices; -import com.jd.blockchain.utils.io.SingleBytesSliceArray; - -public class FixedFieldEncoder extends AbstractFieldEncoder { - - private FixedValueConverter valueConverter; - - public FixedFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader, FixedValueConverter valueConverter) { - super(sliceSpec, fieldSpec, reader); - this.valueConverter = valueConverter; - } - - @Override - public int encode(Object dataContract, BytesOutputBuffer buffer) { - int size = 0; - Object value = readValue(dataContract); - size += encodeValue(value, buffer); - - return size; - } - - /** - * 把固定长度的值序列化到指定的缓冲区; - * - * @param value - * @param buffer - * @return - */ - private int encodeValue(Object value, BytesOutputBuffer buffer) { - byte[] valueBytes = new byte[sliceSpec.getLength()]; - int size = valueConverter.encodeValue(value, valueBytes, 0); - buffer.write(valueBytes); - return size; - } - - @Override - public BytesSlices decode(BytesInputStream bytesStream) { - return SingleBytesSliceArray.create(bytesStream, sliceSpec.getLength()); - } - - @Override - public Object decodeField(BytesSlices fieldBytes) { - // 非数组的字段,最多只有一个数据片段; - if (fieldBytes.getCount() == 0) { - return valueConverter.getDefaultValue(); - } - return valueConverter.decodeValue(fieldBytes.getDataSlice(0)); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedValueConverter.java deleted file mode 100644 index 60e84f96..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/FixedValueConverter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; - -public interface FixedValueConverter extends ValueConverter { - - /** - * 将把固定长度的值序列化到指定的缓冲区; - *

- * - * 注:实现者应用确保写入的范围不要越界(超出 {@link #getSliceSpecification()} 属性指定的长度); - * - * @param value - * 要序列化的值; - * @param buffer - * 保存结果的缓冲区; - * @param offset - * 缓冲区的写入起始位置; - * @return 返回写入的长度; - */ - int encodeValue(Object value, byte[] buffer, int offset); - - Object decodeValue(BytesSlice dataSlice); - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/GenericFieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/GenericFieldEncoder.java deleted file mode 100644 index 05615305..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/GenericFieldEncoder.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; -//package com.jd.blockchain.binaryproto.impl2; -// -//import java.lang.reflect.Array; -//import java.lang.reflect.InvocationTargetException; -//import java.lang.reflect.Method; -// -//import com.jd.blockchain.binaryproto.BinarySliceSpec; -//import com.jd.blockchain.binaryproto.FieldSpec; -// -//import my.utils.io.BytesInputStream; -//import my.utils.io.BytesOutputBuffer; -//import my.utils.io.BytesSlice; -//import my.utils.io.BytesSlices; -//import my.utils.io.DynamicBytesSliceArray; -//import my.utils.io.FixedBytesSliceArray; -//import my.utils.io.NumberMask; -//import my.utils.io.SingleBytesSliceArray; -// -//public abstract class GenericFieldEncoder implements FieldEncoder { -// -// protected BinarySliceSpec sliceSpec; -// -// protected FieldSpec fieldSpec; -// -// protected Method reader; -// -// public GenericFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader) { -// this.sliceSpec = sliceSpec; -// this.fieldSpec = fieldSpec; -// this.reader = reader; -// } -// -// @Override -// public BinarySliceSpec getSliceSpecification() { -// return sliceSpec; -// } -// -// @Override -// public FieldSpec getFieldSpecification() { -// return fieldSpec; -// } -// -// @Override -// public Method getReader() { -// return reader; -// } -// -// @Override -// public int encode(Object dataContract, BytesOutputBuffer buffer) { -// int size = 0; -// if (sliceSpec.isRepeatable()) { -// Object[] values = readArrayValue(dataContract); -// if (sliceSpec.isDynamic()) { -// size += encodeArrayDynamic(values, buffer); -// } else { -// size += encodeArray(values, buffer); -// } -// } else { -// Object value = readValue(dataContract); -// if (sliceSpec.isDynamic()) { -// size += encodeDynamicValue(value, buffer); -// } else { -// size += encodeValue(value, buffer); -// } -// } -// -// return size; -// } -// -// /** -// * 把固定长度的值序列化到指定的缓冲区; -// * -// * @param value -// * @param buffer -// * @return -// */ -// private int encodeValue(Object value, BytesOutputBuffer buffer) { -// byte[] valueBytes = new byte[sliceSpec.getLength()]; -// return encodeValue(value, valueBytes, 0); -// } -// -// /** -// * 将把固定长度的值序列化到指定的缓冲区; -// *

-// * -// * 注:实现者应用确保写入的范围不要越界(超出 {@link #getSliceSpecification()} 属性指定的长度); -// * -// * @param value -// * 要序列化的值; -// * @param buffer -// * 保存结果的缓冲区; -// * @param offset -// * 缓冲区的写入起始位置; -// * @return 返回写入的长度; -// */ -// abstract int encodeValue(Object value, byte[] buffer, int offset); -// -// abstract int encodeDynamicValue(Object value, BytesOutputBuffer buffer); -// -// /** -// * 对数组类型的值进行固定长度的编码; -// * -// * @param values -// * @param buffer -// * @return -// */ -// private int encodeArray(Object[] values, BytesOutputBuffer buffer) { -// int count = values == null ? 0 : values.length; -// -// int counterSize = NumberMask.NORMAL.getMaskLength(count); -// int elementSize = sliceSpec.getLength(); -// -// int size = counterSize + elementSize * count; -// byte[] outbuff = new byte[size]; -// NumberMask.NORMAL.writeMask(count, outbuff, 0); -// -// for (int i = 0; i < count; i++) { -// encodeValue(values[i], outbuff, counterSize + elementSize * i); -// } -// -// buffer.write(outbuff); -// return size; -// } -// -// /** -// * 对数组类型的值进行非固定长度的编码; -// * -// * @param values -// * @param buffer -// * @return -// */ -// private int encodeArrayDynamic(Object[] values, BytesOutputBuffer buffer) { -// int size = 0; -// -// int count = values == null ? 0 : values.length; -// byte[] countBytes = NumberMask.NORMAL.generateMask(count); -// buffer.write(countBytes); -// size += countBytes.length; -// -// for (int i = 0; i < count; i++) { -// size += encodeDynamicValue(values[i], buffer); -// } -// -// return size; -// } -// -// private Object readValue(Object dataContract) { -// try { -// return reader.invoke(dataContract); -// } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { -// throw new IllegalStateException(e.getMessage(), e); -// } -// } -// -// private Object[] readArrayValue(Object dataContract) { -// return (Object[]) readValue(dataContract); -// } -// -// @Override -// public BytesSlices decode(BytesInputStream bytesStream) { -// if (sliceSpec.isRepeatable()) { -// if (sliceSpec.isDynamic()) { -// return DynamicBytesSliceArray.resolve(bytesStream); -// }else { -// return FixedBytesSliceArray.resolve(bytesStream, sliceSpec.getLength()); -// } -// }else { -// if (sliceSpec.isDynamic()) { -// return SingleBytesSliceArray.resolveDynamic(bytesStream); -// }else { -// return SingleBytesSliceArray.create(bytesStream, sliceSpec.getLength()); -// } -// } -// } -// -// @Override -// public Object decodeField(BytesSlices fieldBytes) { -// if (sliceSpec.isRepeatable()) { -// Object[] values = (Object[]) Array.newInstance(getFieldType(), fieldBytes.getCount()); -// for (int i = 0; i < values.length; i++) { -// values[i] = decodeValue(fieldBytes.getDataSlice(i)); -// } -// return values; -// } -// //非数组的字段,最多只有一个数据片段; -// if (fieldBytes.getCount() == 0) { -// return getNullValue(); -// } -// return decodeValue(fieldBytes.getDataSlice(0)); -// } -// -// -// abstract Class getFieldType(); -// -// abstract Object getNullValue(); -// -// abstract Object decodeValue(BytesSlice dataSlice); -// -//} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/HeaderEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/HeaderEncoder.java deleted file mode 100644 index 4c41c353..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/HeaderEncoder.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesSliceArrayWrapper; -import com.jd.blockchain.utils.io.BytesSlices; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * 分段编码器; - * - * @author huanghaiquan - * - */ -public class HeaderEncoder implements SliceEncoder { - - public static final int HEAD_BYTES = 12; - - private BinarySliceSpec sliceSpec; - - private int code; - - private long version; - - private String name; - - private String description; - - public int getCode() { - return code; - } - - public long getVersion() { - return version; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public HeaderEncoder(BinarySliceSpec sliceSpec, int code, long version, String name, String description) { - this.sliceSpec = sliceSpec; - this.code = code; - this.version = version; - this.name = name; - this.description = description; - } - - /** - * 校验指定的数据契约字节列表的头部是否一致; - * - * @param dataContractBytes - * @return - */ - boolean verifyHeaders(BytesSlice dataContractBytes) { - int code = resolveCode(dataContractBytes); - if (code != this.code) { - return false; - } - long version = resolveVersion(dataContractBytes); - return version == this.version; - } - - public static int resolveCode(BytesSlice dataContractBytes) { - return dataContractBytes.getInt(); - } - - public static long resolveVersion(BytesSlice dataContractBytes) { - return dataContractBytes.getLong(4); - } - - @Override - public BinarySliceSpec getSliceSpecification() { - return sliceSpec; - } - - @Override - public int encode(Object dataContract, BytesOutputBuffer buffer) { - byte[] headBytes = new byte[HEAD_BYTES]; - BytesUtils.toBytes(code, headBytes); - BytesUtils.toBytes(version, headBytes, 4); - buffer.write(headBytes); - return HEAD_BYTES; - } - - @Override - public BytesSlices decode(BytesInputStream bytesStream) { - return BytesSliceArrayWrapper.wrap(bytesStream.readSlice(HEAD_BYTES)); - } - - // @Override - // public BytesSlices decode(byte[] dataContractBytes, int offset) { - // return SingleBytesSliceArray.create(dataContractBytes, offset, HEAD_BYTES); - // } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16CharConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16CharConverter.java deleted file mode 100644 index 386ca5b4..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16CharConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int16CharConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return char.class; - } - - @Override - public Object getDefaultValue() { - return '\u0000'; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((char)value, buffer, offset); - return 2; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getChar(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16CharWrapperConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16CharWrapperConverter.java deleted file mode 100644 index b4c35fe4..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16CharWrapperConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int16CharWrapperConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return Character.class; - } - - @Override - public Object getDefaultValue() { - return null; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((char)value, buffer, offset); - return 2; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getChar(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16ShortConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16ShortConverter.java deleted file mode 100644 index 1929239a..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16ShortConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int16ShortConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return short.class; - } - - @Override - public Object getDefaultValue() { - return 0; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((short)value, buffer, offset); - return 2; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getShort(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16ShortWrapperConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16ShortWrapperConverter.java deleted file mode 100644 index 89fc7ac0..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int16ShortWrapperConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int16ShortWrapperConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return Short.class; - } - - @Override - public Object getDefaultValue() { - return null; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((short)value, buffer, offset); - return 2; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getShort(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int32IntConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int32IntConverter.java deleted file mode 100644 index 9c3e6fdf..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int32IntConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int32IntConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return int.class; - } - - @Override - public Object getDefaultValue() { - return 0; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((int)value, buffer, offset); - return 4; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getInt(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int32IntWrapperConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int32IntWrapperConverter.java deleted file mode 100644 index 707cce08..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int32IntWrapperConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int32IntWrapperConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return Integer.class; - } - - @Override - public Object getDefaultValue() { - return null; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((int)value, buffer, offset); - return 4; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getInt(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int64LongConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int64LongConverter.java deleted file mode 100644 index 481a9d97..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int64LongConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int64LongConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return Long.class; - } - - @Override - public Object getDefaultValue() { - return 0; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((long)value, buffer, offset); - return 8; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getLong(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int64LongWrapperConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int64LongWrapperConverter.java deleted file mode 100644 index 80df35fb..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int64LongWrapperConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Int64LongWrapperConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return Long.class; - } - - @Override - public Object getDefaultValue() { - return null; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - BytesUtils.toBytes((long)value, buffer, offset); - return 8; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getLong(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int8ByteConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int8ByteConverter.java deleted file mode 100644 index fc9ce465..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int8ByteConverter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; - -public class Int8ByteConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return byte.class; - } - - @Override - public Object getDefaultValue() { - return 0; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - buffer[offset] = (byte)value; - return 1; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getByte(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int8ByteWrapperConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int8ByteWrapperConverter.java deleted file mode 100644 index ed088a91..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/Int8ByteWrapperConverter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesSlice; - -public class Int8ByteWrapperConverter implements FixedValueConverter{ - - @Override - public Class getValueType() { - return Byte.class; - } - - @Override - public Object getDefaultValue() { - return null; - } - - @Override - public int encodeValue(Object value, byte[] buffer, int offset) { - buffer[offset] = (byte)value; - return 1; - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getByte(); - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/RepeatableFieldEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/RepeatableFieldEncoder.java deleted file mode 100644 index 44a38859..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/RepeatableFieldEncoder.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; -//package com.jd.blockchain.binaryproto.impl2; -// -//import java.lang.reflect.Method; -// -//import com.jd.blockchain.binaryproto.BinarySliceSpec; -//import com.jd.blockchain.binaryproto.FieldSpec; -// -//import my.utils.io.BytesOutputBuffer; -// -//public class RepeatableFieldEncoder extends AbstractFieldEncoder { -// -// -// public RepeatableFieldEncoder(BinarySliceSpec sliceSpec, FieldSpec fieldSpec, Method reader) { -// super(sliceSpec, fieldSpec, reader); -// } -// -// @Override -// public Object decodeValue(byte[] dataContractBytes, int offset) { -// // TODO Auto-generated method stub -// return null; -// } -// -// @Override -// public int encode(Object dataContract, BytesOutputBuffer buffer) { -// // TODO Auto-generated method stub -// return 0; -// } -// -// -// -//} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/SliceEncoder.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/SliceEncoder.java deleted file mode 100644 index 1c465a71..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/SliceEncoder.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.binaryproto.BinarySliceSpec; -import com.jd.blockchain.utils.io.BytesInputStream; -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlices; - -/** - * 分段编码器; - * - * @author huanghaiquan - * - */ -public interface SliceEncoder { - - BinarySliceSpec getSliceSpecification(); - - /** - * 将此编码器表示的数据契约分段输出的指定的缓冲区; - * - * @param dataContract - * 数据契约的实例;当前编码器从中读取分段的值; - * @param buffer - * 要写入的缓冲区;调用者需要确保 - * @param offset - * 缓冲区的写入起始位置; - * @return 写入的字节数; - */ - int encode(Object dataContract, BytesOutputBuffer buffer); - -// /** -// * 从指定的数据契约的数据中读取当前编码器表示的分段的数据; -// * -// * @param dataContractBytes -// * @return -// */ -// BytesSlices decode(BytesSlice dataContractBytes, int offset); - - /** - * 从指定的数据契约的数据中读取当前编码器表示的分段的数据; - * - * @param dataContractBytes - * @return - */ - BytesSlices decode(BytesInputStream bytesStream); - -// /** -// * 从指定的数据契约的数据中读取当前编码器表示的分段的数据; -// * -// * @param dataContractBytes -// * @return -// */ -// BytesSlices decode(byte[] dataContractBytes, int offset); - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/StringValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/StringValueConverter.java deleted file mode 100644 index 725e3960..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/StringValueConverter.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -import com.jd.blockchain.utils.io.BytesOutputBuffer; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public class StringValueConverter extends AbstractDynamicValueConverter { - - public StringValueConverter() { - super(String.class); - } - - @Override - public Object decodeValue(BytesSlice dataSlice) { - return dataSlice.getString(); - } - - @Override - public int encodeDynamicValue(Object value, BytesOutputBuffer buffer) { - byte[] bytes = value == null ? BytesUtils.EMPTY_BYTES : BytesUtils.toBytes((String) value); - int size = bytes.length; - size += writeSize(bytes.length, buffer); - buffer.write(bytes); - return size; - } - -} diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/ValueConverter.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/ValueConverter.java deleted file mode 100644 index 6c4c8e01..00000000 --- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/impl/ValueConverter.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.binaryproto.impl; - -public interface ValueConverter { - - Class getValueType(); - - /** - * 返回类型的默认初始值; - * - * @return - */ - Object getDefaultValue(); - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/BinaryEncodingTest.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/BinaryEncodingTest.java deleted file mode 100644 index b1395038..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/BinaryEncodingTest.java +++ /dev/null @@ -1,547 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractException; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesEncoding; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.NumberMask; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class BinaryEncodingTest { - - /** - * 此测试用例是对序列化过程的验证,包括:头部、基本类型的值(boolean、整数、字符串、字节数组、BytesSerializable)、字段顺序的正确性; - */ - @Test - public void testEncoding_Header_OrderedPrimitiveFields() { - DataContractRegistry.register(PrimitiveDatas.class); - PrimitiveDatasImpl pd = new PrimitiveDatasImpl(); - NetworkAddress networkAddress = new NetworkAddress("192.168.1.1", 9001, false); - pd.setId(123); - pd.setEnable(true); - pd.setBoy((byte) 10); - pd.setAge((short) 100); - pd.setName("John"); - pd.setImage("Image of John".getBytes()); - pd.setFlag('x'); - pd.setValue(93239232); - pd.setConfig(Bytes.fromString("Configuration of something.")); - pd.setNetworkAddress(networkAddress); - - byte[] bytes = BinaryProtocol.encode(pd, PrimitiveDatas.class); - int offset = 0; - int code = BytesUtils.toInt(bytes, offset); - offset += 12; - assertEquals(0x05, code); - offset = assertFieldEncoding(pd, bytes, offset); - - // 到了结尾; - assertEquals(bytes.length, offset); - } - - private int assertFieldEncoding(PrimitiveDatas pd, byte[] bytes, int offset) { - - // Code 和 Version 的占据了 12 字节; - int id = BytesUtils.toInt(bytes, offset); - offset += 4; - assertEquals(pd.getId(), id); - - byte enable = bytes[offset]; - byte expEnable = pd.isEnable() ? (byte) 1 : (byte) 0; - offset += 1; - assertEquals(expEnable, enable); - - byte boy = bytes[offset]; - offset += 1; - assertEquals(pd.isBoy(), boy); - - short age = BytesUtils.toShort(bytes, offset); - offset += 2; - assertEquals(pd.getAge(), age); - - byte[] nameBytes = BytesEncoding.readInNormal(bytes, offset); - String name = BytesUtils.toString(nameBytes); - int maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - offset += nameBytes.length + maskLen; - assertEquals(pd.getName().length(), name.length()); - - long value = BytesUtils.toLong(bytes, offset); - offset += 8; - assertEquals(pd.getValue(), value); - - byte[] image = BytesEncoding.readInNormal(bytes, offset); - maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - offset += image.length + maskLen; - assertTrue(BytesUtils.equals(pd.getImage(), image)); - - char flag = BytesUtils.toChar(bytes, offset); - offset += 2; - assertEquals(pd.getFlag(), flag); - - byte[] config = BytesEncoding.readInNormal(bytes, offset); - maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - offset += config.length + maskLen; - assertTrue(BytesUtils.equals(pd.getConfig().toBytes(), config)); - - byte[] setting = BytesEncoding.readInNormal(bytes, offset); - assertEquals(0, setting.length); - maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - offset += setting.length + maskLen; - - byte[] networkaddr = BytesEncoding.readInNormal(bytes, offset); - maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - offset += networkaddr.length + maskLen; - assertTrue(BytesUtils.equals(pd.getNetworkAddr().toBytes(), networkaddr)); - - return offset; - } - - @Test - public void testEncoding_Null() { - DataContractRegistry.register(PrimitiveDatas.class); - - byte[] bytes = BinaryProtocol.encode(null, PrimitiveDatas.class); - int offset = 0; - int code = BytesUtils.toInt(bytes, offset); - offset += 12;// 暂不校验 version; - assertEquals(0x05, code); - - // 到了结尾; - assertEquals(bytes.length, offset); - } - - /** - * 此测试用例是对序列化过程的验证,包括:头部、基本类型的值(boolean、整数、字符串、字节数组、BytesSerializable)、字段顺序的正确性; - */ - @Test - public void testDecoding_Header_OrderedPrimitiveFields() { - DataContractRegistry.register(PrimitiveDatas.class); - PrimitiveDatasImpl pd = new PrimitiveDatasImpl(); - NetworkAddress networkAddress = new NetworkAddress("192.168.1.1", 9001, false); - pd.setId(123); - pd.setEnable(true); - pd.setBoy((byte) 10); - pd.setAge((short) 100); - pd.setName("John"); - pd.setImage("Image of John".getBytes()); - pd.setFlag('x'); - pd.setValue(93239232); - pd.setConfig(Bytes.fromString("Configuration of something.")); - pd.setNetworkAddress(networkAddress); - - byte[] bytes = BinaryProtocol.encode(pd, PrimitiveDatas.class); - PrimitiveDatas decodeData = BinaryProtocol.decode(bytes); - assertEquals(pd.getId(), decodeData.getId()); - assertEquals(pd.isEnable(), decodeData.isEnable()); - assertEquals(pd.isBoy(), decodeData.isBoy()); - assertEquals(pd.getAge(), decodeData.getAge()); - assertEquals(pd.getName(), decodeData.getName()); - assertTrue(BytesUtils.equals(pd.getImage(), decodeData.getImage())); - assertEquals(pd.getFlag(), decodeData.getFlag()); - assertEquals(pd.getValue(), decodeData.getValue()); - assertEquals(pd.getConfig(), decodeData.getConfig()); - assertNull(decodeData.getSetting()); - assertEquals(pd.getNetworkAddr().getHost(), decodeData.getNetworkAddr().getHost()); - assertEquals(pd.getNetworkAddr().getPort(), decodeData.getNetworkAddr().getPort()); - } - - /** - * 此测试用例是对序列化过程的验证,包括:头部、枚举值、字段顺序的正确性; - */ - @Test - public void testEncoding_Header_OrderedEnumFields() { - DataContractRegistry.register(EnumDatas.class); - EnumDatasImpl enumDatas = new EnumDatasImpl(); - enumDatas.setLevel(EnumLevel.V1); - - byte[] bytes = BinaryProtocol.encode(enumDatas, EnumDatas.class); - int offset = 0; - int code = BytesUtils.toInt(bytes, offset); - offset += 12; - assertEquals(0x07, code); - - byte enumCode = bytes[offset]; - offset += 1; - assertEquals(enumDatas.getLevel().CODE, enumCode); - - // 到了结尾; - assertEquals(bytes.length, offset); - } - - /** - * 此测试用例是对反序列化过程的验证,包括:头部、枚举值、字段顺序的正确性; - */ - @Test - public void testDecoding_Header_OrderedEnumFields() { - DataContractRegistry.register(EnumDatas.class); - EnumDatasImpl enumDatas = new EnumDatasImpl(); - enumDatas.setLevel(EnumLevel.V1); - - byte[] bytes = BinaryProtocol.encode(enumDatas, EnumDatas.class); - EnumDatas decodeData = BinaryProtocol.decode(bytes); - assertEquals(enumDatas.getLevel(), decodeData.getLevel()); - } - - /** - * 此测试用例是对序列化过程的验证,包括:头部、引用数据契约字段值、字段顺序的正确性; - */ - @Test - public void testEncoding_Header_SingleRefContractField() { - DataContractRegistry.register(RefContractDatas.class); - - RefContractDatasImpl refContractDatas = new RefContractDatasImpl(); - PrimitiveDatasImpl primitiveDatas = new PrimitiveDatasImpl(); - NetworkAddress networkAddress = new NetworkAddress("192.168.1.1", 9001, false); - - primitiveDatas.setId(123); - primitiveDatas.setEnable(true); - primitiveDatas.setBoy((byte) 10); - primitiveDatas.setAge((short) 100); - primitiveDatas.setName("John"); - primitiveDatas.setImage("Image of John".getBytes()); - primitiveDatas.setFlag('x'); - primitiveDatas.setValue(93239232); - primitiveDatas.setConfig(Bytes.fromString("Configuration of something.")); - primitiveDatas.setNetworkAddress(networkAddress); - - refContractDatas.setPrimitiveDatas(primitiveDatas); - - byte[] bytes = BinaryProtocol.encode(refContractDatas, RefContractDatas.class); - int offset = 0; - int code = BytesUtils.toInt(bytes, offset); - offset += 12; - assertEquals(0x08, code); - - // 引用合约字段的字节; - byte[] primitiveDataFieldBytes = BytesEncoding.readInNormal(bytes, offset); - int maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - - // 获得引用合约码与版本 - int fieldOffset = 0; - int refCode = BytesUtils.toInt(primitiveDataFieldBytes, fieldOffset); - fieldOffset += 12; - assertEquals(0x05, refCode); - - fieldOffset = assertFieldEncoding(refContractDatas.getPrimitive(), primitiveDataFieldBytes, fieldOffset); - assertEquals(primitiveDataFieldBytes.length, fieldOffset); - offset += primitiveDataFieldBytes.length + maskLen; - // 到了结尾; - assertEquals(bytes.length, offset); - - } - - /** - * 此测试用例是对序列化过程的验证,包括:头部、引用数据契约字段值、字段顺序的正确性; - */ - @Test - public void testEncoding_Header_NullRefContractFields() { - DataContractRegistry.register(RefContractDatas.class); - - RefContractDatasImpl refContractDatas = new RefContractDatasImpl(); - - byte[] bytes = BinaryProtocol.encode(refContractDatas, RefContractDatas.class); - int offset = 0; - int code = BytesUtils.toInt(bytes, offset); - offset += 12; - assertEquals(0x08, code); - - // 引用合约字段的字节; - byte[] primitiveDataFieldBytes = BytesEncoding.readInNormal(bytes, offset); - int maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - assertEquals(12, primitiveDataFieldBytes.length); - - // 获得引用合约码与版本 - int fieldOffset = 0; - int refCode = BytesUtils.toInt(primitiveDataFieldBytes, fieldOffset); - fieldOffset += 12; - assertEquals(0x05, refCode); - - assertEquals(primitiveDataFieldBytes.length, fieldOffset); - offset += primitiveDataFieldBytes.length + maskLen; - // 到了结尾; - assertEquals(bytes.length, offset); - } - - /** - * 此测试用例是对反序列化过程的验证,包括:头部、引用数据契约字段值、字段顺序的正确性; - */ - @Test - public void testDecoding_Header_OrderedRefContractFields() { - DataContractRegistry.register(RefContractDatas.class); - - RefContractDatasImpl refContractDatas = new RefContractDatasImpl(); - PrimitiveDatasImpl primitiveDatas = new PrimitiveDatasImpl(); - NetworkAddress networkAddress = new NetworkAddress("192.168.1.1", 9001, false); - - primitiveDatas.setId(123); - primitiveDatas.setEnable(true); - primitiveDatas.setBoy((byte) 10); - primitiveDatas.setAge((short) 100); - primitiveDatas.setName("John"); - primitiveDatas.setImage("Image of John".getBytes()); - primitiveDatas.setFlag('x'); - primitiveDatas.setValue(93239232); - primitiveDatas.setConfig(Bytes.fromString("Configuration of something.")); - primitiveDatas.setNetworkAddress(networkAddress); - - refContractDatas.setPrimitiveDatas(primitiveDatas); - - byte[] bytes = BinaryProtocol.encode(refContractDatas, RefContractDatas.class); - RefContractDatas decodeData = BinaryProtocol.decode(bytes); - - assertEquals(refContractDatas.getPrimitive().getId(), decodeData.getPrimitive().getId()); - assertEquals(refContractDatas.getPrimitive().isEnable(), decodeData.getPrimitive().isEnable()); - assertEquals(refContractDatas.getPrimitive().isBoy(), decodeData.getPrimitive().isBoy()); - assertEquals(refContractDatas.getPrimitive().getAge(), decodeData.getPrimitive().getAge()); - assertEquals(refContractDatas.getPrimitive().getName(), decodeData.getPrimitive().getName()); - assertTrue(BytesUtils.equals(refContractDatas.getPrimitive().getImage(), decodeData.getPrimitive().getImage())); - assertEquals(refContractDatas.getPrimitive().getFlag(), decodeData.getPrimitive().getFlag()); - assertEquals(refContractDatas.getPrimitive().getValue(), decodeData.getPrimitive().getValue()); - assertEquals(refContractDatas.getPrimitive().getConfig(), decodeData.getPrimitive().getConfig()); - assertEquals(refContractDatas.getPrimitive().getNetworkAddr().getHost(), decodeData.getPrimitive().getNetworkAddr().getHost()); - assertEquals(refContractDatas.getPrimitive().getNetworkAddr().getPort(), decodeData.getPrimitive().getNetworkAddr().getPort()); - } - - /** - * 此测试用例是对序列化过程的验证,包括:头部、Generic引用数据契约字段值、字段顺序的正确性; - */ - @Test - public void testEncoding_Header_GenericRefContractArrayFields() { - - DataContractRegistry.register(GenericRefContractDatas.class); - DataContractRegistry.register(Operation.class); - DataContractRegistry.register(SubOperation.class); - - GenericRefContractDatasImpl genericRefContractDatas = new GenericRefContractDatasImpl(); - SubOperationImpl subOperation = new SubOperationImpl(); - subOperation.setUserName("Jerry"); - - Operation[] operations = new Operation[1]; - operations[0] = subOperation; - genericRefContractDatas.setOperations(operations); - - byte[] bytes = BinaryProtocol.encode(genericRefContractDatas, GenericRefContractDatas.class); - int offset = 0; - int code = BytesUtils.toInt(bytes, offset); - offset += 12; - assertEquals(0xb, code); - - offset = assertGenericRefContractArrayFields(bytes, offset, operations); - - // 到了结尾; - assertEquals(bytes.length, offset); - } - - private int assertGenericRefContractArrayFields(byte[] bytes, int offset, Operation[] expectedOperations) { - // count of operations; - int opCount = NumberMask.NORMAL.resolveMaskedNumber(bytes, offset); - byte opCountHeadBytes = bytes[offset]; - int maskLen = NumberMask.NORMAL.resolveMaskLength(opCountHeadBytes); - offset += maskLen; - assertEquals(expectedOperations.length, opCount); - - // Field: operations; - for (int i = 0; i < opCount; i++) { - byte[] opertionItemBytes = BytesEncoding.readInNormal(bytes, offset); - - int itemMaskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - offset += opertionItemBytes.length + itemMaskLen; - - // verify subOperation; - int itemOffset = 0; - int itemCode = BytesUtils.toInt(opertionItemBytes, itemOffset); - itemOffset += 12; - assertEquals(0xa, itemCode); - - byte[] userNameBytes = BytesEncoding.readInNormal(opertionItemBytes, itemOffset); - int nameMaskLen = NumberMask.NORMAL.resolveMaskLength(opertionItemBytes[itemOffset]); - itemOffset += userNameBytes.length + nameMaskLen; - String userName = BytesUtils.toString(userNameBytes); - assertEquals(((SubOperation) expectedOperations[i]).getUserName(), userName); - - assertEquals(opertionItemBytes.length, itemOffset); - } - - return offset; - } - - /** - * 此测试用例是对反序列化过程的验证,包括:头部、Generic引用数据契约字段值、字段顺序的正确性; - */ - @Test - public void testDecoding_Header_OrderedGenericRefContractFields() { - DataContractRegistry.register(GenericRefContractDatas.class); - DataContractRegistry.register(Operation.class); - DataContractRegistry.register(SubOperation.class); - - GenericRefContractDatasImpl genericRefContractDatas = new GenericRefContractDatasImpl(); - SubOperationImpl subOperation = new SubOperationImpl(); - subOperation.setUserName("Jerry"); - - Operation[] operations = new Operation[1]; - operations[0] = subOperation; - genericRefContractDatas.setOperations(operations); - - byte[] bytes = BinaryProtocol.encode(genericRefContractDatas, GenericRefContractDatas.class); - - GenericRefContractDatas decodeData = BinaryProtocol.decode(bytes); - - assertEquals("Jerry", ((SubOperation) (decodeData.getOperations()[0])).getUserName()); - } - - /** - * 此测试用例是对序列化过程的验证,包括:头部、Primitive, Enum, 引用数据契约, Generic引用数据契约字段值、字段顺序的正确性; - */ - @Test - public void testEncoding_Header_OrderedCompositeFields() { - DataContractRegistry.register(SubOperation.class); - DataContractRegistry.register(CompositeDatas.class); - - CompositeDatasImpl compositeDatas = new CompositeDatasImpl(); - PrimitiveDatasImpl primitiveDatas = new PrimitiveDatasImpl(); - SubOperationImpl subOperation = new SubOperationImpl(); - NetworkAddress networkAddress = new NetworkAddress("192.168.1.1", 9001, false); - - compositeDatas.setEnable(false); - compositeDatas.setLevel(EnumLevel.V1); - - primitiveDatas.setId(123); - primitiveDatas.setEnable(true); - primitiveDatas.setBoy((byte) 10); - primitiveDatas.setAge((short) 100); - primitiveDatas.setName("John"); - primitiveDatas.setImage("Image of John".getBytes()); - primitiveDatas.setFlag('x'); - primitiveDatas.setValue(93239232); - primitiveDatas.setConfig(Bytes.fromString("Configuration of something.")); - primitiveDatas.setNetworkAddress(networkAddress); - - compositeDatas.setPrimitiveDatas(primitiveDatas); - - subOperation.setUserName("Jerry"); - Operation[] operations = new Operation[1]; - operations[0] = subOperation; - compositeDatas.setOperations(operations); - - byte[] bytes = BinaryProtocol.encode(compositeDatas, CompositeDatas.class); - - int offset = 0; - int code = BytesUtils.toInt(bytes, offset); - offset += 12; - assertEquals(0xc, code); - - // primitive type - assertEquals(compositeDatas.isEnable() ? (byte) 1 : (byte) 0, bytes[offset]); - offset += 1; - - byte enumCode = bytes[offset]; - offset += 1; - assertEquals(compositeDatas.getLevel().CODE, enumCode); - - // ---------------- - // 引用合约字段的字节; - byte[] primitiveDataFieldBytes = BytesEncoding.readInNormal(bytes, offset); - int maskLen = NumberMask.NORMAL.resolveMaskLength(bytes[offset]); - - // 获得引用合约码与版本 - int fieldOffset = 0; - int primitiveDataCode = BytesUtils.toInt(primitiveDataFieldBytes, fieldOffset); - fieldOffset += 12; - assertEquals(0x05, primitiveDataCode); - - fieldOffset = assertFieldEncoding(compositeDatas.getPrimitive(), primitiveDataFieldBytes, fieldOffset); - assertEquals(primitiveDataFieldBytes.length, fieldOffset); - offset += primitiveDataFieldBytes.length + maskLen; - - // field: operation; - offset = assertGenericRefContractArrayFields(bytes, offset, operations); - - // primitive - assertEquals(compositeDatas.getAge(), BytesUtils.toShort(bytes, offset)); - offset += 2; - - // 到了结尾; - assertEquals(bytes.length, offset); - } - - /** - * 此测试用例是对反序列化过程的验证,包括:头部、Primitive, Enum, 引用数据契约, Generic引用数据契约字段值、字段顺序的正确性; - */ - @Test - public void testDecoding_Header_OrderedCompositeFields() { - DataContractRegistry.register(SubOperation.class); - DataContractRegistry.register(CompositeDatas.class); - - CompositeDatasImpl compositeDatas = new CompositeDatasImpl(); - PrimitiveDatasImpl primitiveDatas = new PrimitiveDatasImpl(); - SubOperationImpl subOperation = new SubOperationImpl(); - NetworkAddress networkAddress = new NetworkAddress("192.168.1.1", 9001, false); - - compositeDatas.setEnable(false); - compositeDatas.setLevel(EnumLevel.V1); - compositeDatas.setAge((short) 100); - - primitiveDatas.setId(123); - primitiveDatas.setEnable(true); - primitiveDatas.setBoy((byte) 10); - primitiveDatas.setAge((short) 100); - primitiveDatas.setName("John"); - primitiveDatas.setImage("Image of John".getBytes()); - primitiveDatas.setFlag('x'); - primitiveDatas.setValue(93239232); - primitiveDatas.setConfig(Bytes.fromString("Configuration of something.")); - primitiveDatas.setNetworkAddress(networkAddress); - - compositeDatas.setPrimitiveDatas(primitiveDatas); - - subOperation.setUserName("Jerry"); - Operation[] operations = new Operation[1]; - operations[0] = subOperation; - compositeDatas.setOperations(operations); - - byte[] bytes = BinaryProtocol.encode(compositeDatas, CompositeDatas.class); - CompositeDatas decodeData = BinaryProtocol.decode(bytes); - - assertEquals(compositeDatas.isEnable(), decodeData.isEnable()); - assertEquals(compositeDatas.getAge(), decodeData.getAge()); - assertEquals(compositeDatas.getPrimitive().getId(), decodeData.getPrimitive().getId()); - assertEquals(compositeDatas.getPrimitive().isEnable(), decodeData.getPrimitive().isEnable()); - assertEquals(compositeDatas.getPrimitive().isBoy(), decodeData.getPrimitive().isBoy()); - assertEquals(compositeDatas.getPrimitive().getAge(), decodeData.getPrimitive().getAge()); - assertEquals(compositeDatas.getPrimitive().getName(), decodeData.getPrimitive().getName()); - assertTrue(BytesUtils.equals(compositeDatas.getPrimitive().getImage(), decodeData.getPrimitive().getImage())); - assertEquals(compositeDatas.getPrimitive().getFlag(), decodeData.getPrimitive().getFlag()); - assertEquals(compositeDatas.getPrimitive().getValue(), decodeData.getPrimitive().getValue()); - assertEquals(compositeDatas.getPrimitive().getConfig(), decodeData.getPrimitive().getConfig()); - assertEquals(compositeDatas.getPrimitive().getNetworkAddr().getHost(), decodeData.getPrimitive().getNetworkAddr().getHost()); - assertEquals(compositeDatas.getPrimitive().getNetworkAddr().getPort(), decodeData.getPrimitive().getNetworkAddr().getPort()); - assertEquals("Jerry", ((SubOperation) (decodeData.getOperations()[0])).getUserName()); - assertEquals(compositeDatas.getLevel(), decodeData.getLevel()); - - } - - /** - * 验证解析一个定义有顺序重复的两个字段的类型时,将引发异常 {@link DataContractException} - */ - @Test - public void testFields_Order_confliction() { - DataContractException ex = null; - try { - DataContractRegistry.register(FieldOrderConflictedDatas.class); - } catch (DataContractException e) { - ex = e; - System.out.println( - "expected error of [" + FieldOrderConflictedDatas.class.toString() + "] --" + e.getMessage()); - } - assertNotNull(ex); - } -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/CompositeDatas.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/CompositeDatas.java deleted file mode 100644 index b1c9c95e..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/CompositeDatas.java +++ /dev/null @@ -1,28 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -/** - * Created by zhangshuang3 on 2018/11/30. - */ -@DataContract(code = 0xc, name = "CompositeDatas", description = "") -public interface CompositeDatas { - - @DataField(order = 1, primitiveType = PrimitiveType.BOOLEAN) - boolean isEnable(); - - @DataField(order = 2, refEnum = true) - EnumLevel getLevel(); - - @DataField(order = 3, refContract = true) - PrimitiveDatas getPrimitive(); - - @DataField(order=4, list = true, refContract=true, genericContract = true) - Operation[] getOperations(); - - @DataField(order = 5, primitiveType = PrimitiveType.INT16) - short getAge(); - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/CompositeDatasImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/CompositeDatasImpl.java deleted file mode 100644 index d1cbee50..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/CompositeDatasImpl.java +++ /dev/null @@ -1,68 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by zhangshuang3 on 2018/11/30. - */ -public class CompositeDatasImpl implements CompositeDatas{ - private boolean enable; - private EnumLevel level; - PrimitiveDatas primitiveDatas; - private List operationList = new ArrayList(); - private short age; - - @Override - public boolean isEnable() { - return this.enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - @Override - public EnumLevel getLevel() { - return this.level; - } - - public void setLevel(EnumLevel level) { - this.level = level; - } - - @Override - public PrimitiveDatas getPrimitive() { - return this.primitiveDatas; - } - - public void setPrimitiveDatas(PrimitiveDatas primitiveDatas) { - this.primitiveDatas = primitiveDatas; - } - - @Override - public Operation[] getOperations() { - return operationList.toArray(new Operation[operationList.size()]); - } - - public void setOperations(Object[] operations) { - for (Object operation : operations) { - Operation op = (Operation)operation; - addOperation(op); - } - } - - public void addOperation(Operation operation) { - operationList.add(operation); - } - - @Override - public short getAge() { - return this.age; - } - - public void setAge(short age) { - this.age = age; - } - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumDatas.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumDatas.java deleted file mode 100644 index 629dc173..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumDatas.java +++ /dev/null @@ -1,15 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -@DataContract(code = 0x07, name = "EnumDatas", description = "") -public interface EnumDatas { - - @DataField(order = 1, refEnum = true) - EnumLevel getLevel(); - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumDatasImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumDatasImpl.java deleted file mode 100644 index f39e1b40..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumDatasImpl.java +++ /dev/null @@ -1,17 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -public class EnumDatasImpl implements EnumDatas { - private EnumLevel level; - - @Override - public EnumLevel getLevel() { - return this.level; - } - public void setLevel(EnumLevel level) { - this.level = level; - } - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumLevel.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumLevel.java deleted file mode 100644 index 54c94f32..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/EnumLevel.java +++ /dev/null @@ -1,27 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -@EnumContract(code=0x0100, name = "EnumLevel", decription = "") -public enum EnumLevel { - - V1((byte) 1), - - V2((byte) 2); - - @EnumField(type= PrimitiveType.INT8) - public final byte CODE; - public byte getCode() { - return CODE; - } - private EnumLevel(byte code) { - this.CODE = code; - } - -} - diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/FieldOrderConflictedDatas.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/FieldOrderConflictedDatas.java deleted file mode 100644 index 428b74cf..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/FieldOrderConflictedDatas.java +++ /dev/null @@ -1,32 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -@DataContract(code = 0x06, name = "Primitive", description = "") -public interface FieldOrderConflictedDatas { - - @DataField(order = 2, primitiveType = PrimitiveType.BOOLEAN) - boolean isEnable(); - - @DataField(order = 3, primitiveType = PrimitiveType.INT8) - byte isBoy(); - - @DataField(order = 7, primitiveType = PrimitiveType.INT16) - short getAge(); - - @DataField(order = -1, primitiveType = PrimitiveType.INT32) - int getId(); - - @DataField(order = 6, primitiveType = PrimitiveType.TEXT) - String getName(); - - @DataField(order = 7, primitiveType = PrimitiveType.INT64) - long getValue(); - - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/FieldOrderConflictedDatasImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/FieldOrderConflictedDatasImpl.java deleted file mode 100644 index 3c95639d..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/FieldOrderConflictedDatasImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -public class FieldOrderConflictedDatasImpl implements FieldOrderConflictedDatas { - - private boolean enable; - - private byte boy; - private short age; - private int id; - private String name; - - private long value; - - @Override - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public short getAge() { - return age; - } - - public void setAge(short age) { - this.age = age; - } - - @Override - public byte isBoy() { - return this.boy; - } - - public void setBoy(byte boy) { - this.boy = boy; - } - - @Override - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - @Override - public long getValue() { - return value; - } - - public void setValue(long value) { - this.value = value; - } - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/GenericRefContractDatas.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/GenericRefContractDatas.java deleted file mode 100644 index 6c949d57..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/GenericRefContractDatas.java +++ /dev/null @@ -1,15 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -@DataContract(code = 0xb, name = "GenericRefContractDatas", description = "") -public interface GenericRefContractDatas { - - @DataField(order=1, list = true, refContract=true, genericContract = true) - Operation[] getOperations(); - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/GenericRefContractDatasImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/GenericRefContractDatasImpl.java deleted file mode 100644 index d257c612..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/GenericRefContractDatasImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -public class GenericRefContractDatasImpl implements GenericRefContractDatas{ - private List operationList = new ArrayList(); - - @Override - public Operation[] getOperations() { - return operationList.toArray(new Operation[operationList.size()]); - } - - public void setOperations(Object[] operations) { - for (Object operation : operations) { - Operation op = (Operation)operation; - addOperation(op); - } - - } - public void addOperation(Operation operation) { - operationList.add(operation); - } - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/Operation.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/Operation.java deleted file mode 100644 index 6f165db9..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/Operation.java +++ /dev/null @@ -1,10 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -@DataContract(code = 0x09, name = "Operation", description = "") -public interface Operation { -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/PrimitiveDatas.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/PrimitiveDatas.java deleted file mode 100644 index 30848834..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/PrimitiveDatas.java +++ /dev/null @@ -1,48 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -@DataContract(code = 0x05, name = "Primitive", description = "") -public interface PrimitiveDatas { - - @DataField(order = 2, primitiveType = PrimitiveType.BOOLEAN) - boolean isEnable(); - - @DataField(order = 3, primitiveType = PrimitiveType.INT8) - byte isBoy(); - - @DataField(order = 4, primitiveType = PrimitiveType.INT16) - short getAge(); - - @DataField(order = -1, primitiveType = PrimitiveType.INT32) - int getId(); - - @DataField(order = 6, primitiveType = PrimitiveType.TEXT) - String getName(); - - @DataField(order = 7, primitiveType = PrimitiveType.INT64) - long getValue(); - - @DataField(order = 12, primitiveType = PrimitiveType.BYTES) - byte[] getImage(); - - @DataField(order = 100, primitiveType = PrimitiveType.INT16) - char getFlag(); - - @DataField(order = 200, primitiveType = PrimitiveType.BYTES) - Bytes getConfig(); - - @DataField(order = 201, primitiveType = PrimitiveType.BYTES) - Bytes getSetting(); - - @DataField(order = 202, primitiveType = PrimitiveType.BYTES) - NetworkAddress getNetworkAddr(); - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/PrimitiveDatasImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/PrimitiveDatasImpl.java deleted file mode 100644 index b505fb34..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/PrimitiveDatasImpl.java +++ /dev/null @@ -1,128 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -public class PrimitiveDatasImpl implements PrimitiveDatas { - - private boolean enable; - - private byte boy; - private short age; - private int id; - private String name; - - private long value; - - private char flag; - - private byte[] image; - - private Bytes config; - - private Bytes setting; - - private NetworkAddress networkAddress; - - @Override - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public short getAge() { - return age; - } - - public void setAge(short age) { - this.age = age; - } - - @Override - public byte isBoy() { - return this.boy; - } - - public void setBoy(byte boy) { - this.boy = boy; - } - - @Override - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - @Override - public long getValue() { - return value; - } - - @Override - public char getFlag() { - return flag; - } - - public void setValue(long value) { - this.value = value; - } - - public void setFlag(char flag) { - this.flag = flag; - } - - @Override - public byte[] getImage() { - return image; - } - - @Override - public Bytes getConfig() { - return config; - } - - public void setImage(byte[] image) { - this.image = image; - } - - public void setConfig(Bytes config) { - this.config = config; - } - - public void setSetting(Bytes setting) { - this.setting = setting; - } - - @Override - public Bytes getSetting() { - return setting; - } - - @Override - public NetworkAddress getNetworkAddr() { - return networkAddress; - } - - public void setNetworkAddress(NetworkAddress networkAddress) { - this.networkAddress = networkAddress; - } -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/RefContractDatas.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/RefContractDatas.java deleted file mode 100644 index 0c3d1947..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/RefContractDatas.java +++ /dev/null @@ -1,14 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -@DataContract(code = 0x08, name = "RefContractDatas", description = "") -public interface RefContractDatas { - - @DataField(order = 1, refContract = true) - PrimitiveDatas getPrimitive(); -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/RefContractDatasImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/RefContractDatasImpl.java deleted file mode 100644 index 40880428..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/RefContractDatasImpl.java +++ /dev/null @@ -1,18 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -public class RefContractDatasImpl implements RefContractDatas{ - PrimitiveDatas primitiveDatas; - - @Override - public PrimitiveDatas getPrimitive() { - return this.primitiveDatas; - } - - public void setPrimitiveDatas(PrimitiveDatas primitiveDatas) { - this.primitiveDatas = primitiveDatas; - } - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/SubOperation.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/SubOperation.java deleted file mode 100644 index 6760bdcb..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/SubOperation.java +++ /dev/null @@ -1,16 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -@DataContract(code = 0xa, name = "SubOperation", description = "") -public interface SubOperation extends Operation { - - @DataField(order=1, primitiveType = PrimitiveType.TEXT) - String getUserName(); - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/SubOperationImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/SubOperationImpl.java deleted file mode 100644 index 6966fc63..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/SubOperationImpl.java +++ /dev/null @@ -1,17 +0,0 @@ -package test.com.jd.blockchain.binaryproto; - -/** - * Created by zhangshuang3 on 2018/11/29. - */ -public class SubOperationImpl implements SubOperation { - String userName; - - @Override - public String getUserName() { - return this.userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/AddressCodeDuplicate.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/AddressCodeDuplicate.java deleted file mode 100644 index 9e1ac6cc..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/AddressCodeDuplicate.java +++ /dev/null @@ -1,19 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -/** - * Created by zhangshuang3 on 2018/7/9. - */ -@DataContract(code=0x02, name="Address" , description="") -public interface AddressCodeDuplicate { - - @DataField(order=1, primitiveType= PrimitiveType.TEXT) - String getStreet(); - - @DataField(order=2, primitiveType=PrimitiveType.INT32) - int getNumber(); - -} \ No newline at end of file diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/AddressOrderDuplicate.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/AddressOrderDuplicate.java deleted file mode 100644 index f5b33e66..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/AddressOrderDuplicate.java +++ /dev/null @@ -1,19 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -/** - * Created by zhangshuang3 on 2018/7/9. - */ -@DataContract(code=0x03, name="Address" , description="") -public interface AddressOrderDuplicate { - - @DataField(order=1, primitiveType= PrimitiveType.TEXT) - String getStreet(); - - @DataField(order=1, primitiveType=PrimitiveType.INT32) - int getNumber(); - -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/Array.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/Array.java deleted file mode 100644 index 6eaf8c1d..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/Array.java +++ /dev/null @@ -1,25 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -@DataContract(code=0x08, name="Array" , description="") -public interface Array { - - @DataField(order=1, primitiveType= PrimitiveType.INT32, list=true) - int[] getScores(); - - @DataField(order=2, primitiveType=PrimitiveType.TEXT, list=true) - String[] getFeatures(); - - @DataField(order=3, primitiveType=PrimitiveType.BYTES) - byte[] getFamilyMemberAges(); - - @DataField(order=4, primitiveType=PrimitiveType.INT64, list=true) - long[] getFamilyMemberIds(); - -} \ No newline at end of file diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/Level.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/Level.java deleted file mode 100644 index d7e1c676..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/Level.java +++ /dev/null @@ -1,25 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract; - -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; - -@EnumContract(code=0x0100) -public enum Level { - - V1((byte) 1), - - V2((byte) 2); - - @EnumField(type=PrimitiveType.INT8) - public final byte CODE; - public byte getCode() { - return CODE; - } - private Level(byte code) { - this.CODE = code; - } - -} - - diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/PrivilegeModelSetting.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/PrivilegeModelSetting.java deleted file mode 100644 index 52586c94..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/PrivilegeModelSetting.java +++ /dev/null @@ -1,20 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -/** - * Created by zhangshuang3 on 2018/7/30. - */ -@DataContract(code=0x0f, name="PrivilegeModelSetting", description ="Privilege Model setting") -public interface PrivilegeModelSetting { - - @DataField(order=1, primitiveType= PrimitiveType.INT64) - long getLatestVersion(); - - //@DataField(order=2, refContract=true) - //Privilege getPrivilege(long version); - -} - diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/RefEnum.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/RefEnum.java deleted file mode 100644 index 793d0457..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/RefEnum.java +++ /dev/null @@ -1,15 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -@DataContract(code=0x06, name="RefEnum" , description="") -public interface RefEnum { - - @DataField(order=1, refEnum=true) - Level getLevel(); - -} \ No newline at end of file diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/ArrayImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/ArrayImpl.java deleted file mode 100644 index 6c9cd628..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/ArrayImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract.impl; - -import test.com.jd.blockchain.binaryproto.contract.*; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -public class ArrayImpl implements Array { - - private byte[] familyMemberAges; - private int[] scores; - private String[] features; - private long[] familyMemberIds; - - @Override - public int[] getScores() { - // TODO Auto-generated method stub - return this.scores; - } - public void setScores(int[] scores) { - this.scores = scores; - } - - @Override - public String[] getFeatures() { - return this.features; - } - public void setFeatures(String[] features) { - this.features = features; - } - - @Override - public byte[] getFamilyMemberAges() { - return this.familyMemberAges; - } - public void setFamilyMemberAges(byte[] familyMemberAge) { - this.familyMemberAges = familyMemberAge; - } - - @Override - public long[] getFamilyMemberIds() { - return this.familyMemberIds; - } - public void setFamilyMemberIds(long[] familyMemberId) { - this.familyMemberIds = familyMemberId; - } -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/PrivilegeModelSettingImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/PrivilegeModelSettingImpl.java deleted file mode 100644 index 5c1b8c5b..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/PrivilegeModelSettingImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract.impl; - -import test.com.jd.blockchain.binaryproto.contract.PrivilegeModelSetting; - -/** - * Created by zhangshuang3 on 2018/7/30. - */ -public class PrivilegeModelSettingImpl implements PrivilegeModelSetting { - long latestVersion; - - @Override - public long getLatestVersion() { - return this.latestVersion; - } - - public void setLatestVersion(long latestVersion) { - this.latestVersion = latestVersion; - } - - //Privilege getPrivilege(long version) { - //} -} diff --git a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/RefEnumImpl.java b/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/RefEnumImpl.java deleted file mode 100644 index 64bcc30b..00000000 --- a/source/binary-proto/src/test/java/test/com/jd/blockchain/binaryproto/contract/impl/RefEnumImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -package test.com.jd.blockchain.binaryproto.contract.impl; - -import test.com.jd.blockchain.binaryproto.contract.Level; -import test.com.jd.blockchain.binaryproto.contract.RefEnum; - -/** - * Created by zhangshuang3 on 2018/7/11. - */ -public class RefEnumImpl implements RefEnum { - - private Level level; - - @Override - public Level getLevel() { - // TODO Auto-generated method stub - return this.level; - } - public void setLevel(Level level) { - this.level = level; - } -} - diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingConfig.java deleted file mode 100644 index afa21aeb..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingConfig.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.crypto.PubKey; - -public class BftsmartClientIncomingConfig implements BftsmartClientIncomingSettings { - - private BftsmartConsensusSettings consensusSettings; - - private byte[] topology; - - private byte[] tomConfig; - - private int clientId; - - private PubKey pubKey; - - - @Override - public BftsmartConsensusSettings getConsensusSettings() { - return consensusSettings; - } - - public void setConsensusSettings(BftsmartConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - } - - @Override - public byte[] getTopology() { - return topology; - } - - public void setTopology(byte[] topology) { - this.topology = topology; - } - - @Override - public int getClientId() { - return clientId; - } - - @Override - public String getProviderName() { - return BftsmartConsensusProvider.NAME; - } - - public void setClientId(int clientId) { - this.clientId = clientId; - } - - @Override - public byte[] getTomConfig() { - return tomConfig; - } - - public void setTomConfig(byte[] tomConfig) { - this.tomConfig = tomConfig; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - } -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingSettings.java deleted file mode 100644 index 2838542a..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingSettings.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; - -@DataContract(code = DataCodes.CONSENSUS_BFTSMART_CLI_INCOMING_SETTINGS) -public interface BftsmartClientIncomingSettings extends ClientIncomingSettings { - - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - byte[] getTopology(); - - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - byte[] getTomConfig(); - - @DataField(order = 3, primitiveType=PrimitiveType.BYTES) - PubKey getPubKey(); - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockConfig.java deleted file mode 100644 index 5fa31a11..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockConfig.java +++ /dev/null @@ -1,35 +0,0 @@ -//package com.jd.blockchain.consensus.bftsmart; -// -//public class BftsmartCommitBlockConfig implements BftsmartCommitBlockSettings { -// -// private int txSizePerBlock; -// -// private long maxDelayMilliSecondsPerBlock; -// -// -// public BftsmartCommitBlockConfig() { -// -// } -// -// public BftsmartCommitBlockConfig(int txSizePerBlock, long maxDelayMilliSecondsPerBlock) { -// this.txSizePerBlock = txSizePerBlock; -// this.maxDelayMilliSecondsPerBlock = maxDelayMilliSecondsPerBlock; -// } -// @Override -// public int getTxSizePerBlock() { -// return txSizePerBlock; -// } -// -// public void setTxSizePerBlock(int txSizePerBlock) { -// this.txSizePerBlock = txSizePerBlock; -// } -// -// @Override -// public long getMaxDelayMilliSecondsPerBlock() { -// return maxDelayMilliSecondsPerBlock; -// } -// -// public void setMaxDelayMilliSecondsPerBlock(long maxDelayMilliSecondsPerBlock) { -// this.maxDelayMilliSecondsPerBlock = maxDelayMilliSecondsPerBlock; -// } -//} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockSettings.java deleted file mode 100644 index 2924c9f0..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockSettings.java +++ /dev/null @@ -1,17 +0,0 @@ -//package com.jd.blockchain.consensus.bftsmart; -// -//import com.jd.blockchain.binaryproto.DataContract; -//import com.jd.blockchain.binaryproto.DataField; -//import com.jd.blockchain.binaryproto.PrimitiveType; -//import com.jd.blockchain.consts.DataCodes; -// -// -//@DataContract(code = DataCodes.CONSENSUS_BFTSMART_BLOCK_SETTINGS) -//public interface BftsmartCommitBlockSettings { -// -// @DataField(order = 0, primitiveType = PrimitiveType.INT32) -// int getTxSizePerBlock(); -// -// @DataField(order = 1, primitiveType = PrimitiveType.INT64) -// long getMaxDelayMilliSecondsPerBlock(); -//} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusConfig.java deleted file mode 100644 index 48d5acb9..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusConfig.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.utils.Property; - -public class BftsmartConsensusConfig implements BftsmartConsensusSettings { - - private Property[] bftsmartSystemConfig; - - private BftsmartNodeSettings[] nodes; - -// private BftsmartCommitBlockSettings commitBlockSettings; - - static { - DataContractRegistry.register(BftsmartConsensusSettings.class); - } - /** - * 创建 bftsmart 共识配置; - * - * @param nodes - * 节点列表 - * @param commitBlockSettings - * 结块设置; - * @param bftsmartSystemConfigs - * bftsmart系统配置; - */ - public BftsmartConsensusConfig(BftsmartNodeSettings[] nodes, -// BftsmartCommitBlockSettings commitBlockSettings, - Property[] bftsmartSystemConfigs) { - this.nodes = nodes; -// this.commitBlockSettings = commitBlockSettings; - this.bftsmartSystemConfig = bftsmartSystemConfigs; - } - - @Override - public BftsmartNodeSettings[] getNodes() { - return nodes; - } - - @Override - public Property[] getSystemConfigs() { - return bftsmartSystemConfig; - } - -// @Override -// public BftsmartCommitBlockSettings getCommitBlockSettings() { -// return commitBlockSettings; -// } -// -// -// public void setCommitBlockSettings(BftsmartCommitBlockSettings commitBlockSettings) { -// this.commitBlockSettings = commitBlockSettings; -// } -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusProvider.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusProvider.java deleted file mode 100644 index a8290286..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.SettingsFactory; -import com.jd.blockchain.consensus.bftsmart.client.BftsmartConsensusClientFactory; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartNodeServerFactory; -import com.jd.blockchain.consensus.client.ClientFactory; -import com.jd.blockchain.consensus.service.NodeServerFactory; - -public class BftsmartConsensusProvider implements ConsensusProvider { - - public static final String NAME = BftsmartConsensusProvider.class.getName(); - - private static BftsmartSettingsFactory settingsFactory = new BftsmartSettingsFactory(); - - private static BftsmartConsensusClientFactory clientFactory = new BftsmartConsensusClientFactory(); - - private static BftsmartNodeServerFactory nodeServerFactory = new BftsmartNodeServerFactory(); - - - @Override - public String getName() { - return NAME; - } - - @Override - public SettingsFactory getSettingsFactory() { - return settingsFactory; - } - - @Override - public ClientFactory getClientFactory() { - return clientFactory; - } - - @Override - public NodeServerFactory getServerFactory() { - return nodeServerFactory; - } - - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettings.java deleted file mode 100644 index d3ce6494..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettings.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Property; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; - -@DataContract(code = DataCodes.CONSENSUS_BFTSMART_SETTINGS) -public interface BftsmartConsensusSettings extends ConsensusSettings { - - @DataField(order = 1, primitiveType = PrimitiveType.BYTES, list=true) - Property[] getSystemConfigs(); - -// @DataField(order = 2, refContract = true) -// BftsmartCommitBlockSettings getCommitBlockSettings(); - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettingsBuilder.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettingsBuilder.java deleted file mode 100644 index 9d6637db..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettingsBuilder.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.tools.keygen.KeyGenCommand; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.PropertiesUtils; -import com.jd.blockchain.utils.Property; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.ConsensusSettingsBuilder; -import com.jd.blockchain.crypto.PubKey; - -public class BftsmartConsensusSettingsBuilder implements ConsensusSettingsBuilder { - - private static final int DEFAULT_TXSIZE = 1000; - - private static final int DEFAULT_MAXDELAY = 1000; - - private static final String CONFIG_TEMPLATE_FILE = "bftsmart.config"; - - private static final String CONFIG_LEDGER_INIT = "ledger.init"; - - /** - * 参数键:节点数量; - */ - public static final String SERVER_NUM_KEY = "system.servers.num"; - - /** - * 参数键:结块条件设置; - */ - public static final String BFTSMART_BLOCK_TXSIZE_KEY = "system.block.txsize"; - - public static final String BFTSMART_BLOCK_MAXDELAY_KEY = "system.block.maxdelay"; - - // /** - // * 参数键格式:节点地址; - // */ - // public static final String ADDRESS_PATTERN = "node.%s.address"; - - /** - * 参数键格式:节点公钥; - */ - public static final String PUBKEY_PATTERN = "system.server.%s.pubkey"; - - /** - * 参数键格式:节点共识服务的网络地址; - */ - public static final String CONSENSUS_HOST_PATTERN = "system.server.%s.network.host"; - - /** - * 参数键格式:节点共识服务的端口; - */ - public static final String CONSENSUS_PORT_PATTERN = "system.server.%s.network.port"; - - /** - * 参数键格式:节点共识服务的通讯是否开启安全选项; - */ - public static final String CONSENSUS_SECURE_PATTERN = "system.server.%s.network.secure"; - - public static final String BFTSMART_PROVIDER = "com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"; - - - - private static Properties CONFIG_TEMPLATE; - static { - ClassPathResource configResource = new ClassPathResource(CONFIG_TEMPLATE_FILE); - try { - try (InputStream in = configResource.getInputStream()) { - CONFIG_TEMPLATE = PropertiesUtils.load(in, BytesUtils.DEFAULT_CHARSET); - } - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - //解析得到结块的相关配置信息 -// public BftsmartCommitBlockConfig createBlockConfig(Properties resolvingProps) { -// BftsmartCommitBlockConfig blockConfig = new BftsmartCommitBlockConfig(); -// -// String txSizeString = PropertiesUtils.getRequiredProperty(resolvingProps, BFTSMART_BLOCK_TXSIZE_KEY); -// resolvingProps.remove(BFTSMART_BLOCK_TXSIZE_KEY); -// -// if (txSizeString == null || txSizeString.length() == 0) { -// blockConfig.setTxSizePerBlock(DEFAULT_TXSIZE); -// } -// else { -// blockConfig.setTxSizePerBlock(Integer.parseInt(txSizeString)); -// } -// -// String maxDelayString = PropertiesUtils.getRequiredProperty(resolvingProps, BFTSMART_BLOCK_MAXDELAY_KEY); -// resolvingProps.remove(BFTSMART_BLOCK_MAXDELAY_KEY); -// -// if (maxDelayString == null || maxDelayString.length() == 0) { -// blockConfig.setMaxDelayMilliSecondsPerBlock(DEFAULT_MAXDELAY); -// } -// else { -// blockConfig.setMaxDelayMilliSecondsPerBlock(Long.parseLong(maxDelayString)); -// } -// -// return blockConfig; -// } - - @Override - public Properties createPropertiesTemplate() { - return PropertiesUtils.cloneFrom(CONFIG_TEMPLATE); - } - - @Override - public BftsmartConsensusSettings createSettings(Properties props, ParticipantNode[] participantNodes) { - Properties resolvingProps = PropertiesUtils.cloneFrom(props); - int serversNum = PropertiesUtils.getInt(resolvingProps, SERVER_NUM_KEY); - if (serversNum < 0) { - throw new IllegalArgumentException(String.format("Property[%s] is negative!", SERVER_NUM_KEY)); - } - if (serversNum < 4) { - throw new IllegalArgumentException(String.format("Property[%s] is less than 4!", SERVER_NUM_KEY)); - } - if (participantNodes == null) { - throw new IllegalArgumentException("ParticipantNodes is Empty !!!"); - } - if (serversNum != participantNodes.length) { - throw new IllegalArgumentException(String.format("Property[%s] which is [%s] unequal " + - "ParticipantNodes's length which is [%s] !", SERVER_NUM_KEY, serversNum, participantNodes.length)); - } - -// BftsmartCommitBlockConfig blockConfig = createBlockConfig(resolvingProps); - - BftsmartNodeSettings[] nodesSettings = new BftsmartNodeSettings[serversNum]; - for (int i = 0; i < serversNum; i++) { - int id = i; - -// String keyOfPubkey = keyOfNode(PUBKEY_PATTERN, id); -// String base58PubKey = PropertiesUtils.getRequiredProperty(resolvingProps, keyOfPubkey); -// PubKey pubKey = new PubKey(Base58Utils.decode(base58PubKey)); -// PubKey pubKey = KeyGenCommand.decodePubKey(base58PubKey); - PubKey pubKey = participantNodes[i].getPubKey(); -// resolvingProps.remove(keyOfPubkey); - - String keyOfHost = keyOfNode(CONSENSUS_HOST_PATTERN, id); - String networkAddressHost = PropertiesUtils.getRequiredProperty(resolvingProps, keyOfHost); - resolvingProps.remove(keyOfHost); - - String keyOfPort = keyOfNode(CONSENSUS_PORT_PATTERN, id); - int networkAddressPort = PropertiesUtils.getInt(resolvingProps, keyOfPort); - resolvingProps.remove(keyOfPort); - - String keyOfSecure = keyOfNode(CONSENSUS_SECURE_PATTERN, id); - boolean networkAddressSecure = PropertiesUtils.getBoolean(resolvingProps, keyOfSecure); - resolvingProps.remove(keyOfSecure); - - BftsmartNodeConfig nodeConfig = new BftsmartNodeConfig(pubKey, id, - new NetworkAddress(networkAddressHost, networkAddressPort, networkAddressSecure)); - nodesSettings[i] = nodeConfig; - } - - BftsmartConsensusConfig config = new BftsmartConsensusConfig(nodesSettings, -// blockConfig, - PropertiesUtils.getOrderedValues(resolvingProps)); - return config; - } - - @Override - public Bytes updateSettings(Bytes oldConsensusSettings, ParticipantInfo participantInfo) { - - //update consensus setting through node and system config two aspects - BftsmartConsensusSettings consensusSettings = (BftsmartConsensusSettings) ConsensusProviders.getProvider(BFTSMART_PROVIDER).getSettingsFactory().getConsensusSettingsEncoder().decode(oldConsensusSettings.toBytes()); - - Property[] systemConfigs = systemConfigs(consensusSettings.getSystemConfigs()); - - BftsmartNodeSettings[] nodeSettings = nodeSettings(consensusSettings.getNodes(), participantInfo); - - BftsmartConsensusConfig bftsmartConsensusConfig = new BftsmartConsensusConfig(nodeSettings, systemConfigs); - -// for(int i = 0 ;i < bftsmartConsensusConfig.getNodes().length; i++) { -// System.out.printf("id = %d, host = %s, port = %d\r\n", bftsmartConsensusConfig.getNodes()[i].getId(), bftsmartConsensusConfig.getNodes()[i].getNetworkAddress().getHost(), bftsmartConsensusConfig.getNodes()[i].getNetworkAddress().getPort()); -// } -// -// for(int i = 0 ;i < bftsmartConsensusConfig.getSystemConfigs().length; i++) { -// System.out.printf("property name = %s, property value = %s\r\n",bftsmartConsensusConfig.getSystemConfigs()[i].getName(), bftsmartConsensusConfig.getSystemConfigs()[i].getValue()); -// } - - return new Bytes(ConsensusProviders.getProvider(BFTSMART_PROVIDER).getSettingsFactory().getConsensusSettingsEncoder().encode(bftsmartConsensusConfig)); - - } - - private static String keyOfNode(String pattern, int id) { - return String.format(pattern, id); - } - - @Override - public void writeSettings(ConsensusSettings settings, Properties props) { - int serversNum = PropertiesUtils.getInt(props, SERVER_NUM_KEY); - if (serversNum > 0) { - for (int i = 0; i < serversNum; i++) { - int id = i; -// String keyOfPubkey = keyOfNode(PUBKEY_PATTERN, id); -// props.remove(keyOfPubkey); - - String keyOfHost = keyOfNode(CONSENSUS_HOST_PATTERN, id); - props.remove(keyOfHost); - - String keyOfPort = keyOfNode(CONSENSUS_PORT_PATTERN, id); - props.remove(keyOfPort); - - String keyOfSecure = keyOfNode(CONSENSUS_SECURE_PATTERN, id); - props.remove(keyOfSecure); - } - } - - BftsmartConsensusSettings bftsmartSettings = (BftsmartConsensusSettings) settings; - BftsmartNodeSettings[] nodesSettings = (BftsmartNodeSettings[]) bftsmartSettings.getNodes(); - serversNum = nodesSettings.length; - props.setProperty(SERVER_NUM_KEY, serversNum + ""); - - //获得结块相关的属性信息 -// BftsmartCommitBlockSettings blockSettings = bftsmartSettings.getCommitBlockSettings(); -// if (blockSettings == null) { -// props.setProperty(BFTSMART_BLOCK_TXSIZE_KEY, DEFAULT_TXSIZE + ""); -// props.setProperty(BFTSMART_BLOCK_MAXDELAY_KEY, DEFAULT_MAXDELAY + ""); -// } else { -// int txSize = blockSettings.getTxSizePerBlock(); -// long maxDelay = blockSettings.getMaxDelayMilliSecondsPerBlock(); -// props.setProperty(BFTSMART_BLOCK_TXSIZE_KEY, txSize + ""); -// props.setProperty(BFTSMART_BLOCK_MAXDELAY_KEY, maxDelay + ""); -// } - - for (int i = 0; i < serversNum; i++) { - BftsmartNodeSettings ns = nodesSettings[i]; - int id = i; -// String keyOfPubkey = keyOfNode(PUBKEY_PATTERN, id); -// props.setProperty(keyOfPubkey, ns.getPubKey().toBase58()); - - String keyOfHost = keyOfNode(CONSENSUS_HOST_PATTERN, id); - props.setProperty(keyOfHost, ns.getNetworkAddress() == null ? "" : ns.getNetworkAddress().getHost()); - - String keyOfPort = keyOfNode(CONSENSUS_PORT_PATTERN, id); - props.setProperty(keyOfPort, ns.getNetworkAddress() == null ? "" : ns.getNetworkAddress().getPort() + ""); - - String keyOfSecure = keyOfNode(CONSENSUS_SECURE_PATTERN, id); - props.setProperty(keyOfSecure, ns.getNetworkAddress() == null ? "false" : ns.getNetworkAddress().isSecure() + ""); - } - - PropertiesUtils.setValues(props, bftsmartSettings.getSystemConfigs()); - } - - /** - * - * update system.servers.num property - * - */ - private Property[] systemConfigs(Property[] systemConfigs) { - Map propertyMap = convert2Map(systemConfigs); - int serverNum = Integer.parseInt(propertyMap.get("system.servers.num").getValue()); - propertyMap.put("system.servers.num", new Property("system.servers.num", String.valueOf(serverNum + 1))); - return convert2Array(propertyMap); - - } - - private Map convert2Map(Property[] properties) { - Map propertyMap = new HashMap<>(); - for (Property property : properties) { - propertyMap.put(property.getName(), property); - } - return propertyMap; - } - - private Property[] convert2Array(Map map) { - Property[] properties = new Property[map.size()]; - int index = 0; - for (Map.Entry entry : map.entrySet()) { - properties[index++] = entry.getValue(); - } - return properties; - } - - /** - * - * update node setting - * - */ - private BftsmartNodeSettings[] nodeSettings(NodeSettings[] nodeSettings, ParticipantInfo participantInfo) { - - BftsmartNodeConfig bftsmartNodeConfig = new BftsmartNodeConfig(participantInfo.getPubKey(), nodeSettings.length, participantInfo.getNetworkAddress()); - - BftsmartNodeSettings[] bftsmartNodeSettings = new BftsmartNodeSettings[nodeSettings.length + 1]; - for (int i = 0; i < nodeSettings.length; i++) { - bftsmartNodeSettings[i] = (BftsmartNodeSettings)nodeSettings[i]; - } - bftsmartNodeSettings[nodeSettings.length] = bftsmartNodeConfig; - return bftsmartNodeSettings; - } - - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeConfig.java deleted file mode 100644 index fd45b144..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeConfig.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class BftsmartNodeConfig implements BftsmartNodeSettings { - - private int id; - - private String address; - - private PubKey pubKey; - - private NetworkAddress networkAddress; - - public BftsmartNodeConfig() { - } - - static { - DataContractRegistry.register(BftsmartNodeSettings.class); - } - - public BftsmartNodeConfig(PubKey pubKey, int id, NetworkAddress networkAddress) { - this.address = AddressEncoding.generateAddress(pubKey).toBase58(); - this.pubKey = pubKey; - this.id = id; - this.networkAddress = networkAddress; - } - - @Override - public String getAddress() { - return address; - } - - @Override - public int getId() { - return id; - } - - @Override - public NetworkAddress getNetworkAddress() { - return networkAddress; - } - - public void setId(int id) { - this.id = id; - } - - public void setAddress(String address) { - this.address = address; - } - - public void setNetworkAddress(NetworkAddress networkAddress) { - this.networkAddress = networkAddress; - } - - public PubKey getPubKey() { - return pubKey; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - } -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeSettings.java deleted file mode 100644 index a7158b68..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeSettings.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.net.NetworkAddress; - -@DataContract(code = DataCodes.CONSENSUS_BFTSMART_NODE_SETTINGS) -public interface BftsmartNodeSettings extends NodeSettings { - - /** - * 节点所属的参与方的区块链地址; - */ -// @DataField(order = 0, primitiveType = ValueType.TEXT) -// @Override -// String getAddress(); - - /** - * Base58 格式的公钥; - * - * @return - */ -// @DataField(order = 1, primitiveType = ValueType.BYTES) -// PubKey getPubKey(); - - /** - * 节点的ID; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.INT32) - int getId(); - - /** - * 共识协议的网络地址; - * - * @return - */ - @DataField(order = 3, primitiveType = PrimitiveType.BYTES) - NetworkAddress getNetworkAddress(); - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartSettingsFactory.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartSettingsFactory.java deleted file mode 100644 index a3e345ec..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartSettingsFactory.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.*; -import com.jd.blockchain.utils.io.BytesEncoder; - -public class BftsmartSettingsFactory implements SettingsFactory { - - private static ConsensusSettingsEncoder CS_ENCODER = new ConsensusSettingsEncoder(); - - private static ClientIncomingSettingsEncoder CI_ENCODER =new ClientIncomingSettingsEncoder(); - - static { - DataContractRegistry.register(BftsmartConsensusSettings.class); - - DataContractRegistry.register(BftsmartClientIncomingSettings.class); - } - - @Override - public BftsmartConsensusSettingsBuilder getConsensusSettingsBuilder() { - - return new BftsmartConsensusSettingsBuilder(); - } - - @Override - public BytesEncoder getConsensusSettingsEncoder() { - return CS_ENCODER; - } - - @Override - public BytesEncoder getIncomingSettingsEncoder() { - return CI_ENCODER; - } - - - - private static class ConsensusSettingsEncoder implements BytesEncoder{ - - @Override - public byte[] encode(ConsensusSettings data) { - if (data instanceof BftsmartConsensusSettings) { - return BinaryProtocol.encode(data, BftsmartConsensusSettings.class); - } - throw new IllegalArgumentException("Settings data isn't supported! Accept BftsmartConsensusSettings only!"); - } - - @Override - public ConsensusSettings decode(byte[] bytes) { - return BinaryProtocol.decodeAs(bytes, BftsmartConsensusSettings.class); - } - - } - - private static class ClientIncomingSettingsEncoder implements BytesEncoder{ - - @Override - public byte[] encode(ClientIncomingSettings data) { - if (data instanceof BftsmartClientIncomingSettings) { - return BinaryProtocol.encode(data, BftsmartClientIncomingSettings.class); - } - throw new IllegalArgumentException("Settings data isn't supported! Accept BftsmartClientIncomingSettings only!"); - } - - @Override - public ClientIncomingSettings decode(byte[] bytes) { - return BinaryProtocol.decodeAs(bytes, BftsmartClientIncomingSettings.class); - } - - } - - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartTopology.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartTopology.java deleted file mode 100644 index f6832fb8..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartTopology.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart; - -import bftsmart.reconfiguration.views.View; -import com.jd.blockchain.consensus.Topology; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; - -public class BftsmartTopology implements Topology { - - private static final long serialVersionUID = -3042599438265726240L; - - private View view; - - public BftsmartTopology(View view){ - this.view = view; - } - - @Override - public int getId() { - return view.getId(); - } - - @Override - public Topology copyOf() { - return BinarySerializeUtils.copyOf(this); - } - - public View getView() { - return view; - } -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartTransactionType.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartTransactionType.java deleted file mode 100644 index bf42510f..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartTransactionType.java +++ /dev/null @@ -1,16 +0,0 @@ -//package com.jd.blockchain.consensus.bftsmart; -// -//public enum BftsmartTransactionType { -// TRANSACTION((int)0), -// COMMITBLOCK((int)1); -// -// public final int CODE; -// -// public int getCode() { -// return CODE; -// } -// private BftsmartTransactionType(int code) { -// this.CODE = code; -// } -// -//} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientConfig.java deleted file mode 100644 index 89dfe1e4..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientConfig.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.client; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.bftsmart.BftsmartClientIncomingSettings; -import com.jd.blockchain.crypto.PubKey; - - -public class BftsmartClientConfig implements BftsmartClientSettings { - - private int clientId; - private PubKey clientPubkey; - private ConsensusSettings consensusSettings; - private byte[] topology; - private byte[] tomConfig; - BftsmartClientIncomingSettings clientIncomingSettings; - - public BftsmartClientConfig(int clientId, PubKey clientPubkey, ConsensusSettings consensusSettings, byte[] topology, byte[] tomConfig) { - this.clientId = clientId; - this.clientPubkey = clientPubkey; - this.consensusSettings = consensusSettings; - this.topology = topology; - this.tomConfig = tomConfig; - } - - public BftsmartClientConfig(BftsmartClientIncomingSettings clientIncomingSettings) { - this.clientIncomingSettings = clientIncomingSettings; - this.clientId = clientIncomingSettings.getClientId(); - this.clientPubkey = clientIncomingSettings.getPubKey(); - this.consensusSettings = clientIncomingSettings.getConsensusSettings(); - this.topology = clientIncomingSettings.getTopology(); - this.tomConfig = clientIncomingSettings.getTomConfig(); - - } - @Override - public int getClientId() { - return clientId; - } - - public void setClientId(int clientId) { - this.clientId = clientId; - } - - - @Override - public PubKey getClientPubKey() { - return clientPubkey; - } - - public void setClientPubkey(PubKey clientPubkey) { - this.clientPubkey = clientPubkey; - } - - @Override - public ConsensusSettings getConsensusSettings() { - return consensusSettings; - } - - public void setConsensusSettings(ConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - } - - public byte[] getTopology() { - return topology; - } - - public void setTopology(byte[] topology) { - this.topology = topology; - } - - @Override - public byte[] getTomConfig() { - return tomConfig; - } - - public void setTomConfig(byte[] tomConfig) { - this.tomConfig = tomConfig; - } -} - diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientIdentification.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientIdentification.java deleted file mode 100644 index 695e9feb..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientIdentification.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.client; - -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; - -public class BftsmartClientIdentification implements ClientIdentification { - - private byte[] identityInfo; - private PubKey pubKey; - private SignatureDigest signatureDigest; - - public BftsmartClientIdentification() { - - } - - public BftsmartClientIdentification(ClientIdentification clientIdentification) { - identityInfo = clientIdentification.getIdentityInfo(); - pubKey = clientIdentification.getPubKey(); - signatureDigest = clientIdentification.getSignature(); - } - - @Override - public byte[] getIdentityInfo() { - return identityInfo; - } - - public void setIdentityInfo(byte[] identityInfo) { - this.identityInfo = identityInfo; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - } - - @Override - public SignatureDigest getSignature() { - return signatureDigest; - } - - @Override - public String getProviderName() { - return BftsmartConsensusProvider.NAME; - } - - public void setSignatureDigest(SignatureDigest signatureDigest) { - this.signatureDigest = signatureDigest; - } - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientSettings.java deleted file mode 100644 index 94bf3d53..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientSettings.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.client; - -import com.jd.blockchain.consensus.client.ClientSettings; - - -public interface BftsmartClientSettings extends ClientSettings { - - byte[] getTopology(); - - byte[] getTomConfig(); - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClient.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClient.java deleted file mode 100644 index 9561263d..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClient.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.client; - -import com.jd.blockchain.consensus.MessageService; -import com.jd.blockchain.consensus.client.ClientSettings; -import com.jd.blockchain.consensus.client.ConsensusClient; -import java.util.concurrent.atomic.AtomicInteger; - -public class BftsmartConsensusClient implements ConsensusClient { - - - private final AtomicInteger addId = new AtomicInteger(); - - private BftsmartPeerProxyPool asyncPeerProxyPool; - - private int gatewayId; - - private ClientSettings clientSettings; - - public BftsmartConsensusClient(ClientSettings clientSettings) { - - this.clientSettings = clientSettings; - this.gatewayId = clientSettings.getClientId(); - } - - - public BftsmartPeerProxyPool getConsensusClientPool() { - return this.asyncPeerProxyPool; - } - - @Override - public MessageService getMessageService() { - return new BftsmartMessageService(asyncPeerProxyPool); - } - - @Override - public ClientSettings getSettings() { - return clientSettings; - } - - @Override - public boolean isConnected() { - return this.asyncPeerProxyPool != null; - } - - @Override - public synchronized void connect() { - - //consensus client pool - BftsmartPeerProxyFactory peerProxyFactory = new BftsmartPeerProxyFactory((BftsmartClientSettings)clientSettings, gatewayId); - this.asyncPeerProxyPool = new BftsmartPeerProxyPool(peerProxyFactory); - -// MemoryBasedViewStorage viewStorage = new MemoryBasedViewStorage(((BftsmartClientSettings)clientSettings).getTopology().getView()); -// TOMConfiguration tomConfiguration = ((BftsmartConsensusConfig)clientSettings.getConsensusSettings()).getBftsmartConfig(); -// -// //by serialize keep origin tom config -// byte[] tomBytes = BinarySerializeUtils.serialize(tomConfiguration); -// TOMConfiguration decodeTom = BinarySerializeUtils.deserialize(tomBytes); -// -// int clientId = gatewayId *100 + addId.incrementAndGet(); -// -// //every proxy client has unique id; -// decodeTom.setProcessId(clientId); -// this.peerProxy = new AsynchServiceProxy(decodeTom, viewStorage); - - } - - @Override - public void close() { - if (asyncPeerProxyPool != null) { - asyncPeerProxyPool.close(); - } - } - -// public void asyncSendOrdered(byte[] message, AsyncCallback callback) { -// AsyncReplier replier = new AsyncReplier(callback, peerProxy); -// peerProxy.invokeAsynchRequest(message, replier, TOMMessageType.ORDERED_REQUEST); -// } - -// private static class AsyncReplier implements ReplyListener { -// -// private AsynchServiceProxy peerProxy; -// -// private AtomicInteger replies = new AtomicInteger(0); -// -// private AsyncCallback messageHandle; -// -// public AsyncReplier(AsyncCallback messageHandle, AsynchServiceProxy peerProxy) { -// this.messageHandle = messageHandle; -// this.peerProxy = peerProxy; -// } -// -// @Override -// public void reset() { -// replies.set(0); -// } -// -// @Override -// public void replyReceived(RequestContext context, TOMMessage reply) { -// int replyCount = replies.incrementAndGet(); -// -// double q = Math.ceil((double) (peerProxy.getViewManager().getCurrentViewN() -// + peerProxy.getViewManager().getCurrentViewF() + 1) / 2.0); -// -// if (replyCount >= q) { -// peerProxy.cleanAsynchRequest(context.getOperationId()); -// messageHandle.complete(reply.getContent(), null); -// } -// } -// -// } - -// private static class BftsmartAsyncFuture extends CompletableAsyncFuture { -// @Override -// public void setSuccess(T value) { -// super.setSuccess(value); -// } -// -// @Override -// public void setError(Throwable ex) { -// super.setError(ex); -// } -// -// @Override -// public void setError(String errorCode) { -// super.setError(errorCode); -// } -// } - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClientFactory.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClientFactory.java deleted file mode 100644 index 16d8bfae..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClientFactory.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.client; - -import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consensus.ConsensusManageService; -import com.jd.blockchain.consensus.bftsmart.BftsmartClientIncomingSettings; -import com.jd.blockchain.consensus.client.ClientFactory; -import com.jd.blockchain.consensus.client.ClientSettings; -import com.jd.blockchain.consensus.client.ConsensusClient; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class BftsmartConsensusClientFactory implements ClientFactory { - - - private AtomicInteger addId = new AtomicInteger(); - - private String localDomain = "localhost"; - private String localIp = "127.0.0.1"; - - public BftsmartConsensusClientFactory() { - - } - - - @Override - public BftsmartClientIdentification buildAuthId(AsymmetricKeypair clientKeyPair) { - - PubKey pubKey = clientKeyPair.getPubKey(); - PrivKey privKey = clientKeyPair.getPrivKey(); - - SignatureFunction signatureFunction =Crypto.getSignatureFunction(pubKey.getAlgorithm()); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, pubKey.toBytes()); - - BftsmartClientIdentification bftsmartClientIdentification = new BftsmartClientIdentification(); - bftsmartClientIdentification.setIdentityInfo(pubKey.toBytes()); - bftsmartClientIdentification.setPubKey(pubKey); - bftsmartClientIdentification.setSignatureDigest(signatureDigest); - - return bftsmartClientIdentification; - } - - @Override - public ClientSettings buildClientSettings(ClientIncomingSettings incomingSettings) { - - BftsmartClientIncomingSettings clientIncomingSettings = (BftsmartClientIncomingSettings) incomingSettings; - - BftsmartClientSettings clientSettings = new BftsmartClientConfig(clientIncomingSettings); - - return clientSettings; - } - - @Override - public ConsensusClient setupClient(ClientSettings settings) { - - return new BftsmartConsensusClient(settings); - } - - @Override - public ConsensusManageService createManageServiceClient(String[] serviceNodes) { -// BftsmartConsensusManageService consensusManageService = null; -// BftsmartClientIncomingSettings clientIncomingSettings; -// -// -// try { -// if (serviceNodes == null) { -// throw new ConsensusSecurityException("createManageServiceClient param error!"); -// } -// -// for (int i = 0; i < serviceNodes.length; i++) { -// -// NetworkAddress networkAddress = getIpPortFromUrl(serviceNodes[i]); -// if (networkAddress == null) { -// continue; -// } -// ServiceEndpoint peerServer = new ServiceEndpoint(networkAddress.getHost(), networkAddress.getPort(), false); -// consensusManageService = HttpServiceAgent.createService(BftsmartConsensusManageService.class, peerServer); -// clientIncomingSettings = consensusManageService.authClientIncoming(clientIdentification); -// -// if (clientIncomingSettings == null) { -// consensusManageService = null; -// } else { -// //认证成功 -// break; -// } -// } -// -// } catch (Exception e) { -// e.printStackTrace(); -// } - -// return consensusManageService; - return null; - } - - private NetworkAddress getIpPortFromUrl(String url) { - - // 1.check null - if (url == null || url.trim().equals("")) { - return null; - } - - // 2. localhost replace to 127.0.0.1 - if(url.startsWith("http://" + localDomain) ){ - url = url.replace("http://" + localDomain, "http://" + localIp) ; - } - - String host = ""; - Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+(:\\d{0,5})?"); - Matcher matcher = p.matcher(url); - if (matcher.find()) { - host = matcher.group() ; - } - - if(host.contains(":") == false){ - //default port :80 - return new NetworkAddress(host, 80); - } - else { - String[] ipPortArr = host.split(":"); - return new NetworkAddress(ipPortArr[0], Integer.parseInt(ipPortArr[1])); - } - } - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyFactory.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyFactory.java deleted file mode 100644 index 306a71f0..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.client; - -import bftsmart.reconfiguration.util.TOMConfiguration; -import bftsmart.reconfiguration.views.MemoryBasedViewStorage; -import bftsmart.tom.AsynchServiceProxy; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusConfig; -import com.jd.blockchain.consensus.bftsmart.BftsmartTopology; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; - -import org.apache.commons.pool2.BasePooledObjectFactory; -import org.apache.commons.pool2.PooledObject; -import org.apache.commons.pool2.impl.DefaultPooledObject; - -import java.util.concurrent.atomic.AtomicInteger; - -public class BftsmartPeerProxyFactory extends BasePooledObjectFactory { - - private BftsmartClientSettings bftsmartClientSettings; - - private int gatewayId; - - private AtomicInteger index = new AtomicInteger(1); - - public BftsmartPeerProxyFactory(BftsmartClientSettings bftsmartClientSettings, int gatewayId) { - this.bftsmartClientSettings = bftsmartClientSettings; - this.gatewayId = gatewayId; - } - - @Override - public AsynchServiceProxy create() throws Exception { - - BftsmartTopology topology = BinarySerializeUtils.deserialize(bftsmartClientSettings.getTopology()); - - MemoryBasedViewStorage viewStorage = new MemoryBasedViewStorage(topology.getView()); - TOMConfiguration tomConfiguration = BinarySerializeUtils.deserialize(bftsmartClientSettings.getTomConfig()); - - //every proxy client has unique id; - tomConfiguration.setProcessId(gatewayId + index.getAndIncrement()); - AsynchServiceProxy peerProxy = new AsynchServiceProxy(tomConfiguration, viewStorage); - return peerProxy; - } - - @Override - public PooledObject wrap(AsynchServiceProxy asynchServiceProxy) { - return new DefaultPooledObject<>(asynchServiceProxy); - } -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyPool.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyPool.java deleted file mode 100644 index 1b5a5f8e..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyPool.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.bft.BftsmartConsensusClientPool - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/10/30 下午6:50 - * Description: - */ -package com.jd.blockchain.consensus.bftsmart.client; - -import bftsmart.tom.AsynchServiceProxy; -import org.apache.commons.pool2.PooledObjectFactory; -import org.apache.commons.pool2.impl.GenericObjectPool; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - -public class BftsmartPeerProxyPool extends GenericObjectPool { - - public BftsmartPeerProxyPool(PooledObjectFactory factory) { - this(factory, null); - } - - public BftsmartPeerProxyPool(PooledObjectFactory factory, GenericObjectPoolConfig config) { - super(factory, config == null ? new BftsmartPeerProxyPoolConfig() : config); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyPoolConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyPoolConfig.java deleted file mode 100644 index fb0b3884..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartPeerProxyPoolConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.bft.BftsmartConsensusClientPool - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/10/30 下午6:50 - * Description: - */ -package com.jd.blockchain.consensus.bftsmart.client; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - -public class BftsmartPeerProxyPoolConfig extends GenericObjectPoolConfig { - - public static final int MAX_TOTAL = 100; - - private final int MIN_IDLE = 0; - - private final int MAX_IDLE = 100; - - public BftsmartPeerProxyPoolConfig() { - setMaxTotal(MAX_TOTAL); - setMinIdle(MIN_IDLE); - setMaxIdle(MAX_IDLE); - } - - public BftsmartPeerProxyPoolConfig(int maxTotal, int minIdle, int maxIdle) { - setMaxTotal(maxTotal); - setMinIdle(minIdle); - setMaxIdle(maxIdle); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartConsensusManageService.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartConsensusManageService.java deleted file mode 100644 index 1e82ee0f..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartConsensusManageService.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.service; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.ConsensusManageService; -import com.jd.blockchain.consensus.bftsmart.BftsmartClientIncomingConfig; -import com.jd.blockchain.consensus.bftsmart.BftsmartClientIncomingSettings; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; - -public class BftsmartConsensusManageService implements ConsensusManageService { - - public static final int GATEWAY_SIZE = 100; - - public static final int CLIENT_SIZE_PER_GATEWAY = 1000; - - public static final int CLIENT_RANGE = GATEWAY_SIZE * CLIENT_SIZE_PER_GATEWAY; - - private BftsmartNodeServer nodeServer; - - private int clientId; - - private static final Lock authLock = new ReentrantLock(); - - public BftsmartConsensusManageService(BftsmartNodeServer nodeServer) { - this.nodeServer = nodeServer; - // Assume that each peer node corresponds to up to 100 gateways - clientId = nodeServer.getServerId() * CLIENT_RANGE; - } - - @Override - public BftsmartClientIncomingSettings authClientIncoming(ClientIdentification authId) { - if (verify(authId)) { - BftsmartClientIncomingConfig clientIncomingSettings = new BftsmartClientIncomingConfig(); - - clientIncomingSettings - .setTopology(BinarySerializeUtils.serialize(nodeServer.getTopology())); - - clientIncomingSettings - .setTomConfig(BinarySerializeUtils.serialize(nodeServer.getTomConfig())); - - clientIncomingSettings - .setConsensusSettings(nodeServer.getConsensusSetting()); - - clientIncomingSettings.setPubKey(authId.getPubKey()); - // compute gateway id - authLock.lock(); - try { - clientIncomingSettings.setClientId(clientId++); - clientId += CLIENT_SIZE_PER_GATEWAY; - } finally { - authLock.unlock(); - } - - return clientIncomingSettings; - } - - return null; - } - - public boolean verify(ClientIdentification authId) { - - SignatureFunction signatureFunction = Crypto - .getSignatureFunction(authId.getPubKey().getAlgorithm()); - - return signatureFunction.verify(authId.getSignature(), authId.getPubKey(), authId.getIdentityInfo()); - } -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartNodeServerFactory.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartNodeServerFactory.java deleted file mode 100644 index 50ffd90f..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartNodeServerFactory.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.service; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; -import com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings; -import com.jd.blockchain.consensus.service.MessageHandle; -import com.jd.blockchain.consensus.service.NodeServer; -import com.jd.blockchain.consensus.service.NodeServerFactory; -import com.jd.blockchain.consensus.service.ServerSettings; -import com.jd.blockchain.consensus.service.StateMachineReplicate; -import com.jd.blockchain.utils.net.NetworkAddress; - -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class BftsmartNodeServerFactory implements NodeServerFactory { - - private static Map nodeServerMap = new ConcurrentHashMap<>(); - - - @Override - public ServerSettings buildServerSettings(String realmName, ConsensusSettings consensusSetting, String currentNodeAddress) { - - NodeSettings serverNode = null; - - BftsmartServerSettingConfig serverSettings = new BftsmartServerSettingConfig(); - - //find current node according to current address - for (NodeSettings nodeSettings : consensusSetting.getNodes()) { - if (nodeSettings.getAddress().equals(currentNodeAddress)) { - serverNode = nodeSettings; - break; - } - } - - if (serverNode == null) { - throw new IllegalArgumentException(); - } - - //set server settings - serverSettings.setRealmName(realmName); - - serverSettings.setReplicaSettings(serverNode); - - serverSettings.setConsensusSettings((BftsmartConsensusSettings) consensusSetting); - - return serverSettings; - - } - - @Override - public NodeServer setupServer(ServerSettings serverSettings, MessageHandle messageHandler, - StateMachineReplicate stateMachineReplicator) { - - NodeSettings[] currNodeSettings = (((BftsmartServerSettings)serverSettings).getConsensusSettings()).getNodes(); - - //check conflict realm - if (!hasIntersection(currNodeSettings)) { - BftsmartNodeServer nodeServer = new BftsmartNodeServer(serverSettings, messageHandler, stateMachineReplicator); - nodeServerMap.put(serverSettings.getRealmName(), currNodeSettings); - return nodeServer; - } - else { - throw new IllegalArgumentException("setupServer serverSettings parameters error!"); - } - } - - - //check if consensus realm conflict, by this support multi ledgers - private boolean hasIntersection(NodeSettings[] currNodeSettings) { - - int currHashCode = getHashcode(currNodeSettings); - - //first check if is same consensus realm - for (NodeSettings[] exisitNodeSettings : nodeServerMap.values()) { - if (currHashCode == getHashcode(exisitNodeSettings)) { - return false; - } - } - //check conflict - for (NodeSettings[] exisitNodeSettings : nodeServerMap.values()) { - for (NodeSettings curr : currNodeSettings) { - for (NodeSettings exist : exisitNodeSettings) { - if (((BftsmartNodeSettings)curr).getNetworkAddress().equals(((BftsmartNodeSettings)exist).getNetworkAddress())) { - return true; - } - } - } - } - - return false; - } - - //compute hashcode for consensus nodes - private int getHashcode(NodeSettings[] nodeSettings) { - - int i = 0; - NetworkAddress[] nodeAddrs = new NetworkAddress[nodeSettings.length]; - for (NodeSettings setting : nodeSettings) { - - nodeAddrs[i++] = ((BftsmartNodeSettings)setting).getNetworkAddress(); - } - int hashCode = Arrays.hashCode(nodeAddrs); - return hashCode; - - } - -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartServerSettingConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartServerSettingConfig.java deleted file mode 100644 index 3b42bb0d..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartServerSettingConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.service; - -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; - -public class BftsmartServerSettingConfig implements BftsmartServerSettings { - private NodeSettings replicaSettings; - private String realmName; - private BftsmartConsensusSettings consensusSettings; - - - @Override - public String getRealmName() { - return realmName; - } - - public void setRealmName(String realmName) { - this.realmName = realmName; - } - - - @Override - public NodeSettings getReplicaSettings() { - return replicaSettings; - } - - public void setReplicaSettings(NodeSettings replicaSettings) { - this.replicaSettings = replicaSettings; - } - - - @Override - public BftsmartConsensusSettings getConsensusSettings() { - return consensusSettings; - } - - public void setConsensusSettings(BftsmartConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - } -} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartServerSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartServerSettings.java deleted file mode 100644 index f6806b96..00000000 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartServerSettings.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jd.blockchain.consensus.bftsmart.service; - -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; -import com.jd.blockchain.consensus.service.ServerSettings; - -public interface BftsmartServerSettings extends ServerSettings { - - BftsmartConsensusSettings getConsensusSettings(); - -} diff --git a/source/consensus/consensus-bftsmart/src/main/resources/bftsmart.config b/source/consensus/consensus-bftsmart/src/main/resources/bftsmart.config deleted file mode 100644 index df69caf5..00000000 --- a/source/consensus/consensus-bftsmart/src/main/resources/bftsmart.config +++ /dev/null @@ -1,144 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#Configuration of all node servers; -#PubKey of node server with specified ID, with base58 encoding. -system.server.0.pubkey= -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=8900 -system.server.0.network.secure=false - -system.server.1.pubkey= -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=8910 -system.server.1.network.secure=false - -system.server.2.pubkey= -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=8920 -system.server.2.network.secure=false - -system.server.3.pubkey= -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=8920 -system.server.3.network.secure=false diff --git a/source/consensus/consensus-bftsmart/src/test/java/test/com/jd/blockchain/consensus/bftsmart/ProxyClientTest.java b/source/consensus/consensus-bftsmart/src/test/java/test/com/jd/blockchain/consensus/bftsmart/ProxyClientTest.java deleted file mode 100644 index 3f32fd6b..00000000 --- a/source/consensus/consensus-bftsmart/src/test/java/test/com/jd/blockchain/consensus/bftsmart/ProxyClientTest.java +++ /dev/null @@ -1,137 +0,0 @@ -package test.com.jd.blockchain.consensus.bftsmart; - -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consensus.bftsmart.*; -import com.jd.blockchain.consensus.bftsmart.client.BftsmartClientConfig; -import com.jd.blockchain.consensus.bftsmart.client.BftsmartConsensusClient; -import com.jd.blockchain.consensus.bftsmart.client.BftsmartMessageService; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartNodeServer; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartServerSettingConfig; -import com.jd.blockchain.consensus.service.ServerSettings; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.utils.PropertiesUtils; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.net.NetworkAddress; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.Random; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -public class ProxyClientTest { - - int number = 1500000; - - int peerStartPort = 11000; - - int nodeNum = 4; - - Random random = new Random(); - - byte[] bytes = null; - - CountDownLatch startPeer = new CountDownLatch(nodeNum); - - private static Properties bftsmartConf; - - private final ExecutorService nodeStartPools = Executors.newCachedThreadPool(); - - private final ExecutorService txSendPools = Executors.newFixedThreadPool(20); - - static { - ClassPathResource configResource = new ClassPathResource("system.config"); - try { - try (InputStream in = configResource.getInputStream()) { - bftsmartConf = PropertiesUtils.load(in, BytesUtils.DEFAULT_CHARSET); - } - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public void peerStart(BftsmartNodeServer[] nodeServers) { - - BftsmartNodeSettings[] nodesSettings = new BftsmartNodeSettings[nodeNum]; - - for (int i = 0; i < nodeNum; i++) { - BlockchainKeypair keyPair = BlockchainKeyGenerator.getInstance().generate(); - PubKey pubKey = keyPair.getPubKey(); - NetworkAddress peerNodeServ = new NetworkAddress("127.0.0.1", peerStartPort + i * 10); - NodeSettings node = new BftsmartNodeConfig(pubKey, i, peerNodeServ); - nodesSettings[i] = (BftsmartNodeSettings) node; - } - - BftsmartConsensusConfig consensusConfig = new BftsmartConsensusConfig(nodesSettings, -// null, - PropertiesUtils.getOrderedValues(bftsmartConf)); - - for (int j = 0; j < nodeNum; j++) { - BftsmartServerSettingConfig serverSettings = new BftsmartServerSettingConfig(); - serverSettings.setReplicaSettings(nodesSettings[j]); - serverSettings.setConsensusSettings(consensusConfig); - BftsmartNodeServer server = new BftsmartNodeServer(serverSettings, null, null); - nodeServers[j] = server; - nodeStartPools.execute(() -> { - server.start(); - startPeer.countDown(); - }); - } - } - - public void proxyClientSend(BftsmartNodeServer nodeServer) { - BftsmartClientIncomingConfig clientIncomingConfig = new BftsmartClientIncomingConfig(); - BlockchainKeypair keyPair = BlockchainKeyGenerator.getInstance().generate(); - clientIncomingConfig.setPubKey(keyPair.getPubKey()); - clientIncomingConfig.setClientId(0); - clientIncomingConfig.setConsensusSettings(nodeServer.getConsensusSetting()); - clientIncomingConfig.setTomConfig(BinarySerializeUtils.serialize(nodeServer.getTomConfig())); - clientIncomingConfig.setTopology(BinarySerializeUtils.serialize(nodeServer.getTopology())); - - BftsmartClientConfig clientSettings = new BftsmartClientConfig(clientIncomingConfig); - BftsmartConsensusClient consensusClient = new BftsmartConsensusClient(clientSettings); - bytes = new byte[1024]; - - BftsmartMessageService messageService = (BftsmartMessageService) consensusClient.getMessageService(); - - for (int j = 0; j < number; j++) { - txSendPools.execute(() -> { - random.nextBytes(bytes); - messageService.sendOrdered(bytes); - }); - } - - } - -// @Test - public void sendTest() { - - BftsmartNodeServer[] nodeServers = new BftsmartNodeServer[nodeNum]; - //启动服务 - peerStart(nodeServers); - - try { - startPeer.await(); - Thread.sleep(5000); - } catch (Exception e) { - e.printStackTrace(); - } - - proxyClientSend(nodeServers[0]); - - - try { - Thread.sleep(50000); - System.out.println("send test complete!"); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/source/consensus/consensus-bftsmart/src/test/resources/bftsmart.config b/source/consensus/consensus-bftsmart/src/test/resources/bftsmart.config deleted file mode 100644 index 970ddf4b..00000000 --- a/source/consensus/consensus-bftsmart/src/test/resources/bftsmart.config +++ /dev/null @@ -1,178 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=15 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=500 - -############################################ -###### Consensus Participant0 ###### -############################################ -system.server.0.pubkey=endPsK36koyFr1D245Sa9j83vt6pZUdFBJoJRB3xAsWM6cwhRbna - -system.server.0.network.host=127.0.0.1 - -system.server.0.network.port=8910 - -system.server.0.network.secure=false - -############################################ -###### #Consensus Participant1 ###### -############################################ -system.server.1.pubkey=endPsK36sC5JdPCDPDAXUwZtS3sxEmqEhFcC4whayAsTTh8Z6eoZ - -system.server.1.network.host=127.0.0.1 - -system.server.1.network.port=8920 - -system.server.1.network.secure=false - -############################################ -###### #Consensus Participant2 ###### -############################################ -system.server.2.pubkey=endPsK36jEG281HMHeh6oSqzqLkT95DTnCM6REDURjdb2c67uR3R - -system.server.2.network.host=127.0.0.1 - -system.server.2.network.port=8930 - -system.server.2.network.secure=false - -############################################ -###### Consensus Participant3 ###### -############################################ -system.server.3.pubkey=endPsK36nse1dck4uF19zPvAMijCV336Y3zWdgb4rQG8QoRj5ktR - -system.server.3.network.host=127.0.0.1 - -system.server.3.network.port=8940 - -system.server.3.network.secure=false - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -#system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -#system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - diff --git a/source/consensus/consensus-bftsmart/src/test/resources/system.config b/source/consensus/consensus-bftsmart/src/test/resources/system.config deleted file mode 100644 index 275edc4e..00000000 --- a/source/consensus/consensus-bftsmart/src/test/resources/system.config +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -#system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -#system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncActionResponse.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncActionResponse.java deleted file mode 100644 index 992e448a..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncActionResponse.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jd.blockchain.consensus; - -public interface AsyncActionResponse { - - byte[] process(); - -} \ No newline at end of file diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncInvoker.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncInvoker.java deleted file mode 100644 index 72969da7..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncInvoker.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jd.blockchain.consensus; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -import com.jd.blockchain.utils.concurrent.AsyncFuture; - -public class AsyncInvoker { - - private static ThreadLocal> resultHolder; - - static { - resultHolder = new ThreadLocal<>(); - } - - - @SuppressWarnings("unchecked") - public static T asynchorize(Class serviceClazz, T serviceInstance) { - if (serviceInstance instanceof AsyncService) { - return (T) Proxy.newProxyInstance(serviceClazz.getClassLoader(), new Class[] { serviceClazz }, - new AsyncInvocationHandle(serviceClazz, (AsyncService) serviceInstance)); - } - throw new IllegalArgumentException("The specified service instance is not supported by this asynchronize util!"); - } - - @SuppressWarnings("unchecked") - public static AsyncFuture call(T methodCall){ - AsyncFuture result = (AsyncFuture) resultHolder.get(); - resultHolder.set(null); - return result; - } - - - - private static class AsyncInvocationHandle implements InvocationHandler { - - private Class serviceClazz; - private AsyncService serviceInstance; - - public AsyncInvocationHandle(Class serviceClazz, AsyncService serviceInstance) { - this.serviceInstance = serviceInstance; - this.serviceClazz = serviceClazz; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - resultHolder.remove(); - if (method.getDeclaringClass() == serviceClazz) { - //async invoke; - AsyncFuture asyncResult = serviceInstance.invoke(method, args); - resultHolder.set(asyncResult); - return null; - } - return method.invoke(serviceInstance, args); - } - - } -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncService.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncService.java deleted file mode 100644 index 2b113718..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/AsyncService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.consensus; - -import java.lang.reflect.Method; - -import com.jd.blockchain.utils.concurrent.AsyncFuture; - -public interface AsyncService { - - AsyncFuture invoke(Method method, Object[] args); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/BinaryMessageConverter.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/BinaryMessageConverter.java deleted file mode 100644 index 5fe2f44e..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/BinaryMessageConverter.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.consensus; - -public interface BinaryMessageConverter { - - byte[] encode(Object message); - - Object decode(byte[] messageBytes); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentification.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentification.java deleted file mode 100644 index 99b3b9a3..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentification.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; - -/** - * 客户端的身份证明; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.CLIENT_IDENTIFICATION) -public interface ClientIdentification { - - /** - * 身份信息; - * - * @return - */ - @DataField(order = 0, primitiveType = PrimitiveType.BYTES) - byte[] getIdentityInfo(); - - /** - * 客户端的公钥; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - PubKey getPubKey(); - - /** - * 客户端对认证信息的签名; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - SignatureDigest getSignature(); - - /** - * 具体实现类 - * - * @return - */ - @DataField(order = 3, primitiveType = PrimitiveType.TEXT) - String getProviderName(); -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentifications.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentifications.java deleted file mode 100644 index 7fe4aa92..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentifications.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.ClientIdentifications - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/19 下午3:58 - * Description: - */ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.consts.DataCodes; - -/** - * - * @author shaozhuguang - * @create 2018/12/19 - * @since 1.0.0 - */ -@DataContract(code = DataCodes.CLIENT_IDENTIFICATIONS) -public interface ClientIdentifications { - - @DataField(order = 0, list = true, refContract = true, genericContract = true) - ClientIdentification[] getClientIdentifications(); -} \ No newline at end of file diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentificationsProvider.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentificationsProvider.java deleted file mode 100644 index e2e83453..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentificationsProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.ClientIdentificationsProvider - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/19 下午3:59 - * Description: - */ -package com.jd.blockchain.consensus; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author shaozhuguang - * @create 2018/12/19 - * @since 1.0.0 - */ - -public class ClientIdentificationsProvider implements ClientIdentifications { - - private List clientIdentifications = new ArrayList<>(); - - public void add(ClientIdentification clientIdentification) { - clientIdentifications.add(clientIdentification); - } - - @Override - public ClientIdentification[] getClientIdentifications() { - return clientIdentifications.toArray(new ClientIdentification[clientIdentifications.size()]); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIncomingSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIncomingSettings.java deleted file mode 100644 index a879a54a..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIncomingSettings.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -/** - * 共识网络的客户接入参数; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.CONSENSUS_CLI_INCOMING_SETTINGS) -public interface ClientIncomingSettings { - - /** - * 分配的客户端ID; - * - * @return - */ - @DataField(order = 0, primitiveType = PrimitiveType.INT32) - int getClientId(); - - /** - * ProviderName - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.TEXT) - String getProviderName(); - - /** - * 共识网络的配置参数; - * - * @return - */ - @DataField(order = 2, refContract = true, genericContract = true) - ConsensusSettings getConsensusSettings(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusManageService.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusManageService.java deleted file mode 100644 index c589fc6b..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusManageService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.consensus; - -/** - * 共识节点的管理服务; - * - * @author huanghaiquan - * - */ -public interface ConsensusManageService { - - /** - * 对客户端的接入进行认证; - * - * @param authId - * 客户端的身份信息; - * @return 如果通过认证,则返回接入参数;如果认证失败,则返回 null; - */ - ClientIncomingSettings authClientIncoming(ClientIdentification authId) throws ConsensusSecurityException; - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusProvider.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusProvider.java deleted file mode 100644 index f3c41ef9..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusProvider.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.consensus.client.ConsensusClientProvider; -import com.jd.blockchain.consensus.service.ConsensusServiceProvider; - -public interface ConsensusProvider extends ConsensusClientProvider, ConsensusServiceProvider { - - String getName(); - - SettingsFactory getSettingsFactory(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusProviders.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusProviders.java deleted file mode 100644 index 58853099..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusProviders.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jd.blockchain.consensus; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.beans.BeanUtils; -import org.springframework.util.ClassUtils; - -public class ConsensusProviders { - - private static final Object mutex = new Object(); - - private static Map providers = new ConcurrentHashMap<>(); - - public static ConsensusProvider getProvider(String className) { - ConsensusProvider provider = providers.get(className); - if (provider == null) { - synchronized (mutex) { - provider = providers.get(className); - if (provider == null) { - provider = loadProvider(ConsensusProvider.class, className); -// providers.put(className, provider); - registerProvider(provider); - } - } - } - return provider; - } - - private static T loadProvider(Class assignableTo, String implementClassName) { - Class providerClass = ClassUtils.resolveClassName(implementClassName, - ConsensusProviders.class.getClassLoader()); - if (!assignableTo.isAssignableFrom(providerClass)) { - throw new IllegalArgumentException( - String.format("%s is not implement %s!", implementClassName, assignableTo.getName())); - } - return BeanUtils.instantiateClass(providerClass, assignableTo); - } - - public static void registerProvider(ConsensusProvider provider) { - providers.put(provider.getName(), provider); - } - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettings.java deleted file mode 100644 index b75996f5..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettings.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.consts.DataCodes; - -/** - * 共识网络的配置参数; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.CONSENSUS_SETTINGS) -public interface ConsensusSettings { - - /** - * 共识网络中的节点列表; - * - * @return - */ - @DataField(order = 0, refContract = true, list = true, genericContract = true) - NodeSettings[] getNodes(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettingsBuilder.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettingsBuilder.java deleted file mode 100644 index 4a58f024..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettingsBuilder.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.utils.Bytes; - -import java.util.Properties; - -public interface ConsensusSettingsBuilder { - - /** - * 从属性表中解析生成共识网络的参数配置; - * - * @param props - * 属性表; - * @param participantNodes - * 参与方列表;
- * @return - */ - ConsensusSettings createSettings(Properties props, ParticipantNode[] participantNodes); - - Bytes updateSettings(Bytes oldConsensusSettings, ParticipantInfo participantInfo); - - Properties createPropertiesTemplate(); - - void writeSettings(ConsensusSettings settings, Properties props); -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/GroupIndexer.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/GroupIndexer.java deleted file mode 100644 index 11330d16..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/GroupIndexer.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.consensus; - -/** - * @author huanghaiquan - * - */ -public interface GroupIndexer { - - byte[] getGroupId(Object[] messageObjects); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/MessageService.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/MessageService.java deleted file mode 100644 index 4740e6d9..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/MessageService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.utils.concurrent.AsyncFuture; - -public interface MessageService { - - AsyncFuture sendOrdered(byte[] message); - - AsyncFuture sendUnordered(byte[] message); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/NodeSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/NodeSettings.java deleted file mode 100644 index 1c81163f..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/NodeSettings.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; - -/** - * 节点的配置参数; - * - * @author huanghaiquan - * - */ -@DataContract(code=DataCodes.CONSENSUS_NODE_SETTINGS) -public interface NodeSettings { - - /** - * 用于标识一个节点的地址;
- * - * 该值没有一个通用定义,可以是具体的通讯地址,也可以只是标识符,或者区块链地址,而是由特定的共识服务提供者的实现进行定义; - * - * @return - */ - @DataField(order=0, primitiveType=PrimitiveType.TEXT) - String getAddress(); - - /** - * Base58 格式的公钥; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - PubKey getPubKey(); -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/SettingsFactory.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/SettingsFactory.java deleted file mode 100644 index 449e39fa..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/SettingsFactory.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.consensus; - -import com.jd.blockchain.utils.io.BytesEncoder; - -/** - * 配置参数的编码器; - * - * @author huanghaiquan - * - */ -public interface SettingsFactory { - - ConsensusSettingsBuilder getConsensusSettingsBuilder(); - - BytesEncoder getConsensusSettingsEncoder(); - - BytesEncoder getIncomingSettingsEncoder(); - - - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/Topology.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/Topology.java deleted file mode 100644 index dbb2fd3b..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/Topology.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.consensus; - -import java.io.Serializable; - -public interface Topology extends Serializable { - int getId(); - - Topology copyOf(); -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequest.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequest.java deleted file mode 100644 index 731ffef7..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.consensus.action; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code= DataCodes.CONSENSUS_ACTION_REQUEST) -public interface ActionRequest { - - @DataField(order=1, list=true, primitiveType= PrimitiveType.INT8) - byte[] getGroupId(); - - @DataField(order=2, primitiveType=PrimitiveType.TEXT) - String getHandleType(); - - @DataField(order=3, primitiveType=PrimitiveType.TEXT) - String getHandleMethod(); - -// String getMessageType(); - - @DataField(order=4, list=true, primitiveType= PrimitiveType.INT8) - byte[] getMessageBody(); - - @DataField(order=5, primitiveType= PrimitiveType.TEXT) - String getTransactionType(); - -// String getReponseType(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequestData.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequestData.java deleted file mode 100644 index aa1514bb..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequestData.java +++ /dev/null @@ -1,60 +0,0 @@ -//package com.jd.blockchain.consensus.action; -// -//public class ActionRequestData implements ActionRequest{ -// -// private byte[] groupId; -// -// private String handleType; -// -// private String handleMethod; -// -// private byte[] messageBody; -// -// private String transactionType; -// -// @Override -// public byte[] getGroupId() { -// return groupId; -// } -// -// @Override -// public String getHandleType() { -// return handleType; -// } -// -// @Override -// public String getHandleMethod() { -// return handleMethod; -// } -// -// @Override -// public byte[] getMessageBody() { -// return messageBody; -// } -// -// @Override -// public String getTransactionType() { -// return transactionType; -// } -// -// public void setGroupId(byte[] groupId) { -// this.groupId = groupId; -// } -// -// public void setHandleType(String handleType) { -// this.handleType = handleType; -// } -// -// public void setHandleMethod(String handleMethod) { -// this.handleMethod = handleMethod; -// } -// -// public void setMessageBody(byte[] messageBody) { -// this.messageBody = messageBody; -// } -// -// public void setTransactionType(String transactionType) { -// this.transactionType = transactionType; -// } -// -//} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponse.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponse.java deleted file mode 100644 index 5e35e911..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponse.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.consensus.action; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code= DataCodes.CONSENSUS_ACTION_RESPONSE) -public interface ActionResponse { - - @DataField(order=1, list=true, primitiveType= PrimitiveType.INT8) - byte[] getMessage(); - - @DataField(order=2, primitiveType=PrimitiveType.BOOLEAN) - boolean getError(); - - @DataField(order=3, primitiveType=PrimitiveType.TEXT) - String getErrorMessage(); - - @DataField(order=4, primitiveType=PrimitiveType.TEXT) - String getErrorType(); - -} \ No newline at end of file diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientFactory.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientFactory.java deleted file mode 100644 index 57fc2dd3..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jd.blockchain.consensus.client; - -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consensus.ConsensusManageService; -import com.jd.blockchain.crypto.AsymmetricKeypair; - -public interface ClientFactory { - - /** - * 创建客户端的认证身份; - * - * @param clientKeyPair - * @return - */ - ClientIdentification buildAuthId(AsymmetricKeypair clientKeyPair); - - /** - * 根据接入配置信息创建客户端的本地连接配置; - * - * @param incomingSettings - * @return - */ - ClientSettings buildClientSettings(ClientIncomingSettings incomingSettings); - - /** - * 创建共识管理服务的客户端代理;
- * - * 当一个共识网络的节点启动共识服务之后,其中的一些或者全部节点会暴露一个专门的管理服务端口,用于提供客户端接入认证服务和新节点接入认证服务; - * - *
- * - * 作为客户端,可以选择其中的一个或者多个节点的管理服务端口进行接入认证;
- * - * 不同的共识算法可以自行决定实现不同的连接策略,例如:从参数指定的地址列表中随机挑选一个可成功建立连接的节点,或者同时连接多个以进行客户端交叉验证; - * - * @param serviceNodes - * @return - */ - ConsensusManageService createManageServiceClient(String[] serviceNodes); - - /** - * 根据共识客户端的配置信息建立一个共识客户端实例; - * - * @param settings - * @return - */ - ConsensusClient setupClient(ClientSettings settings); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientSettings.java deleted file mode 100644 index 9c4fa89f..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientSettings.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.consensus.client; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.PubKey; - -/** - * 共识客户端的配置参数; - * - * @author huanghaiquan - * - */ -public interface ClientSettings { - - /** - * 客户端ID; - * - * @return - */ - int getClientId(); - - /** - * 客户端的公钥; - * - * @return - */ - PubKey getClientPubKey(); - - /** - * 共识网络的配置参数; - * - * @return - */ - ConsensusSettings getConsensusSettings(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ConsensusClient.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ConsensusClient.java deleted file mode 100644 index 7e41f1d4..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ConsensusClient.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.consensus.client; - -import java.io.Closeable; - -import com.jd.blockchain.consensus.MessageService; - -public interface ConsensusClient extends Closeable { - - /** - * 消息服务; - * - * @return - */ - MessageService getMessageService(); - - /** - * 共识客户端的配置信息; - * - * @return - */ - ClientSettings getSettings(); - - /** - * 是否已连接; - * - * @return - */ - boolean isConnected(); - - /** - * 接入共识网络; - */ - void connect(); - - /** - * 断开与共识网络的连接; - */ - @Override - void close(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ConsensusClientProvider.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ConsensusClientProvider.java deleted file mode 100644 index fe1c2c54..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ConsensusClientProvider.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.consensus.client; - -import com.jd.blockchain.consensus.SettingsFactory; - -public interface ConsensusClientProvider { - - - ClientFactory getClientFactory(); -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/event/EventEntity.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/event/EventEntity.java deleted file mode 100644 index e93ccd9b..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/event/EventEntity.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: EventEntity - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午11:18 - * Description: - */ -package com.jd.blockchain.consensus.event; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class EventEntity { - - private T entity; - - public T getEntity() { - return this.entity; - } - - public void setEntity(T entity) { - this.entity = entity; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/event/EventProducer.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/event/EventProducer.java deleted file mode 100644 index baa5e0a3..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/event/EventProducer.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.exchange.EventProducer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午11:15 - * Description: - */ -package com.jd.blockchain.consensus.event; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public interface EventProducer { - - public void publish(T t); -} \ No newline at end of file diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/ConsensusServiceProvider.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/ConsensusServiceProvider.java deleted file mode 100644 index 8feea616..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/ConsensusServiceProvider.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jd.blockchain.consensus.service; - -public interface ConsensusServiceProvider { - - NodeServerFactory getServerFactory(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/MessageHandle.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/MessageHandle.java deleted file mode 100644 index e864d2d0..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/MessageHandle.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.jd.blockchain.consensus.service; - -import com.jd.blockchain.utils.concurrent.AsyncFuture; - -/** - * 消息处理器; - * - * @author huanghaiquan - * - */ -public interface MessageHandle { - - /** - * 开始一个新批次来处理有序的消息; - * - * @return 返回新批次的 ID ; - */ - String beginBatch(String realmName); - - /** - * 处理有序的消息; - * - * @param messageId - * 消息ID; - * @param message - * 消息内容; - * @param batchId - * 批次ID; - */ - AsyncFuture processOrdered(int messageId, byte[] message, String realmName, String batchId); - - /** - * 完成处理批次,返回要进行一致性校验的状态快照; - * - * @param batchId - * @return - */ - StateSnapshot completeBatch(String realmName, String batchId); - - /** - * 提交处理批次; - * - * @param batchId - */ - void commitBatch(String realmName, String batchId); - - /** - * 回滚处理批次; - * - * @param batchId - */ - void rollbackBatch(String realmName, String batchId, int reasonCode); - - /** - * 处理无序消息; - * - * @param message - * @return - */ - AsyncFuture processUnordered(byte[] message); - - /** - * 获得当前最新区块的状态快照 - * - * @param realmName - * @return 最新区块的状态快照 - */ - StateSnapshot getStateSnapshot(String realmName); - - /** - * 获得创世区块的状态快照 - * @param realmName - * @return 创世区块的状态快照 - */ - StateSnapshot getGenisStateSnapshot(String realmName); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/NodeServer.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/NodeServer.java deleted file mode 100644 index 8fb50f2d..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/NodeServer.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jd.blockchain.consensus.service; - -import com.jd.blockchain.consensus.ConsensusManageService; - -public interface NodeServer { - - String getProviderName(); - - ConsensusManageService getManageService(); - - ServerSettings getSettings(); - - boolean isRunning(); - - void start(); - - void stop(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/NodeServerFactory.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/NodeServerFactory.java deleted file mode 100644 index 67e60d22..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/NodeServerFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jd.blockchain.consensus.service; - -import com.jd.blockchain.consensus.ConsensusSettings; - -/** - * 共识节点服务器的工厂; - * - * @author huanghaiquan - * - */ -public interface NodeServerFactory { - - /** - * 构建一个共识节点的参数配置; - * - * @param realmName - * 共识域的名称; - * @param consensusSetting - * 共识配置; - * @param currentNodeAddress - * 共识节点的虚拟地址;必须是 {@link ConsensusSettings#getNodes()} 中的一项; - * @return 共识节点的参数配置; - */ - ServerSettings buildServerSettings(String realmName, ConsensusSettings consensusSetting, String currentNodeAddress); - - /** - * 创建一个节点服务器; - * - * @param serverSettings - * 服务器配置; - * @param messageHandler - * @param stateMachineReplicator - * @return - */ - NodeServer setupServer(ServerSettings serverSettings, MessageHandle messageHandler, - StateMachineReplicate stateMachineReplicator); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/ServerSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/ServerSettings.java deleted file mode 100644 index 14454a72..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/ServerSettings.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.consensus.service; - -import com.jd.blockchain.consensus.NodeSettings; - -/** - * Replica 服务器的本地配置; - * - * @author huanghaiquan - * - */ -public interface ServerSettings { - - String getRealmName(); - - NodeSettings getReplicaSettings(); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateHandle.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateHandle.java deleted file mode 100644 index b0aca23f..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateHandle.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.consensus.service; - -public interface StateHandle { - - byte[] takeSnapshot(); - - void installSnapshot(byte[] snapshot); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateMachineReplicate.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateMachineReplicate.java deleted file mode 100644 index a9929c0b..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateMachineReplicate.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.consensus.service; - -import java.io.InputStream; -import java.util.Iterator; - -/** - * 状态机复制接口; - * - * @author huanghaiquan - * - */ -public interface StateMachineReplicate { - - /** - * 获取最新的状态编号;
- * - * 注:新的状态编号总数比旧的状态编号大; - * - * @return - */ - long getLatestStateID(String realmName); - - /** - * 返回指定状态编号的快照; - * - * @param stateId - * @return - */ - StateSnapshot getSnapshot(String realmName, long stateId); - - /** - * 返回包含指定的起止状态编号在内的全部状态快照; - * - * @param fromStateId - * 起始的状态编号(含); - * @param toStateId - * 截止的状态编号(含); - * @return - */ - Iterator getSnapshots(String realmName, long fromStateId, long toStateId); - - /** - * 读状态数据; - * - * @param stateId - * @return - */ - InputStream readState(String realmName, long stateId); - - /** - * 装载状态数据; - * - * @param snapshot - * @param state - */ - void setupState(String realmName, StateSnapshot snapshot, InputStream state); - -} diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateSnapshot.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateSnapshot.java deleted file mode 100644 index 883e4e03..00000000 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/service/StateSnapshot.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.consensus.service; - -/** - * 状态快照; - * - * @author huanghaiquan - * - */ -public interface StateSnapshot { - - /** - * 状态的唯一编号; - * - * @return - */ - long getId(); - - /** - * 状态的快照数据; - * - * @return - */ - byte[] getSnapshot(); -} diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusProvider.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusProvider.java deleted file mode 100644 index 4bd555ce..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusProvider.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/18 下午2:50 - * Description: - */ -package com.jd.blockchain.consensus.mq; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.SettingsFactory; -import com.jd.blockchain.consensus.client.ClientFactory; -import com.jd.blockchain.consensus.mq.client.MsgQueueClientFactory; -import com.jd.blockchain.consensus.mq.config.MsgQueueSettingsFactory; -import com.jd.blockchain.consensus.mq.server.MsgQueueNodeServerFactory; -import com.jd.blockchain.consensus.service.NodeServerFactory; - -/** - * - * @author shaozhuguang - * @create 2018/12/18 - * @since 1.0.0 - */ - -public class MsgQueueConsensusProvider implements ConsensusProvider { - - public static final String NAME = MsgQueueConsensusProvider.class.getName(); - - private static MsgQueueSettingsFactory settingsFactory = new MsgQueueSettingsFactory(); - - private static MsgQueueClientFactory clientFactory = new MsgQueueClientFactory(); - - private static MsgQueueNodeServerFactory nodeServerFactory = new MsgQueueNodeServerFactory(); - - @Override - public String getName() { - return NAME; - } - - @Override - public SettingsFactory getSettingsFactory() { - return settingsFactory; - } - - @Override - public ClientFactory getClientFactory() { - return clientFactory; - } - - @Override - public NodeServerFactory getServerFactory() { - return nodeServerFactory; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java deleted file mode 100644 index 448955c8..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java +++ /dev/null @@ -1,301 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.MsgQueueConsensusSettingsBuilder - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午1:46 - * Description: - */ -package com.jd.blockchain.consensus.mq; - -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.ConsensusSettingsBuilder; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consensus.mq.config.MsgQueueBlockConfig; -import com.jd.blockchain.consensus.mq.config.MsgQueueConsensusConfig; -import com.jd.blockchain.consensus.mq.config.MsgQueueNetworkConfig; -import com.jd.blockchain.consensus.mq.config.MsgQueueNodeConfig; -import com.jd.blockchain.consensus.mq.settings.MsgQueueBlockSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.PropertiesUtils; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesEncoder; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import org.springframework.core.io.ClassPathResource; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueConsensusSettingsBuilder implements ConsensusSettingsBuilder { - - private static final String DEFAULT_TOPIC_TX = "tx-topic"; - - private static final String DEFAULT_TOPIC_BL = "bl-topic"; - - private static final String DEFAULT_TOPIC_MSG = "msg-topic"; - - private static final int DEFAULT_TXSIZE = 1000; - - private static final int DEFAULT_MAXDELAY = 1000; - - /** - * - */ - private static final String CONFIG_TEMPLATE_FILE = "mq.config"; - - /** - * 参数键:节点数量; - */ - public static final String SERVER_NUM_KEY = "system.servers.num"; - - /** - * 参数键格式:节点公钥; - */ - public static final String PUBKEY_PATTERN = "system.server.%s.pubkey"; - - public static final String MSG_QUEUE_SERVER = "system.msg.queue.server"; - - public static final String MSG_QUEUE_TOPIC_TX = "system.msg.queue.topic.tx"; - - public static final String MSG_QUEUE_TOPIC_BL = "system.msg.queue.topic.bl"; - - public static final String MSG_QUEUE_TOPIC_MSG = "system.msg.queue.topic.msg"; - - public static final String MSG_QUEUE_BLOCK_TXSIZE = "system.msg.queue.block.txsize"; - - public static final String MSG_QUEUE_BLOCK_MAXDELAY = "system.msg.queue.block.maxdelay"; - - public static final String MSG_QUEUE_PROVIDER = "com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider"; - - private static Properties CONFIG_TEMPLATE; - - static { - if (FileUtils.existFile(CONFIG_TEMPLATE_FILE)) { - ClassPathResource configResource = new ClassPathResource(CONFIG_TEMPLATE_FILE); - try { - try (InputStream in = configResource.getInputStream()) { - CONFIG_TEMPLATE = PropertiesUtils.load(in, BytesUtils.DEFAULT_CHARSET); - } - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - @Override - public MsgQueueConsensusSettings createSettings(Properties props, ParticipantNode[] participantNodes) { - MsgQueueNetworkConfig networkConfig = new MsgQueueNetworkConfig(); - Properties resolvingProps = PropertiesUtils.cloneFrom(props); - - String server = PropertiesUtils.getProperty(resolvingProps, MSG_QUEUE_SERVER, true); - if (server == null || server.length()<= 0) { - throw new IllegalArgumentException(String.format("Property[%s] is empty!", MSG_QUEUE_SERVER)); - } - networkConfig.setServer(server) - .setTxTopic(initProp(resolvingProps, MSG_QUEUE_TOPIC_TX, DEFAULT_TOPIC_TX)) - .setBlTopic(initProp(resolvingProps, MSG_QUEUE_TOPIC_BL, DEFAULT_TOPIC_BL)) - .setMsgTopic(initProp(resolvingProps, MSG_QUEUE_TOPIC_MSG, DEFAULT_TOPIC_MSG)) - ; - - MsgQueueBlockConfig blockConfig = new MsgQueueBlockConfig() - .setTxSizePerBlock(initProp(resolvingProps, MSG_QUEUE_BLOCK_TXSIZE, DEFAULT_TXSIZE)) - .setMaxDelayMilliSecondsPerBlock(initProp(resolvingProps, MSG_QUEUE_BLOCK_MAXDELAY, DEFAULT_MAXDELAY)) - ; - - MsgQueueConsensusConfig consensusConfig = new MsgQueueConsensusConfig() - .setBlockSettings(blockConfig) - .setNetworkSettings(networkConfig) - ; - // load node settings - int serversNum = PropertiesUtils.getInt(resolvingProps, SERVER_NUM_KEY); - for (int i = 0; i < serversNum; i++) { - int id = i; - - String keyOfPubkey = nodeKey(PUBKEY_PATTERN, id); - - String base58PubKey = PropertiesUtils.getRequiredProperty(resolvingProps, keyOfPubkey); - PubKey pubKey = KeyGenUtils.decodePubKey(base58PubKey); - -// PubKey pubKey = new PubKey(Base58Utils.decode(base58PubKey)); - resolvingProps.remove(keyOfPubkey); - Bytes address = AddressEncoding.generateAddress(pubKey); - - String networkAddress = address.toBase58(); - MsgQueueNodeConfig nodeConfig = new MsgQueueNodeConfig() - .setAddress(networkAddress) - .setPubKey(pubKey) - ; - consensusConfig.addNodeSettings(nodeConfig); - } - return consensusConfig; - } - - private MsgQueueNodeSettings[] nodeSettings(NodeSettings[] nodeSettings, ParticipantInfo participantInfo) { - - MsgQueueNodeSettings msgQueueNodeSettings = new MsgQueueNodeConfig(); - ((MsgQueueNodeConfig) msgQueueNodeSettings).setAddress(AddressEncoding.generateAddress(participantInfo.getPubKey()).toBase58()); - ((MsgQueueNodeConfig) msgQueueNodeSettings).setPubKey(participantInfo.getPubKey()); - - MsgQueueNodeSettings[] msgQueuetNodeSettings = new MsgQueueNodeSettings[nodeSettings.length + 1]; - for (int i = 0; i < nodeSettings.length; i++) { - msgQueuetNodeSettings[i] = (MsgQueueNodeSettings)nodeSettings[i]; - } - msgQueuetNodeSettings[nodeSettings.length] = msgQueueNodeSettings; - - return msgQueuetNodeSettings; - } - - @Override - public Bytes updateSettings(Bytes oldConsensusSettings, ParticipantInfo participantInfo) { - - BytesEncoder consensusEncoder = ConsensusProviders.getProvider(MSG_QUEUE_PROVIDER).getSettingsFactory().getConsensusSettingsEncoder(); - - MsgQueueConsensusSettings consensusSettings = (MsgQueueConsensusSettings) consensusEncoder.decode(oldConsensusSettings.toBytes()); - - MsgQueueNodeSettings[] nodeSettings = nodeSettings(consensusSettings.getNodes(), participantInfo); - - MsgQueueConsensusConfig msgQueueConsensusConfig = new MsgQueueConsensusConfig(); - for (int i = 0; i < nodeSettings.length; i++) { - msgQueueConsensusConfig.addNodeSettings(nodeSettings[i]); - } - - msgQueueConsensusConfig.setBlockSettings(consensusSettings.getBlockSettings()); - - msgQueueConsensusConfig.setNetworkSettings(consensusSettings.getNetworkSettings()); - - -// for(int i = 0 ;i < msgQueueConsensusConfig.getNodes().length; i++) { -// System.out.printf("node addr = %s\r\n", msgQueueConsensusConfig.getNodes()[i].getAddress()); -// } - - return new Bytes(consensusEncoder.encode(msgQueueConsensusConfig)); - - } - - @Override - public Properties createPropertiesTemplate() { - return PropertiesUtils.cloneFrom(CONFIG_TEMPLATE); - } - - @Override - public void writeSettings(ConsensusSettings settings, Properties props) { - - if (!(settings instanceof MsgQueueConsensusSettings)) { - throw new IllegalArgumentException("ConsensusSettings data isn't supported! Accept MsgQueueConsensusSettings only!"); - } - - MsgQueueConsensusSettings consensusSettings = (MsgQueueConsensusSettings) settings; - - MsgQueueNetworkSettings networkSettings = consensusSettings.getNetworkSettings(); - if (networkSettings == null || networkSettings.getServer() == null || networkSettings.getServer().length() <= 0) { - throw new IllegalArgumentException("MsgQueue Consensus server is empty!"); - } - - String server = networkSettings.getServer(); - props.setProperty(MSG_QUEUE_SERVER, server); - - String txTopic = networkSettings.getTxTopic(); - if (txTopic == null || txTopic.length() <= 0) { - txTopic = DEFAULT_TOPIC_TX; - } - props.setProperty(MSG_QUEUE_TOPIC_TX, txTopic); - - String blTopic = networkSettings.getBlTopic(); - if (blTopic == null || blTopic.length() <= 0) { - blTopic = DEFAULT_TOPIC_BL; - } - props.setProperty(MSG_QUEUE_TOPIC_BL, blTopic); - - String msgTopic = networkSettings.getMsgTopic(); - if (msgTopic == null || msgTopic.length() <= 0) { - msgTopic = DEFAULT_TOPIC_MSG; - } - props.setProperty(MSG_QUEUE_TOPIC_MSG, msgTopic); - - MsgQueueBlockSettings blockSettings = consensusSettings.getBlockSettings(); - if (blockSettings == null) { - props.setProperty(MSG_QUEUE_BLOCK_TXSIZE, DEFAULT_TXSIZE + ""); - props.setProperty(MSG_QUEUE_BLOCK_MAXDELAY, DEFAULT_MAXDELAY + ""); - } else { - int txSize = blockSettings.getTxSizePerBlock(); - long maxDelay = blockSettings.getMaxDelayMilliSecondsPerBlock(); - props.setProperty(MSG_QUEUE_BLOCK_TXSIZE, txSize + ""); - props.setProperty(MSG_QUEUE_BLOCK_MAXDELAY, maxDelay + ""); - } - - -// int serversNum = PropertiesUtils.getInt(props, SERVER_NUM_KEY); -// if (serversNum > 0) { -// for (int i = 0; i < serversNum; i++) { -// int id = i; -// String keyOfPubkey = nodeKey(PUBKEY_PATTERN, id); -// props.remove(keyOfPubkey); -// -// String keyOfHost = nodeKey(CONSENSUS_HOST_PATTERN, id); -// props.remove(keyOfHost); -// } -// } -// -// NodeSettings[] nodesSettings = consensusSettings.getNodes(); -// serversNum = nodesSettings.length; -// props.setProperty(SERVER_NUM_KEY, serversNum + ""); -// -// for (int i = 0; i < serversNum; i++) { -// MsgQueueNodeSettings mqns = (MsgQueueNodeSettings) nodesSettings[i]; -// int id = i; -// String keyOfPubkey = nodeKey(PUBKEY_PATTERN, id); -// props.setProperty(keyOfPubkey, mqns.getPubKey().toBase58()); -// -// String keyOfHost = nodeKey(CONSENSUS_HOST_PATTERN, id); -// props.setProperty(keyOfHost, mqns.getAddress() == null ? "" : mqns.getAddress()); -// } - } - - private String initProp(Properties resolvingProps, String key, String defaultVal) { - try { - String value = PropertiesUtils.getProperty(resolvingProps, key, true); - if (value == null || value.length() <= 0) { - value = defaultVal; - } - return value; - } catch (Exception e) { - return defaultVal; - } - } - - private int initProp(Properties resolvingProps, String key, int defaultVal) { - try { - int value = PropertiesUtils.getInt(resolvingProps, key); - if (value <= 0) { - value = defaultVal; - } - return value; - } catch (Exception e) { - return defaultVal; - } - } - - private static String nodeKey(String pattern, int id) { - return String.format(pattern, id); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/DefaultMessageTransmitter.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/DefaultMessageTransmitter.java deleted file mode 100644 index 61333cfc..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/DefaultMessageTransmitter.java +++ /dev/null @@ -1,311 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.client.DefaultMessageTransmitter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午3:05 - * Description: - */ -package com.jd.blockchain.consensus.mq.client; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.lmax.disruptor.EventHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jd.blockchain.consensus.MessageService; -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.event.TxBlockedEvent; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.consensus.mq.util.MessageConvertUtil; -import com.jd.blockchain.utils.concurrent.AsyncFuture; -import com.jd.blockchain.utils.concurrent.CompletableAsyncFuture; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class DefaultMessageTransmitter implements MessageTransmitter, MessageService { - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageTransmitter.class); - - private final ExecutorService messageExecutorArray = Executors.newFixedThreadPool(10); - -// private final ExecutorService blockExecutor = Executors.newSingleThreadExecutor(); -// -// private final ExecutorService extendExecutor = Executors.newSingleThreadExecutor(); - - private final Map messageListeners = new ConcurrentHashMap<>(); - - private final BlockEventHandler blockEventHandler = new BlockEventHandler(); - - private final ExtendEventHandler extendEventHandler = new ExtendEventHandler(); - - private MsgQueueProducer txProducer; - - private MsgQueueProducer msgProducer; - - private MsgQueueConsumer blConsumer; - - private MsgQueueConsumer msgConsumer; - - private boolean isConnected = false; - - public DefaultMessageTransmitter setTxProducer(MsgQueueProducer txProducer) { - this.txProducer = txProducer; - return this; - } - - public DefaultMessageTransmitter setMsgProducer(MsgQueueProducer msgProducer) { - this.msgProducer = msgProducer; - return this; - } - - public DefaultMessageTransmitter setBlConsumer(MsgQueueConsumer blConsumer) { - this.blConsumer = blConsumer; - return this; - } - - public DefaultMessageTransmitter setMsgConsumer(MsgQueueConsumer msgConsumer) { - this.msgConsumer = msgConsumer; - return this; - } - - @Override - public AsyncFuture sendOrdered(byte[] message) { - - AsyncFuture messageFuture; - - try { - publishMessage(txProducer, message); - messageFuture = messageHandle(message); - } catch (Exception e) { - throw new RuntimeException(e); - } - return messageFuture; - } - - @Override - public AsyncFuture sendUnordered(byte[] message) { - AsyncFuture messageFuture; - try { - publishMessage(msgProducer, message); - messageFuture = messageHandle(message); - } catch (Exception e) { - throw new RuntimeException(e); - } - return messageFuture; - } - - @Override - public void connect() throws Exception{ - if (!isConnected) { - this.txProducer.connect(); - this.blConsumer.connect(blockEventHandler); - this.msgProducer.connect(); - this.msgConsumer.connect(extendEventHandler); - isConnected = true; - blConsumer.start(); - msgConsumer.start(); -// blockConsumerListening(); -// extendConsumerListening(); - } - } - - @Override - public void publishMessage(MsgQueueProducer producer, byte[] message) throws Exception { - producer.publish(message); - } - - @Override - public void close() { - try { - txProducer.close(); - blConsumer.close(); - msgProducer.close(); - msgConsumer.close(); - isConnected = false; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private AsyncFuture messageHandle(byte[] message) throws Exception { -// 异步回调 -// 需要监听MQ结块的应答 -// 首先需要一个Consumer,在子类已实现 - String messageKey = messageKey(message); - AsyncFuture messageFuture = registerMessageListener(messageKey); - return messageFuture; - } - - private String messageKey(byte[] message) { - return MessageConvertUtil.messageKey(message); - } - - private AsyncFuture registerMessageListener(String messageKey) { - CompletableAsyncFuture future = new CompletableAsyncFuture<>(); - MessageListener messageListener = new MessageListener(messageKey, future); - messageListener.addListener(); - return future; - } - -// private void blockConsumerListening() { -// // 区块事件由单独一个线程处理 -// blockExecutor.execute(() -> { -// while(isConnected) { -// try { -// byte[] txBlockedEventBytes = blConsumer.start(); -// // 交由事件处理机制来处理 -// if (txBlockedEventBytes != null && txBlockedEventBytes.length > 0) { -// txBlockedEventHandle(txBlockedEventBytes); -// } -// } catch (Exception e) { -// LOGGER.error("process block listening message exception {}", e.getMessage()); -// } -// } -// }); -// } - -// private void extendConsumerListening() { -// extendExecutor.execute(() -> { -// while (isConnected) { -// try { -// byte[] msgBytes = msgConsumer.start(); -// // 交由事件处理机制来处理 -// if (msgBytes != null && msgBytes.length > 0) { -// extendMessageHandle(msgBytes); -// } -// } catch (Exception e) { -// LOGGER.error("process extend listening message exception {}", e.getMessage()); -// } -// } -// }); -// } - - private void txBlockedEventHandle(byte[] bytes) { - messageExecutorArray.execute(() -> { - if (!this.messageListeners.isEmpty()) { - // 首先将字节数组转换为BlockEvent - final TxBlockedEvent txBlockedEvent = - MessageConvertUtil.convertBytes2TxBlockedEvent(bytes); - if (txBlockedEvent != null) { - // 需要判断该区块是否需要处理 - if (isTxBlockedEventNeedManage(txBlockedEvent)) { - dealTxBlockedEvent(txBlockedEvent); - } - } - } - }); - } - - private void extendMessageHandle(byte[] message) { - messageExecutorArray.execute(() -> { - String messageKey = messageKey(message); - if (messageListeners.containsKey(messageKey)) { - dealExtendMessage(messageKey, message); - } - }); - } - - private boolean isTxBlockedEventNeedManage(final TxBlockedEvent txBlockedEvent) { - if (this.messageListeners.isEmpty()) { - return false; - } - if (messageListeners.containsKey(txBlockedEvent.getTxKey())) { - return true; - } - // 无须处理区块高度 - return false; - } - - private void dealTxBlockedEvent(final TxBlockedEvent txBlockedEvent) { - String txKey = txBlockedEvent.getTxKey(); - MessageListener txListener = this.messageListeners.get(txKey); - if (txListener != null) { - txListener.received(txBlockedEvent); - this.messageListeners.remove(txKey); - } - } - - private void dealExtendMessage(final String messageKey, final byte[] message) { - MessageListener txListener = this.messageListeners.get(messageKey); - if (txListener != null) { - txListener.received(message); - this.messageListeners.remove(messageKey); - } - } - - private class MessageListener { - - final String messageKey; - - final CompletableAsyncFuture future; - - final AtomicBoolean isDeal = new AtomicBoolean(false); - - public MessageListener(String messageKey, CompletableAsyncFuture future) { - this.messageKey = messageKey; - this.future = future; - addListener(); - } - - public void addListener() { - synchronized (messageListeners) { - messageListeners.put(messageKey, this); - } - } - - public void received(final TxBlockedEvent txBlockedEvent) { - // 期望是false,假设是false则设置为true,成功的情况下表示是第一次 - byte[] txResp = txBlockedEvent.txResponseBytes(); - if (txResp != null) { - if (isDeal.compareAndSet(false, true)) { - //生成对应的交易应答 - future.complete(txResp); - } - } - } - - public void received(final byte[] message) { - // 期望是false,假设是false则设置为true,成功的情况下表示是第一次 - if (message != null) { - if (isDeal.compareAndSet(false, true)) { - //生成对应的交易应答 - future.complete(message); - } - } - } - } - - public class BlockEventHandler implements EventHandler> { - - @Override - public void onEvent(EventEntity event, long sequence, boolean endOfBatch) throws Exception { - byte[] txBlockedEventBytes = event.getEntity(); - if (txBlockedEventBytes != null && txBlockedEventBytes.length > 0) { - txBlockedEventHandle(txBlockedEventBytes); - } - } - } - - public class ExtendEventHandler implements EventHandler> { - - @Override - public void onEvent(EventEntity event, long sequence, boolean endOfBatch) throws Exception { - byte[] msgBytes = event.getEntity(); - if (msgBytes != null && msgBytes.length > 0) { - extendMessageHandle(msgBytes); - } - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MessageTransmitter.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MessageTransmitter.java deleted file mode 100644 index 73c574e0..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MessageTransmitter.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.client.MessageTransmitter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:21 - * Description: - */ -package com.jd.blockchain.consensus.mq.client; - - -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public interface MessageTransmitter { - - void connect() throws Exception; - - void publishMessage(MsgQueueProducer producer, byte[] message) throws Exception; - -// void processMsg(byte[] message); - - void close(); -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientFactory.java deleted file mode 100644 index 227a0d78..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientFactory.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.client.MsgQueueClientFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:23 - * Description: - */ -package com.jd.blockchain.consensus.mq.client; - -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consensus.ConsensusManageService; -import com.jd.blockchain.consensus.client.ClientFactory; -import com.jd.blockchain.consensus.client.ClientSettings; -import com.jd.blockchain.consensus.mq.config.MsgQueueClientConfig; -import com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueClientSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueClientFactory implements ClientFactory { - - @Override - public MsgQueueClientIdentification buildAuthId(AsymmetricKeypair clientKeyPair) { - PubKey pubKey = clientKeyPair.getPubKey(); - byte[] address = pubKey.toBytes(); // 使用公钥地址作为认证信息 - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(pubKey.getAlgorithm()); - SignatureDigest signatureDigest = signatureFunction.sign(clientKeyPair.getPrivKey(), address); - - MsgQueueClientIdentification mqci = new MsgQueueClientIdentification() - .setPubKey(clientKeyPair.getPubKey()) - .setIdentityInfo(address) - .setSignature(signatureDigest) - ; - return mqci; - } - - @Override - public MsgQueueClientSettings buildClientSettings(ClientIncomingSettings incomingSettings) { - - MsgQueueClientIncomingSettings mqcic = (MsgQueueClientIncomingSettings)incomingSettings; - if (mqcic != null) { - return buildClientSettings(mqcic.getClientId(), mqcic.getPubKey(), (MsgQueueConsensusSettings)(mqcic.getConsensusSettings())); - } - throw new IllegalArgumentException("ClientIncomingSettings data isn't supported! Accept MsgQueueClientIncomingSettings only!"); - } - - private MsgQueueClientSettings buildClientSettings(int clientId, PubKey pubKey, MsgQueueConsensusSettings mqcs) { - - MsgQueueClientSettings msgQueueClientConfig = new MsgQueueClientConfig() - .setId(clientId) - .setPubKey(pubKey) - .setConsensusSettings(mqcs) - ; - return msgQueueClientConfig; - } - - @Override - public ConsensusManageService createManageServiceClient(String[] serviceNodes) { - // todo serviceNodes // IP:port - return null; - } - - @Override - public MsgQueueConsensusClient setupClient(ClientSettings settings) { - if (settings instanceof MsgQueueClientSettings) { - return setupClient((MsgQueueClientSettings)settings); - } - throw new IllegalArgumentException("ClientSettings data isn't supported! Accept MsgQueueClientSettings only!"); - } - - private MsgQueueConsensusClient setupClient(MsgQueueClientSettings settings) { - MsgQueueConsensusClient mqcc = new MsgQueueConsensusClient() - .setClientSettings(settings) - .setMsgQueueNetworkSettings(settings.getMsgQueueNetworkSettings()) - ; - mqcc.init(); - return mqcc; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientIdentification.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientIdentification.java deleted file mode 100644 index 7dca555f..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientIdentification.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.client.MsgQueueClientIdentification - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午2:04 - * Description: - */ -package com.jd.blockchain.consensus.mq.client; - -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueClientIdentification implements ClientIdentification { - - private byte[] identityInfo; - - private PubKey pubKey; - - private SignatureDigest signature; - - public MsgQueueClientIdentification() { - } - - public MsgQueueClientIdentification(ClientIdentification clientIdentification) { - identityInfo = clientIdentification.getIdentityInfo(); - pubKey = clientIdentification.getPubKey(); - signature = clientIdentification.getSignature(); - } - - public MsgQueueClientIdentification setIdentityInfo(byte[] identityInfo) { - this.identityInfo = identityInfo; - return this; - } - - public MsgQueueClientIdentification setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - return this; - } - - public MsgQueueClientIdentification setSignature(SignatureDigest signature) { - this.signature = signature; - return this; - } - - @Override - public byte[] getIdentityInfo() { - return this.identityInfo; - } - - @Override - public PubKey getPubKey() { - return this.pubKey; - } - - @Override - public SignatureDigest getSignature() { - return this.signature; - } - - @Override - public String getProviderName() { - return MsgQueueConsensusProvider.NAME; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueConsensusClient.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueConsensusClient.java deleted file mode 100644 index 6432dcb3..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueConsensusClient.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.client.MsgQueueConsensusClient - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午3:23 - * Description: - */ -package com.jd.blockchain.consensus.mq.client; - -import com.jd.blockchain.consensus.MessageService; -import com.jd.blockchain.consensus.client.ClientSettings; -import com.jd.blockchain.consensus.client.ConsensusClient; -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.factory.MsgQueueFactory; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.consensus.mq.settings.MsgQueueClientSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueConsensusClient implements ConsensusClient { - - private boolean isConnected; - - private DefaultMessageTransmitter transmitter; - - private MsgQueueNetworkSettings msgQueueNetworkSettings; - - private MsgQueueClientSettings clientSettings; - - public MsgQueueConsensusClient setClientSettings(MsgQueueClientSettings clientSettings) { - this.clientSettings = clientSettings; - return this; - } - - public MsgQueueConsensusClient setMsgQueueNetworkSettings(MsgQueueNetworkSettings msgQueueNetworkSettings) { - this.msgQueueNetworkSettings = msgQueueNetworkSettings; - return this; - } - - public void init() { - String server = msgQueueNetworkSettings.getServer(); - String txTopic = msgQueueNetworkSettings.getTxTopic(); - String blTopic = msgQueueNetworkSettings.getBlTopic(); - String msgTopic = msgQueueNetworkSettings.getMsgTopic(); - - MsgQueueProducer txProducer = MsgQueueFactory.newProducer(server, txTopic); - MsgQueueProducer msgProducer = MsgQueueFactory.newProducer(server, msgTopic); - MsgQueueConsumer blConsumer = MsgQueueFactory.newConsumer(server, blTopic); - MsgQueueConsumer msgConsumer = MsgQueueFactory.newConsumer(server, msgTopic); - - transmitter = new DefaultMessageTransmitter() - .setTxProducer(txProducer) - .setMsgProducer(msgProducer) - .setBlConsumer(blConsumer) - .setMsgConsumer(msgConsumer) - ; - } - - @Override - public MessageService getMessageService() { - return transmitter; - } - - @Override - public ClientSettings getSettings() { - return clientSettings; - } - - @Override - public boolean isConnected() { - return isConnected; - } - - @Override - public synchronized void connect() { - if (!isConnected) { - try { - this.transmitter.connect(); - isConnected = true; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - @Override - public synchronized void close() { - if (isConnected) { - transmitter.close(); - isConnected = false; - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueBlockConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueBlockConfig.java deleted file mode 100644 index 7a8a7560..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueBlockConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueBlockConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午2:57 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.consensus.mq.settings.MsgQueueBlockSettings; - -import java.lang.reflect.Method; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -public class MsgQueueBlockConfig implements MsgQueueBlockSettings { - - private int txSizePerBlock; - - private long maxDelayMilliSecondsPerBlock; - - @Override - public int getTxSizePerBlock() { - return txSizePerBlock; - } - - public MsgQueueBlockConfig setTxSizePerBlock(int txSizePerBlock) { - this.txSizePerBlock = txSizePerBlock; - return this; - } - - @Override - public long getMaxDelayMilliSecondsPerBlock() { - return maxDelayMilliSecondsPerBlock; - } - - public MsgQueueBlockConfig setMaxDelayMilliSecondsPerBlock(long maxDelayMilliSecondsPerBlock) { - this.maxDelayMilliSecondsPerBlock = maxDelayMilliSecondsPerBlock; - return this; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientConfig.java deleted file mode 100644 index 78f9f7c3..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientConfig.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueClientConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午2:23 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.consensus.mq.settings.MsgQueueClientSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; -import com.jd.blockchain.crypto.PubKey; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueClientConfig implements MsgQueueClientSettings { - - private int id; - - private PubKey pubKey; - - private MsgQueueConsensusSettings consensusSettings; - - public MsgQueueClientConfig setId(int id) { - this.id = id; - return this; - } - - public MsgQueueClientConfig setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - return this; - } - - public MsgQueueClientConfig setConsensusSettings(MsgQueueConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - return this; - } - - @Override - public int getClientId() { - return this.id; - } - - @Override - public PubKey getClientPubKey() { - return this.pubKey; - } - - @Override - public MsgQueueConsensusSettings getConsensusSettings() { - return this.consensusSettings; - } - - @Override - public MsgQueueNetworkSettings getMsgQueueNetworkSettings() { - return this.consensusSettings.getNetworkSettings(); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientIncomingConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientIncomingConfig.java deleted file mode 100644 index 967c03de..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientIncomingConfig.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.config.MsgQueueClientIncomingConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:50 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider; -import com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.crypto.PubKey; - -import java.lang.reflect.Method; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueClientIncomingConfig implements MsgQueueClientIncomingSettings { - - private int clientId; - - private PubKey pubKey; - - private MsgQueueConsensusSettings consensusSettings; - - public MsgQueueClientIncomingConfig setConsensusSettings(MsgQueueConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - return this; - } - - public MsgQueueClientIncomingConfig setClientId(int clientId) { - this.clientId = clientId; - return this; - } - - public MsgQueueClientIncomingConfig setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - return this; - } - - @Override - public int getClientId() { - return this.clientId; - } - - @Override - public String getProviderName() { - return MsgQueueConsensusProvider.NAME; - } - - @Override - public MsgQueueConsensusSettings getConsensusSettings() { - return this.consensusSettings; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueConsensusConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueConsensusConfig.java deleted file mode 100644 index 9ece2285..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueConsensusConfig.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.config.MsgQueueConsensusConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:26 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consensus.mq.settings.*; -import com.jd.blockchain.crypto.PubKey; - -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.List; - -/** - * 设置消息队列的信息 - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueConsensusConfig implements MsgQueueConsensusSettings { - - private List nodeSettingsList = new ArrayList<>(); - - private MsgQueueNetworkSettings networkSettings; - - private MsgQueueBlockSettings blockSettings; - - public MsgQueueConsensusConfig addNodeSettings(MsgQueueNodeSettings nodeSettings) { - nodeSettingsList.add(nodeSettings); - return this; - } - - public MsgQueueConsensusConfig setNetworkSettings(MsgQueueNetworkSettings networkSettings) { - this.networkSettings = networkSettings; - return this; - } - - public MsgQueueConsensusConfig setBlockSettings(MsgQueueBlockSettings blockSettings) { - this.blockSettings = blockSettings; - return this; - } - - @Override - public NodeSettings[] getNodes() { - return nodeSettingsList.toArray(new NodeSettings[nodeSettingsList.size()]); - } - - @Override - public MsgQueueNetworkSettings getNetworkSettings() { - return networkSettings; - } - - @Override - public MsgQueueBlockSettings getBlockSettings() { - return blockSettings; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNetworkConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNetworkConfig.java deleted file mode 100644 index d73c6b65..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNetworkConfig.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueNetworkConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午4:55 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; - -import java.lang.reflect.Method; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueNetworkConfig implements MsgQueueNetworkSettings { - - private String server; - - private String txTopic; - - private String blTopic; - - private String msgTopic; - - public MsgQueueNetworkConfig setServer(String server) { - this.server = server; - return this; - } - - public MsgQueueNetworkConfig setTxTopic(String txTopic) { - this.txTopic = txTopic; - return this; - } - - public MsgQueueNetworkConfig setBlTopic(String blTopic) { - this.blTopic = blTopic; - return this; - } - - public MsgQueueNetworkConfig setMsgTopic(String msgTopic) { - this.msgTopic = msgTopic; - return this; - } - - @Override - public String getServer() { - return server; - } - - @Override - public String getTxTopic() { - return txTopic; - } - - @Override - public String getBlTopic() { - return blTopic; - } - - @Override - public String getMsgTopic() { - return msgTopic; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNodeConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNodeConfig.java deleted file mode 100644 index 9e9506ed..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNodeConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.config.MsgQueueNodeConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:33 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; -import com.jd.blockchain.crypto.PubKey; - -/** - * peer节点IP - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueNodeConfig implements MsgQueueNodeSettings { - - private String address; - - private PubKey pubKey; - - public MsgQueueNodeConfig setAddress(String address) { - this.address = address; - return this; - } - - public MsgQueueNodeConfig setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - return this; - } - - @Override - public String getAddress() { - return this.address; - } - - @Override - public PubKey getPubKey() { - return this.pubKey; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueServerConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueServerConfig.java deleted file mode 100644 index 7b7a79b9..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueServerConfig.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.config.MsgQueueServerConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:32 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.consensus.mq.settings.MsgQueueBlockSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueServerSettings; - -/** - * peer节点配置 - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueServerConfig implements MsgQueueServerSettings { - - private MsgQueueBlockSettings blockSettings; - - private MsgQueueConsensusSettings consensusSettings; - - private MsgQueueNodeSettings nodeSettings; - - private String realmName; - - public MsgQueueServerConfig setRealmName(String realmName) { - this.realmName = realmName; - return this; - } - - public MsgQueueServerConfig setBlockSettings(MsgQueueBlockSettings blockSettings) { - this.blockSettings = blockSettings; - return this; - } - - public MsgQueueServerConfig setConsensusSettings(MsgQueueConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - return setBlockSettings(consensusSettings.getBlockSettings()); - } - - public MsgQueueServerConfig setNodeSettings(MsgQueueNodeSettings nodeSettings) { - this.nodeSettings = nodeSettings; - return this; - } - - @Override - public String getRealmName() { - return this.realmName; - } - - @Override - public MsgQueueNodeSettings getReplicaSettings() { - return nodeSettings; - } - - @Override - public MsgQueueBlockSettings getBlockSettings() { - return blockSettings; - } - - @Override - public MsgQueueConsensusSettings getConsensusSettings() { - return consensusSettings; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueSettingsFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueSettingsFactory.java deleted file mode 100644 index 61449436..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueSettingsFactory.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.config.MsgQueueSettingsFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:49 - * Description: - */ -package com.jd.blockchain.consensus.mq.config; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consensus.SettingsFactory; -import com.jd.blockchain.consensus.mq.MsgQueueConsensusSettingsBuilder; -import com.jd.blockchain.consensus.mq.settings.MsgQueueBlockSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; -import com.jd.blockchain.utils.io.BytesEncoder; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueSettingsFactory implements SettingsFactory { - - static { - DataContractRegistry.register(NodeSettings.class); - - DataContractRegistry.register(MsgQueueNodeSettings.class); - - DataContractRegistry.register(ConsensusSettings.class); - - DataContractRegistry.register(MsgQueueConsensusSettings.class); - - DataContractRegistry.register(MsgQueueNetworkSettings.class); - - DataContractRegistry.register(MsgQueueBlockSettings.class); - - DataContractRegistry.register(MsgQueueClientIncomingSettings.class); - - DataContractRegistry.register(ClientIncomingSettings.class); - } - - private static final MsgQueueConsensusSettingsEncoder MQCS_ENCODER = new MsgQueueConsensusSettingsEncoder(); - - private static final MsgQueueClientIncomingSettingsEncoder MQCIS_ENCODER = new MsgQueueClientIncomingSettingsEncoder(); - - private static final MsgQueueConsensusSettingsBuilder BUILDER = new MsgQueueConsensusSettingsBuilder(); - - @Override - public MsgQueueConsensusSettingsBuilder getConsensusSettingsBuilder() { - return BUILDER; - } - - @Override - public BytesEncoder getConsensusSettingsEncoder() { - return MQCS_ENCODER; - } - - @Override - public BytesEncoder getIncomingSettingsEncoder() { - return MQCIS_ENCODER; - } - - private static class MsgQueueConsensusSettingsEncoder implements BytesEncoder{ - - @Override - public byte[] encode(ConsensusSettings data) { - if (data instanceof MsgQueueConsensusSettings) { - return BinaryProtocol.encode(data, MsgQueueConsensusSettings.class); - } - throw new IllegalArgumentException("Settings data isn't supported! Accept MsgQueueConsensusSettings only!"); - } - - @Override - public MsgQueueConsensusSettings decode(byte[] bytes) { - return BinaryProtocol.decodeAs(bytes, MsgQueueConsensusSettings.class); - } - } - - private static class MsgQueueClientIncomingSettingsEncoder implements BytesEncoder{ - - @Override - public byte[] encode(ClientIncomingSettings data) { - if (data instanceof MsgQueueClientIncomingSettings) { - return BinaryProtocol.encode(data, MsgQueueClientIncomingSettings.class); - } - throw new IllegalArgumentException("Settings data isn't supported! Accept MsgQueueClientIncomingSettings only!"); - } - - @Override - public MsgQueueClientIncomingSettings decode(byte[] bytes) { - return BinaryProtocol.decodeAs(bytes, MsgQueueClientIncomingSettings.class); - } - - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/AbstractConsumer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/AbstractConsumer.java deleted file mode 100644 index 9c39d8e9..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/AbstractConsumer.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.consumer.AbstractConsumer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/29 下午12:31 - * Description: - */ -package com.jd.blockchain.consensus.mq.consumer; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.jd.blockchain.consensus.event.EventProducer; -import com.jd.blockchain.consensus.mq.exchange.BytesEventFactory; -import com.jd.blockchain.consensus.mq.exchange.BytesEventProducer; -import com.lmax.disruptor.BlockingWaitStrategy; -import com.lmax.disruptor.EventHandler; -import com.lmax.disruptor.RingBuffer; -import com.lmax.disruptor.dsl.Disruptor; -import com.lmax.disruptor.dsl.ProducerType; - -/** - * - * @author shaozhuguang - * @create 2018/12/29 - * @since 1.0.0 - */ - -public abstract class AbstractConsumer implements MsgQueueConsumer { - - protected EventProducer eventProducer; - - protected void initEventHandler(EventHandler eventHandler) { - Disruptor> disruptor = - new Disruptor<>(new BytesEventFactory(), - BytesEventFactory.BUFFER_SIZE, r -> { - return new Thread(r); - }, ProducerType.SINGLE, new BlockingWaitStrategy()); - - disruptor.handleEventsWith(eventHandler); - disruptor.start(); - RingBuffer> ringBuffer = disruptor.getRingBuffer(); - this.eventProducer = new BytesEventProducer(ringBuffer); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/MsgQueueConsumer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/MsgQueueConsumer.java deleted file mode 100644 index 43908abb..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/MsgQueueConsumer.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: MsgQueueConsumer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:38 - * Description: - */ -package com.jd.blockchain.consensus.mq.consumer; - -import com.lmax.disruptor.EventHandler; - -import java.io.Closeable; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public interface MsgQueueConsumer extends Closeable { - - void connect(EventHandler eventHandler) throws Exception; - - void start() throws Exception; -} - diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/NatsConsumer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/NatsConsumer.java deleted file mode 100644 index 0df9c6dd..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/NatsConsumer.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.nats.RabbitConsumer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:40 - * Description: - */ -package com.jd.blockchain.consensus.mq.consumer; - -import com.jd.blockchain.utils.ConsoleUtils; -import com.lmax.disruptor.EventHandler; -import io.nats.client.*; - -import java.io.IOException; -import java.time.Duration; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class NatsConsumer extends AbstractConsumer implements MsgQueueConsumer { - - private final ExecutorService msgListener = Executors.newSingleThreadExecutor(); - - private Connection nc; - - private Subscription sub; - - private String server; - - private String topic; - - public NatsConsumer(String server, String topic) { - this.server = server; - this.topic = topic; - } - - @Override - public void connect(EventHandler eventHandler) throws Exception { - initEventHandler(eventHandler); - Options options = new Options.Builder().server(server).noReconnect().build(); - this.nc = Nats.connect(options); - this.sub = nc.subscribe(topic); - this.nc.flush(Duration.ZERO); - ConsoleUtils.info("[*] NatsConsumer[%s, %s] connect success !!!", this.server, this.topic); - } - - @Override - public void start() { - msgListener.execute(() -> { - for (;;) { - try { - Message msg = this.sub.nextMessage(Duration.ZERO); - eventProducer.publish(msg.getData()); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - @Override - public void close() throws IOException { - try { - nc.close(); - } catch (Exception e) { - throw new IOException(e); - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/RabbitConsumer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/RabbitConsumer.java deleted file mode 100644 index 5076537a..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/consumer/RabbitConsumer.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.nats.RabbitConsumer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:40 - * Description: - */ -package com.jd.blockchain.consensus.mq.consumer; - -import com.jd.blockchain.consensus.mq.factory.RabbitFactory; -import com.jd.blockchain.utils.ConsoleUtils; -import com.lmax.disruptor.EventHandler; -import com.rabbitmq.client.*; - -import java.io.IOException; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class RabbitConsumer extends AbstractConsumer implements MsgQueueConsumer { - - private Connection connection; - - private Channel channel; - - private String exchangeName; - - private String server; - - private String queueName; - - public RabbitConsumer(String server, String topic) { - this.server = server; - this.exchangeName = topic; - } - - private void rabbitConsumerHandle() throws Exception { - rabbitConsumerHandleByQueue(); - } - - private void rabbitConsumerHandleByQueue() throws IOException { - DefaultConsumer consumer = new DefaultConsumer(channel) { - @Override - public void handleDelivery(String consumerTag, Envelope envelope, - AMQP.BasicProperties properties, byte[] body) { - // 此处将收到的消息加入队列即可 - try { - eventProducer.publish(body); - channel.basicAck(envelope.getDeliveryTag(), false); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }; - this.channel.basicConsume(this.queueName, false, consumer); - } - - @Override - public void connect(EventHandler eventHandler) throws Exception { - initEventHandler(eventHandler); - ConnectionFactory factory = RabbitFactory.initConnectionFactory(server); - connection = factory.newConnection(); - channel = connection.createChannel(); - - channel.exchangeDeclare(this.exchangeName, "fanout"); - queueName = channel.queueDeclare().getQueue(); - channel.queueBind(queueName, this.exchangeName, ""); - channel.basicQos(8); - - ConsoleUtils.info("[*] RabbitConsumer[%s, %s] connect success !!!", this.server, this.exchangeName); - } - - @Override - public void start() throws Exception { - rabbitConsumerHandle(); - } - - @Override - public void close() throws IOException { - try { - this.channel.close(); - this.connection.close(); - } catch (Exception e) { - throw new IOException(e); - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/BlockEvent.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/BlockEvent.java deleted file mode 100644 index 03b92113..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/BlockEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: BlockEvent - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/20 上午11:32 - * Description: - */ -package com.jd.blockchain.consensus.mq.event; - -import com.jd.blockchain.consensus.mq.util.MessageConvertUtil; - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author shaozhuguang - * @create 2018/11/20 - * @since 1.0.0 - */ - -public class BlockEvent { - - private Map txMap = new HashMap<>(); - - public Map getTxMap() { - return txMap; - } - - public void setTxMap(Map txMap) { - this.txMap = txMap; - } - - public void put(String txKey, String txResp) { - txMap.put(txKey, txResp); - } - - public void put(String txKey, byte[] txResp) { - put(txKey, MessageConvertUtil.base64Encode(txResp)); - } - - public String getTxResp(String txKey) { - return txMap.get(txKey); - } - - public byte[] getTxRespBytes(String txKey) { - String txResp = getTxResp(txKey); - if (txResp != null && txResp.length() > 0) { - // 字符串转字节数组 - return MessageConvertUtil.base64Decode(txResp); - } - return null; - } - - public boolean containTxResp(String txKey) { - return txMap.containsKey(txKey); - } - - public boolean isEmpty() { - if (txMap == null) return true; - return txMap.isEmpty(); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/MessageEvent.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/MessageEvent.java deleted file mode 100644 index 94710a43..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/MessageEvent.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.peer.consensus.MessageEvent - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/23 上午11:45 - * Description: - */ -package com.jd.blockchain.consensus.mq.event; - -/** - * - * @author shaozhuguang - * @create 2018/11/23 - * @since 1.0.0 - */ - -public class MessageEvent { - - String messageKey; - - byte[] message; - - public MessageEvent(String messageKey, byte[] message) { - this.messageKey = messageKey; - this.message = message; - } - - public String getMessageKey() { - return messageKey; - } - - public void setMessageKey(String messageKey) { - this.messageKey = messageKey; - } - - public byte[] getMessage() { - return message; - } - - public void setMessage(byte[] message) { - this.message = message; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/TxBlockedEvent.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/TxBlockedEvent.java deleted file mode 100644 index 5c0515d6..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/event/TxBlockedEvent.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: BlockEvent - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/20 上午11:32 - * Description: - */ -package com.jd.blockchain.consensus.mq.event; - - -import com.jd.blockchain.consensus.mq.util.MessageConvertUtil; - -/** - * - * @author shaozhuguang - * @create 2018/11/20 - * @since 1.0.0 - */ - -public class TxBlockedEvent { - - private String txKey; - - private String transaction; - - public TxBlockedEvent() { - } - - public TxBlockedEvent(String txKey, String transaction) { - this.txKey = txKey; - this.transaction = transaction; - } - - public void setTxKey(String txKey) { - this.txKey = txKey; - } - - public void setTransaction(String transaction) { - this.transaction = transaction; - } - - public String getTxKey() { - return txKey; - } - - public String getTransaction() { - return transaction; - } - - public byte[] txResponseBytes() { - if (transaction != null && transaction.length() > 0) { - // 字符串转字节数组 - return MessageConvertUtil.base64Decode(transaction); - } - return null; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/BytesEventFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/BytesEventFactory.java deleted file mode 100644 index 557c2649..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/BytesEventFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.rabbitmq.nats.consensus.disruptor.ExchangeEventFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 上午10:48 - * Description: - */ -package com.jd.blockchain.consensus.mq.exchange; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.lmax.disruptor.EventFactory; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class BytesEventFactory implements EventFactory> { - - public static final int BUFFER_SIZE = 256 * 1024; -// public static final int BUFFER_SIZE = 8 * 1024; - - @Override - public EventEntity newInstance() { - return new EventEntity<>(); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/BytesEventProducer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/BytesEventProducer.java deleted file mode 100644 index 0421e425..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/BytesEventProducer.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.rabbitmq.nats.consensus.disruptor.ExchangeEventProducer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 上午10:50 - * Description: - */ -package com.jd.blockchain.consensus.mq.exchange; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.jd.blockchain.consensus.event.EventProducer; -import com.lmax.disruptor.RingBuffer; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class BytesEventProducer implements EventProducer { - - private final RingBuffer> ringBuffer; - - public BytesEventProducer(RingBuffer> ringBuffer) { - this.ringBuffer = ringBuffer; - } - - @Override - public void publish(byte[] entity) { - long sequence = ringBuffer.next(); - try { - EventEntity event = ringBuffer.get(sequence); - event.setEntity(entity); - } finally { - this.ringBuffer.publish(sequence); - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEntityFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEntityFactory.java deleted file mode 100644 index 39c7494a..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEntityFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.ExchangeEntityFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午4:08 - * Description: - */ -package com.jd.blockchain.consensus.mq.exchange; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class ExchangeEntityFactory { - - public static ExchangeEventInnerEntity newBlockInstance() { - return new ExchangeEventInnerEntity(ExchangeType.BLOCK); - } - - public static ExchangeEventInnerEntity newEmptyInstance() { - return new ExchangeEventInnerEntity(ExchangeType.EMPTY); - } - - public static ExchangeEventInnerEntity newTransactionInstance(byte[] content) { - return new ExchangeEventInnerEntity(ExchangeType.TRANSACTION, content); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventFactory.java deleted file mode 100644 index 6d16b8c7..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.rabbitmq.nats.consensus.disruptor.ExchangeEventFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 上午10:48 - * Description: - */ -package com.jd.blockchain.consensus.mq.exchange; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.lmax.disruptor.EventFactory; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class ExchangeEventFactory implements EventFactory> { - - public static final int BUFFER_SIZE = 256 * 1024; -// public static final int BUFFER_SIZE = 8 * 1024; - - @Override - public EventEntity newInstance() { - return new EventEntity<>(); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventInnerEntity.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventInnerEntity.java deleted file mode 100644 index 752c1414..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventInnerEntity.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.ExchangeEventInnerEntity - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午4:04 - * Description: - */ -package com.jd.blockchain.consensus.mq.exchange; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class ExchangeEventInnerEntity { - - private ExchangeType type; - - private byte[] content; - - public ExchangeEventInnerEntity() { - } - - public ExchangeEventInnerEntity(ExchangeType type) { - this.type = type; - } - - public ExchangeEventInnerEntity(ExchangeType type, byte[] content) { - this.type = type; - this.content = content; - } - - - - public ExchangeType getType() { - return type; - } - - public void setType(ExchangeType type) { - this.type = type; - } - - public byte[] getContent() { - return content; - } - - public void setContent(byte[] content) { - this.content = content; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventProducer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventProducer.java deleted file mode 100644 index 942fe167..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeEventProducer.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.rabbitmq.nats.consensus.disruptor.ExchangeEventProducer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 上午10:50 - * Description: - */ -package com.jd.blockchain.consensus.mq.exchange; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.jd.blockchain.consensus.event.EventProducer; -import com.lmax.disruptor.RingBuffer; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class ExchangeEventProducer implements EventProducer { - - private final RingBuffer> ringBuffer; - - public ExchangeEventProducer(RingBuffer> ringBuffer) { - this.ringBuffer = ringBuffer; - } - - @Override - public void publish(ExchangeEventInnerEntity entity) { - long sequence = ringBuffer.next(); - try { - EventEntity event = ringBuffer.get(sequence); - event.setEntity(entity); - } finally { - this.ringBuffer.publish(sequence); - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeType.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeType.java deleted file mode 100644 index 1920d89e..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/exchange/ExchangeType.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.nats.ExchangeType - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午3:34 - * Description: - */ -package com.jd.blockchain.consensus.mq.exchange; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public enum ExchangeType { - BLOCK, - EMPTY, - TRANSACTION, - ; -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/MsgQueueConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/MsgQueueConfig.java deleted file mode 100644 index 1d4419a7..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/MsgQueueConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.factory.MsgQueueConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午5:16 - * Description: - */ -package com.jd.blockchain.consensus.mq.factory; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public final class MsgQueueConfig { - - public static final String NATS_PREFIX = "nats"; - - public static final String RABBIT_PREFIX = "rabbit"; -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/MsgQueueFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/MsgQueueFactory.java deleted file mode 100644 index db2b0c1a..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/MsgQueueFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: MsgQueueFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:13 - * Description: - */ -package com.jd.blockchain.consensus.mq.factory; - - -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; - -import static com.jd.blockchain.consensus.mq.factory.MsgQueueConfig.NATS_PREFIX; -import static com.jd.blockchain.consensus.mq.factory.MsgQueueConfig.RABBIT_PREFIX; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class MsgQueueFactory { - - public static MsgQueueProducer newProducer(String server, String topic) { - try { - if (server.startsWith(NATS_PREFIX)) { - return NatsFactory.newProducer(server, topic); - } else if (server.startsWith(RABBIT_PREFIX)) { - return RabbitFactory.newProducer(server, topic); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - return null; - } - - public static MsgQueueConsumer newConsumer(String server, String topic) { - try { - if (server.startsWith(NATS_PREFIX)) { - return NatsFactory.newConsumer(server, topic); - } else if (server.startsWith(RABBIT_PREFIX)) { - return RabbitFactory.newConsumer(server, topic); - } - return null; - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/NatsFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/NatsFactory.java deleted file mode 100644 index c5a4d8f0..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/NatsFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: NatsFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:15 - * Description: - */ -package com.jd.blockchain.consensus.mq.factory; - -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.consumer.NatsConsumer; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.consensus.mq.producer.NatsProducer; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class NatsFactory { - - public static MsgQueueProducer newProducer(String server, String topic) throws Exception { - return new NatsProducer(server, topic); - } - - public static MsgQueueConsumer newConsumer(String server, String topic) throws Exception { - return new NatsConsumer(server, topic); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/RabbitFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/RabbitFactory.java deleted file mode 100644 index b66cf3b6..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/factory/RabbitFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.nats.RabbitFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:15 - * Description: - */ -package com.jd.blockchain.consensus.mq.factory; - -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.consumer.RabbitConsumer; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.consensus.mq.producer.RabbitProducer; -import com.rabbitmq.client.ConnectionFactory; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class RabbitFactory { - - public static MsgQueueProducer newProducer(String server, String topic) throws Exception { - return new RabbitProducer(server, topic); - } - - public static MsgQueueConsumer newConsumer(String server, String topic) throws Exception { - return new RabbitConsumer(server, topic); - } - - public static ConnectionFactory initConnectionFactory(String server) { - ConnectionFactory factory = new ConnectionFactory(); - // 解析server,生成host+port,默认格式:rabbit://localhost:5672 - try { - String[] hostAndPort = server.split("//")[1].split(":"); - if (hostAndPort == null || hostAndPort.length == 0) { - factory.setHost("localhost"); - } else if (hostAndPort.length == 1) { - factory.setHost(hostAndPort[0]); - } else { - factory.setHost(hostAndPort[0]); - factory.setPort(Integer.parseInt(hostAndPort[1])); - } - } catch (Exception e) { - factory.setHost("localhost"); - } - return factory; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/MsgQueueProducer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/MsgQueueProducer.java deleted file mode 100644 index 91cee801..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/MsgQueueProducer.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: MsgQueueProducer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:37 - * Description: - */ -package com.jd.blockchain.consensus.mq.producer; - -import java.io.Closeable; -import java.util.List; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public interface MsgQueueProducer extends Closeable { - - void connect() throws Exception; - - void publish(byte[] message) throws Exception; - - void publishString(String message) throws Exception; - - void publishStringList(List messages) throws Exception; - - void publishStringArray(String[] messages) throws Exception; - - void publishBytesArray(byte[][] message) throws Exception; - - void publishBytesList(List messages) throws Exception; -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/NatsProducer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/NatsProducer.java deleted file mode 100644 index 2f3b2357..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/NatsProducer.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: NatsProducer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:39 - * Description: - */ -package com.jd.blockchain.consensus.mq.producer; - -import io.nats.client.Connection; -import io.nats.client.Nats; -import io.nats.client.Options; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import com.jd.blockchain.utils.ConsoleUtils; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class NatsProducer implements MsgQueueProducer { - - // 主要操作:发送MQ请求 - private Connection nc; - - private String server; - - // 主题 - private String topic; - - public NatsProducer() { - - } - - public NatsProducer(String server, String topic) { - this.topic = topic; - this.server = server; - } - - @Override - public void connect() throws Exception{ - Options o = new Options.Builder().server(server).noReconnect().build(); - this.nc = Nats.connect(o); - ConsoleUtils.info("[*] NatsProducer[%s, %s] connect success !!!", this.server, this.topic); - } - - @Override - public void publish(byte[] message) { - nc.publish(topic, message); - } - - @Override - public void publishString(String message) { - publish(message.getBytes(StandardCharsets.UTF_8)); - } - - @Override - public void publishStringList(List messages) { - for (String message : messages) { - publishString(message); - } - } - - @Override - public void publishStringArray(String[] messages) { - for (String message : messages) { - publishString(message); - } - } - - @Override - public void publishBytesArray(byte[][] message) { - for (byte[] bytes : message) { - publish(bytes); - } - } - - @Override - public void publishBytesList(List messages) { - for (byte[] message : messages) { - publish(message); - } - } - - @Override - public void close() throws IOException { - try { - nc.close(); - } catch (Exception e) { - throw new IOException(e); - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/RabbitProducer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/RabbitProducer.java deleted file mode 100644 index fcd6979b..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/producer/RabbitProducer.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.nats.RabbitProducer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/5 下午10:39 - * Description: - */ -package com.jd.blockchain.consensus.mq.producer; - -import com.jd.blockchain.consensus.mq.factory.RabbitFactory; -import com.jd.blockchain.utils.ConsoleUtils; -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; - -/** - * - * @author shaozhuguang - * @create 2018/11/5 - * @since 1.0.0 - */ - -public class RabbitProducer implements MsgQueueProducer { - - // 主要操作时发送JMQ请求 - private Channel channel; - - private Connection connection; - - private String exchangeName; - - private String server; - - public RabbitProducer() { - - } - - public RabbitProducer(String server, String topic) throws Exception { - this.exchangeName = topic; - this.server = server; - } - - @Override - public void connect() throws Exception { - ConnectionFactory factory = RabbitFactory.initConnectionFactory(server); - connection = factory.newConnection(); - channel = connection.createChannel(); - channel.exchangeDeclare(this.exchangeName, "fanout"); - ConsoleUtils.info("[*] RabbitProducer[%s, %s] connect success !!!", this.server, this.exchangeName); - } - - @Override - public void publish(byte[] message) throws Exception { - channel.basicPublish(this.exchangeName, "", null, message); - } - - @Override - public void publishString(String message) throws Exception { - publish(message.getBytes(StandardCharsets.UTF_8)); - } - - @Override - public void publishStringList(List messages) throws Exception { - for (String message : messages) { - publishString(message); - } - } - - @Override - public void publishStringArray(String[] messages) throws Exception { - for (String message : messages) { - publishString(message); - } - } - - @Override - public void publishBytesArray(byte[][] message) throws Exception { - for (byte[] bytes : message) { - publish(bytes); - } - } - - @Override - public void publishBytesList(List messages) throws Exception { - for (byte[] message : messages) { - publish(message); - } - } - - @Override - public void close() throws IOException { - try { - channel.close(); - connection.close(); - } catch (Exception e) { - throw new IOException(e); - } - } - - -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/DefaultMsgQueueMessageDispatcher.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/DefaultMsgQueueMessageDispatcher.java deleted file mode 100644 index 63af3844..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/DefaultMsgQueueMessageDispatcher.java +++ /dev/null @@ -1,297 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.server.DefaultMsgQueueMessageDispatcher - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 上午11:05 - * Description: - */ -package com.jd.blockchain.consensus.mq.server; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.jd.blockchain.consensus.event.EventProducer; -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.exchange.ExchangeEntityFactory; -import com.jd.blockchain.consensus.mq.exchange.ExchangeEventFactory; -import com.jd.blockchain.consensus.mq.exchange.ExchangeEventInnerEntity; -import com.jd.blockchain.consensus.mq.exchange.ExchangeEventProducer; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.lmax.disruptor.BlockingWaitStrategy; -import com.lmax.disruptor.EventHandler; -import com.lmax.disruptor.RingBuffer; -import com.lmax.disruptor.dsl.Disruptor; -import com.lmax.disruptor.dsl.ProducerType; - -import java.io.IOException; -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicLong; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -public class DefaultMsgQueueMessageDispatcher implements MsgQueueMessageDispatcher, EventHandler> { - - private static final byte[] blockCommitBytes = new byte[]{0x00}; - - private final BlockingQueue dataQueue = new ArrayBlockingQueue<>(1024 * 16); - - private final ExecutorService dataExecutor = Executors.newSingleThreadExecutor(); - - private final ScheduledThreadPoolExecutor timeHandleExecutor = new ScheduledThreadPoolExecutor(2); - - private final AtomicLong blockIndex = new AtomicLong(); - - private long syncIndex = 0L; - - private MsgQueueProducer txProducer; - - private MsgQueueConsumer txConsumer; - - private EventProducer eventProducer; - - private EventHandler eventHandler; - - private final int TX_SIZE_PER_BLOCK; - - private final long MAX_DELAY_MILLISECONDS_PER_BLOCK; - - private boolean isRunning; - - private boolean isConnected; - - public DefaultMsgQueueMessageDispatcher(int txSizePerBlock, long maxDelayMilliSecondsPerBlock) { - this.TX_SIZE_PER_BLOCK = txSizePerBlock; - this.MAX_DELAY_MILLISECONDS_PER_BLOCK = maxDelayMilliSecondsPerBlock; - } - - public DefaultMsgQueueMessageDispatcher setTxProducer(MsgQueueProducer txProducer) { - this.txProducer = txProducer; - return this; - } - - public DefaultMsgQueueMessageDispatcher setTxConsumer(MsgQueueConsumer txConsumer) { - this.txConsumer = txConsumer; - return this; - } - - public DefaultMsgQueueMessageDispatcher setEventHandler(EventHandler eventHandler) { - this.eventHandler = eventHandler; - return this; - } - - public void init() { - handleDisruptor(eventHandler); - } - - private void handleDisruptor(EventHandler eventHandler) { - Disruptor> disruptor = - new Disruptor<>(new ExchangeEventFactory(), - ExchangeEventFactory.BUFFER_SIZE, r -> { - return new Thread(r); - }, ProducerType.SINGLE, new BlockingWaitStrategy()); - - disruptor.handleEventsWith(eventHandler); - disruptor.start(); - RingBuffer> ringBuffer = disruptor.getRingBuffer(); - - this.eventProducer = new ExchangeEventProducer(ringBuffer); - } - - public synchronized void connect() throws Exception { - if (!isConnected) { - txProducer.connect(); - txConsumer.connect(this); - isConnected = true; - } - } - - @Override - public synchronized void stop() throws Exception { - isRunning = false; - close(); - } - - @Override - public void run() { - this.isRunning = true; - try { - txConsumer.start(); - } catch (Exception e) { - - } -// handleData(); -// listen(); - } - -// private void listen() { -// while (isRunning) { -// try { -// byte[] data = this.txConsumer.start(); -// dataQueue.put(data); -// // 收到数据后由队列处理 -//// handleData(data); -// } catch (Exception e) { -// // 日志打印 -// ConsoleUtils.info("ERROR dispatcher start data exception {%s}", e.getMessage()); -// } -// } -// } - -// private void handleData() { -// dataExecutor.execute(() -> { -// byte[] data; -// for (;;) { -// try { -// data = dataQueue.take(); -// if (data.length == 1) { -// // 结块标识优先处理 -// syncIndex = 0L; -// this.blockIndex.getAndIncrement(); -// eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); -// } else { -// if (syncIndex == 0) { // 收到第一个交易 -// // 需要判断是否需要进行定时任务 -// if (MAX_DELAY_MILLISECONDS_PER_BLOCK > 0) { -// this.timeHandleExecutor.schedule( -// timeBlockTask(this.blockIndex.get()), -// MAX_DELAY_MILLISECONDS_PER_BLOCK, TimeUnit.MILLISECONDS); -// } -// } -// syncIndex++; -// eventProducer.publish(ExchangeEntityFactory.newTransactionInstance(data)); -// if (syncIndex == TX_SIZE_PER_BLOCK) { -// syncIndex = 0L; -// this.blockIndex.getAndIncrement(); -// eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); -// } -// } -// -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// }); -// for (;;) { -// try { -// final byte[] data = dataQueue.take(); -// dataExecutor.execute(() -> { -// if (data.length == 1) { -// // 结块标识优先处理 -// syncIndex = 0L; -// this.blockIndex.getAndIncrement(); -// eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); -// } else { -// if (syncIndex == 0) { // 收到第一个交易 -// // 需要判断是否需要进行定时任务 -// if (MAX_DELAY_MILLISECONDS_PER_BLOCK > 0) { -// this.timeHandleExecutor.schedule( -// timeBlockTask(this.blockIndex.get()), -// MAX_DELAY_MILLISECONDS_PER_BLOCK, TimeUnit.MILLISECONDS); -// } -// } -// syncIndex++; -// eventProducer.publish(ExchangeEntityFactory.newTransactionInstance(data)); -// if (syncIndex == TX_SIZE_PER_BLOCK) { -// syncIndex = 0L; -// this.blockIndex.getAndIncrement(); -// eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); -// } -// } -// } -// ); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } - -// private void handleData(final byte[] data) { -// dataExecutor.execute(() -> { -// try { -// if (data.length == 1) { -// // 结块标识优先处理 -// syncIndex = 0L; -// this.blockIndex.getAndIncrement(); -// eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); -// } else { -// if (syncIndex == 0) { // 收到第一个交易 -// // 需要判断是否需要进行定时任务 -// if (MAX_DELAY_MILLISECONDS_PER_BLOCK > 0) { -// this.timeHandleExecutor.schedule( -// timeBlockTask(this.blockIndex.get()), -// MAX_DELAY_MILLISECONDS_PER_BLOCK, TimeUnit.MILLISECONDS); -// } -// } -// syncIndex++; -// eventProducer.publish(ExchangeEntityFactory.newTransactionInstance(data)); -// if (syncIndex == TX_SIZE_PER_BLOCK) { -// syncIndex = 0L; -// this.blockIndex.getAndIncrement(); -// eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); -// } -// } -// } catch (Exception e) { -// // 记录日志 -// ConsoleUtils.info("ERROR TransactionDispatcher process queue data exception {%s}", e.getMessage()); -// } -// }); -// -// } - - private Runnable timeBlockTask(final long currentBlockIndex) { - return () -> { - final boolean isEqualBlock = this.blockIndex.compareAndSet( - currentBlockIndex, currentBlockIndex + 1); - if (isEqualBlock) { - try { - txProducer.publish(blockCommitBytes); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }; - } - - @Override - public void close() throws IOException { - this.txProducer.close(); - this.txConsumer.close(); - } - - @Override - public void onEvent(EventEntity event, long sequence, boolean endOfBatch) throws Exception { - try { - byte[] data = event.getEntity(); -// System.out.printf("Thread [%s, $s] on event !!!\r\n", -// Thread.currentThread().getId(), Thread.currentThread().getName()); - if (data.length == 1) { - // 结块标识优先处理 - syncIndex = 0L; - this.blockIndex.getAndIncrement(); - eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); - } else { - if (syncIndex == 0) { // 收到第一个交易 - // 需要判断是否需要进行定时任务 - if (MAX_DELAY_MILLISECONDS_PER_BLOCK > 0) { - this.timeHandleExecutor.schedule( - timeBlockTask(this.blockIndex.get()), - MAX_DELAY_MILLISECONDS_PER_BLOCK, TimeUnit.MILLISECONDS); - } - } - syncIndex++; - eventProducer.publish(ExchangeEntityFactory.newTransactionInstance(data)); - if (syncIndex == TX_SIZE_PER_BLOCK) { - syncIndex = 0L; - this.blockIndex.getAndIncrement(); - eventProducer.publish(ExchangeEntityFactory.newBlockInstance()); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/ExtendMsgQueueMessageExecutor.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/ExtendMsgQueueMessageExecutor.java deleted file mode 100644 index 9a73ece4..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/ExtendMsgQueueMessageExecutor.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.server.DefaultMsgQueueMessageDispatcher - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 上午11:05 - * Description: - */ -package com.jd.blockchain.consensus.mq.server; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.consensus.service.MessageHandle; -import com.jd.blockchain.utils.concurrent.AsyncFuture; -import com.lmax.disruptor.EventHandler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -public class ExtendMsgQueueMessageExecutor implements MsgQueueMessageDispatcher, EventHandler> { - - private static final Logger LOGGER = LoggerFactory.getLogger(ExtendMsgQueueMessageExecutor.class); - - private final ExecutorService dataExecutor = Executors.newSingleThreadExecutor(); - - private MsgQueueProducer msgProducer; - - private MsgQueueConsumer msgConsumer; - - private MessageHandle messageHandle; - - private boolean isRunning; - - private boolean isConnected; - - public ExtendMsgQueueMessageExecutor setMsgProducer(MsgQueueProducer msgProducer) { - this.msgProducer = msgProducer; - return this; - } - - public ExtendMsgQueueMessageExecutor setMsgConsumer(MsgQueueConsumer msgConsumer) { - this.msgConsumer = msgConsumer; - return this; - } - - public ExtendMsgQueueMessageExecutor setMessageHandle(MessageHandle messageHandle) { - this.messageHandle = messageHandle; - return this; - } - - @Override - public void init() { - // do nothing - } - - public synchronized void connect() throws Exception { - if (!isConnected) { - msgProducer.connect(); - msgConsumer.connect(this); - msgConsumer.start(); - isConnected = true; - } - } - - @Override - public synchronized void stop() throws Exception { - isRunning = false; - close(); - } - - @Override - public void run() { - this.isRunning = true; -// this.msgConsumer.start(); -// listen(); - } - -// private void listen() { -// while (isRunning) { -// try { -// byte[] data = this.msgConsumer.start(); -// // 收到数据后由队列处理 -// handleData(data); -// } catch (Exception e) { -// // 日志打印 -// LOGGER.error("extend message handle exception {}", e.getMessage()); -// } -// } -// } - - private void handleData(byte[] data) { - dataExecutor.execute(() -> { - try { - AsyncFuture result = messageHandle.processUnordered(data); - msgProducer.publish(result.get()); - } catch (Exception e) { - LOGGER.error("process Unordered message exception {}", e.getMessage()); - } - }); - } - - @Override - public void close() throws IOException { - isConnected = false; - this.msgProducer.close(); - this.msgConsumer.close(); - } - - @Override - public void onEvent(EventEntity event, long sequence, boolean endOfBatch) throws Exception { - byte[] data = event.getEntity(); - handleData(data); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueConsensusManageService.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueConsensusManageService.java deleted file mode 100644 index 72368e95..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueConsensusManageService.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.server.MsgQueueConsensusManageService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 下午1:46 - * Description: - */ -package com.jd.blockchain.consensus.mq.server; - -import java.util.Arrays; - -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.ConsensusManageService; -import com.jd.blockchain.consensus.ConsensusSecurityException; -import com.jd.blockchain.consensus.mq.config.MsgQueueClientIncomingConfig; -import com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureFunction; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueConsensusManageService implements ConsensusManageService { - - private MsgQueueConsensusSettings consensusSettings; - - public MsgQueueConsensusManageService setConsensusSettings(MsgQueueConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - return this; - } - - @Override - public MsgQueueClientIncomingSettings authClientIncoming(ClientIdentification authId) throws ConsensusSecurityException { - boolean isLegal = isLegal(authId); - if (isLegal) { - MsgQueueClientIncomingSettings mqcis = new MsgQueueClientIncomingConfig() - .setPubKey(authId.getPubKey()) - .setClientId(clientId(authId.getIdentityInfo())) - .setConsensusSettings(this.consensusSettings) - ; - return mqcis; - } - return null; - } - - private int clientId(byte[] identityInfo) { - // todo - - return 0; - } - - public boolean isLegal(ClientIdentification authId) { - boolean isLegal = false; - PubKey pubKey = authId.getPubKey(); - byte[] identityInfo = authId.getIdentityInfo(); - byte[] address = pubKey.toBytes(); // 使用公钥地址作为认证信息 - if (Arrays.equals(address, identityInfo)) { - SignatureFunction signatureFunction = Crypto.getSignatureFunction(pubKey.getAlgorithm()); - isLegal = signatureFunction.verify(authId.getSignature(), pubKey, identityInfo); - } - return isLegal; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueMessageDispatcher.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueMessageDispatcher.java deleted file mode 100644 index a3b6e286..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueMessageDispatcher.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.server.MsgQueueMessageDispatcher - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:30 - * Description: - */ -package com.jd.blockchain.consensus.mq.server; - - -import java.io.Closeable; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public interface MsgQueueMessageDispatcher extends Runnable, Closeable { - - void init(); - - void connect() throws Exception; - - void stop() throws Exception; -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueMessageExecutor.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueMessageExecutor.java deleted file mode 100644 index 36454696..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueMessageExecutor.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.server.MsgQueueMessageExecutor - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午2:10 - * Description: - */ -package com.jd.blockchain.consensus.mq.server; - -import com.jd.blockchain.consensus.event.EventEntity; -import com.jd.blockchain.consensus.mq.event.MessageEvent; -import com.jd.blockchain.consensus.mq.event.TxBlockedEvent; -import com.jd.blockchain.consensus.mq.exchange.ExchangeEventInnerEntity; -import com.jd.blockchain.consensus.mq.exchange.ExchangeType; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.consensus.mq.util.MessageConvertUtil; -import com.jd.blockchain.consensus.service.MessageHandle; -import com.jd.blockchain.consensus.service.StateMachineReplicate; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.utils.concurrent.AsyncFuture; -import com.lmax.disruptor.EventHandler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -public class MsgQueueMessageExecutor implements EventHandler> { - - private static final Logger LOGGER = LoggerFactory.getLogger(MsgQueueMessageExecutor.class); - - // todo 暂不处理队列溢出导致的OOM - private final ExecutorService blockEventExecutor = Executors.newFixedThreadPool(10); - - private MsgQueueProducer blProducer; - - private List exchangeEvents = new ArrayList<>(); - - private String realmName; - - private MessageHandle messageHandle; - - private final AtomicInteger messageId = new AtomicInteger(); - - private int txSizePerBlock = 1000; - - private StateMachineReplicate stateMachineReplicator; - - public MsgQueueMessageExecutor setRealmName(String realmName) { - this.realmName = realmName; - return this; - } - - public MsgQueueMessageExecutor setBlProducer(MsgQueueProducer blProducer) { - this.blProducer = blProducer; - return this; - } - - public MsgQueueMessageExecutor setTxSizePerBlock(int txSizePerBlock) { - this.txSizePerBlock = txSizePerBlock; - return this; - } - - public MsgQueueMessageExecutor setMessageHandle(MessageHandle messageHandle) { - this.messageHandle = messageHandle; - return this; - } - - public MsgQueueMessageExecutor setStateMachineReplicator(StateMachineReplicate stateMachineReplicator) { - this.stateMachineReplicator = stateMachineReplicator; - return this; - } - - public MsgQueueMessageExecutor init() { - try { - long latestStateId = stateMachineReplicator.getLatestStateID(realmName); - // 设置基础消息ID - messageId.set(((int)latestStateId + 1) * txSizePerBlock); - blProducer.connect(); - } catch (Exception e) { - throw new RuntimeException(e); - } - return this; - } - - @Override - public void onEvent(EventEntity event, long sequence, boolean endOfBatch) throws Exception { - ExchangeEventInnerEntity entity = event.getEntity(); - if (entity != null) { - if (entity.getType() == ExchangeType.BLOCK || entity.getType() == ExchangeType.EMPTY) { - if (!exchangeEvents.isEmpty()) { - process(exchangeEvents); - exchangeEvents.clear(); - } - } else { - byte[] bytes = event.getEntity().getContent(); - String key = bytes2Key(bytes); - exchangeEvents.add(new MessageEvent(key, bytes)); - } - } - } - - private void process(List messageEvents) { - if (messageEvents != null && !messageEvents.isEmpty()) { - try { - Map> txResponseMap = execute(messageEvents); - if (txResponseMap != null && !txResponseMap.isEmpty()) { -// byte[] asyncFuture; - for (Map.Entry> entry : txResponseMap.entrySet()) { - final String txKey = entry.getKey(); - final AsyncFuture asyncFuture = entry.getValue(); -// asyncFuture = entry.getValue().get(); - - blockEventExecutor.execute(() -> { - TxBlockedEvent txBlockedEvent = new TxBlockedEvent(txKey, - MessageConvertUtil.base64Encode(asyncFuture.get())); - byte[] serializeBytes = MessageConvertUtil.serializeTxBlockedEvent(txBlockedEvent); - // 通过消息队列发送该消息 - try { - this.blProducer.publish(serializeBytes); - } catch (Exception e) { - LOGGER.error("publish block event message exception {}", e.getMessage()); - } - }); - } - } - } catch (Exception e) { - // 打印日志 - LOGGER.error("process message exception {}", e.getMessage()); - } - } - } - - private Map> execute(List messageEvents) { -// System.out.printf("Thread[%s %s] execute messageEvents !!! \r\n", -// Thread.currentThread().getId(), Thread.currentThread().getName()); - Map> asyncFutureMap = new HashMap<>(); - // 使用MessageHandle处理 -// long startTime = System.currentTimeMillis(); -// int txSize = messageEvents.size(); - String batchId = messageHandle.beginBatch(realmName); - try { - for (MessageEvent messageEvent : messageEvents) { - String txKey = messageEvent.getMessageKey(); - byte[] txContent = messageEvent.getMessage(); - AsyncFuture asyncFuture = messageHandle.processOrdered(messageId.getAndIncrement(), txContent, realmName, batchId); - asyncFutureMap.put(txKey, asyncFuture); - } - messageHandle.completeBatch(realmName, batchId); - messageHandle.commitBatch(realmName, batchId); -// long totalTime = System.currentTimeMillis() - startTime; -// String content = String.format("batch[%s] process, time = {%s}ms, TPS = %.2f \r\n", -// batchId, totalTime, txSize * 1000.0D / totalTime); -// System.out.println(content); -// logQueue.put(content); - // 提交之后需要获取对应的结果 - } catch (Exception e) { - // todo 需要处理应答码 404 - messageHandle.rollbackBatch(realmName, batchId, TransactionState.CONSENSUS_ERROR.CODE); - } - return asyncFutureMap; - } - - - private String bytes2Key(byte[] bytes) { - return MessageConvertUtil.messageKey(bytes); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueNodeServer.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueNodeServer.java deleted file mode 100644 index 3f1f0b82..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueNodeServer.java +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.server.MsgQueueNodeServer - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 上午11:20 - * Description: - */ -package com.jd.blockchain.consensus.mq.server; - -import com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider; -import com.jd.blockchain.consensus.mq.consumer.MsgQueueConsumer; -import com.jd.blockchain.consensus.mq.factory.MsgQueueFactory; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.consensus.mq.settings.MsgQueueBlockSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueServerSettings; -import com.jd.blockchain.consensus.service.MessageHandle; -import com.jd.blockchain.consensus.service.NodeServer; -import com.jd.blockchain.consensus.service.StateMachineReplicate; - -import java.util.concurrent.Executors; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -public class MsgQueueNodeServer implements NodeServer { - - private DefaultMsgQueueMessageDispatcher dispatcher; - - private ExtendMsgQueueMessageExecutor extendExecutor; - - private MessageHandle messageHandle; - - private StateMachineReplicate stateMachineReplicator; - - private MsgQueueMessageExecutor messageExecutor; - - private MsgQueueNetworkSettings networkSettings; - - private MsgQueueConsensusManageService manageService; - - private int txSizePerBlock = 1000; - - private long maxDelayMilliSecondsPerBlock = 1000; - - private MsgQueueServerSettings serverSettings; - - private boolean isRunning; - - public MsgQueueNodeServer setMessageHandle(MessageHandle messageHandle) { - this.messageHandle = messageHandle; - return this; - } - - public MsgQueueNodeServer setStateMachineReplicator(StateMachineReplicate stateMachineReplicator) { - this.stateMachineReplicator = stateMachineReplicator; - return this; - } - - public MsgQueueNodeServer setTxSizePerBlock(int txSizePerBlock) { - this.txSizePerBlock = txSizePerBlock; - return this; - } - - public MsgQueueNodeServer setMaxDelayMilliSecondsPerBlock(long maxDelayMilliSecondsPerBlock) { - this.maxDelayMilliSecondsPerBlock = maxDelayMilliSecondsPerBlock; - return this; - } - - public MsgQueueNodeServer setMsgQueueNetworkSettings(MsgQueueNetworkSettings networkSettings) { - this.networkSettings = networkSettings; - return this; - } - - public MsgQueueNodeServer setServerSettings(MsgQueueServerSettings serverSettings) { - this.serverSettings = serverSettings; - this.manageService = new MsgQueueConsensusManageService() - .setConsensusSettings(serverSettings.getConsensusSettings()); - return this; - } - - public MsgQueueNodeServer init() { - String realmName = this.serverSettings.getRealmName(); - MsgQueueBlockSettings blockSettings = this.serverSettings.getBlockSettings(); - MsgQueueConsensusSettings consensusSettings = this.serverSettings.getConsensusSettings(); - - this.setTxSizePerBlock(blockSettings.getTxSizePerBlock()) - .setMaxDelayMilliSecondsPerBlock(blockSettings.getMaxDelayMilliSecondsPerBlock()) - .setMsgQueueNetworkSettings(consensusSettings.getNetworkSettings()) - ; - - String server = networkSettings.getServer(), - txTopic = networkSettings.getTxTopic(), - blTopic = networkSettings.getBlTopic(), - msgTopic = networkSettings.getMsgTopic(); - - MsgQueueProducer blProducer = MsgQueueFactory.newProducer(server, blTopic), - txProducer = MsgQueueFactory.newProducer(server, txTopic), - msgProducer = MsgQueueFactory.newProducer(server, msgTopic); - - MsgQueueConsumer txConsumer = MsgQueueFactory.newConsumer(server, txTopic), - msgConsumer = MsgQueueFactory.newConsumer(server, msgTopic); - - initMessageExecutor(blProducer, realmName); - - initDispatcher(txProducer, txConsumer); - - initExtendExecutor(msgProducer, msgConsumer); - - return this; - } - - @Override - public String getProviderName() { - return MsgQueueConsensusProvider.NAME; - } - - @Override - public MsgQueueConsensusManageService getManageService() { - return this.manageService; - } - - @Override - public MsgQueueServerSettings getSettings() { - return serverSettings; - } - - @Override - public boolean isRunning() { - return isRunning; - } - - @Override - public synchronized void start() { - if (!isRunning) { - try { - dispatcher.connect(); - Executors.newSingleThreadExecutor().execute(dispatcher); - extendExecutor.connect(); - Executors.newSingleThreadExecutor().execute(extendExecutor); - isRunning = true; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - @Override - public synchronized void stop() { - if (isRunning) { - try { - dispatcher.stop(); - extendExecutor.stop(); - isRunning = false; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - private void initMessageExecutor(MsgQueueProducer blProducer, final String realmName) { - messageExecutor = new MsgQueueMessageExecutor() - .setRealmName(realmName) - .setMessageHandle(messageHandle) - .setBlProducer(blProducer) - .setStateMachineReplicator(stateMachineReplicator) - .setTxSizePerBlock(txSizePerBlock) - .init() - ; - } - - private void initDispatcher(MsgQueueProducer txProducer, MsgQueueConsumer txConsumer) { - dispatcher = new DefaultMsgQueueMessageDispatcher(txSizePerBlock, maxDelayMilliSecondsPerBlock) - .setTxProducer(txProducer) - .setTxConsumer(txConsumer) - .setEventHandler(messageExecutor) - ; - dispatcher.init(); - } - - - private void initExtendExecutor(MsgQueueProducer msgProducer, MsgQueueConsumer msgConsumer) { - extendExecutor = new ExtendMsgQueueMessageExecutor() - .setMessageHandle(messageHandle) - .setMsgConsumer(msgConsumer) - .setMsgProducer(msgProducer) - ; - extendExecutor.init(); - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueNodeServerFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueNodeServerFactory.java deleted file mode 100644 index c8d8f337..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueNodeServerFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.server.MsgQueueNodeServerFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:30 - * Description: - */ -package com.jd.blockchain.consensus.mq.server; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.mq.config.MsgQueueNodeConfig; -import com.jd.blockchain.consensus.mq.config.MsgQueueServerConfig; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueServerSettings; -import com.jd.blockchain.consensus.service.*; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ - -public class MsgQueueNodeServerFactory implements NodeServerFactory { - - @Override - public MsgQueueServerSettings buildServerSettings(String realmName, ConsensusSettings consensusSetting, String currentNodeAddress) { - - if (!(consensusSetting instanceof MsgQueueConsensusSettings)) { - throw new IllegalArgumentException("ConsensusSettings data isn't supported! Accept MsgQueueConsensusSettings only!"); - } - - MsgQueueNodeSettings nodeSettings = new MsgQueueNodeConfig().setAddress(currentNodeAddress); - - MsgQueueServerSettings serverSettings = new MsgQueueServerConfig() - .setRealmName(realmName) - .setNodeSettings(nodeSettings) - .setConsensusSettings((MsgQueueConsensusSettings) consensusSetting) - ; - return serverSettings; - - - } - - @Override - public MsgQueueNodeServer setupServer(ServerSettings serverSettings, MessageHandle messageHandler, StateMachineReplicate stateMachineReplicator) { - if (!(serverSettings instanceof MsgQueueServerSettings)) { - throw new IllegalArgumentException("ServerSettings data isn't supported! Accept MsgQueueServerSettings only!"); - } - - MsgQueueNodeServer nodeServer = new MsgQueueNodeServer() - .setServerSettings((MsgQueueServerSettings) serverSettings) - .setMessageHandle(messageHandler) - .setStateMachineReplicator(stateMachineReplicator) - .init() - ; - return nodeServer; - } -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueBlockSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueBlockSettings.java deleted file mode 100644 index 80832ca7..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueBlockSettings.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueBlockSettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午4:28 - * Description: - */ -package com.jd.blockchain.consensus.mq.settings; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ -@DataContract(code = DataCodes.CONSENSUS_MSGQUEUE_BLOCK_SETTINGS) -public interface MsgQueueBlockSettings { - - @DataField(order = 0, primitiveType = PrimitiveType.INT32) - int getTxSizePerBlock(); - - @DataField(order = 1, primitiveType = PrimitiveType.INT64) - long getMaxDelayMilliSecondsPerBlock(); -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientIncomingSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientIncomingSettings.java deleted file mode 100644 index 09d2c882..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientIncomingSettings.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueClientIncomingSettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午4:35 - * Description: - */ -package com.jd.blockchain.consensus.mq.settings; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ -@DataContract(code = DataCodes.CONSENSUS_MSGQUEUE_CLI_INCOMING_SETTINGS) -public interface MsgQueueClientIncomingSettings extends ClientIncomingSettings { - - @DataField(order = 1, primitiveType=PrimitiveType.BYTES) - PubKey getPubKey(); -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientSettings.java deleted file mode 100644 index 95f24516..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientSettings.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueClientSettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午4:30 - * Description: - */ -package com.jd.blockchain.consensus.mq.settings; - -import com.jd.blockchain.consensus.client.ClientSettings; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -public interface MsgQueueClientSettings extends ClientSettings { - - MsgQueueNetworkSettings getMsgQueueNetworkSettings(); -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueConsensusSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueConsensusSettings.java deleted file mode 100644 index 80cadcd7..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueConsensusSettings.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueConsensusSettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午4:37 - * Description: - */ -package com.jd.blockchain.consensus.mq.settings; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.mq.config.MsgQueueBlockConfig; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Property; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ -@DataContract(code = DataCodes.CONSENSUS_MSGQUEUE_SETTINGS) -public interface MsgQueueConsensusSettings extends ConsensusSettings { - - @DataField(order = 0, refContract = true) - MsgQueueNetworkSettings getNetworkSettings(); - - @DataField(order = 1, refContract = true) - MsgQueueBlockSettings getBlockSettings(); -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNetworkSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNetworkSettings.java deleted file mode 100644 index 0bfd5061..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNetworkSettings.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.mq.config.MsgQueueNetworkSettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/12 上午11:43 - * Description: - */ -package com.jd.blockchain.consensus.mq.settings; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -/** - * - * @author shaozhuguang - * @create 2018/12/12 - * @since 1.0.0 - */ -@DataContract(code = DataCodes.CONSENSUS_MSGQUEUE_NETWORK_SETTINGS) -public interface MsgQueueNetworkSettings { - - @DataField(order = 0, primitiveType = PrimitiveType.TEXT) - String getServer(); - - @DataField(order = 1, primitiveType = PrimitiveType.TEXT) - String getTxTopic(); - - @DataField(order = 2, primitiveType = PrimitiveType.TEXT) - String getBlTopic(); - - @DataField(order = 3, primitiveType = PrimitiveType.TEXT) - String getMsgTopic(); -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java deleted file mode 100644 index 9bd2a159..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午4:50 - * Description: - */ -package com.jd.blockchain.consensus.mq.settings; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consts.DataCodes; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -@DataContract(code=DataCodes.CONSENSUS_MSGQUEUE_NODE_SETTINGS) -public interface MsgQueueNodeSettings extends NodeSettings { - -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueServerSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueServerSettings.java deleted file mode 100644 index 04ea74c2..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueServerSettings.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.consensus.mq.config.MsgQueueServerSettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/13 下午4:39 - * Description: - */ -package com.jd.blockchain.consensus.mq.settings; - -import com.jd.blockchain.consensus.service.ServerSettings; - -/** - * - * @author shaozhuguang - * @create 2018/12/13 - * @since 1.0.0 - */ - -public interface MsgQueueServerSettings extends ServerSettings { - - MsgQueueBlockSettings getBlockSettings(); - - MsgQueueConsensusSettings getConsensusSettings(); -} \ No newline at end of file diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/util/MessageConvertUtil.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/util/MessageConvertUtil.java deleted file mode 100644 index c0b032a4..00000000 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/util/MessageConvertUtil.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.mq.event.MessageConvertUtil - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/21 下午7:28 - * Description: - */ -package com.jd.blockchain.consensus.mq.util; - -import com.alibaba.fastjson.JSON; -import com.jd.blockchain.consensus.mq.event.BlockEvent; -import com.jd.blockchain.consensus.mq.event.TxBlockedEvent; -import com.jd.blockchain.utils.security.ShaUtils; - -import org.springframework.util.Base64Utils; - - -/** - * - * @author shaozhuguang - * @create 2018/11/21 - * @since 1.0.0 - */ - -public class MessageConvertUtil { - - public static final String defaultCharsetName = "UTF-8"; - - public static String base64Encode(byte[] src) { - return Base64Utils.encodeToString(src); - } - - public static byte[] base64Decode(String src) { - return Base64Utils.decodeFromString(src); - } - - public static String messageKey(byte[] src) { - return base64Encode(ShaUtils.hash_256(src)); - } - - public static BlockEvent convertBytes2BlockEvent(byte[] serializeBytes) { - String text; - try{ - text = new String(serializeBytes, defaultCharsetName); - } catch (Exception e) { - throw new RuntimeException(e); - } - return convertString2BlockEvent(text); - } - - public static BlockEvent convertString2BlockEvent(String serializeString) { - return JSON.parseObject(serializeString, BlockEvent.class); - } - - public static TxBlockedEvent convertBytes2TxBlockedEvent(byte[] serializeBytes) { - String text; - try{ - text = new String(serializeBytes, defaultCharsetName); - } catch (Exception e) { - throw new RuntimeException(e); - } - return convertString2TxBlockedEvent(text); - } - - public static TxBlockedEvent convertString2TxBlockedEvent(String serializeString) { - return JSON.parseObject(serializeString, TxBlockedEvent.class); - } - - public static byte[] serializeBlockEvent(BlockEvent blockEvent) { - String serializeString = serializeEvent(blockEvent); - byte[] serializeBytes; - try { - serializeBytes = serializeString.getBytes(defaultCharsetName); - } catch (Exception e) { - throw new RuntimeException(e); - } - return serializeBytes; - } - - public static byte[] serializeTxBlockedEvent(TxBlockedEvent txBlockedEvent) { - String serializeString = JSON.toJSONString(txBlockedEvent); - byte[] serializeBytes; - try { - serializeBytes = serializeString.getBytes(defaultCharsetName); - } catch (Exception e) { - throw new RuntimeException(e); - } - return serializeBytes; - } - - public static String serializeEvent(BlockEvent blockEvent) { - return JSON.toJSONString(blockEvent); - } -} \ No newline at end of file diff --git a/source/contract/README.MD b/source/contract/README.MD deleted file mode 100644 index 9e940486..00000000 --- a/source/contract/README.MD +++ /dev/null @@ -1,27 +0,0 @@ -### 合约相关说明 -1. 编译合约入口:ContractCompilerCmdTest.java; -2. 账本调用合约测试入口:ContractEventSendOperationHandleTest.java; - -### 单元测试注意事项 -使用ContractEventSendOperationHandleTest.java进行单元测试,注意事项: -1. 设置合约使用PUB_CLASS_PATH、CORE_CLASS_PATH位置(sys-contract.properties); -PUB包在根目录中的contract-libs文件夹;core包需要编译来生成。具体如下: - - 进入contract-jar模块,执行maven命令: - ``` - mvn clean assembly:assembly - ``` - - 生成的core包位于模块的target中的contract-jar-xxx所在的coreLib中; - - 将此coreLib目录作为CORE_CLASS_PATH指向的目录。 -2. 编译生成合约压缩包,即执行:ContractCompilerCmdTest.java对应的mainTestOk(); -在编译之前,修改sys-contract.properties文件的变量CONTRACT_FROM_PATH(合约源文件位置)、CONTRACT_SAVE_TO_PATH(合约保存位置)。 -3. 在合约保存位置中可看到生成的压缩包:xxx.contract;然后执行 ContractEventSendOperationHandleTest.java测试用例test1()即可。 - -### 20180910版本改造 -1. 在contract-jar中添加了mvn assembly处理逻辑,将合约用到的lib包全部放置其target/xxx/pubLib文件夹中,执行: -``` -mvn clean assembly:assembly -``` -2. 修改了sys-contract.properties文件,新增了CONTRACT_CLASS_LIBS参数; - - 将CONTRACT_CLASS_PATH专用于存储路径 - - CONTRACT_CLASS_LIBS来存放所有的jar包 -3. 删减了contract-libs文件夹中需要动态生成的jar。 diff --git a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractCode.java b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractCode.java deleted file mode 100644 index 2f363a55..00000000 --- a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractCode.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.contract.engine; - -import com.jd.blockchain.contract.ContractEventContext; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.utils.Bytes; - -public interface ContractCode { - - Bytes getAddress(); - - long getVersion(); - - BytesValue processEvent(ContractEventContext eventContext); -} diff --git a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractEngine.java b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractEngine.java deleted file mode 100644 index 8567c13e..00000000 --- a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractEngine.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jd.blockchain.contract.engine; - -import com.jd.blockchain.utils.Bytes; - -/** - * 合约引擎; - * - * @author huanghaiquan - * - */ -public interface ContractEngine { - - /** - * 返回指定地址的合约代码;
- * - * 如果不存在,则返回 null; - * - * @param address - * @return - */ - ContractCode getContract(Bytes address, long version); - - /** - * 装入合约代码;
- * - * 如果已经存在,则直接返回已有实例; - * - * @param address - * @param codeBytes - * @return - */ - ContractCode setupContract(Bytes address, long version, byte[] codeBytes); - -} diff --git a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractServiceProvider.java b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractServiceProvider.java deleted file mode 100644 index 753efd2f..00000000 --- a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractServiceProvider.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.contract.engine; - -public interface ContractServiceProvider { - - String getName(); - - /** - * 返回合约代码执行引擎实例; - * - * @return - */ - ContractEngine getEngine(); - -} diff --git a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractServiceProviders.java b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractServiceProviders.java deleted file mode 100644 index 146dffa6..00000000 --- a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/engine/ContractServiceProviders.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.contract.engine; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.beans.BeanUtils; -import org.springframework.util.ClassUtils; - -public class ContractServiceProviders { - - private static final Object mutex = new Object(); - private static Map providers = new ConcurrentHashMap<>(); - - public static ContractServiceProvider getProvider(String className) { - ContractServiceProvider provider = providers.get(className); - if (provider == null) { - synchronized (mutex) { - provider = providers.get(className); - if (provider == null) { - provider = loadProvider(ContractServiceProvider.class, className); - providers.put(className, provider); - } - } - } - return provider; - } - - private static T loadProvider(Class assignableTo, String implementClassName) { - Class providerClass = ClassUtils.resolveClassName(implementClassName, - ContractServiceProvider.class.getClassLoader()); - if (!assignableTo.isAssignableFrom(providerClass)) { - throw new IllegalArgumentException( - String.format("%s is not implement %s!", implementClassName, assignableTo.getName())); - } - return BeanUtils.instantiateClass(providerClass, assignableTo); - } - - public static void registerProvider(ContractServiceProvider provider) { - providers.put(provider.getName(), provider); - } -} diff --git a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/AbstractContractCode.java b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/AbstractContractCode.java deleted file mode 100644 index 2aee31f8..00000000 --- a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/AbstractContractCode.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.jd.blockchain.contract.jvm; - -import java.lang.reflect.Method; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.ReflectionUtils; - -import com.jd.blockchain.contract.ContractEventContext; -import com.jd.blockchain.contract.ContractException; -import com.jd.blockchain.contract.EventProcessingAware; -import com.jd.blockchain.contract.engine.ContractCode; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.BytesValueEncoding; -import com.jd.blockchain.ledger.BytesValueList; -import com.jd.blockchain.utils.Bytes; - -/** - * @author huanghaiquan - * - */ -public abstract class AbstractContractCode implements ContractCode { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractContractCode.class); - private Bytes address; - private long version; - - private ContractDefinition contractDefinition; - - public AbstractContractCode(Bytes address, long version, ContractDefinition contractDefinition) { - this.address = address; - this.version = version; - this.contractDefinition = contractDefinition; - } - - public ContractDefinition getContractDefinition() { - return contractDefinition; - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public BytesValue processEvent(ContractEventContext eventContext) { - EventProcessingAware evtProcAwire = null; - Object retn = null; - Method handleMethod = null; - Exception error = null; - try { - // 执行预处理; - Object contractInstance = getContractInstance(); - if (contractInstance instanceof EventProcessingAware) { - evtProcAwire = (EventProcessingAware) contractInstance; - } - - if (evtProcAwire != null) { - evtProcAwire.beforeEvent(eventContext); - } - - // 反序列化参数; - handleMethod = contractDefinition.getType().getHandleMethod(eventContext.getEvent()); - - if (handleMethod == null) { - throw new ContractException( - String.format("Contract[%s:%s] has no handle method to handle event[%s]!", address.toString(), - contractDefinition.getType().getName(), eventContext.getEvent())); - } - - BytesValueList bytesValues = eventContext.getArgs(); - Object[] args = BytesValueEncoding.decode(bytesValues, handleMethod.getParameterTypes()); - - retn = ReflectionUtils.invokeMethod(handleMethod, contractInstance, args); - - } catch (Exception e) { - error = e; - } - - if (evtProcAwire != null) { - try { - evtProcAwire.postEvent(eventContext, error); - } catch (Exception e) { - String errorMessage = "Error occurred while posting contract event! --" + e.getMessage(); - LOGGER.error(errorMessage, e); - throw new ContractException(errorMessage, e); - } - } - if (error != null) { - // Rethrow error; - throw new ContractException(String.format("Error occurred while processing event[%s] of contract[%s]! --%s", - eventContext.getEvent(), address.toString(), error.getMessage()), error); - } - - BytesValue retnBytes = BytesValueEncoding.encodeSingle(retn, handleMethod.getReturnType()); - return retnBytes; - } - - protected abstract Object getContractInstance(); - -} diff --git a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/ContractDefinition.java b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/ContractDefinition.java deleted file mode 100644 index d61e037a..00000000 --- a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/ContractDefinition.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.contract.jvm; - -import com.jd.blockchain.contract.ContractType; - -public class ContractDefinition { - - private ContractType type; - - private Class mainClass; - - public Class getMainClass() { - return mainClass; - } - - public ContractType getType() { - return type; - } - - public ContractDefinition(ContractType type, Class mainClass) { - this.type = type; - this.mainClass = mainClass; - } - -} diff --git a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/InstantiatedContractCode.java b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/InstantiatedContractCode.java deleted file mode 100644 index 94adc3a7..00000000 --- a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/InstantiatedContractCode.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jd.blockchain.contract.jvm; - -import com.jd.blockchain.contract.ContractType; -import com.jd.blockchain.utils.Bytes; - -public class InstantiatedContractCode extends AbstractContractCode { - - private T instance; - - public InstantiatedContractCode(Bytes address, long version, Class delaredInterface, T instance) { - super(address, version, resolveContractDefinition(delaredInterface, instance.getClass())); - this.instance = instance; - } - - private static ContractDefinition resolveContractDefinition(Class declaredIntf, Class implementedClass) { - ContractType contractType = ContractType.resolve(declaredIntf); - return new ContractDefinition(contractType, implementedClass); - } - - @Override - protected T getContractInstance() { - return instance; - } - - } \ No newline at end of file diff --git a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JVMContractEngine.java b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JVMContractEngine.java deleted file mode 100644 index ea1ee9fa..00000000 --- a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JVMContractEngine.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.contract.jvm; - -import com.jd.blockchain.contract.engine.ContractCode; -import com.jd.blockchain.contract.engine.ContractEngine; -import com.jd.blockchain.runtime.Module; -import com.jd.blockchain.runtime.RuntimeContext; -import com.jd.blockchain.utils.Bytes; - -public class JVMContractEngine implements ContractEngine { - - private RuntimeContext runtimeContext = RuntimeContext.get(); - - private String getCodeName(Bytes address, long version) { - return address.toBase58() + "_" + version; - } - - @Override - public ContractCode getContract(Bytes address, long version) { - String codeName = getCodeName(address, version); - Module module = runtimeContext.getDynamicModule(codeName); - if (module == null) { - return null; - } - return new JavaContractCode(address, version, module); - } - - @Override - public ContractCode setupContract(Bytes address, long version, byte[] code) { - //is there the contractCode before setup? if yes ,then return; - ContractCode contractCode = getContract(address,version); - if(contractCode != null){ - return contractCode; - } - String codeName = getCodeName(address, version); - Module module = runtimeContext.createDynamicModule(codeName,code); - if (module == null) { - return null; - } - return new JavaContractCode(address, version, module); - } -} diff --git a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JVMContractServiceProvider.java b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JVMContractServiceProvider.java deleted file mode 100644 index 013537bf..00000000 --- a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JVMContractServiceProvider.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.contract.jvm; - -import com.jd.blockchain.contract.engine.ContractEngine; -import com.jd.blockchain.contract.engine.ContractServiceProvider; - -public class JVMContractServiceProvider implements ContractServiceProvider { - @Override - public String getName() { - return JVMContractServiceProvider.class.getName(); - } - - @Override - public ContractEngine getEngine() { - return InnerEngine.INSTANCE; - } - - private static class InnerEngine { - private static final ContractEngine INSTANCE = new JVMContractEngine(); - } -} diff --git a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JavaContractCode.java b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JavaContractCode.java deleted file mode 100644 index fa4d8260..00000000 --- a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JavaContractCode.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jd.blockchain.contract.jvm; - -import java.util.concurrent.Callable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEventContext; -import com.jd.blockchain.contract.ContractException; -import com.jd.blockchain.contract.ContractType; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.runtime.Module; -import com.jd.blockchain.utils.Bytes; - -/** - * 基于 java jar 包并且以模块化方式独立加载的合约代码; - * - * @author huanghaiquan - * - */ -public class JavaContractCode extends AbstractContractCode { - private static final Logger LOGGER = LoggerFactory.getLogger(JavaContractCode.class); - private Module codeModule; - private Bytes address; - private long version; - - public JavaContractCode(Bytes address, long version, Module codeModule) { - super(address, version, resolveContractDefinition(codeModule)); - this.address = address; - this.version = version; - this.codeModule = codeModule; - } - - protected static ContractDefinition resolveContractDefinition(Module codeModule) { - String mainClassName = codeModule.getMainClass(); - Class mainClass = codeModule.loadClass(mainClassName); - Class[] interfaces = mainClass.getInterfaces(); - Class contractInterface = null; - for (Class itf : interfaces) { - Contract annoContract = itf.getAnnotation(Contract.class); - if (annoContract != null) { - if (contractInterface == null) { - contractInterface = itf; - } else { - throw new ContractException( - "One contract definition is only allowed to implement one contract type!"); - } - } - } - if (contractInterface == null) { - throw new ContractException("No contract type is implemented!"); - } - ContractType type = ContractType.resolve(contractInterface); - return new ContractDefinition(type, mainClass); - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public BytesValue processEvent(ContractEventContext eventContext) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Start processing event{} of contract{}...", eventContext.getEvent(), address.toString()); - } - try { - return codeModule.call(new ContractExecution(eventContext)); - } catch (Exception ex) { - LOGGER.error(String.format("Error occurred while processing event[%s] of contract[%s]! --%s", - eventContext.getEvent(), address.toString(), ex.getMessage()), ex); - throw ex; - } finally { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("End processing event{} of contract{}. ", eventContext.getEvent(), address.toString()); - } - } - } - - protected Object getContractInstance() { - try { - // 每一次调用都通过反射创建合约的实例; - return getContractDefinition().getMainClass().newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private class ContractExecution implements Callable { - private ContractEventContext eventContext; - - public ContractExecution(ContractEventContext contractEventContext) { - this.eventContext = contractEventContext; - } - - @Override - public BytesValue call() throws Exception { - return JavaContractCode.super.processEvent(eventContext); - } - } - -} diff --git a/source/contract/contract-maven-plugin/ReadME.MD b/source/contract/contract-maven-plugin/ReadME.MD deleted file mode 100644 index 1cc457b6..00000000 --- a/source/contract/contract-maven-plugin/ReadME.MD +++ /dev/null @@ -1,274 +0,0 @@ -# 合约编译插件使用教程 - -### 1、maven引入 - -在pom.xml文件中引入合约编译插件: -```xml - - com.jd.blockchain - contract-maven-plugin - 1.0.0.RELEASE - - - make-contract - package - - compile - - - - - - - com.jd.chain.contracts.ContractTestInfImpl - - - contract - - - -``` - -需要说明的几点如下: - + 1)version:请根据实际JDChain发布版本确认,不同版本会有区别; - + 2)executions->execution->id:该值请随意指定; - + 3)executions->execution->phase:建议使用package及其后续阶段(若不了解phase含义,请自行查阅相关信息); - + 4)executions->execution->goals->goal:必须使用compile; - + 5)mainClass:必填,该类为需要发布的合约执行类(注意此处是类,不是接口),必须正确配置; - + 6)finalName:必填,最终在编译正常的情况下,会产生{finalName}-JDChain-Contract.jar文件,只有该文件是可以发布到JDChain的合约包; - - -### 2、执行命令 -使用mvn执行命令,下面两种方式均可: - -方式一:只执行contract插件命令 -```shell - mvn clean compile contract:compile -``` - -方式二:直接执行打包命令: -```shell -mvn clean package -``` - - -### 3、合约编写要求 -合约的执行结果会对整条链产生比较深刻的影响,为了使用户能够更好、更合理的使用合约,目前JDChain约定合约编写规则包括以下几点: - -(违反其中任何一点都可能导致合约编译失败,但即使合约编译通过也不能保证合约可百分百运行正常) - - + 1)合约工程必须引入com.jd.blockchain:sdk-pack:该包中有合约正常编写需要使用的基本类; - + 2)com.jd.blockchain:sdk-pack的scope必须定义为provided; - + 3)合约发布必须通过合约编译插件进行打包:合约编译插件不但会对Jar包进行校验,同时也会加入JDChain独有的特征,只有具有该特征的Jar才能正常发布; - + 4)合约中严禁使用随机数、IO、NIO等操作; - + 5)合约打包时,请使用provided排除常用的工具包,例如FastJson、apache下的一些工具包等; - + 6)合约必须有一个接口和该接口的实现类,详细要求如下: - - a. 接口必须有@Contract注解; - - b. 接口的可调用方法上必须有@ContractEvent注解,且每个注解中的name属性不能重复; - - c. 合约方法支持入参和返回值,其主要包括所有基本类型; - - - -### 4、合约案例 - -#### 4.1、代码实例 -以下是一个可创建银行账户,指定具体金额,并可以转账的合约代码(逻辑较简单,仅供参考): - -合约接口代码如下: -```java -package com.jd.chain.contract; - - -@Contract -public interface TransferContract { - - @ContractEvent(name = "create") - String create(String address, String account, long money); - - @ContractEvent(name = "transfer") - String transfer(String address, String from, String to, long money); - - @ContractEvent(name = "read") - long read(String address, String account); - - @ContractEvent(name = "readAll") - String readAll(String address, String account); -} - -``` - -合约实现类代码如下: -```java -package com.jd.chain.contract; - -import com.alibaba.fastjson.JSON; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.KVDataEntry; -import com.jd.blockchain.ledger.KVDataVO; -import com.jd.blockchain.ledger.KVInfoVO; - -public class TransferContractImpl implements EventProcessingAware, TransferContract { - - private ContractEventContext eventContext; - - private HashDigest ledgerHash; - - @Override - public String create(String address, String account, long money) { - KVDataEntry[] kvDataEntries = eventContext.getLedger().getDataEntries(ledgerHash, address, account); - // 肯定有返回值,但若不存在则返回version=-1 - if (kvDataEntries != null && kvDataEntries.length > 0) { - long currVersion = kvDataEntries[0].getVersion(); - if (currVersion > -1) { - throw new IllegalStateException(String.format("%s -> %s already have created !!!", address, account)); - } - eventContext.getLedger().dataAccount(address).setInt64(account, money, -1L); - } else { - throw new IllegalStateException(String.format("Ledger[%s] inner Error !!!", ledgerHash.toBase58())); - } - return String.format("DataAccountAddress[%s] -> Create(By Contract Operation) Account = %s and Money = %s Success!!! \r\n", - address, account, money); - } - - @Override - public String transfer(String address, String from, String to, long money) { - // 首先查询余额 - KVDataEntry[] kvDataEntries = eventContext.getLedger().getDataEntries(ledgerHash, address, from, to); - if (kvDataEntries == null || kvDataEntries.length != 2) { - throw new IllegalStateException(String.format("%s -> %s - %s may be not created !!!", address, from, to)); - } else { - // 判断from账号中钱数量是否足够 - long fromMoney = 0L, toMoney = 0L, fromVersion = 0L, toVersion = 0L; - for (KVDataEntry kvDataEntry : kvDataEntries) { - if (kvDataEntry.getKey().equals(from)) { - fromMoney = (long) kvDataEntry.getValue(); - fromVersion = kvDataEntry.getVersion(); - } else { - toMoney = (long) kvDataEntry.getValue(); - toVersion = kvDataEntry.getVersion(); - } - } - if (fromMoney < money) { - throw new IllegalStateException(String.format("%s -> %s not have enough money !!!", address, from)); - } - long fromNewMoney = fromMoney - money; - long toNewMoney = toMoney + money; - // 重新设置 - eventContext.getLedger().dataAccount(address).setInt64(from, fromNewMoney, fromVersion); - eventContext.getLedger().dataAccount(address).setInt64(to, toNewMoney, toVersion); - } - - return String.format("DataAccountAddress[%s] transfer from [%s] to [%s] and [money = %s] Success !!!", address, from, to, money); - } - - @Override - public long read(String address, String account) { - KVDataEntry[] kvDataEntries = eventContext.getLedger().getDataEntries(ledgerHash, address, account); - if (kvDataEntries == null || kvDataEntries.length == 0) { - return -1; - } - return (long)kvDataEntries[0].getValue(); - } - - @Override - public String readAll(String address, String account) { - KVDataEntry[] kvDataEntries = eventContext.getLedger().getDataEntries(ledgerHash, address, account); - // 获取最新的版本号 - if (kvDataEntries == null || kvDataEntries.length == 0) { - return ""; - } - long newestVersion = kvDataEntries[0].getVersion(); - if (newestVersion == -1) { - return ""; - } - KVDataVO[] kvDataVOS = new KVDataVO[1]; - long[] versions = new long[(int)newestVersion + 1]; - for (int i = 0; i < versions.length; i++) { - versions[i] = i; - } - KVDataVO kvDataVO = new KVDataVO(account, versions); - - kvDataVOS[0] = kvDataVO; - - KVInfoVO kvInfoVO = new KVInfoVO(kvDataVOS); - - KVDataEntry[] allEntries = eventContext.getLedger().getDataEntries(ledgerHash, address, kvInfoVO); - - return JSON.toJSONString(allEntries); - } - - @Override - public void beforeEvent(ContractEventContext eventContext) { - this.eventContext = eventContext; - this.ledgerHash = eventContext.getCurrentLedgerHash(); - } - - @Override - public void postEvent(ContractEventContext eventContext, Exception error) { - - } -} -``` - - -#### 4.2、pom.xml文件实例 - -```xml - - - - - com.jd.chain - 1.0.0.RELEASE - 4.0.0 - - contract-samples - - contract-samples - - - - com.jd.blockchain - sdk-pack - 1.0.0.RELEASE - provided - - - - com.alibaba - fastjson - 1.2.32 - provided - - - - - - - com.jd.blockchain - contract-maven-plugin - 1.0.0.RELEASE - - - make-contract - package - - compile - - - - - - - com.jd.chain.contract.TransferContractImpl - - - contract - - - - - - -``` \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/conf/jd-com.priv b/source/contract/contract-maven-plugin/conf/jd-com.priv deleted file mode 100644 index 93d38cf8..00000000 --- a/source/contract/contract-maven-plugin/conf/jd-com.priv +++ /dev/null @@ -1 +0,0 @@ -177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/conf/jd-com.pub b/source/contract/contract-maven-plugin/conf/jd-com.pub deleted file mode 100644 index 29ca057d..00000000 --- a/source/contract/contract-maven-plugin/conf/jd-com.pub +++ /dev/null @@ -1 +0,0 @@ -endPsK36imXrY66pru6ttZ8dZ3TynWekmdqoM1K7ZRRoRBBiYVzM \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/conf/ownerPassword.txt b/source/contract/contract-maven-plugin/conf/ownerPassword.txt deleted file mode 100644 index f2ba8f84..00000000 --- a/source/contract/contract-maven-plugin/conf/ownerPassword.txt +++ /dev/null @@ -1 +0,0 @@ -abc \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/readme.txt b/source/contract/contract-maven-plugin/readme.txt deleted file mode 100644 index 46697cce..00000000 --- a/source/contract/contract-maven-plugin/readme.txt +++ /dev/null @@ -1,19 +0,0 @@ -说明 -1.编译:mvn clean install - -快速自测: -1.ContractRemoteAutoMojoTest类用于快速自测发布和执行,快速自测是在测试链的环境中发布和执行合约; -2.修改sys-contract.properties文件中的相关信息; -3.合约发布之后,会在控制台生成合约地址,待5秒钟之后,会执行此合约。sys-contract.properties的contractArgs参数可修改,查看其不同效果; -### -contract's address=5SmEqUsnLY4APVfS32xYDpRPuz55Rsuupdt1 -execute the contract,result=true -exeContract(),SUCCESS -### -4.在peer节点的控制台可以看到输出的结果信息。 - -通过maven插件中通过ContractAllAutoMojo做简单的编译、发布和执行测试,对应单元测试类ContractAllAutoMojoTest; - - - - diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployExeUtil.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployExeUtil.java deleted file mode 100644 index b84cc712..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployExeUtil.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.jd.blockchain; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * @Author zhaogw - * @Date 2018/11/2 10:18 - */ -public enum ContractDeployExeUtil { - instance; - private BlockchainService bcsrv; - private Bytes contractAddress; - - public BlockchainKeypair getKeyPair(String pubPath, String prvPath, String rawPassword){ - PubKey pub = null; - PrivKey prv = null; - try { - prv = KeyGenUtils.readPrivKey(prvPath, KeyGenUtils.encodePassword(rawPassword)); - pub = KeyGenUtils.readPubKey(pubPath); - - } catch (Exception e) { - e.printStackTrace(); - } - - return new BlockchainKeypair(pub, prv); - } - - public PubKey getPubKey(String pubPath){ - PubKey pub = null; - try { - if(pubPath == null){ - BlockchainKeypair contractKeyPair = BlockchainKeyGenerator.getInstance().generate(); - pub = contractKeyPair.getPubKey(); - }else { - pub = KeyGenUtils.readPubKey(pubPath); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return pub; - } - public byte[] getChainCode(String path){ - byte[] chainCode = null; - File file = null; - InputStream input = null; - try { - file = new File(path); - input = new FileInputStream(file); - chainCode = new byte[input.available()]; - input.read(chainCode); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if(input!=null){ - input.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return chainCode; - } - - private void register(){ - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class); - DataContractRegistry.register(Operation.class); - DataContractRegistry.register(ContractCodeDeployOperation.class); - DataContractRegistry.register(ContractEventSendOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - } - - public BlockchainService initBcsrv(String host, int port) { - if(bcsrv!=null){ - return bcsrv; - } - NetworkAddress addr = new NetworkAddress(host, port); - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(addr); - bcsrv = gwsrvFact.getBlockchainService(); - return bcsrv; - } - - public boolean deploy(HashDigest ledgerHash, BlockchainIdentity contractIdentity, BlockchainKeypair ownerKey, byte[] chainCode){ - register(); - - TransactionTemplate txTpl = bcsrv.newTransaction(ledgerHash); - txTpl.contracts().deploy(contractIdentity, chainCode); - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(ownerKey); - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - contractAddress = contractIdentity.getAddress(); - this.setContractAddress(contractAddress); - System.out.println("contract's address="+contractAddress); - return txResp.isSuccess(); - } - public boolean deploy(String host, int port, HashDigest ledgerHash, BlockchainKeypair ownerKey, byte[] chainCode){ - register(); - - BlockchainIdentity contractIdentity = BlockchainKeyGenerator.getInstance().generate().getIdentity(); - initBcsrv(host,port); - return deploy(ledgerHash, contractIdentity, ownerKey, chainCode); - } - - // 根据用户指定的公钥生成合约地址 - public boolean deploy(String host, int port, String ledger,String ownerPubPath, String ownerPrvPath, - String ownerPassword, String chainCodePath,String pubPath){ - PubKey pubKey = getPubKey(pubPath); - BlockchainIdentity contractIdentity = new BlockchainIdentityData(pubKey); - byte[] chainCode = getChainCode(chainCodePath); - - BlockchainKeypair ownerKey = getKeyPair(ownerPubPath, ownerPrvPath, ownerPassword); - HashDigest ledgerHash = new HashDigest(Base58Utils.decode(ledger)); - initBcsrv(host,port); - return deploy(ledgerHash, contractIdentity, ownerKey, chainCode); - } - - -// 暂不支持从插件执行合约;此外,由于合约参数调用的格式发生变化,故此方法被废弃;by: huanghaiquan at 2019-04-30; - -// public boolean exeContract(String ledger,String ownerPubPath, String ownerPrvPath, -// String ownerPassword,String event,String contractArgs){ -// BlockchainKeypair ownerKey = getKeyPair(ownerPubPath, ownerPrvPath, ownerPassword); -// HashDigest ledgerHash = new HashDigest(Base58Utils.decode(ledger)); -// -// // 定义交易,传输最简单的数字、字符串、提取合约中的地址; -// TransactionTemplate txTpl = bcsrv.newTransaction(ledgerHash); -// txTpl.contractEvents().send(getContractAddress(),event,contractArgs.getBytes()); -// -// // 签名; -// PreparedTransaction ptx = txTpl.prepare(); -// ptx.sign(ownerKey); -// -// // 提交并等待共识返回; -// TransactionResponse txResp = ptx.commit(); -// -// // 验证结果; -// return txResp.isSuccess(); -// } - - public Bytes getContractAddress() { - return contractAddress; - } - - public void setContractAddress(Bytes contractAddress) { - this.contractAddress = contractAddress; - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployMojo.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployMojo.java deleted file mode 100644 index 427fe00f..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployMojo.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.jd.blockchain; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.utils.StringUtils; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.FileUtils; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * for contract remote deploy; - * @goal contractDeploy - * @phase process-sources - * @Author zhaogw - * @Date 2018/10/18 10:12 - */ - -@Mojo(name = "deploy") -public class ContractDeployMojo extends AbstractMojo { - Logger logger = LoggerFactory.getLogger(ContractDeployMojo.class); - - @Parameter - private File config; - - @Override - public void execute()throws MojoFailureException { - Properties prop = new Properties(); - InputStream input = null; - - try { - input = new FileInputStream(config); - prop.load(input); - - } catch (IOException ex) { - logger.error(ex.getMessage()); - throw new MojoFailureException("io error"); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - logger.error(e.getMessage()); - } - } - } - int port; - try { - port = Integer.parseInt(prop.getProperty("port")); - }catch (NumberFormatException e){ - logger.error(e.getMessage()); - throw new MojoFailureException("invalid port"); - } - String host = prop.getProperty("host"); - String ledger = prop.getProperty("ledger"); - String pubKey = prop.getProperty("pubKey"); - String prvKey = prop.getProperty("prvKey"); - String password = prop.getProperty("password"); - String contractPath = prop.getProperty("contractPath"); - - - if(StringUtils.isEmpty(host)){ - logger.info("host不能为空"); - return; - } - - if(StringUtils.isEmpty(ledger)){ - logger.info("ledger不能为空."); - return; - } - if(StringUtils.isEmpty(pubKey)){ - logger.info("pubKey不能为空."); - return; - } - if(StringUtils.isEmpty(prvKey)){ - logger.info("prvKey不能为空."); - return; - } - if(StringUtils.isEmpty(contractPath)){ - logger.info("contractPath不能为空."); - return; - } - - File contract = new File(contractPath); - if (!contract.isFile()){ - logger.info("文件"+contractPath+"不存在"); - return; - } - byte[] contractBytes = FileUtils.readBytes(contractPath); - - - PrivKey prv = KeyGenUtils.decodePrivKeyWithRawPassword(prvKey, password); - PubKey pub = KeyGenUtils.decodePubKey(pubKey); - BlockchainKeypair blockchainKeyPair = new BlockchainKeypair(pub, prv); - HashDigest ledgerHash = new HashDigest(Base58Utils.decode(ledger)); - - StringBuffer sb = new StringBuffer(); - sb.append("host:"+ host).append(",port:"+port).append(",ledgerHash:"+ledgerHash.toBase58()). - append(",pubKey:"+pubKey).append(",prvKey:"+prv).append(",contractPath:"+contractPath); - logger.info(sb.toString()); - ContractDeployExeUtil.instance.deploy(host,port,ledgerHash, blockchainKeyPair, contractBytes); - } - -} - - diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/AbstractContract.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/AbstractContract.java deleted file mode 100644 index 389dd33a..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/AbstractContract.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.jd.blockchain.contract.maven; - -import com.jd.blockchain.contract.maven.rule.BlackList; -import com.jd.blockchain.contract.maven.rule.WhiteList; - -import java.util.List; - -public abstract class AbstractContract { - - protected String className; - - public String getClassName() { - return className; - } - - public String getDotClassName() { - return className.replaceAll("/", "."); - } - - protected String format(final String inputFormat) { - String formatResult; - - String outputFormat = inputFormat; - if (inputFormat.endsWith(";")) { - outputFormat = inputFormat.substring(0, inputFormat.length() - 1); - } - if (outputFormat.startsWith("[L") && outputFormat.length() > 2) { - // 说明是数组,但不显示 - formatResult = outputFormat.substring(2); - } else if (outputFormat.startsWith("[") && outputFormat.length() > 1) { - // 说明是数组 - formatResult = outputFormat.substring(1); - } else if (outputFormat.startsWith("L") && outputFormat.length() > 1) { - // 说明是非基础类型 - formatResult = outputFormat.substring(1); - } else { - formatResult = outputFormat; - } - - return formatResult; - } - - public static BlackList initBlack(List blackList) { - BlackList contractBlack = new BlackList(); - if (blackList != null && !blackList.isEmpty()) { - for (String black : blackList) { - // 首先判断该black是package还是 - String packageName = isPackageAndReturn(black); - if (packageName != null) { - // 说明是包 - contractBlack.addBlackPackage(packageName); - } else { - String[] classAndMethod = black.split("-"); - if (classAndMethod.length == 1) { - // 说明只有ClassName - contractBlack.addBlack(classAndMethod[0], BlackList.COMMON_METHOD); - } else { - contractBlack.addBlack(classAndMethod[0], classAndMethod[1]); - } - } - } - } - - return contractBlack; - } - - public static WhiteList initWhite(List whiteList) { - WhiteList contractWhite = new WhiteList(); - - if (whiteList != null && !whiteList.isEmpty()) { - for (String white : whiteList) { - String packageName = isPackageAndReturn(white); - if (packageName != null) { - // 说明是包 - contractWhite.addWhite(packageName); - } else { - contractWhite.addWhite(white); - } - } - } - - return contractWhite; - } - - /** - * 获取配置的packageName - * - * @param config - * @return - * 假设为包,则返回其包名,否则返回NULL - */ - public static String isPackageAndReturn(String config) { - if (config.endsWith("*")) { - return config.substring(0, config.length() - 2); - } - return null; - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractClass.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractClass.java deleted file mode 100644 index b9d3de7b..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractClass.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jd.blockchain.contract.maven; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class ContractClass extends AbstractContract { - - // 若出现同名的方法则进行合并(将两个方法中涉及到的内容合并在一起) - private Map methods = new ConcurrentHashMap<>(); - - public ContractClass(String className) { - if (className.contains(".")) { - this.className = className.replaceAll("\\.", "/"); - } else { - this.className = className; - } - } - - /** - * 返回构造方法 - * - * @return - */ - public ContractMethod constructor() { - return methods.get(ContractConstant.METHOD_INIT); - } - - /** - * 返回该类的所有变量 - * - * @return - */ - public List fields() { - - List fields = new ArrayList<>(); - - // 构造方法 - ContractMethod initMethod = constructor(); - if (initMethod != null) { - fields.addAll(initMethod.getClassFieldList(className)); - } - // CLINIT方法 - ContractMethod clInitMethod = methods.get(ContractConstant.METHOD_CLINIT); - if (clInitMethod != null) { - fields.addAll(clInitMethod.getClassFieldList(className)); - } - return fields; - } - - public synchronized ContractMethod method(String methodName) { - if (methods.containsKey(methodName)) { - return methods.get(methodName); - } - ContractMethod method = new ContractMethod(this.className, methodName); - - methods.put(methodName, method); - - return method; - } - - public Map getMethods() { - return methods; - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractCompileMojo.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractCompileMojo.java deleted file mode 100644 index a98eeca3..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractCompileMojo.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.jd.blockchain.contract.maven; - -import com.jd.blockchain.contract.maven.rule.BlackList; -import com.jd.blockchain.contract.maven.rule.WhiteList; -import com.jd.blockchain.contract.maven.rule.DependencyExclude; -import com.jd.blockchain.contract.maven.verify.ResolveEngine; -import com.jd.blockchain.contract.maven.verify.VerifyEngine; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.assembly.mojos.SingleAssemblyMojo; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.project.MavenProject; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -import static com.jd.blockchain.contract.ContractJarUtils.BLACK_CONF; -import static com.jd.blockchain.contract.ContractJarUtils.WHITE_CONF; - -@Mojo(name = "compile") -public class ContractCompileMojo extends SingleAssemblyMojo { - - public static final String JAR_DEPENDENCE = "jar-with-dependencies"; - - public static final String SCOPE_PROVIDED = "provided"; - - public static final String SCOPE_COMPILE = "compile"; - - private DependencyExclude dependencyExclude = new DependencyExclude(); - - private static BlackList black; - - private static WhiteList white; - - static { - init(); - } - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - // 首先对MainClass进行校验,要求必须有MainClass - String mainClass = mainClassVerify(); - - // 排除所有依赖,只打包当前代码 -// excludeAllArtifactExclude(super.getProject().getDependencyArtifacts()); -// handleArtifactCompile(super.getProject().getDependencyArtifacts()); - handleArtifactExclude(super.getProject().getDependencyArtifacts()); - - // 此参数用于设置将所有第三方依赖的Jar包打散为.class,与主代码打包在一起,生成一个jar包 - super.setDescriptorRefs(new String[]{JAR_DEPENDENCE}); - - // 执行打包命令 - // 该命令生成的是只含有当前项目的实际代码的Jar包,该Jar包仅用于校验MainClass - super.execute(); - - // 生成解析引擎 - ResolveEngine resolveEngine = new ResolveEngine(getLog(), mainClass); - - // 获取本次生成的Jar文件 - File defaultJarFile; - try { - defaultJarFile = rename(getProject(), getFinalName()); - // 校验当前MainClass是否满足需求 - resolveEngine.verifyCurrentProjectMainClass(defaultJarFile); - // 校验完成后将该Jar删除 -// FileUtils.forceDelete(mainClassFile); - } catch (Exception e) { - getLog().error(e); - throw new MojoFailureException(e.getMessage()); - } - -// // 将JDChain本身之外的代码打包进Jar包,然后编译 -// handleArtifactExclude(super.getProject().getDependencyArtifacts()); -// -// // 此参数用于设置将所有第三方依赖的Jar包打散为.class,与主代码打包在一起,生成一个jar包 -// super.setDescriptorRefs(new String[]{JAR_DEPENDENCE}); -// -// // 生成Jar包(该Jar包中不包含JDChain内部的代码) -// super.execute(); -// -// File defaultJarFile; -// try { -// defaultJarFile = rename(getProject(), getFinalName()); -// } catch (Exception e) { -// getLog().error(e); -// throw new MojoFailureException(e.getMessage()); -// } - - // 校验该Jar包 - verify(defaultJarFile, mainClass); - - File deployJarFile = resolveEngine.verify(defaultJarFile); - - // 删除中间产生的临时文件 - try { - FileUtils.forceDelete(defaultJarFile); - } catch (Exception e) { - getLog().error(e); - } - - getLog().info(String.format("JDChain's Contract compile success, path = %s !", deployJarFile.getPath())); - - - -// // 将JDChain本身代码之外的代码移除(不打包进整个Jar) -// handleArtifactExclude(super.getProject().getDependencyArtifacts()); -// -// // 此参数用于设置将所有第三方依赖的Jar包打散为.class,与主代码打包在一起,生成一个jar包 -// super.setDescriptorRefs(new String[]{JAR_DEPENDENCE}); -// -// // 执行打包命令 -// super.execute(); - -// // 将本次打包好的文件重新命名,以便于后续重新打包需要 -// // 把文件改名,然后重新再生成一个文件 -// File dstFile; -// try { -// dstFile = rename(getProject(), getFinalName()); -// } catch (IOException e) { -// getLog().error(e); -// throw new MojoFailureException(e.getMessage()); -// } -// -// // dstFile理论上应该含有 -// -// // 首先校验该类的Jar包中是否包含不符合规范的命名,以及该类的代码中的部分解析 -// -// ResolveEngine resolveEngine = new ResolveEngine(getLog(), mainClass); -// -// // 校验mainClass -// resolveEngine.verifyCurrentProjectMainClass(dstFile); -// -// -// -// File finalJarFile = resolveEngine.verify(); -// -// // 将所有的依赖的jar包全部打包进一个包中,以便于进行ASM检查 -// handleArtifactCompile(super.getProject().getDependencyArtifacts()); -// -// // 然后再打包一次,本次打包完成后,其中的代码包含所有的class(JDK自身的除外) -// super.execute(); -// -// File jarFile = new File(jarPath(getProject(), getFinalName())); -// -// // 校验mainClass -// resolveEngine.verifyCurrentProjectMainClass(jarFile); -// -// // 对代码中的一些规则进行校验,主要是校验其是否包含一些不允许使用的类、包、方法等 -// verify(jarFile, mainClass); -// -// // 删除中间的一些文件 -//// try { -//// FileUtils.forceDelete(dstFile); -//// } catch (IOException e) { -//// throw new MojoFailureException(e.getMessage()); -//// } -// - // 若执行到此处没有异常则表明打包成功,打印打包成功消息 -// getLog().info(String.format("JDChain's Contract compile success, path = %s !", finalJarFile.getPath())); - } - - private String mainClassVerify() throws MojoFailureException { - // 要求必须有MainClass - String mainClass; - try { - mainClass = super.getJarArchiveConfiguration().getManifest().getMainClass(); - // 校验MainClass,要求MainClass必须不能为空 - if (mainClass == null || mainClass.length() == 0) { - throw new MojoFailureException("MainClass is NULL !!!"); - } - super.getLog().debug("MainClass is " + mainClass); - } catch (Exception e) { - throw new MojoFailureException("MainClass is null: " + e.getMessage(), e ); - } - return mainClass; - } - - private void handleArtifactExclude(Set artifacts) { - for (Artifact artifact : artifacts) { - String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(); - if (dependencyExclude.isExclude(groupId, artifactId)) { - getLog().info(String.format("GroupId[%s] ArtifactId[%s] belongs to DependencyExclude !!!", groupId, artifactId)); - // 属于排除的名单之中 - artifact.setScope(SCOPE_PROVIDED); - } else { - getLog().info(String.format("GroupId[%s] ArtifactId[%s] not belongs to DependencyExclude !!!", groupId, artifactId)); - // 属于排除的名单之中 - artifact.setScope(SCOPE_COMPILE); - } - } - } - - private void excludeAllArtifactExclude(Set artifacts) { - for (Artifact artifact : artifacts) { - artifact.setScope(SCOPE_PROVIDED); - } - } - - private void handleArtifactCompile(Set artifacts) { - for (Artifact artifact : artifacts) { - if (artifact.getScope().equals(SCOPE_PROVIDED)) { - // 将所有的provided设置为compile,以便于后续编译 - artifact.setScope(SCOPE_COMPILE); - } - } - } - - private File rename(MavenProject project, String finalName) throws IOException { - String srcJarPath = jarPath(project, finalName); - String dstJarPath = project.getBuild().getDirectory() + - File.separator + finalName + ".jar"; - File dstFile = new File(dstJarPath); - FileUtils.copyFile(new File(srcJarPath), dstFile); - FileUtils.forceDelete(new File(srcJarPath)); - return dstFile; - } - - private String jarPath(MavenProject project, String finalName) { - return project.getBuild().getDirectory() + - File.separator + finalName + "-" + JAR_DEPENDENCE + ".jar"; - } - - private void verify(File jarFile, String mainClass) throws MojoFailureException { - try { - VerifyEngine verifyEngine = new VerifyEngine(getLog(), jarFile, mainClass, black, white); - - verifyEngine.verify(); - - // 校验完成后将该jar包删除 -// FileUtils.forceDelete(jarFile); - - } catch (Exception e) { - getLog().error(e); - throw new MojoFailureException(e.getMessage()); - } - } - - - - private static void init() { - try { - black = AbstractContract.initBlack(loadBlackConf()); - white = AbstractContract.initWhite(loadWhiteConf()); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - private static List loadWhiteConf() { - - return resolveConfig(WHITE_CONF); - } - - private static List loadBlackConf() { - return resolveConfig(BLACK_CONF); - } - - private static List resolveConfig(String fileName) { - List configs = new ArrayList<>(); - - try { - List readLines = loadConfig(fileName); - if (!readLines.isEmpty()) { - for (String readLine : readLines) { - String[] lines = readLine.split(","); - configs.addAll(Arrays.asList(lines)); - } - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - - return configs; - } - - public static List loadConfig(String fileName) throws Exception { - - return IOUtils.readLines( - ContractCompileMojo.class.getResourceAsStream("/" + fileName)); - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractConstant.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractConstant.java deleted file mode 100644 index a94fb624..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractConstant.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.contract.maven; - -public class ContractConstant { - - public static final String METHOD_INIT = ""; - - public static final String METHOD_CLINIT = ""; - -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractField.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractField.java deleted file mode 100644 index f4b0f396..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractField.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jd.blockchain.contract.maven; - -public class ContractField extends AbstractContract { - - private String fieldName; - - private String fieldType; - - private boolean isStatic; - - public ContractField(String className, String fieldName, String fieldType) { - this(className, fieldName, fieldType, false); - } - - public ContractField(String className, String fieldName, String fieldType, boolean isStatic) { - this.className = format(className); - this.fieldName = fieldName; - this.fieldType = format(fieldType); - this.isStatic = isStatic; - } - - public String getFieldName() { - return fieldName; - } - - public String getFieldType() { - return fieldType; - } - - public boolean isStatic() { - return isStatic; - } - - @Override - public String toString() { - return "ContractField{" + - "className='" + className + '\'' + - ", fieldName='" + fieldName + '\'' + - ", fieldType='" + fieldType + '\'' + - ", isStatic=" + isStatic + - '}'; - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractMethod.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractMethod.java deleted file mode 100644 index 6dc2e3a7..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/ContractMethod.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.jd.blockchain.contract.maven; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class ContractMethod extends AbstractContract { - - private String methodName; - - private String[] paramTypes; - - private String[] returnTypes; - - private List fieldList = new ArrayList<>(); - - private List methodList = new ArrayList<>(); - - public ContractMethod(String className, String methodName) { - this(className, methodName, null, null); - } - - public ContractMethod(String className, String methodName, String[] paramTypes, String[] returnTypes) { - this.className = format(className); - this.methodName = methodName; - this.paramTypes = paramTypes; - this.returnTypes = returnTypes; - } - - public void addMethod(String className, String methodName, String[] paramTypes, String[] returnTypes) { - methodList.add(new ContractMethod(className, methodName, paramTypes, returnTypes)); - } - - public void addField(String className, String fieldName, String fieldType) { - this.fieldList.add(new ContractField(className, fieldName, fieldType)); - } - - public void addStaticField(String className, String fieldName, String fieldType) { - this.fieldList.add(new ContractField(className, fieldName, fieldType, true)); - } - - public String getMethodName() { - return methodName; - } - - public String[] getParamTypes() { - return paramTypes; - } - - public List getAllFieldList() { - return fieldList; - } - - public List getClassFieldList(String cName) { - List classFieldList = new ArrayList<>(); - if (!fieldList.isEmpty()) { - for (ContractField field : fieldList) { - if (field.getClassName().equals(cName)) { - classFieldList.add(field); - } - } - } - return classFieldList; - } - - public List getMethodList() { - return methodList; - } - - @Override - public String toString() { - return "ContractMethod{" + - "className='" + className + '\'' + - ", methodName='" + methodName + '\'' + - ", paramTypes=" + Arrays.toString(paramTypes) + - ", returnTypes=" + Arrays.toString(returnTypes) + - ", fieldList=" + fieldList + - ", methodList=" + methodList + - '}'; - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/asm/ASMClassVisitor.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/asm/ASMClassVisitor.java deleted file mode 100644 index 27bfeee4..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/asm/ASMClassVisitor.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.contract.maven.asm; - -import com.jd.blockchain.contract.maven.ContractClass; -import com.jd.blockchain.contract.maven.ContractMethod; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -public class ASMClassVisitor extends ClassVisitor { - - private ContractClass contractClass; - - public ASMClassVisitor(ContractClass contractClass) { - super(Opcodes.ASM5); - this.contractClass = contractClass; - } - public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - MethodVisitor superMV = super.visitMethod(access, name, desc, signature, exceptions); - ContractMethod method = this.contractClass.method(name); - return new ASMMethodVisitor(superMV, method); - } -} \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/asm/ASMMethodVisitor.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/asm/ASMMethodVisitor.java deleted file mode 100644 index 03488203..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/asm/ASMMethodVisitor.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jd.blockchain.contract.maven.asm; - -import com.jd.blockchain.contract.maven.ContractMethod; -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.TypePath; - -import java.util.ArrayList; -import java.util.List; - -public class ASMMethodVisitor extends MethodVisitor { - - private ContractMethod method; - - public ASMMethodVisitor(MethodVisitor mv, ContractMethod method) { - super(Opcodes.ASM5, mv); - this.method = method; - } - - @Override - public void visitFieldInsn(int type, String cName, String fName, String fType) { - if (type == 178 || type == 179) { - this.method.addStaticField(cName, fName, fType); - } else { - this.method.addField(cName, fName, fType); - } - super.visitFieldInsn(type, cName, fName, fType); - } - - @Override - public void visitMethodInsn(int type, String cName, String mName, String params, boolean b) { - ParamsAndReturn paramsAndReturn = resolveParamsAndReturn(params); - this.method.addMethod(cName, mName, paramsAndReturn.paramTypes, paramsAndReturn.returnTypes); - super.visitMethodInsn(type, cName, mName, params, b); - } - - private ParamsAndReturn resolveParamsAndReturn(String params) { - // 格式: - // 1、(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; - // 2、()I - // 3、(Ljava/lang/String;)V - // 4、()V - // 5、([Ljava/lang/Object;)Ljava/util/List; false - // 从上面分析可以得出:括号内的是入参,右括号后面的是返回值,其中V表示Void,即空; - String[] paramArray = params.split("\\)"); - String paramTypeChars = ""; - if (!paramArray[0].equals("(")) { - // 表明入参不为空 - paramTypeChars = paramArray[0].split("\\(")[1]; - } - String returnTypeChars = paramArray[1]; - return new ParamsAndReturn(paramTypeChars, returnTypeChars); - } - - static class ParamsAndReturn { - - String[] paramTypes; - - String[] returnTypes; - - public ParamsAndReturn(String paramsTypeChars, String returnTypeChars) { - initParamsType(paramsTypeChars); - initReturnType(returnTypeChars); - } - - private void initParamsType(String paramsTypeChars) { - List paramList = handleTypes(paramsTypeChars); - if (!paramList.isEmpty()) { - this.paramTypes = new String[paramList.size()]; - paramList.toArray(this.paramTypes); - } - } - - private void initReturnType(String returnTypeChar) { - // 按照分号分隔 - List returnList = handleTypes(returnTypeChar); - if (!returnList.isEmpty()) { - this.returnTypes = new String[returnList.size()]; - returnList.toArray(this.returnTypes); - } - } - - private List handleTypes(String typeChars) { - String[] types = typeChars.split(";"); - List typeList = new ArrayList<>(); - if (types.length > 0) { - for (String type : types) { - if (type.length() > 0) { - if (type.startsWith("[L") && type.length() > 2) { - // 说明是数组 - typeList.add(type.substring(2) + "[]"); - } else if (type.startsWith("[") && type.length() > 1) { - // 说明是数组 - typeList.add(type.substring(1)); - } else if (type.startsWith("L") && type.length() > 1) { - // 说明是非基础类型 - typeList.add(type.substring(1)); - } else { - typeList.add(type); - } - } - } - } - return typeList; - } - } -} \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/BlackList.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/BlackList.java deleted file mode 100644 index 593093aa..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/BlackList.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.jd.blockchain.contract.maven.rule; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -public class BlackList { - - public static final String COMMON_METHOD = "*"; - - public static final String INIT_METHOD = "init"; - - // 合约黑名单 - private final Map blackClassMap = new ConcurrentHashMap<>(); - - private final List blackPackages = new ArrayList<>(); - - public synchronized BlackList addBlack(String className, String methodName) { - String trimClassName = className.trim(); - BlackClass blackClass = blackClassMap.get(trimClassName); - if (blackClass != null) { - blackClass.addMethod(methodName); - } else { - blackClass = new BlackClass(trimClassName); - blackClass.addMethod(methodName); - blackClassMap.put(trimClassName, blackClass); - } - return this; - } - - public synchronized BlackList addBlack(Class clazz, String methodName) { - return addBlack(clazz.getName(), methodName); - } - - public synchronized BlackList addBlack(Class clazz) { - return addBlack(clazz.getName(), COMMON_METHOD); - } - - public synchronized BlackList addBlackPackage(String packageName) { - blackPackages.add(packageName.trim() + "."); // 末尾增加一个点,防止后续判断是拼凑 - return this; - } - - public boolean isBlackClass(String className) { - if (isContainsPackage(className)) { - return true; - } - BlackClass blackClass = blackClassMap.get(className); - if (blackClass == null) { - return false; - } - return blackClass.isBlack(); - } - - public boolean isBlack(Class clazz, String methodName) { - - // 判断该Class是否属于黑名单 - if (isCurrentClassBlack(clazz, methodName)) { - return true; - } - // 当前Class不是黑名单的情况下,处理其对应的父类和接口 - // 获取该Class对应的接口和父类列表 - Set> superClassAndAllInterfaces = new HashSet<>(); - - loadSuperClassAndAllInterfaces(clazz, superClassAndAllInterfaces); - - // 循环判断每个父类和接口 - for (Class currClass : superClassAndAllInterfaces) { - if (isCurrentClassBlack(currClass, methodName)) { - return true; - } - } - return false; - } - - public boolean isCurrentClassBlack(Class clazz, String methodName) { - - String packageName = clazz.getPackage().getName(); - for (String bp : blackPackages) { - if ((packageName + ".").equals(bp) || packageName.startsWith(bp)) { - return true; - } - } - // 判断该类本身是否属于黑名单 - String className = clazz.getName(); - BlackClass blackClass = blackClassMap.get(className); - if (blackClass != null) { - // 判断其方法 - return blackClass.isBlack(methodName); - } - return false; - } - - public boolean isBlackField(Class clazz) { - return isBlack(clazz, INIT_METHOD); - } - - private boolean isContainsPackage(String className) { - for (String bp : blackPackages) { - if (className.equals(bp) || className.startsWith(bp)) { - return true; - } - } - return false; - } - - private void loadSuperClassAndAllInterfaces(Class currentClass, Set> allClassList) { - if (currentClass == null) { - return; - } - - if (!allClassList.contains(currentClass)) { - allClassList.add(currentClass); - // 处理其父类 - Class superClass = currentClass.getSuperclass(); - loadSuperClassAndAllInterfaces(superClass, allClassList); - - // 处理其所有接口 - Class[] allInterfaces = currentClass.getInterfaces(); - if (allInterfaces != null && allInterfaces.length > 0) { - for (Class intf : allInterfaces) { - loadSuperClassAndAllInterfaces(intf, allClassList); - } - } - } - } - - private static class BlackClass { - - String className; - - Set methods = new HashSet<>(); - - BlackClass(String className) { - this.className = className; - } - - void addMethod(String methodName) { - methods.add(methodName); - } - - boolean isBlack(String methodName) { - // 假设method为*则表示所有的方法 - if (methods.contains(COMMON_METHOD)) { - return true; - } - return methods.contains(methodName); - } - - boolean isBlack() { - return isBlack(COMMON_METHOD); - } - } -} - - diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/DependencyExclude.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/DependencyExclude.java deleted file mode 100644 index c20ce777..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/DependencyExclude.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.jd.blockchain.contract.maven.rule; - -import com.jd.blockchain.contract.maven.ContractCompileMojo; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class DependencyExclude { - - private static final String COMMON_ARTIFACTID = "*"; - - private static final String CONFIG = "providers.conf"; - - private static final Map> DEPENDENCYS = new ConcurrentHashMap<>(); - - static { - try { - init(); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - private static void init() throws Exception { - List readLines = ContractCompileMojo.loadConfig(CONFIG); - if (!readLines.isEmpty()) { - for (String line : readLines) { - // groupId/artifactId - String[] lines = line.split(","); - if (lines.length > 0) { - for (String depend : lines) { - String[] depends = depend.split("/"); - if (depends.length == 2) { - String groupId = depends[0], artifactId = depends[1]; - Dependency dependency = new Dependency(groupId, artifactId); - addDependency(dependency); - } - } - } - } - } - } - - private synchronized static void addDependency(Dependency dependency) { - String groupId = dependency.groupId; - if (!DEPENDENCYS.containsKey(groupId)) { - List dependencies = new ArrayList<>(); - dependencies.add(dependency); - DEPENDENCYS.put(groupId, dependencies); - } else { - List dependencies = DEPENDENCYS.get(groupId); - dependencies.add(dependency); - } - } - - public boolean isExclude(String groupId, String artifactId) { - List dependencies = DEPENDENCYS.get(groupId); - - if (dependencies == null || dependencies.isEmpty()) { - return false; - } - - for (Dependency dependency : dependencies) { - if (dependency.isEqualArtifactId(artifactId)) { - return true; - } - } - - return false; - } - - - static class Dependency { - - String groupId; - - String artifactId; - - public Dependency(String groupId, String artifactId) { - this.groupId = groupId; - this.artifactId = artifactId; - } - - public boolean isEqualArtifactId(String artiId) { - if (artifactId.equals(COMMON_ARTIFACTID)) { - return true; - } - return artifactId.equals(artiId); - } - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/WhiteList.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/WhiteList.java deleted file mode 100644 index eeb1e250..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/rule/WhiteList.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.contract.maven.rule; - -import java.util.ArrayList; -import java.util.List; - -public class WhiteList { - - // 合约白名单(白名单通常数量较少,主要是JDChain内部包) - private final List whiteClasses = new ArrayList<>(); - - public void addWhite(String className) { - whiteClasses.add(className.trim()); - } - - public boolean isWhite(Class clazz) { - String className = clazz.getName(); - return isWhite(className); - } - - public boolean isWhite(String className) { - for (String white : whiteClasses) { - if (white.equals(className) || className.startsWith(white)) { - return true; - } - } - return false; - } -} - - diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/verify/ResolveEngine.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/verify/ResolveEngine.java deleted file mode 100644 index 97744689..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/verify/ResolveEngine.java +++ /dev/null @@ -1,169 +0,0 @@ -package com.jd.blockchain.contract.maven.verify; - -import com.alibaba.fastjson.JSON; -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractJarUtils; -import com.jd.blockchain.contract.ContractType; -import com.jd.blockchain.contract.EventProcessingAware; -import org.apache.commons.io.FileUtils; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.logging.Log; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import static com.jd.blockchain.contract.ContractJarUtils.*; - -public class ResolveEngine { - - private Log LOGGER; - -// private File jarFile; - - private String mainClass; - -// public ResolveEngine(Log LOGGER, File jarFile, String mainClass) { - public ResolveEngine(Log LOGGER, String mainClass) { - this.LOGGER = LOGGER; -// this.jarFile = jarFile; - this.mainClass = mainClass; - } - - /** - * 校验当前项目中MainClass其是否满足JDChain合约写法 - * - * @param mainClassJarFile - * @throws MojoFailureException - */ - public void verifyCurrentProjectMainClass(File mainClassJarFile) throws MojoFailureException { - // 校验MainClass - try { - LOGGER.debug(String.format("Verify Jar [%s] 's MainClass start...", mainClassJarFile.getName())); - // 自定义ClassLoader,必须使用Thread.currentThread().getContextClassLoader() - // 保证其项目内部加载的Jar包无须再加载一次 - URLClassLoader classLoader = new URLClassLoader(new URL[]{mainClassJarFile.toURI().toURL()}, - Thread.currentThread().getContextClassLoader()); - - // 从MainClass作为入口进行MainClass代码校验 - Class mClass = classLoader.loadClass(mainClass); - ContractType.resolve(mClass); - - // 校验完成后需要释放,否则无法删除该Jar文件 - classLoader.close(); - - LOGGER.debug(String.format("Verify Jar [%s] 's MainClass end...", mainClassJarFile.getName())); - } catch (Exception e) { - throw new MojoFailureException(e.getMessage()); - } - } - - public File verify(File defaultJarFile) throws MojoFailureException { - try { - // 检查jar包中所有的class的命名,要求其包名不能为com.jd.blockchain.* - LinkedList totalClasses = loadAllClass(defaultJarFile); - - if (!totalClasses.isEmpty()) { - - for (String clazz : totalClasses) { - - String dotClassName = dotClassName(clazz); - - LOGGER.debug(String.format("Verify Dependency Class[%s] start......", dotClassName)); - // 获取其包名 - // 将class转换为包名 - String packageName = class2Package(dotClassName); - - if (ContractJarUtils.isJDChainPackage(packageName)) { - throw new IllegalStateException(String.format("Class[%s]'s package[%s] cannot start with %s !", - dotClassName, packageName, ContractJarUtils.JDCHAIN_PACKAGE)); - } - - LOGGER.debug(String.format("Verify Class[%s] end......", clazz)); - } - } - - // 处理完成之后,生成finalName-JDChain-Contract.jar - return compileCustomJar(defaultJarFile); - } catch (Exception e) { - LOGGER.error(e.getMessage()); - throw new MojoFailureException(e.getMessage()); - } - } - - private String class2Package(String dotClassName) { - - return dotClassName.substring(0, dotClassName.lastIndexOf(".")); - } - - private File compileCustomJar(File defaultJarFile) throws IOException { - - String fileParentPath = defaultJarFile.getParentFile().getPath(); - - String jarFileName = defaultJarFile.getName(); - - String fileName = jarFileName.substring(0, jarFileName.lastIndexOf(".")); - - // 首先将Jar包转换为指定的格式 - String dstJarPath = fileParentPath + File.separator + - fileName + "-temp-" + System.currentTimeMillis() + ".jar"; - - File srcJar = defaultJarFile, dstJar = new File(dstJarPath); - - LOGGER.debug(String.format("Jar from [%s] to [%s] Copying", defaultJarFile.getPath(), dstJarPath)); - // 首先进行Copy处理 - copy(srcJar, dstJar); - - LOGGER.debug(String.format("Jar from [%s] to [%s] Copied", defaultJarFile.getPath(), dstJarPath)); - - byte[] txtBytes = contractMF(FileUtils.readFileToByteArray(dstJar)).getBytes(StandardCharsets.UTF_8); - - String finalJarPath = fileParentPath + File.separator + fileName + "-JDChain-Contract.jar"; - - File finalJar = new File(finalJarPath); - - // 生成最终的Jar文件 - copy(dstJar, finalJar, contractMFJarEntry(), txtBytes, null); - - // 删除临时文件 - FileUtils.forceDelete(dstJar); - - return finalJar; - } - - private ClassLoader verifyMainClass(File jarFile) throws Exception { - // 加载main-class,开始校验类型 - LOGGER.debug(String.format("Verify Jar [%s] 's MainClass start...", jarFile.getName())); - URL jarURL = jarFile.toURI().toURL(); - ClassLoader classLoader = new URLClassLoader(new URL[]{jarURL}); - Class mClass = classLoader.loadClass(mainClass); - ContractType.resolve(mClass); - LOGGER.debug(String.format("Verify Jar [%s] 's MainClass end...", jarFile.getName())); - return classLoader; - } - - private LinkedList loadAllClass(File file) throws Exception { - JarFile jarFile = new JarFile(file); - LinkedList allClass = new LinkedList<>(); - Enumeration jarEntries = jarFile.entries(); - while (jarEntries.hasMoreElements()) { - JarEntry jarEntry = jarEntries.nextElement(); - String entryName = jarEntry.getName(); - if (entryName.endsWith(".class")) { - // 内部类,不需要处理 - if (!entryName.contains("$")) { - allClass.addLast(entryName.substring(0, entryName.length() - 6)); - } - } - } - // Jar文件使用完成后需要关闭,否则可能会产生无法删除的问题 - jarFile.close(); - - return allClass; - } -} diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/verify/VerifyEngine.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/verify/VerifyEngine.java deleted file mode 100644 index 7fd59c7e..00000000 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/contract/maven/verify/VerifyEngine.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.jd.blockchain.contract.maven.verify; - -import com.jd.blockchain.contract.ContractJarUtils; -import com.jd.blockchain.contract.maven.ContractClass; -import com.jd.blockchain.contract.maven.ContractField; -import com.jd.blockchain.contract.maven.ContractMethod; -import com.jd.blockchain.contract.maven.asm.ASMClassVisitor; -import com.jd.blockchain.contract.maven.rule.BlackList; -import com.jd.blockchain.contract.maven.rule.WhiteList; -import org.apache.maven.plugin.logging.Log; -import org.objectweb.asm.ClassReader; - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import static com.jd.blockchain.contract.ContractJarUtils.loadAllClasses; - - -public class VerifyEngine { - - private Log LOGGER; - - private File jarFile; - - private String mainClass; - - private BlackList black; - - private WhiteList white; - - // 代表的只是当前方法,不代表该方法中的内部方法 - private Set haveManagedMethods = new HashSet<>(); - - // 代表的是处理的参数 - private Set haveManagedFields = new HashSet<>(); - - public VerifyEngine(Log LOGGER, File jarFile, String mainClass, BlackList black, WhiteList white) { - this.LOGGER = LOGGER; - this.jarFile = jarFile; - this.mainClass = mainClass; - this.black = black; - this.white = white; - } - - public void verify() throws Exception { - // 加载所有的jar,然后ASM获取MAP - URL jarURL = jarFile.toURI().toURL(); - - URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{jarURL}, - Thread.currentThread().getContextClassLoader()); - - // 解析Jar包中所有的Class - Map allContractClasses = resolveClasses(jarClasses()); - - // 开始处理MainClass - verify(urlClassLoader, allContractClasses); - - // 校验完成后需要释放ClassLoader,否则无法删除该Jar包 - urlClassLoader.close(); - } - - public void verify(URLClassLoader urlClassLoader, Map allContractClasses) throws Exception { - // 获取MainClass - String mainClassKey = convertClassKey(mainClass); - ContractClass mainContractClass = allContractClasses.get(mainClassKey); - if (mainContractClass == null) { - LOGGER.error(String.format("Load Main Class = [%s] NULL !!!", mainClass)); - throw new IllegalStateException("MainClass is NULL !!!"); - } - // 校验该Class中所有方法 - Map methods = mainContractClass.getMethods(); - if (!methods.isEmpty()) { - for (Map.Entry entry : methods.entrySet()) { - ContractMethod method = entry.getValue(); - verify(urlClassLoader, allContractClasses, method); - } - } - } - - public void verify(URLClassLoader urlClassLoader, Map allContractClasses, ContractMethod method) throws Exception { - // 获取方法中涉及到的所有的Class及Method - // 首先判断该方法对应的Class是否由urlClassLoader加载 - // 首先判断该ClassName对应方法是否处理过 - String managedKey = managedKey(method); - if (haveManagedMethods.contains(managedKey)) { - return; - } - // 将该方法设置为已处理 - haveManagedMethods.add(managedKey); - String dotClassName = method.getDotClassName(); - - - Class dotClass = urlClassLoader.loadClass(dotClassName); - - if (dotClass == null) { - return; - } - String dotClassLoader = null; - ClassLoader classLoader = dotClass.getClassLoader(); - - if (classLoader != null) { - dotClassLoader = dotClass.getClassLoader().toString(); - } - - if (dotClassLoader != null && dotClassLoader.contains("URLClassLoader")) { - - // 说明是URLClassLoader,这个需要先从黑名单和白名单列表中操作 - // 首先判断是否是黑名单,黑名单优先级最高 - if (black.isBlack(dotClass, method.getMethodName())) { - throw new IllegalStateException(String.format("Class [%s] Method [%s] is Black !!!", dotClassName, method.getMethodName())); - } else { - // 不是黑名单的情况下,判断是否为白名单 - if (white.isWhite(dotClass)) { - return; - } - // 如果不属于白名单,则需要判断其子方法 - List innerMethods = method.getMethodList(); - if (!innerMethods.isEmpty()) { - for (ContractMethod innerMethod : innerMethods) { - // 需要重新从AllMap中获取,因为生成时并未处理其关联关系 - ContractClass innerClass = allContractClasses.get(innerMethod.getClassName()); - if (innerClass != null) { - ContractMethod verifyMethod = innerClass.method(innerMethod.getMethodName()); - verify(urlClassLoader, allContractClasses, verifyMethod); - } else { - verify(urlClassLoader, allContractClasses, innerMethod); - } - } - } - List innerFields = method.getAllFieldList(); - if (!innerFields.isEmpty()) { - for (ContractField innerField : innerFields) { - verify(urlClassLoader, innerField); - } - } - } - } else { - // 非URLClassLoader加载的类,只需要做判断即可 - // 对于系统加载的类,其白名单优先级高于黑名单 - // 1、不再需要获取其方法; - // 首先判断是否为白名单 - if (white.isWhite(dotClass)) { - return; - } - // 然后判断其是否为黑名单 - if (black.isBlack(dotClass, method.getMethodName())) { - throw new IllegalStateException(String.format("Class [%s] Method [%s] is Black !!!", dotClassName, method.getMethodName())); - } - } - } - - public void verify(URLClassLoader urlClassLoader, ContractField field) throws Exception { - // 获取方法中涉及到的所有的Class及Method - // 首先判断该方法对应的Class是否由urlClassLoader加载 - // 首先判断该ClassName对应方法是否处理过 - String managedKey = managedKey(field); - if (haveManagedFields.contains(managedKey)) { - return; - } - // 将该字段设置为已读 - haveManagedFields.add(managedKey); - - Class dotClass = urlClassLoader.loadClass(field.getDotClassName()); - - if (dotClass == null) { - return; - } - - if (black.isBlackField(dotClass)) { - throw new IllegalStateException(String.format("Class [%s] Field [%s] is Black !!!", field.getDotClassName(), field.getFieldName())); - } - } - - private Map jarClasses() throws Exception { - return loadAllClasses(jarFile); - } - - private Map resolveClasses(Map allClasses) { - - Map allContractClasses = new ConcurrentHashMap<>(); - - for (Map.Entry entry : allClasses.entrySet()) { - byte[] classContent = entry.getValue(); - if (classContent == null || classContent.length == 0) { - continue; - } - String className = entry.getKey().substring(0, entry.getKey().length() - 6); - - String dotClassName = ContractJarUtils.dotClassName(className); - if (white.isWhite(dotClassName) || black.isBlackClass(dotClassName)) { - continue; - } - - ContractClass contractClass = new ContractClass(className); - ClassReader cr = new ClassReader(classContent); - cr.accept(new ASMClassVisitor(contractClass), ClassReader.SKIP_DEBUG); - allContractClasses.put(className, contractClass); - } - return allContractClasses; - } - - private String convertClassKey(final String classKey) { - String newClassKey = classKey; - if (classKey.endsWith(".class")) { - newClassKey = classKey.substring(0, classKey.length() - 6); - } - newClassKey = newClassKey.replaceAll("\\.", "/"); - return newClassKey; - } - - private String managedKey(ContractMethod method) { - return method.getDotClassName() + "-" + method.getMethodName(); - } - - private String managedKey(ContractField field) { - return field.getDotClassName() + "--" + field.getFieldName(); - } -} diff --git a/source/contract/contract-maven-plugin/src/main/resources/blacks.conf b/source/contract/contract-maven-plugin/src/main/resources/blacks.conf deleted file mode 100644 index caa20370..00000000 --- a/source/contract/contract-maven-plugin/src/main/resources/blacks.conf +++ /dev/null @@ -1,19 +0,0 @@ -java.io.File -java.io.InputStream -java.io.OutputStream -java.io.DataInput -java.io.DataOutput -java.io.Reader -java.io.Writer -java.io.Flushable -java.nio.channels.* -java.nio.file.* -java.net.* -java.sql.* -java.lang.reflect.* -java.lang.Class -java.lang.ClassLoader -java.util.Random -java.lang.System-currentTimeMillis -java.lang.System-nanoTime -com.jd.blockchain.ledger.BlockchainKeyGenerator-generate \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/src/main/resources/providers.conf b/source/contract/contract-maven-plugin/src/main/resources/providers.conf deleted file mode 100644 index b2df66eb..00000000 --- a/source/contract/contract-maven-plugin/src/main/resources/providers.conf +++ /dev/null @@ -1,22 +0,0 @@ -com.jd.blockchain/* -com.alibaba/fastjson -org.slf4j/* -org.apache.logging.log4j/* -org.aspectj/* -redis.clients/* -org.rocksdb/* -io.grpc/* -org.apache.commons/* -org.apache.httpcomponents/* -org.apache.logging.log4j/* -org.reflections/reflections -com.google.guava/guava -commons-cli/commons-cli -commons-codec/commons-codec -commons-httpclient/commons-httpclient -commons-io/commons-io -io.netty/* -org.slf4j/* -org.springframework.boot/* -org.springframework.security/* -org.springframework/* \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/src/main/resources/whites.conf b/source/contract/contract-maven-plugin/src/main/resources/whites.conf deleted file mode 100644 index 08e7d754..00000000 --- a/source/contract/contract-maven-plugin/src/main/resources/whites.conf +++ /dev/null @@ -1,3 +0,0 @@ -com.jd.blockchain.* -java.nio.charset.Charset -com.alibaba.fastjson.* \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractDeployMojoTest.java b/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractDeployMojoTest.java deleted file mode 100644 index bb907445..00000000 --- a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractDeployMojoTest.java +++ /dev/null @@ -1,21 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import com.jd.blockchain.contract.maven.ContractDeployMojo; -// -//import java.lang.reflect.Field; -// -///** -// * for contract deploy and exe; -// * @Author zhaogw -// * @Date 2018/11/02 09:06 -// */ -//public class ContractDeployMojoTest { -// private ContractDeployMojo contractDeployMojo = new ContractDeployMojo(); -// -// private void fieldHandle(String fieldName,Object objValue) throws NoSuchFieldException, IllegalAccessException { -// Field field = contractDeployMojo.getClass().getDeclaredField(fieldName);//name为类Instance中的private属性 -// field.setAccessible(true);//=true,可访问私有变量。 -// Class typeClass = field.getType(); -// field.set(contractDeployMojo, objValue); -// } -//} diff --git a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractTestBase.java b/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractTestBase.java deleted file mode 100644 index e3065766..00000000 --- a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractTestBase.java +++ /dev/null @@ -1,50 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import org.apache.maven.model.Build; -//import org.apache.maven.project.MavenProject; -//import org.junit.Test; -//import org.springframework.core.io.ClassPathResource; -// -//import java.io.File; -// -//public class ContractTestBase { -// -// public static MavenProject mavenProjectInit() { -// MavenProject mavenProject = new MavenProject(); -// mavenProject.setBuild(buildInit()); -// mavenProject.setFile(file()); -// return mavenProject; -// } -// -// public static File file() { -// String resDir = resourceDir(); -// File file = new File(resDir); -// String path = file.getParentFile().getParentFile().getPath(); -// return new File(path + File.separator + "src"); -// } -// -// public static Build buildInit() { -// Build build = new Build(); -// build.setDirectory(resourceDir()); -// return build; -// } -// -// public static String resourceDir() { -// try { -// ClassPathResource classPathResource = new ClassPathResource("complex.jar"); -// return classPathResource.getFile().getParentFile().getPath(); -// } catch (Exception e) { -// throw new IllegalStateException(e); -// } -// } -// -// @Test -// public void testResourceDir() { -// System.out.println(resourceDir()); -// } -// -// @Test -// public void testFile() { -// System.out.println(file().getPath()); -// } -//} diff --git a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractVerifyMojoTest.java b/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractVerifyMojoTest.java deleted file mode 100644 index 119f5cbf..00000000 --- a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractVerifyMojoTest.java +++ /dev/null @@ -1,28 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import com.jd.blockchain.contract.maven.ContractVerifyMojo; -//import org.apache.maven.plugin.testing.AbstractMojoTestCase; -//import org.junit.Test; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -// -//import java.io.File; -// -///** -// * @Author zhaogw -// * @Date 2019/3/1 21:27 -// */ -//public class ContractVerifyMojoTest extends AbstractMojoTestCase { -// Logger logger = LoggerFactory.getLogger(ContractVerifyMojoTest.class); -// -// @Test -// public void test1() throws Exception { -// File pom = getTestFile( "src/test/resources/project-to-test/pom.xml" ); -// assertNotNull( pom ); -// assertTrue( pom.exists() ); -// -// ContractVerifyMojo myMojo = (ContractVerifyMojo) lookupMojo( "contractVerify", pom ); -// assertNotNull( myMojo ); -// myMojo.execute(); -// } -//} diff --git a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractVerifyTest_.java b/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractVerifyTest_.java deleted file mode 100644 index ea6828b6..00000000 --- a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/ContractVerifyTest_.java +++ /dev/null @@ -1,47 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import com.jd.blockchain.contract.maven.ContractVerifyMojo; -//import org.apache.maven.project.MavenProject; -//import org.junit.Before; -//import org.junit.Test; -// -//import java.lang.reflect.Field; -// -//import static com.jd.blockchain.ledger.ContractTestBase.mavenProjectInit; -// -//public class ContractVerifyTest_ { -// -// private MavenProject project; -// -// private String finalName; -// -// @Before -// public void testInit() { -// project = mavenProjectInit(); -// finalName = "complex"; -// } -// -// @Test -// public void test() throws Exception { -// ContractVerifyMojo contractVerifyMojo = contractVerifyMojoConf(); -// contractVerifyMojo.execute(); -// } -// -// private ContractVerifyMojo contractVerifyMojoConf() throws Exception { -// ContractVerifyMojo contractVerifyMojo = new ContractVerifyMojo(); -// // 为不影响其内部结构,通过反射进行私有变量赋值 -// Class clazz = contractVerifyMojo.getClass(); -// Field projectField = clazz.getDeclaredField("project"); -// Field finalNameField = clazz.getDeclaredField("finalName"); -// -// // 更新权限 -// projectField.setAccessible(true); -// finalNameField.setAccessible(true); -// -// // 设置具体值 -// projectField.set(contractVerifyMojo, project); -// finalNameField.set(contractVerifyMojo, finalName); -// -// return contractVerifyMojo; -// } -//} diff --git a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/MyProjectStub.java b/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/MyProjectStub.java deleted file mode 100644 index 34614e30..00000000 --- a/source/contract/contract-maven-plugin/src/test/java/com/jd/blockchain/ledger/MyProjectStub.java +++ /dev/null @@ -1,67 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import org.apache.maven.model.Build; -//import org.apache.maven.model.Model; -//import org.apache.maven.model.io.xpp3.MavenXpp3Reader; -//import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -//import org.codehaus.plexus.util.ReaderFactory; -// -//import java.io.File; -//import java.util.ArrayList; -//import java.util.List; -// -///** -// * @author zhaogw -// * date 2019/6/4 18:33 -// */ -// -//public class MyProjectStub extends MavenProjectStub -//{ -// /** -// * Default constructor -// */ -// public MyProjectStub() -// { -// MavenXpp3Reader pomReader = new MavenXpp3Reader(); -// Model model; -// try -// { -// model = pomReader.read( ReaderFactory.newXmlReader( new File( getBasedir(), "pom.xml" ) ) ); -// setModel( model ); -// } -// catch ( Exception e ) -// { -// throw new RuntimeException( e ); -// } -// -// setGroupId( model.getGroupId() ); -// setArtifactId( model.getArtifactId() ); -// setVersion( model.getVersion() ); -// setName( model.getName() ); -// setUrl( model.getUrl() ); -// setPackaging( model.getPackaging() ); -// -// Build build = new Build(); -// build.setFinalName( model.getArtifactId() ); -// build.setDirectory( getBasedir() + "/target" ); -// build.setSourceDirectory( getBasedir() + "/src/main/java" ); -// build.setOutputDirectory( getBasedir() + "/target/classes" ); -// build.setTestSourceDirectory( getBasedir() + "/src/test/java" ); -// build.setTestOutputDirectory( getBasedir() + "/target/test-classes" ); -// setBuild( build ); -// -// List compileSourceRoots = new ArrayList(); -// compileSourceRoots.add( getBasedir() + "/src/main/java" ); -// setCompileSourceRoots( compileSourceRoots ); -// -// List testCompileSourceRoots = new ArrayList(); -// testCompileSourceRoots.add( getBasedir() + "/src/test/java" ); -// setTestCompileSourceRoots( testCompileSourceRoots ); -// } -// -// /** {@inheritDoc} */ -// public File getBasedir() -// { -// return new File( super.getBasedir() + "/src/test/resources/project-to-test/" ); -// } -//} diff --git a/source/contract/contract-maven-plugin/src/test/resources/AssetContract3.contract b/source/contract/contract-maven-plugin/src/test/resources/AssetContract3.contract deleted file mode 100644 index 0874a68f..00000000 Binary files a/source/contract/contract-maven-plugin/src/test/resources/AssetContract3.contract and /dev/null differ diff --git a/source/contract/contract-maven-plugin/src/test/resources/complex.jar b/source/contract/contract-maven-plugin/src/test/resources/complex.jar deleted file mode 100644 index 3c595b4d..00000000 Binary files a/source/contract/contract-maven-plugin/src/test/resources/complex.jar and /dev/null differ diff --git a/source/contract/contract-maven-plugin/src/test/resources/contract.properties b/source/contract/contract-maven-plugin/src/test/resources/contract.properties deleted file mode 100644 index b0f816f9..00000000 --- a/source/contract/contract-maven-plugin/src/test/resources/contract.properties +++ /dev/null @@ -1,3 +0,0 @@ -#\u5408\u7EA6\u76F8\u5173\u5C5E\u6027 -#Fri Nov 02 17:13:02 CST 2018 -contract=com.jd.blockchain.contract.AssetContract3 diff --git a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/AssetContract2.java b/source/contract/contract-maven-plugin/src/test/resources/project-to-test/AssetContract2.java deleted file mode 100644 index 19822d00..00000000 --- a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/AssetContract2.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jd.blockchain.contract; - -import com.jd.blockchain.utils.Bytes; - -/** - * 示例:一个“资产管理”智能合约; - * - * @author zhaogw - */ -@Contract -public interface AssetContract2 { - - /** - * 发行资产; - * 新发行的资产数量; - * @param assetHolderAddress - * 新发行的资产的持有账户; - */ - @ContractEvent(name = "issue-asset-0") - void issue(ContractBizContent contractBizContent, String assetHolderAddress); - - /** - * 发行资产; - * 新发行的资产数量; - * @param assetHolderAddress - * 新发行的资产的持有账户; - */ - @ContractEvent(name = "issue-asset") - void issue(ContractBizContent contractBizContent, String assetHolderAddress, long cashNumber); - - @ContractEvent(name = "issue-asset-2") - void issue(Bytes bytes, String assetHolderAddress, long cashNumber); - - @ContractEvent(name = "issue-asset-3") - void issue(Byte byteObj, String assetHolderAddress, long cashNumber); - - @ContractEvent(name = "issue-asset-4") - void issue(Byte byteObj, String assetHolderAddress, Bytes cashNumber); -} \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/AssetContractImpl2.java b/source/contract/contract-maven-plugin/src/test/resources/project-to-test/AssetContractImpl2.java deleted file mode 100644 index 9f5588bb..00000000 --- a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/AssetContractImpl2.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.jd.blockchain.contract; - -import com.jd.blockchain.ledger.KVDataEntry; -import com.jd.blockchain.ledger.KVDataObject; -import com.jd.blockchain.utils.Bytes; - -import java.util.Arrays; - -/** - * 示例:一个“资产管理”智能合约的实现; - * - * 注: 1、实现 EventProcessingAwire 接口以便合约实例在运行时可以从上下文获得合约生命周期事件的通知; 2、实现 - * AssetContract 接口定义的合约方法; - * - * @author huanghaiquan - * - */ -@Contract -public class AssetContractImpl2 implements EventProcessingAwire, AssetContract2 { - public static String KEY_TOTAL = "total"; - // 合约事件上下文; - private ContractEventContext eventContext; - - @Override - @ContractEvent(name = "issue-asset-0") - public void issue(ContractBizContent contractBizContent, String assetHolderAddress) { - System.out.println("input addr="+ Arrays.toString(contractBizContent.getAttrs())); - } - - @Override - @ContractEvent(name = "issue-asset") - public void issue(ContractBizContent contractBizContent, String assetHolderAddress, long cashNumber) { - System.out.println("eventContext="+eventContext.getCurrentLedgerHash().toBase58()); - System.out.println("getAttrs: "+Arrays.toString(contractBizContent.getAttrs())+",address="+assetHolderAddress+",cashNumber="+cashNumber); - - eventContext.getLedger().dataAccount(assetHolderAddress).set(contractBizContent.getAttrs()[0], "value1",-1); - eventContext.getLedger().dataAccount(assetHolderAddress).set(contractBizContent.getAttrs()[1], 888,-1); - } - - @Override - @ContractEvent(name = "issue-asset-2") - public void issue(Bytes bytes, String assetHolderAddress, long cashNumber){ - System.out.println(String.format("bytes=%s,assetHolderAddress=%s,cashNumber=%d",new String(bytes.toBytes()),assetHolderAddress,cashNumber)); - } - - @ContractEvent(name = "issue-asset-3") - @Override - public void issue(Byte byteObj, String assetHolderAddress, long cashNumber) { - System.out.println(String.format("issue(),bytes=%d,assetHolderAddress=%s,cashNumber=%d",byteObj.intValue(),assetHolderAddress,cashNumber)); - } - - @ContractEvent(name = "issue-asset-4") - @Override - public void issue(Byte byteObj, String assetHolderAddress, Bytes cashNumber) { - System.out.println(String.format("issue(),bytes=%d,assetHolderAddress=%s,cashNumber=%s",byteObj.intValue(),assetHolderAddress,cashNumber.toString())); - System.out.println("current LedgerHash="+eventContext.getCurrentLedgerHash().toBase58()); - // 查询当前值; - KVDataEntry[] kvEntries = eventContext.getLedger().getDataEntries(eventContext.getCurrentLedgerHash(), assetHolderAddress, KEY_TOTAL); -// 计算资产的发行总数; - KVDataObject curTotal = (KVDataObject) kvEntries[0]; - System.out.println("currTotal version="+curTotal.getVersion()+",value="+curTotal.getValue().toString()); - eventContext.getLedger().dataAccount(assetHolderAddress).set(KEY_TOTAL, 100,curTotal.getVersion()); - } - - /* - * (non-Javadoc) - * - * @see - * com.jd.blockchain.contract.model.EventProcessingAwire#beforeEvent(com.jd. - * blockchain.contract.model.ContractEventContext) - */ - @Override - public void beforeEvent(ContractEventContext eventContext) { - this.eventContext = eventContext; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.contract.model.EventProcessingAwire#postEvent(com.jd. - * blockchain.contract.model.ContractEventContext, - * com.jd.blockchain.contract.model.ContractError) - */ - @Override - public void postEvent(ContractEventContext eventContext, ContractException error) { - this.eventContext = null; - } - - @Override - public void postEvent(ContractException error) { - - } - - @Override - public void postEvent() { - - } -} diff --git a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/pom.xml b/source/contract/contract-maven-plugin/src/test/resources/project-to-test/pom.xml deleted file mode 100644 index 80bf8e27..00000000 --- a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - com.jd.blockchain - project-to-test - 1.0-SNAPSHOT - jar - Test MyMojo - - - - - contract-maven-plugin - - - - - contract - - - - - \ No newline at end of file diff --git a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/target/contract.jar b/source/contract/contract-maven-plugin/src/test/resources/project-to-test/target/contract.jar deleted file mode 100644 index 8e693437..00000000 Binary files a/source/contract/contract-maven-plugin/src/test/resources/project-to-test/target/contract.jar and /dev/null differ diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/ecvrf/VRF.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/ecvrf/VRF.java deleted file mode 100644 index 45e05083..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/ecvrf/VRF.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.jd.blockchain.crypto.ecvrf; - - -import com.jd.blockchain.crypto.CryptoException; -import com.sun.jna.Library; -import com.sun.jna.Native; - -import java.security.SecureRandom; -import java.util.Objects; - - -public class VRF { - - public static String getLib() throws IllegalArgumentException{ - - String lib; - String path; - String osName = System.getProperty("os.name").toLowerCase(); - - // Mac OS - if (osName.startsWith("mac")){ - lib = "libsodium.23.dylib"; - } - - // Linux OS - else if (osName.contains("linux")){ - lib = "libsodium.so.23.1.0"; - } - - // unsupported OS - else { - throw new CryptoException("The VRF implementation is not supported in this Operation System!"); - } - - path = Objects.requireNonNull(VRF.class.getClassLoader().getResource(lib)).getPath(); - return path; - } - - public interface CLibrary extends Library { - - CLibrary INSTANCE = (CLibrary) - Native.load((getLib()), CLibrary.class); - - int crypto_vrf_is_valid_key(byte[] pk); - int crypto_vrf_keypair_from_seed(byte[] pk, byte[] sk, byte[] seed); - int crypto_vrf_prove(byte[] proof, byte[] sk, byte[] m, long mlen); - int crypto_vrf_verify(byte[] output, byte[] pk, byte[] proof, byte[] m, long mlen); - int crypto_vrf_proof_to_hash(byte[] hash, byte[] proof); - void crypto_vrf_ietfdraft03_sk_to_pk(byte[] pk, byte[] sk); - } - - public static byte[] genSecretKey(){ - byte [] seed = new byte[32]; - byte [] sk = new byte[64]; - byte [] pk = new byte[32]; - try{ - SecureRandom.getInstanceStrong().nextBytes(seed); - CLibrary.INSTANCE.crypto_vrf_keypair_from_seed(pk, sk, seed); - }catch (Exception e){ - e.printStackTrace(); - } - return sk; - } - - public static byte[] sk2pk(byte[] sk){ - if (sk.length != 64){ - return null; - } - byte [] pk = new byte[32]; - CLibrary.INSTANCE.crypto_vrf_ietfdraft03_sk_to_pk(pk, sk); - return pk; - } - - public static boolean IsValidPk(byte[] pk){ - if (pk.length != 32){ - return false; - } - return CLibrary.INSTANCE.crypto_vrf_is_valid_key(pk) == 1; - } - - public static byte[] prove(byte[] sk, byte[] msg){ - byte[] proof = new byte[80]; - if (CLibrary.INSTANCE.crypto_vrf_prove(proof, sk, msg, msg.length)==0){ - return proof; - } - return null; - } - - public static byte[] proof2hash(byte[] proof){ - byte[] hash = new byte[64]; - if (proof.length != 80){ - return null; - } - CLibrary.INSTANCE.crypto_vrf_proof_to_hash(hash, proof); - return hash; - } - - public static boolean verify(byte[] pk, byte[] proof, byte[]msg){ - byte[] output = new byte[64]; - if (proof.length != 80 || pk.length != 32){ - return false; - } - return CLibrary.INSTANCE.crypto_vrf_verify(output, pk, proof, msg, msg.length) == 0; - } -} diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/elgamal/ElGamalUtils.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/elgamal/ElGamalUtils.java deleted file mode 100644 index d5d31efa..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/elgamal/ElGamalUtils.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.jd.blockchain.crypto.elgamal; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.engines.ElGamalEngine; -import org.bouncycastle.crypto.generators.ElGamalKeyPairGenerator; -import org.bouncycastle.crypto.params.*; - -import java.math.BigInteger; -import java.security.SecureRandom; - -public class ElGamalUtils { - - private static final BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); - private static final BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); - - private static final ElGamalParameters dhParams = new ElGamalParameters(p512, g512, 0); - - - - //-----------------Key Pair Generation Algorithm----------------- - - /** - * key generation - * - * @return key pair - */ - public static AsymmetricCipherKeyPair generateKeyPair(){ - - SecureRandom random = new SecureRandom(); - return generateKeyPair(random); - } - - public static AsymmetricCipherKeyPair generateKeyPair(SecureRandom random){ - - ElGamalKeyGenerationParameters params = new ElGamalKeyGenerationParameters(random, dhParams); - ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator(); - - // To generate the key pair - kpGen.init(params); - return kpGen.generateKeyPair(); - } - - public static byte[] retrievePublicKey(byte[] privateKey) - { - BigInteger g = dhParams.getG(); - BigInteger p = dhParams.getP(); - - - BigInteger pubKey = g.modPow(new BigInteger(1,privateKey), p); - byte[] pubKey2Bytes = pubKey.toByteArray(); - - int pubKeySize = (p.bitLength() + 7)/8; - byte[] result = new byte[pubKeySize]; - - if (pubKey2Bytes.length > result.length) - { - System.arraycopy(pubKey2Bytes, 1, result, result.length - (pubKey2Bytes.length - 1), pubKey2Bytes.length - 1); - } - else - { - System.arraycopy(pubKey2Bytes, 0, result, result.length - pubKey2Bytes.length, pubKey2Bytes.length); - } - - return result; - } - - //-----------------Public Key Encryption Algorithm----------------- - - /** - * encryption - * - * @param plainBytes plaintext - * @param publicKey public key - * @return ciphertext - */ - public static byte[] encrypt(byte[] plainBytes, byte[] publicKey){ - - SecureRandom random = new SecureRandom(); - return encrypt(plainBytes,publicKey,random); - } - - public static byte[] encrypt(byte[] plainBytes, byte[] publicKey, SecureRandom random){ - - BigInteger pubKey = new BigInteger(1,publicKey); - - ElGamalPublicKeyParameters pubKeyParams = new ElGamalPublicKeyParameters(pubKey,dhParams); - return encrypt(plainBytes, pubKeyParams, random); - } - - public static byte[] encrypt(byte[] plainBytes, ElGamalPublicKeyParameters pubKeyParams){ - - SecureRandom random = new SecureRandom(); - return encrypt(plainBytes, pubKeyParams, random); - } - - public static byte[] encrypt(byte[] plainBytes, ElGamalPublicKeyParameters pubKeyParams, SecureRandom random){ - - ParametersWithRandom params = new ParametersWithRandom(pubKeyParams, random); - - ElGamalEngine encryptor = new ElGamalEngine(); - encryptor.init(true, params); - return encryptor.processBlock(plainBytes,0,plainBytes.length); - } - - - public static byte[] decrypt(byte[] cipherBytes, byte[] privateKey){ - BigInteger privKey = new BigInteger(1,privateKey); - - ElGamalPrivateKeyParameters privKeyParams = new ElGamalPrivateKeyParameters(privKey,dhParams); - - ElGamalEngine decryptor = new ElGamalEngine(); - decryptor.init(false,privKeyParams); - return decryptor.processBlock(cipherBytes,0,cipherBytes.length); - } - - public static ElGamalParameters getElGamalParameters(){return dhParams;} - -} diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/EqualVerify.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/EqualVerify.java deleted file mode 100644 index 68393c8c..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/EqualVerify.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.jd.blockchain.crypto.mpc; - -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.elgamal.ElGamalUtils; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ElGamalPrivateKeyParameters; -import org.bouncycastle.crypto.params.ElGamalPublicKeyParameters; - -import java.math.BigInteger; -import java.util.Arrays; - -public class EqualVerify { - - private static final int ELEMENTLENGTH = 64; - - private static BigInteger p; - - private static byte[] sponsorEPubKeyBytes; - private static byte[] sponsorEPrivKeyBytes; - - private static byte[] responderEPubKeyBytes; - private static byte[] responderEPrivKeyBytes; - - public static void generateParams(){ - p = ElGamalUtils.getElGamalParameters().getP(); - } - - public static void generateSponsorKeyPair(){ - - AsymmetricCipherKeyPair keyPair = ElGamalUtils.generateKeyPair(); - ElGamalPublicKeyParameters pubKeyParams = (ElGamalPublicKeyParameters) keyPair.getPublic(); - ElGamalPrivateKeyParameters privKeyParams = (ElGamalPrivateKeyParameters) keyPair.getPrivate(); - - sponsorEPubKeyBytes = bigIntegerTo64Bytes(pubKeyParams.getY()); - sponsorEPrivKeyBytes = bigIntegerTo64Bytes(privKeyParams.getX()); - } - - public static void generateResponderKeyPair(){ - - AsymmetricCipherKeyPair keyPair = ElGamalUtils.generateKeyPair(); - ElGamalPublicKeyParameters pubKeyParams = (ElGamalPublicKeyParameters) keyPair.getPublic(); - ElGamalPrivateKeyParameters privKeyParams = (ElGamalPrivateKeyParameters) keyPair.getPrivate(); - - responderEPubKeyBytes = bigIntegerTo64Bytes(pubKeyParams.getY()); - responderEPrivKeyBytes = bigIntegerTo64Bytes(privKeyParams.getX()); - } - - public static byte[] sponsor(int sponsorInput, byte[] sponsorEPubKeyBytes){ - - BigInteger sponsorBigInt = BigInteger.valueOf(sponsorInput); - BigInteger sponsorEPubKey = new BigInteger(1, sponsorEPubKeyBytes); - BigInteger result = sponsorBigInt.multiply(sponsorEPubKey).mod(p); - return bigIntegerTo64Bytes(result); - } - - public static byte[] responder(int responderInput, byte[] sponsorOutput, byte[] responderEPubKeyBytes, - byte[] responderEPrivKeyBytes) { - - if (sponsorOutput.length != ELEMENTLENGTH) { - throw new CryptoException("The sponsorOutput' length is not 64!"); - } - - BigInteger responderBigInt = BigInteger.valueOf(responderInput); - BigInteger responderEPubKey = new BigInteger(1,responderEPubKeyBytes); - BigInteger responderCipher = responderBigInt.multiply(responderEPubKey).mod(p); - - BigInteger responderInputInverse = BigInteger.valueOf(responderInput).modInverse(p); - BigInteger tmp = new BigInteger(1, sponsorOutput).multiply(responderInputInverse).mod(p); - BigInteger dhValue = tmp.modPow(new BigInteger(1,responderEPrivKeyBytes), p); - - return BytesUtils.concat(bigIntegerTo64Bytes(responderCipher), bigIntegerTo64Bytes(dhValue)); - } - - public static boolean sponsorCheck(int sponsorInput, byte[] responderOutput, byte[] sponsorEPrivKeyBytes){ - - if (responderOutput.length != 2 * ELEMENTLENGTH) { - throw new CryptoException("The responderOutput's length is not 128!"); - } - - byte[] responderCipherBytes = new byte[ELEMENTLENGTH]; - byte[] dhValueBytes = new byte[ELEMENTLENGTH]; - System.arraycopy(responderOutput, 0, responderCipherBytes, 0, responderCipherBytes.length); - System.arraycopy(responderOutput, responderCipherBytes.length, dhValueBytes, 0,dhValueBytes.length); - - BigInteger sponsorInputInverse = BigInteger.valueOf(sponsorInput).modInverse(p); - BigInteger tmp = new BigInteger(1, responderCipherBytes).multiply(sponsorInputInverse); - BigInteger dhVerifier = tmp.modPow(new BigInteger(1,sponsorEPrivKeyBytes), p); - - return Arrays.equals(dhValueBytes, bigIntegerTo64Bytes(dhVerifier)); - } - - public static byte[] getSponsorEPubKeyBytes(){return sponsorEPubKeyBytes;} - - public static byte[] getSponsorEPrivKeyBytes(){return sponsorEPrivKeyBytes;} - - public static byte[] getResponderEPubKeyBytes(){return responderEPubKeyBytes;} - - public static byte[] getResponderEPrivKeyBytes(){return responderEPrivKeyBytes;} - - // To convert BigInteger to byte[] whose length is 64 - private static byte[] bigIntegerTo64Bytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[64]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } -} diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/IntCompare.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/IntCompare.java deleted file mode 100644 index f6ff71c6..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/IntCompare.java +++ /dev/null @@ -1,284 +0,0 @@ -package com.jd.blockchain.crypto.mpc; - -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.elgamal.ElGamalUtils; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ElGamalParameters; -import org.bouncycastle.crypto.params.ElGamalPrivateKeyParameters; -import org.bouncycastle.crypto.params.ElGamalPublicKeyParameters; - -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.Random; - -public class IntCompare { - - private static final int INTLENGTH = 32; - private static final int ELEMENTLENGTH = 64; - private static final int CIPHERLENGTH = 128; - - private static BigInteger p; - - private static byte[] pubKeyBytes; - private static byte[] privKeyBytes; - - public static void generateKeyPair(){ - - ElGamalParameters dhParams = ElGamalUtils.getElGamalParameters(); - - p = dhParams.getP(); - - AsymmetricCipherKeyPair keyPair = ElGamalUtils.generateKeyPair(); - ElGamalPublicKeyParameters pubKeyParams = (ElGamalPublicKeyParameters) keyPair.getPublic(); - ElGamalPrivateKeyParameters privKeyParams = (ElGamalPrivateKeyParameters) keyPair.getPrivate(); - - pubKeyBytes = bigIntegerTo64Bytes(pubKeyParams.getY()); - privKeyBytes = bigIntegerTo64Bytes(privKeyParams.getX()); - } - - public static byte[][] sponsor(int sponsorInput, byte[] pubKeyBytes){ - - String sponsorBinaryStr = to32BinaryString(sponsorInput); - - - byte[][] cipherArray = new byte[INTLENGTH * 2][CIPHERLENGTH]; - - byte[] unitMsg = bigIntegerTo64Bytes(BigInteger.ONE); - byte[] randMsg = new byte[ELEMENTLENGTH - 1]; - - int i; - for (i = 0; i < INTLENGTH; i++){ - - SecureRandom random = new SecureRandom(); - random.nextBytes(randMsg); - - if (sponsorBinaryStr.charAt(i) == '1'){ - cipherArray[i] = ElGamalUtils.encrypt(unitMsg, pubKeyBytes); - cipherArray[i + INTLENGTH] = ElGamalUtils.encrypt(randMsg, pubKeyBytes); - } - else { - cipherArray[i] = ElGamalUtils.encrypt(randMsg, pubKeyBytes); - cipherArray[i + INTLENGTH] = ElGamalUtils.encrypt(unitMsg, pubKeyBytes); - } - } - - return cipherArray; - } - - public static byte[][] responder(int responderInt, byte[][] cipherArray, byte[] pubKeyBytes){ - - if (cipherArray.length != 2 * INTLENGTH) { - throw new CryptoException("The cipherArray has wrong format!"); - } - - int i,j; - for (i = 0; i < cipherArray.length; i++){ - if(cipherArray[i].length != CIPHERLENGTH) { - throw new CryptoException("The cipherArray has wrong format!"); - } - } - - String[] responderStrSet = encoding(responderInt, false); - - BigInteger tmpLeftBigInteger; - BigInteger tmpRightBigInteger; - BigInteger leftBigInteger; - BigInteger rightBigInteger; - byte[] tmpCipherArray = new byte[CIPHERLENGTH]; - - byte[] randMsg = new byte[ELEMENTLENGTH -1 ]; - - byte[][] aggregatedCipherArray = new byte[INTLENGTH][CIPHERLENGTH]; - - for (i = 0; i < aggregatedCipherArray.length; i++){ - - if (responderStrSet[i] != null){ - - tmpLeftBigInteger = BigInteger.ONE; - tmpRightBigInteger = BigInteger.ONE; - - for (j = 0; j < responderStrSet[i].length(); j++){ - if (responderStrSet[i].charAt(j) == '1'){ - System.arraycopy(cipherArray[j], 0, tmpCipherArray, 0, tmpCipherArray.length); - } - else{ - System.arraycopy(cipherArray[j + INTLENGTH], 0,tmpCipherArray, 0, tmpCipherArray.length); - } - - leftBigInteger = getLeftBigIntegerFrom128Bytes(tmpCipherArray); - tmpLeftBigInteger = tmpLeftBigInteger.multiply(leftBigInteger).mod(p); - rightBigInteger = getRightBigIntegerFrom128Bytes(tmpCipherArray); - tmpRightBigInteger = tmpRightBigInteger.multiply(rightBigInteger).mod(p); - } - - aggregatedCipherArray[i] = BytesUtils.concat(bigIntegerTo64Bytes(tmpLeftBigInteger),bigIntegerTo64Bytes(tmpRightBigInteger)); - } - else { - SecureRandom random = new SecureRandom(); - random.nextBytes(randMsg); - aggregatedCipherArray[i] = ElGamalUtils.encrypt(randMsg, pubKeyBytes); - } - } - - int[] permutation = randPermute(INTLENGTH); - - for (i = 0; i < INTLENGTH; i++){ - System.arraycopy(aggregatedCipherArray[i], 0, tmpCipherArray, 0, CIPHERLENGTH); - System.arraycopy(aggregatedCipherArray[permutation[i]-1], 0, aggregatedCipherArray[i], 0, CIPHERLENGTH); - System.arraycopy(tmpCipherArray, 0, aggregatedCipherArray[permutation[i]-1], 0, CIPHERLENGTH); - } - - return aggregatedCipherArray; - } - - public static int sponsorOutput(byte[][] aggregatedCipherArray, byte[] privKeyBytes){ - - if (aggregatedCipherArray.length != INTLENGTH) { - throw new CryptoException("The aggregatedCipherArray has wrong format!"); - } - - int i; - byte[] plaintext; - - for (i = 0; i < aggregatedCipherArray.length; i++){ - - if(aggregatedCipherArray[i].length != CIPHERLENGTH) { - throw new CryptoException("The aggregatedCipherArray has wrong format!"); - } - - plaintext = ElGamalUtils.decrypt(aggregatedCipherArray[i], privKeyBytes); - - if ((plaintext.length ==1) && (BigInteger.ONE.equals(BigInteger.valueOf((int) plaintext[0])))){ - return 1; - } - } - - return 0; - } - - public static byte[] getPubKeyBytes(){return pubKeyBytes;} - - public static byte[] getPrivKeyBytes(){return privKeyBytes;} - - - - private static String[] encoding(int integer, boolean encodingOpts){ - String str = to32BinaryString(integer); - String[] strArray = new String[INTLENGTH]; - int i; - - // 1-encoding - if (encodingOpts){ - for (i = 0; i < INTLENGTH; i++){ - if (str.charAt(i) == '1'){ - strArray[i] = str.substring(0, i + 1); - } - } - } - // 0-encoding - else { - for (i = 0; i < INTLENGTH; i++) { - if (str.charAt(i) == '0') { - strArray[i] = str.substring(0, i) + "1"; - } - } - } - - return strArray; - } - - - private static String to32BinaryString(int integer) { - - if (integer < 0) { - throw new CryptoException("integer must be non-negative!"); - } - - int i; - String str = Integer.toBinaryString(integer); - StringBuilder result = new StringBuilder(); - for (i = 0; i < INTLENGTH - str.length(); i++) { - result.append("0"); - } - return result.append(str).toString(); - } - - /** - * @param min the lower bound (inclusive). Must be non-negative. - * @param max the upper bound (inclusive). Must be positive. - * @return the next pseudorandom, uniformly distributed {@code int} - * value between min (inclusive) and max (inclusive) - * from this random number generator's sequence - * @throws CryptoException if min is not non-negative, - * max is not positive, or min is bigger than max - */ - private static int randInt(int min, int max) { - if (min < 0) { - throw new CryptoException("min must be non-negative!"); - } - if (max <= 0) { - throw new CryptoException("max must be positive!"); - } - if (min > max) { - throw new CryptoException("min must not be greater than max"); - } - - Random random = new Random(); - return random.nextInt(max) % (max - min + 1) + min; - } - - private static int[] randPermute(int num) { - - int[] array = new int[num]; - int i; - int rand; - int tmp; - - for (i = 0; i < num; i++) { - array[i] = i + 1; - } - - for (i = 0; i < num; i++) { - rand = randInt(1, num); - tmp = array[i]; - array[i] = array[rand - 1]; - array[rand - 1] = tmp; - } - - return array; - } - - // To convert BigInteger to byte[] whose length is 64 - private static byte[] bigIntegerTo64Bytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[64]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } - - private static BigInteger getLeftBigIntegerFrom128Bytes(byte[] byteArray){ - if (byteArray.length != 128) { - throw new CryptoException("The byteArray's length must be 128!"); - } - byte[] tmp = new byte[64]; - System.arraycopy(byteArray, 0, tmp, 0, tmp.length); - return new BigInteger(1, tmp); - } - - private static BigInteger getRightBigIntegerFrom128Bytes(byte[] byteArray){ - if (byteArray.length != 128) { - throw new CryptoException("The byteArray's length must be 128!"); - } - byte[] tmp = new byte[64]; - System.arraycopy(byteArray, 64, tmp, 0, tmp.length); - return new BigInteger(1, tmp); - } -} - - diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/MultiSum.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/MultiSum.java deleted file mode 100644 index 45392f29..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/MultiSum.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.jd.blockchain.crypto.mpc; - -import java.math.BigInteger; - -import com.jd.blockchain.crypto.paillier.PaillierPublicKeyParameters; -import com.jd.blockchain.crypto.paillier.PaillierUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.math.ec.ECPoint; - -import com.jd.blockchain.crypto.utils.sm.SM2Utils; -import com.jd.blockchain.crypto.utils.sm.SM3Utils; -import com.jd.blockchain.utils.io.BytesUtils; - -public class MultiSum { - - private static byte[] ePrivKey; - private static byte[] ePubKey; - private static ECCurve curve; - private static ECDomainParameters domainParams; - - public static void generateEphemeralKeyPair(){ - AsymmetricCipherKeyPair eKeyPair = SM2Utils.generateKeyPair(); - ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters) eKeyPair.getPrivate(); - ECPublicKeyParameters ecPubKey= (ECPublicKeyParameters) eKeyPair.getPublic(); - ePrivKey = bigIntegerToBytes(ecPrivKey.getD()); - ePubKey = ecPubKey.getQ().getEncoded(false); - curve = SM2Utils.getCurve(); - domainParams = SM2Utils.getDomainParams(); - } - - public static byte[] calculateAgreement(byte[] otherEPubKey, byte[] ePrivKey){ - ECDHBasicAgreement basicAgreement = new ECDHBasicAgreement(); - ECPoint ePubKeyPoint = resolvePubKeyBytes(otherEPubKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(ePubKeyPoint, domainParams); - ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters(new BigInteger(1,ePrivKey), domainParams); - - basicAgreement.init(privateKey); - BigInteger agreement = basicAgreement.calculateAgreement(pubKey); - return bigIntegerToBytes(agreement); - } - - public static byte[] deriveShares(byte[] frontID, byte[] rearID, byte[] agreementBytes){ - byte[] inputBytes = BytesUtils.concat(frontID,rearID,agreementBytes); - return SM3Utils.hash(inputBytes); - } - - public static byte[] encryptBlindedMsg(byte[] paillierPubKey, int input, byte[] frontShare, byte[] rearShare){ - BigInteger integer = BigInteger.valueOf(input); - BigInteger frontInteger = new BigInteger(1,frontShare); - BigInteger rearInteger = new BigInteger(1,rearShare); - PaillierPublicKeyParameters encKey = PaillierUtils.bytes2PubKey(paillierPubKey); - BigInteger modulus = encKey.getModulus(); - BigInteger plaintext = integer.add(frontInteger).subtract(rearInteger).mod(modulus); - return PaillierUtils.encrypt(plaintext.toByteArray(),encKey); - } - - public static byte[] aggregateCiphertexts(byte[] paillierPubKey, byte[]... ciphertexts){ - return PaillierUtils.add(paillierPubKey,ciphertexts); - } - - public static byte[] decrypt(byte[] paillierPrivKey, byte[] ciphertext){ - return PaillierUtils.decrypt(ciphertext,paillierPrivKey); - } - - public static byte[] getEPubKey(){return ePubKey;} - - public static byte[] getEPrivKey(){return ePrivKey;} - - -// public byte[] getEPubKeyBytes(){ -// byte[] ePubKeyBytes = new byte[65]; -// byte[] ePubKeyBytesX = ePubKey.getQ().getAffineXCoord().getEncoded(); -// byte[] ePubKeyBytesY = ePubKey.getQ().getAffineYCoord().getEncoded(); -// System.arraycopy(Hex.decode("04"),0,ePubKeyBytes,0,1); -// System.arraycopy(ePubKeyBytesX,0,ePubKeyBytes,1,32); -// System.arraycopy(ePubKeyBytesY,0,ePubKeyBytes,1+32,32); -// return ePubKeyBytes; -// } -// -// public byte[] getEPrivKeyBytes(){ -// return bigIntegerToBytes(ePrivKey.getD()); -// } - - public ECPublicKeyParameters resolveEPubKey(byte[] ePubKeyBytes){ - byte[] ePubKeyX = new byte[32]; - byte[] ePubKeyY = new byte[32]; - System.arraycopy(ePubKeyBytes,1,ePubKeyX,0,32); - System.arraycopy(ePubKeyBytes,1+32,ePubKeyY,0,32); - ECPoint ePubKeyPoint = curve.createPoint(new BigInteger(1,ePubKeyX), new BigInteger(1,ePubKeyY)); - return new ECPublicKeyParameters(ePubKeyPoint,domainParams); - } - - public ECPrivateKeyParameters resolveEPrivKey(byte[] ePrivKeyBytes){ - return new ECPrivateKeyParameters(new BigInteger(1,ePrivKeyBytes),domainParams); - } - - // To convert BigInteger to byte[] whose length is l - private static byte[] bigIntegerToBytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[32]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } - - // To retrieve the public key point from publicKey in byte array mode - private static ECPoint resolvePubKeyBytes(byte[] publicKey){ - return curve.decodePoint(publicKey); - } - -} diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierKeyPairGenerator.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierKeyPairGenerator.java deleted file mode 100644 index abb72987..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierKeyPairGenerator.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.jd.blockchain.crypto.paillier; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.math.Primes; -import org.bouncycastle.util.BigIntegers; - -import java.math.BigInteger; -import java.security.SecureRandom; - -/** - * @author zhanglin33 - * @title: PaillierKeyPairGenerator - * @description: generator of paillier key pair - * @date 2019-04-30, 14:48 - */ -public class PaillierKeyPairGenerator { - - private static final int STRENGTH = 2048; - - public AsymmetricCipherKeyPair generateKeyPair() { - - int pLength = (STRENGTH + 1) / 2; - int qLength = STRENGTH - pLength; - - BigInteger p; - BigInteger q; - BigInteger n; - - do { - do { - SecureRandom pRandom = new SecureRandom(); - p = BigIntegers.createRandomPrime(pLength, 1, pRandom); - } while (!isProbablePrime(p)); - do { - SecureRandom qRandom = new SecureRandom(); - q = BigIntegers.createRandomPrime(qLength, 1, qRandom); - } while (q.equals(p) || !isProbablePrime(p)); - n = q.multiply(p); - } while (n.bitLength() != STRENGTH); - - return new AsymmetricCipherKeyPair(new PaillierPublicKeyParameters(n), new PaillierPrivateKeyParameters(p,q)); - } - - // Primes class for FIPS 186-4 C.3 primality checking - private boolean isProbablePrime(BigInteger x) - { - int iterations = 3; - SecureRandom random = new SecureRandom(); - return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, random, iterations); - } -} diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierPrivateKeyParameters.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierPrivateKeyParameters.java deleted file mode 100644 index 5dcb2f0f..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierPrivateKeyParameters.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jd.blockchain.crypto.paillier; - -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; - -import java.math.BigInteger; - -import static org.bouncycastle.util.BigIntegers.ONE; - -/** - * @author zhanglin33 - * @title: PaillierPrivateKeyParameters - * @description: parameters about Paillier private key - * @date 2019-04-30, 14:39 - */ -public class PaillierPrivateKeyParameters extends AsymmetricKeyParameter { - - private BigInteger p; - - private BigInteger q; - - private BigInteger pSquared; - - private BigInteger qSquared; - - private BigInteger pInverse; - - private BigInteger muP; - - private BigInteger muQ; - - public PaillierPrivateKeyParameters(BigInteger p, BigInteger q) { - super(true); - BigInteger generator = p.multiply(q).add(ONE); - this.p = p; - this.pSquared = p.multiply(p); - this.q = q; - this.qSquared = q.multiply(q); - this.pInverse = p.modInverse(q); - this.muP = hFunction(generator, p, pSquared); - this.muQ = hFunction(generator, q, qSquared); - } - - public PaillierPrivateKeyParameters(BigInteger p, BigInteger pSquared, BigInteger q, BigInteger qSquared, - BigInteger pInverse, BigInteger muP, BigInteger muQ){ - super(true); - this.p = p; - this.pSquared = pSquared; - this.q = q; - this.qSquared = qSquared; - this.pInverse = pInverse; - this.muP = muP; - this.muQ = muQ; - } - - - // mu = h(x) = (L(g^(x-1) mod x^2))^(-1) mod n - private BigInteger hFunction(BigInteger generator, BigInteger x, BigInteger xSquared) { - BigInteger phiX = lFunction(generator.modPow(x.subtract(ONE),xSquared),x); - return phiX.modInverse(x); - } - - // L(x) = (x-1) / n - public BigInteger lFunction(BigInteger x, BigInteger n) { - return x.subtract(ONE).divide(n); - } - - public BigInteger getP() - { - return p; - } - - public BigInteger getPSquared() - { - return pSquared; - } - - public BigInteger getQ() - { - return q; - } - - public BigInteger getQSquared() - { - return qSquared; - } - - public BigInteger getPInverse() - { - return pInverse; - } - - public BigInteger getMuP() - { - return muP; - } - - public BigInteger getMuQ() - { - return muQ; - } -} diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierPublicKeyParameters.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierPublicKeyParameters.java deleted file mode 100644 index 3706b6b2..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierPublicKeyParameters.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jd.blockchain.crypto.paillier; - -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; - -import java.math.BigInteger; - -import static org.bouncycastle.util.BigIntegers.ONE; - -/** - * @author zhanglin33 - * @title: PaillierPublicKeyParameters - * @description: parameters about Paillier public key - * @date 2019-04-30, 14:41 - */ -public class PaillierPublicKeyParameters extends AsymmetricKeyParameter { - - private BigInteger modulus; - private BigInteger modulusSquared; - private BigInteger generator; - - public PaillierPublicKeyParameters(BigInteger modulus) { - super(false); - this.modulus = validate(modulus); - this.modulusSquared = modulus.multiply(modulus); - this.generator = modulus.add(ONE); - } - - public BigInteger getModulus() { - return modulus; - } - - public BigInteger getModulusSquared() { - return modulusSquared; - } - - public BigInteger getGenerator() { - return generator; - } - - private BigInteger validate(BigInteger modulus) - { - if ((modulus.intValue() & 1) == 0) - { - throw new IllegalArgumentException("The modulus is even!"); - } - - // the value is the product of the 132 smallest primes from 3 to 751 - if (!modulus.gcd(new BigInteger("145188775577763990151158743208307020242261438098488931355057091965" + - "931517706595657435907891265414916764399268423699130577757433083166" + - "651158914570105971074227669275788291575622090199821297575654322355" + - "049043101306108213104080801056529374892690144291505781966373045481" + - "8359472391642885328171302299245556663073719855")).equals(ONE)) - { - throw new IllegalArgumentException("The modulus has a small prime factor!"); - } - - return modulus; - } -} diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierUtils.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierUtils.java deleted file mode 100644 index 3d765df3..00000000 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierUtils.java +++ /dev/null @@ -1,218 +0,0 @@ -package com.jd.blockchain.crypto.paillier; - -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; - -import java.math.BigInteger; -import java.security.SecureRandom; - -import static org.bouncycastle.util.BigIntegers.ONE; - -/** - * @author zhanglin33 - * @title: PaillierUtils - * @description: encryption, decryption, homomorphic addition and scalar multiplication in Paillier algorithm - * @date 2019-04-30, 14:49 - */ -public class PaillierUtils { - - private static final int MODULUS_LENGTH = 256; - private static final int MODULUSSQUARED_LENGTH = 512; - - private static final int P_LENGTH = 128; - private static final int PSQUARED_LENGTH = 256; - private static final int Q_LENGTH = 128; - private static final int QSQUARED_LENGTH = 256; - private static final int PINVERSE_LENGTH = 128; - private static final int MUP_LENGTH = 128; - private static final int MUQ_LENGTH = 128; - - private static final int PRIVKEY_LENGTH = P_LENGTH + PSQUARED_LENGTH + Q_LENGTH + QSQUARED_LENGTH - + PINVERSE_LENGTH + MUP_LENGTH + MUQ_LENGTH; - - public static AsymmetricCipherKeyPair generateKeyPair(){ - PaillierKeyPairGenerator generator = new PaillierKeyPairGenerator(); - return generator.generateKeyPair(); - } - - public static byte[] encrypt(byte[] plainBytes, byte[] publicKey) { - PaillierPublicKeyParameters pubKeyParams = bytes2PubKey(publicKey); - return encrypt(plainBytes, pubKeyParams); - } - - public static byte[] encrypt(byte[] plainBytes, PaillierPublicKeyParameters pubKeyParams) { - SecureRandom random = new SecureRandom(); - return encrypt(plainBytes, pubKeyParams, random); - } - - // c = g^m * r^n mod n^2 = (1+n)^m * r^n mod n^2 = (1 + n*m mod n^2) * r^n mod n^2 - public static byte[] encrypt(byte[] plainBytes, PaillierPublicKeyParameters pubKeyParams, SecureRandom random){ - - BigInteger n = pubKeyParams.getModulus(); - BigInteger nSquared = pubKeyParams.getModulusSquared(); - - BigInteger m = new BigInteger(1,plainBytes); - BigInteger r = new BigInteger(n.bitLength(), random); - - BigInteger rawCiphertext = n.multiply(m).add(ONE).mod(nSquared); - BigInteger c = r.modPow(n, nSquared).multiply(rawCiphertext).mod(nSquared); - - return bigIntegerToBytes(c, MODULUSSQUARED_LENGTH); - } - - - public static byte[] decrypt(byte[] cipherBytes, byte[] privateKey) { - PaillierPrivateKeyParameters privKeyParams = bytes2PrivKey(privateKey); - return decrypt(cipherBytes,privKeyParams); - } - // m mod p = L(c^(p-1) mod p^2) * muP mod p - // m mod q = L(c^(q-1) mod q^2) * muQ mod q - // m = (m mod p) * (1/q mod p) * q + (m mod q) * (1/p mod q) * p - // = ((m mod q)-(m mod p)) * (1/p mod q) mod q * p + (m mod p) - public static byte[] decrypt(byte[] cipherBytes, PaillierPrivateKeyParameters privKeyParams){ - - BigInteger cihphertext = new BigInteger(1, cipherBytes); - - BigInteger p = privKeyParams.getP(); - BigInteger pSquared = privKeyParams.getPSquared(); - BigInteger q = privKeyParams.getQ(); - BigInteger qSquared = privKeyParams.getQSquared(); - BigInteger pInverse = privKeyParams.getPInverse(); - BigInteger muP = privKeyParams.getMuP(); - BigInteger muQ = privKeyParams.getMuQ(); - - BigInteger mModP = - privKeyParams.lFunction(cihphertext.modPow(p.subtract(ONE),pSquared),p).multiply(muP).mod(p); - BigInteger mModQ = - privKeyParams.lFunction(cihphertext.modPow(q.subtract(ONE),qSquared),q).multiply(muQ).mod(q); - - BigInteger midValue = mModQ.subtract(mModP).multiply(pInverse).mod(q); - BigInteger m = midValue.multiply(p).add(mModP); - - return m.toByteArray(); - } - - - public static byte[] pubKey2Bytes(PaillierPublicKeyParameters pubKeyParams) { - BigInteger n = pubKeyParams.getModulus(); - return bigIntegerToBytes(n, MODULUS_LENGTH); - } - - public static PaillierPublicKeyParameters bytes2PubKey(byte[] publicKey) { - - if (publicKey.length != MODULUS_LENGTH) { - throw new IllegalArgumentException("publicKey's length does not meet algorithm's requirement!"); - } - - BigInteger n = new BigInteger(1, publicKey); - return new PaillierPublicKeyParameters(n); - } - - - public static byte[] privKey2Bytes(PaillierPrivateKeyParameters privKeyParams) { - - BigInteger p = privKeyParams.getP(); - BigInteger pSquared = privKeyParams.getPSquared(); - BigInteger q = privKeyParams.getQ(); - BigInteger qSquared = privKeyParams.getQSquared(); - BigInteger pInverse = privKeyParams.getPInverse(); - BigInteger muP = privKeyParams.getMuP(); - BigInteger muQ = privKeyParams.getMuQ(); - - byte[] pBytes = bigIntegerToBytes(p, P_LENGTH); - byte[] pSquaredBytes = bigIntegerToBytes(pSquared, PSQUARED_LENGTH); - byte[] qBytes = bigIntegerToBytes(q, Q_LENGTH); - byte[] qSquaredBytes = bigIntegerToBytes(qSquared, QSQUARED_LENGTH); - byte[] pInverseBytes = bigIntegerToBytes(pInverse, PINVERSE_LENGTH); - byte[] muPBytes = bigIntegerToBytes(muP, MUP_LENGTH); - byte[] muQBytes = bigIntegerToBytes(muQ, MUQ_LENGTH); - - return BytesUtils.concat(pBytes,pSquaredBytes,qBytes,qSquaredBytes,pInverseBytes,muPBytes,muQBytes); - } - - public static PaillierPrivateKeyParameters bytes2PrivKey(byte[] privateKey) { - - if (privateKey.length != PRIVKEY_LENGTH) { - throw new IllegalArgumentException("privateKey's length does not meet algorithm's requirement!"); - } - - byte[] pBytes = new byte[P_LENGTH]; - byte[] pSquaredBytes = new byte[PSQUARED_LENGTH]; - byte[] qBytes = new byte[Q_LENGTH]; - byte[] qSquaredBytes = new byte[QSQUARED_LENGTH]; - byte[] pInverseBytes = new byte[PINVERSE_LENGTH]; - byte[] muPBytes = new byte[MUP_LENGTH]; - byte[] muQBytes = new byte[MUQ_LENGTH]; - - split(privateKey,pBytes,pSquaredBytes,qBytes,qSquaredBytes,pInverseBytes,muPBytes,muQBytes); - - BigInteger p = new BigInteger(1, pBytes); - BigInteger pSquared = new BigInteger(1, pSquaredBytes); - BigInteger q = new BigInteger(1, qBytes); - BigInteger qSquared = new BigInteger(1, qSquaredBytes); - BigInteger pInverse = new BigInteger(1, pInverseBytes); - BigInteger muP = new BigInteger(1, muPBytes); - BigInteger muQ = new BigInteger(1, muQBytes); - - return new PaillierPrivateKeyParameters(p,pSquared,q,qSquared,pInverse,muP,muQ); - } - - public static byte[] add(byte[] publicKey, byte[]... ciphertexts) { - PaillierPublicKeyParameters pubKeyParams = bytes2PubKey(publicKey); - return add(pubKeyParams,ciphertexts); - } - - public static byte[] add(PaillierPublicKeyParameters pubKeyParams, byte[]... ciphertexts) { - - BigInteger result = ONE; - BigInteger multiplier; - BigInteger nSquared = pubKeyParams.getModulusSquared(); - for (byte[] each: ciphertexts) { - multiplier = new BigInteger(1, each); - result = result.multiply(multiplier).mod(nSquared); - } - - return bigIntegerToBytes(result, MODULUSSQUARED_LENGTH); - } - - public static byte[] scalarMultiply(byte[] publicKey, byte[] cipherBytes, long scalar) { - PaillierPublicKeyParameters pubKeyParams = bytes2PubKey(publicKey); - return scalarMultiply(pubKeyParams,cipherBytes,scalar); - } - - public static byte[] scalarMultiply(PaillierPublicKeyParameters pubKeyParams, byte[] cipherBytes, long scalar) { - - BigInteger nSquared = pubKeyParams.getModulusSquared(); - BigInteger cihertext = new BigInteger(1, cipherBytes); - BigInteger exponent = BigInteger.valueOf(scalar); - - BigInteger result = cihertext.modPow(exponent,nSquared); - - return bigIntegerToBytes(result, MODULUSSQUARED_LENGTH); - } - - // To convert BigInteger to byte array in specified size - private static byte[] bigIntegerToBytes(BigInteger b, int bytesSize){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[bytesSize]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } - - private static void split(byte[] src, byte[]... bytesList) { - - int srcPos = 0; - for (byte[] each: bytesList){ - System.arraycopy(src,srcPos,each,0,each.length); - srcPos += each.length; - if (srcPos >= src.length){ - break; - } - } - } -} diff --git a/source/crypto/crypto-adv/src/main/resources/libsodium.23.dylib b/source/crypto/crypto-adv/src/main/resources/libsodium.23.dylib deleted file mode 100755 index bce89d3f..00000000 Binary files a/source/crypto/crypto-adv/src/main/resources/libsodium.23.dylib and /dev/null differ diff --git a/source/crypto/crypto-adv/src/main/resources/libsodium.so.23.1.0 b/source/crypto/crypto-adv/src/main/resources/libsodium.so.23.1.0 deleted file mode 100755 index 44c1ef1a..00000000 Binary files a/source/crypto/crypto-adv/src/main/resources/libsodium.so.23.1.0 and /dev/null differ diff --git a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/ecvrf/VRFTest.java b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/ecvrf/VRFTest.java deleted file mode 100644 index 426c3cf4..00000000 --- a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/ecvrf/VRFTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package test.com.jd.blockchain.crypto.ecvrf; - -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.ecvrf.VRF; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class VRFTest { - - @Test - public void testVRF() { - - byte[] msg = BytesUtils.toBytes("你好"); - - //初始化一个异常 - Exception actualEx = null; - - try{ - VRF.getLib(); - long skGenStartTime = System.currentTimeMillis(); - byte[] sk = VRF.genSecretKey(); - long skGenTime = System.currentTimeMillis() - skGenStartTime; - System.out.println(String.format("VRF sk generation time = %s ms", skGenTime)); - - long pkGenStartTime = System.currentTimeMillis(); - byte[] pk = VRF.sk2pk(sk); - long pkGenTime = System.currentTimeMillis() - pkGenStartTime; - System.out.println(String.format("VRF pk generation time = %s ms", pkGenTime)); - - long proofGenStartTime = System.currentTimeMillis(); - byte[] proof = VRF.prove(sk, msg); - long proofGenTime = System.currentTimeMillis() - proofGenStartTime; - System.out.println(String.format("VRF proof generation time = %s ms", proofGenTime)); - - long pkValidationStartTime = System.currentTimeMillis(); - assertTrue(VRF.IsValidPk(pk)); - long pkValidationTime = System.currentTimeMillis() - pkValidationStartTime; - System.out.println(String.format("VRF pk validation time = %s ms", pkValidationTime)); - - assertNotNull(proof); - - long proof2hashStartTime = System.currentTimeMillis(); - byte[] output = VRF.proof2hash(proof); - long proof2hashTime = System.currentTimeMillis() - proof2hashStartTime; - System.out.println(String.format("VRF proof2hash time = %s ms", proof2hashTime)); - - long verificationStartTime = System.currentTimeMillis(); - boolean isValid = VRF.verify(pk, proof, msg); - long verificationTime = System.currentTimeMillis() - verificationStartTime; - System.out.println(String.format("VRF verification time = %s ms", verificationTime)); - - assertTrue(isValid); - assertNotNull(output); - - }catch (Exception e){ - actualEx = e; - } - - String osName = System.getProperty("os.name").toLowerCase(); - - if (osName.startsWith("mac") - || osName.contains("linux")) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - Class expectedException = CryptoException.class; - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } -} diff --git a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/elgamal/ElGamalUtilsTest.java b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/elgamal/ElGamalUtilsTest.java deleted file mode 100644 index d5d8b1d1..00000000 --- a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/elgamal/ElGamalUtilsTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package test.com.jd.blockchain.crypto.elgamal; - -import com.jd.blockchain.crypto.elgamal.ElGamalUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ElGamalPrivateKeyParameters; -import org.bouncycastle.crypto.params.ElGamalPublicKeyParameters; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import java.math.BigInteger; - -import static org.junit.Assert.*; - -public class ElGamalUtilsTest { - - @Test - public void testGenerateKeyPair() { - - AsymmetricCipherKeyPair keyPair = ElGamalUtils.generateKeyPair(); - - ElGamalPublicKeyParameters pubKeyParams = (ElGamalPublicKeyParameters) keyPair.getPublic(); - ElGamalPrivateKeyParameters privKeyParams = (ElGamalPrivateKeyParameters) keyPair.getPrivate(); - - byte[] privKeyBytes = bigIntegerTo64Bytes(privKeyParams.getX()); - byte[] pubKeyBytes = bigIntegerTo64Bytes(pubKeyParams.getY()); - - byte[] retrievedPubKeyBytes = ElGamalUtils.retrievePublicKey(privKeyBytes); - - assertEquals(64,privKeyBytes.length); - assertEquals(64,pubKeyBytes.length); - - assertArrayEquals(retrievedPubKeyBytes,pubKeyBytes); - } - - // To convert BigInteger to byte[] whose length is 64 - private byte[] bigIntegerTo64Bytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[64]; - if (tmp.length > result.length) - System.arraycopy(tmp, tmp.length-result.length, result, 0, result.length); - else System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - return result; - } - - - @Test - public void testDecrypt() { - - AsymmetricCipherKeyPair keyPair = ElGamalUtils.generateKeyPair(); - - ElGamalPublicKeyParameters pubKeyParams = (ElGamalPublicKeyParameters) keyPair.getPublic(); - ElGamalPrivateKeyParameters privKeyParams = (ElGamalPrivateKeyParameters) keyPair.getPrivate(); - - byte[] privKeyBytes = bigIntegerTo64Bytes(privKeyParams.getX()); - byte[] pubKeyBytes = bigIntegerTo64Bytes(pubKeyParams.getY()); - - byte[] message = Hex.decode("5468697320697320612074657374"); - - byte[] ciphertext = ElGamalUtils.encrypt(message,pubKeyBytes); - byte[] plaintext = ElGamalUtils.decrypt(ciphertext,privKeyBytes); - - assertEquals(128,ciphertext.length); - assertArrayEquals(plaintext,message); - - BigInteger one = BigInteger.ONE; - - ciphertext = ElGamalUtils.encrypt(bigIntegerTo64Bytes(one),pubKeyBytes); - plaintext = ElGamalUtils.decrypt(ciphertext,privKeyBytes); - - assertEquals(one,BigInteger.valueOf((int) plaintext[0])); - assertTrue(BigInteger.ONE.equals(BigInteger.valueOf((int) plaintext[0]))); - } -} \ No newline at end of file diff --git a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/EqualVerifyTest.java b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/EqualVerifyTest.java deleted file mode 100644 index d310beab..00000000 --- a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/EqualVerifyTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package test.com.jd.blockchain.crypto.mpc; - -import com.jd.blockchain.crypto.mpc.EqualVerify; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class EqualVerifyTest { - - private byte[] sponsorEPubKeyBytes; - private byte[] sponsorEPrivKeyBytes; - - private byte[] responderEPubKeyBytes; - private byte[] responderEPrivKeyBytes; - - @Before - public void init() { - - EqualVerify.generateParams(); - EqualVerify.generateSponsorKeyPair(); - EqualVerify.generateResponderKeyPair(); - - sponsorEPubKeyBytes = EqualVerify.getSponsorEPubKeyBytes(); - sponsorEPrivKeyBytes = EqualVerify.getSponsorEPrivKeyBytes(); - - responderEPubKeyBytes = EqualVerify.getResponderEPubKeyBytes(); - responderEPrivKeyBytes = EqualVerify.getResponderEPrivKeyBytes(); - } - - - @Test - public void testIntCompare() { - - int sponsorInput; - int responderInput; - - byte[] sponsorOutput; - byte[] responderOutput; - boolean isEqual; - - - sponsorInput = 666; - responderInput = 666; - - sponsorOutput = EqualVerify.sponsor(sponsorInput,sponsorEPubKeyBytes); - responderOutput = EqualVerify.responder(responderInput,sponsorOutput, - responderEPubKeyBytes,responderEPrivKeyBytes); - - isEqual = EqualVerify.sponsorCheck(sponsorInput,responderOutput,sponsorEPrivKeyBytes); - - assertTrue(isEqual); - - - sponsorInput = 666; - responderInput = 667; - - sponsorOutput = EqualVerify.sponsor(sponsorInput,sponsorEPubKeyBytes); - responderOutput = EqualVerify.responder(responderInput,sponsorOutput, - responderEPubKeyBytes,responderEPrivKeyBytes); - - isEqual = EqualVerify.sponsorCheck(sponsorInput,responderOutput,sponsorEPrivKeyBytes); - - assertTrue(!isEqual); - - } -} \ No newline at end of file diff --git a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/IntCompareTest.java b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/IntCompareTest.java deleted file mode 100644 index e018fb50..00000000 --- a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/IntCompareTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package test.com.jd.blockchain.crypto.mpc; - -import com.jd.blockchain.crypto.mpc.IntCompare; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class IntCompareTest { - - private byte[] pubKeyBytes; - private byte[] privKeyBytes; - - @Before - public void init() { - IntCompare.generateKeyPair(); - pubKeyBytes = IntCompare.getPubKeyBytes(); - privKeyBytes = IntCompare.getPrivKeyBytes(); - } - - @Test - public void testIntCompare() { - - byte[][] cipherArray; - byte[][] aggregatedCipherArray; - int output; - - int sponsorInput = 10000; - int responderInput = 9999; - - cipherArray = IntCompare.sponsor(sponsorInput, pubKeyBytes); - aggregatedCipherArray = IntCompare.responder(responderInput, cipherArray, pubKeyBytes); - output = IntCompare.sponsorOutput(aggregatedCipherArray, privKeyBytes); - assertEquals(1, output); - - sponsorInput = 10000; - responderInput = 19999; - - cipherArray = IntCompare.sponsor(sponsorInput, pubKeyBytes); - aggregatedCipherArray = IntCompare.responder(responderInput, cipherArray, pubKeyBytes); - output = IntCompare.sponsorOutput(aggregatedCipherArray, privKeyBytes); - assertEquals(0, output); - } -} \ No newline at end of file diff --git a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/MultiSumTest.java b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/MultiSumTest.java deleted file mode 100644 index 5b5e8128..00000000 --- a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/mpc/MultiSumTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package test.com.jd.blockchain.crypto.mpc; - -import com.jd.blockchain.crypto.mpc.MultiSum; -import com.jd.blockchain.crypto.paillier.PaillierPrivateKeyParameters; -import com.jd.blockchain.crypto.paillier.PaillierPublicKeyParameters; -import com.jd.blockchain.crypto.paillier.PaillierUtils; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class MultiSumTest { - - @Test - public void testMultiSum() { - - AsymmetricCipherKeyPair keyPair = PaillierUtils.generateKeyPair(); - PaillierPublicKeyParameters pubKeyParams = (PaillierPublicKeyParameters) keyPair.getPublic(); - PaillierPrivateKeyParameters privKeyParams = (PaillierPrivateKeyParameters) keyPair.getPrivate(); - - byte[] encKey = PaillierUtils.pubKey2Bytes(pubKeyParams); - byte[] decKey = PaillierUtils.privKey2Bytes(privKeyParams); - - int int1 = 6; - int int2 = 60; - int int3 = 600; - int sum = 666; - - byte[] id1 = BytesUtils.toBytes("1"); - byte[] id2 = BytesUtils.toBytes("2"); - byte[] id3 = BytesUtils.toBytes("3"); - - MultiSum.generateEphemeralKeyPair(); - byte[] ePubKey1 = MultiSum.getEPubKey(); - byte[] ePrivKey1 = MultiSum.getEPrivKey(); - - MultiSum.generateEphemeralKeyPair(); - byte[] ePubKey2 = MultiSum.getEPubKey(); - byte[] ePrivKey2 = MultiSum.getEPrivKey(); - - MultiSum.generateEphemeralKeyPair(); - byte[] ePubKey3 = MultiSum.getEPubKey(); - byte[] ePrivKey3 = MultiSum.getEPrivKey(); - - - byte[] sk12 = MultiSum.calculateAgreement(ePubKey2,ePrivKey1); - byte[] sk23 = MultiSum.calculateAgreement(ePubKey3,ePrivKey2); - byte[] sk31 = MultiSum.calculateAgreement(ePubKey1,ePrivKey3); - - assertArrayEquals(sk12,MultiSum.calculateAgreement(ePubKey1,ePrivKey2)); - assertArrayEquals(sk23,MultiSum.calculateAgreement(ePubKey2,ePrivKey3)); - assertArrayEquals(sk31,MultiSum.calculateAgreement(ePubKey3,ePrivKey1)); - - byte[] s12 = MultiSum.deriveShares(id1,id2,sk12); - byte[] s23 = MultiSum.deriveShares(id2,id3,sk23); - byte[] s31 = MultiSum.deriveShares(id3,id1,sk31); - - assertArrayEquals(s12, MultiSum.deriveShares(id1,id2,sk12)); - assertArrayEquals(s23, MultiSum.deriveShares(id2,id3,sk23)); - assertArrayEquals(s31, MultiSum.deriveShares(id3,id1,sk31)); - - byte[] c1 = MultiSum.encryptBlindedMsg(encKey,int1,s12,s31); - byte[] c2 = MultiSum.encryptBlindedMsg(encKey,int2,s23,s12); - byte[] c3 = MultiSum.encryptBlindedMsg(encKey,int3,s31,s23); - - byte[] aggregatedCiphertext = MultiSum.aggregateCiphertexts(encKey,c1,c2,c3); - - byte[] decryptedValue = MultiSum.decrypt(decKey,aggregatedCiphertext); - - assertEquals(sum,byteArrayToInt(decryptedValue)); - } - - private static int byteArrayToInt(byte[] input) { - int result; - int length = input.length; - byte[] buffer = new byte[4]; - if (length <= buffer.length){ - System.arraycopy(input,0,buffer,buffer.length - length,length); - } else { - System.arraycopy(input,length - buffer.length,buffer,0, buffer.length); - } - result = buffer[3] & 0xFF | - (buffer[2] & 0xFF) << 8 | - (buffer[1] & 0xFF) << 16 | - (buffer[0] & 0xFF) << 24; - return result; - } -} \ No newline at end of file diff --git a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/paillier/PaillierUtilsTest.java b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/paillier/PaillierUtilsTest.java deleted file mode 100644 index a88b14ed..00000000 --- a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/paillier/PaillierUtilsTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package test.com.jd.blockchain.crypto.paillier; - -import com.jd.blockchain.crypto.paillier.PaillierPrivateKeyParameters; -import com.jd.blockchain.crypto.paillier.PaillierPublicKeyParameters; -import com.jd.blockchain.crypto.paillier.PaillierUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.junit.Test; - -import java.math.BigInteger; -import java.security.SecureRandom; - -import static org.junit.Assert.assertEquals; - -/** - * @author zhanglin33 - * @title: PaillierUtilsTest - * @description: Tests on PaillierUtils - * @date 2019-04-30, 14:54 - */ -public class PaillierUtilsTest { - @Test - public void test() { - - AsymmetricCipherKeyPair keyPair = PaillierUtils.generateKeyPair(); - PaillierPublicKeyParameters pubKeyParams = (PaillierPublicKeyParameters) keyPair.getPublic(); - PaillierPrivateKeyParameters privKeyParams = (PaillierPrivateKeyParameters) keyPair.getPrivate(); - - BigInteger n = pubKeyParams.getModulus(); - BigInteger nSquared = pubKeyParams.getModulusSquared(); - BigInteger g = pubKeyParams.getGenerator(); - - BigInteger nConverted = new BigInteger(1, bigIntegerToBytes(n,256)); - BigInteger nSquaredConverted = new BigInteger(1, bigIntegerToBytes(nSquared,512)); - BigInteger gConverted = new BigInteger(1, bigIntegerToBytes(g,256)); - assertEquals(nConverted, n); - assertEquals(nSquaredConverted, nSquared); - assertEquals(gConverted, g); - - BigInteger p = privKeyParams.getP(); - BigInteger pSquared = privKeyParams.getPSquared(); - BigInteger q = privKeyParams.getQ(); - BigInteger qSquared = privKeyParams.getQSquared(); - BigInteger pInverse = privKeyParams.getPInverse(); - BigInteger muP = privKeyParams.getMuP(); - BigInteger muQ = privKeyParams.getMuQ(); - - BigInteger pConverted = new BigInteger(1, bigIntegerToBytes(p,128)); - BigInteger pSquaredConverted = new BigInteger(1, bigIntegerToBytes(pSquared,256)); - BigInteger qConverted = new BigInteger(1, bigIntegerToBytes(q,128)); - BigInteger qSquaredConverted = new BigInteger(1, bigIntegerToBytes(qSquared,256)); - BigInteger pInverseConverted = new BigInteger(1, bigIntegerToBytes(pInverse,128)); - BigInteger muPConverted = new BigInteger(1, bigIntegerToBytes(muP,128)); - BigInteger muQConverted = new BigInteger(1, bigIntegerToBytes(muQ,128)); - assertEquals(pConverted, p); - assertEquals(pSquaredConverted, pSquared); - assertEquals(qConverted, q); - assertEquals(qSquaredConverted, qSquared); - assertEquals(pInverseConverted, pInverse); - assertEquals(muPConverted, muP); - assertEquals(muQConverted, muQ); - - byte[] pubKeyBytes = PaillierUtils.pubKey2Bytes(pubKeyParams); - - SecureRandom random = new SecureRandom(); - byte[] data = new byte[256]; - random.nextBytes(data); - - byte[] ciphertextFromParams = PaillierUtils.encrypt(data,pubKeyParams); - byte[] ciphertextFromBytes = PaillierUtils.encrypt(data,pubKeyBytes); - - assertEquals(512,ciphertextFromParams.length); - assertEquals(512,ciphertextFromBytes.length); - - - byte[] privKeyBytes = PaillierUtils.privKey2Bytes(privKeyParams); - - int input = 666; - byte[] inputBytes = intToByteArray(input); - - ciphertextFromParams = PaillierUtils.encrypt(inputBytes,pubKeyParams); - ciphertextFromBytes = PaillierUtils.encrypt(inputBytes,pubKeyBytes); - - byte[] plaintextFromParams = PaillierUtils.decrypt(ciphertextFromBytes,privKeyParams); - byte[] plaintextFromBytes = PaillierUtils.decrypt(ciphertextFromParams,privKeyBytes); - - int outputFromParams = byteArrayToInt(plaintextFromParams); - int outputFromBytes = byteArrayToInt(plaintextFromBytes); - - assertEquals(input,outputFromParams); - assertEquals(input,outputFromBytes); - - - pubKeyBytes = PaillierUtils.pubKey2Bytes(pubKeyParams); - - int input1 = 600; - int input2 = 60; - int input3 = 6; - - int sum = 666; - - byte[] data1 = intToByteArray(input1); - byte[] data2 = intToByteArray(input2); - byte[] data3 = intToByteArray(input3); - - byte[] ciphertext1 = PaillierUtils.encrypt(data1,pubKeyParams); - byte[] ciphertext2 = PaillierUtils.encrypt(data2,pubKeyParams); - byte[] ciphertext3 = PaillierUtils.encrypt(data3,pubKeyParams); - - byte[] aggregatedCiphertext = PaillierUtils.add(pubKeyParams,ciphertext1,ciphertext2,ciphertext3); - byte[] plaintext = PaillierUtils.decrypt(aggregatedCiphertext,privKeyParams); - - int output = byteArrayToInt(plaintext); - assertEquals(sum,output); - - aggregatedCiphertext = PaillierUtils.add(pubKeyBytes,ciphertext1,ciphertext2,ciphertext3); - plaintext = PaillierUtils.decrypt(aggregatedCiphertext,privKeyParams); - - output = byteArrayToInt(plaintext); - assertEquals(sum,output); - - - pubKeyBytes = PaillierUtils.pubKey2Bytes(pubKeyParams); - - input = 111; - int scalar = 6; - data = intToByteArray(input); - - byte[] ciphertext = PaillierUtils.encrypt(data,pubKeyParams); - byte[] ciphertextPowered = PaillierUtils.scalarMultiply(pubKeyBytes,ciphertext,scalar); - byte[] plaintextMultiplied = PaillierUtils.decrypt(ciphertextPowered,privKeyParams); - - output = byteArrayToInt(plaintextMultiplied); - assertEquals(input * scalar, output); - } - - private static byte[] intToByteArray(int input) { - byte[] result = new byte[4]; - result[0] = (byte) ((input >> 24) & 0xFF); - result[1] = (byte) ((input >> 16) & 0xFF); - result[2] = (byte) ((input >> 8 ) & 0xFF); - result[3] = (byte) ((input ) & 0xFF); - return result; - } - - private static int byteArrayToInt(byte[] input) { - int result; - int length = input.length; - byte[] buffer = new byte[4]; - if (length <= buffer.length){ - System.arraycopy(input,0,buffer,buffer.length - length,length); - } else { - System.arraycopy(input,length - buffer.length,buffer,0, buffer.length); - } - result = buffer[3] & 0xFF | - (buffer[2] & 0xFF) << 8 | - (buffer[1] & 0xFF) << 16 | - (buffer[0] & 0xFF) << 24; - return result; - } - - // To convert BigInteger to byte array in specified size - private static byte[] bigIntegerToBytes(BigInteger b, int bytesSize){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[bytesSize]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/AESEncryptionFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/AESEncryptionFunction.java deleted file mode 100644 index 3903e5eb..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/AESEncryptionFunction.java +++ /dev/null @@ -1,228 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.CryptoKey; -import com.jd.blockchain.crypto.SymmetricCiphertext; -import com.jd.blockchain.crypto.SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.SymmetricKey; -import com.jd.blockchain.utils.security.AESUtils; - -public class AESEncryptionFunction implements SymmetricEncryptionFunction { - - public static final CryptoAlgorithm AES = ClassicAlgorithm.AES; - - private static final int KEY_SIZE = 128 / 8; - private static final int BLOCK_SIZE = 128 / 8; - - // AES-ECB - private static final int PLAINTEXT_BUFFER_LENGTH = 256; - private static final int CIPHERTEXT_BUFFER_LENGTH = 256 + 16 + 2; - - private static final int SYMMETRICKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + KEY_SIZE; - - AESEncryptionFunction() { - } - - @Override - public Ciphertext encrypt(SymmetricKey key, byte[] data) { - - byte[] rawKeyBytes = key.getRawKeyBytes(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应AES算法 - if (key.getAlgorithm() != AES.code()) { - throw new CryptoException("The is not AES symmetric key!"); - } - - // 调用底层AES128算法并计算密文数据 - return new SymmetricCiphertext(AES, AESUtils.encrypt(data, rawKeyBytes)); - } - - @Override - public void encrypt(SymmetricKey key, InputStream in, OutputStream out) { - // 读输入流得到明文,加密,密文数据写入输出流 - try { - - - byte[] buffBytes = new byte[PLAINTEXT_BUFFER_LENGTH]; - - // The final byte of plaintextWithPadding represents the length of padding in the first 256 bytes, - // and the padded value in hexadecimal - byte[] plaintextWithPadding = new byte[buffBytes.length + 1]; - - byte padding; - - int len; - int i; - - while((len=in.read(buffBytes)) > 0) { - padding = (byte) (PLAINTEXT_BUFFER_LENGTH - len); - i = len; - while (i < plaintextWithPadding.length) { - plaintextWithPadding[i] = padding; - i++; - } - out.write(encrypt(key,plaintextWithPadding).toBytes()); - } -// // TODO: 错误地使用 available 方法; -// int size = in.available(); -// if (size < 1){ -// throw new CryptoException("The input is null!"); -// } -// -// byte[] aesData = new byte[size]; -// -// if (in.read(aesData) != -1) { -// out.write(encrypt(key, aesData).); -// } -// -// in.close(); -// out.close(); - - } catch (IOException e) { - throw new CryptoException(e.getMessage(), e); - } - } - - @Override - public byte[] decrypt(SymmetricKey key, Ciphertext ciphertext) { - byte[] rawKeyBytes = key.getRawKeyBytes(); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应AES算法 - if (key.getAlgorithm() != AES.code()) { - throw new CryptoException("The is not AES symmetric key!"); - } - - // 验证原始密文长度为分组长度的整数倍 - if (rawCiphertextBytes.length % BLOCK_SIZE != 0) { - throw new CryptoException("This ciphertext has wrong format!"); - } - - // 验证密文数据算法标识对应AES算法 - if (ciphertext.getAlgorithm() != AES.code()) { - throw new CryptoException("This is not AES ciphertext!"); - } - - // 调用底层AES128算法解密,得到明文 - return AESUtils.decrypt(rawCiphertextBytes, rawKeyBytes); - } - - @Override - public void decrypt(SymmetricKey key, InputStream in, OutputStream out) { - // 读输入流得到密文数据,解密,明文写入输出流 - try { - byte[] buffBytes = new byte[CIPHERTEXT_BUFFER_LENGTH]; - byte[] plaintextWithPadding; - - byte padding; - byte[] plaintext; - - int len,i; - while ((len = in.read(buffBytes)) > 0) { - if (len != CIPHERTEXT_BUFFER_LENGTH) { - throw new CryptoException("inputStream's length is wrong!"); - } - if (!supportCiphertext(buffBytes)) { - throw new CryptoException("InputStream is not valid AES ciphertext!"); - } - - plaintextWithPadding = decrypt(key,resolveCiphertext(buffBytes)); - - if (plaintextWithPadding.length != (PLAINTEXT_BUFFER_LENGTH + 1)) { - throw new CryptoException("The decrypted plaintext is invalid"); - } - - padding = plaintextWithPadding[PLAINTEXT_BUFFER_LENGTH]; - i = PLAINTEXT_BUFFER_LENGTH; - - while ((PLAINTEXT_BUFFER_LENGTH - padding) < i) { - - if (plaintextWithPadding[i] != padding) { - throw new CryptoException("The inputSteam padding is invalid!"); - } - i--; - } - plaintext = new byte[PLAINTEXT_BUFFER_LENGTH - padding]; - System.arraycopy(plaintextWithPadding,0,plaintext,0,plaintext.length); - out.write(plaintext); - } - -// // TODO: 错误地使用 available 方法; -// byte[] aesData = new byte[in.available()]; -// in.read(aesData); -// in.close(); -// -// if (!supportCiphertext(aesData)) { -// throw new CryptoException("InputStream is not valid AES ciphertext!"); -// } -// -// out.write(decrypt(key, resolveCiphertext(aesData))); -// out.close(); - } catch (IOException e) { - throw new CryptoException(e.getMessage(), e); - } - } - - @Override - public boolean supportSymmetricKey(byte[] symmetricKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,字节数组的算法标识对应AES算法且密钥密钥类型是对称密钥 - return symmetricKeyBytes.length == SYMMETRICKEY_LENGTH && CryptoAlgorithm.match(AES, symmetricKeyBytes) - && symmetricKeyBytes[ALGORYTHM_CODE_SIZE] == SYMMETRIC.CODE; - } - - @Override - public SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes) { - if (supportSymmetricKey(symmetricKeyBytes)) { - return new SymmetricKey(symmetricKeyBytes); - } else { - throw new CryptoException("symmetricKeyBytes is invalid!"); - } - } - - @Override - public boolean supportCiphertext(byte[] ciphertextBytes) { - // 验证(输入字节数组长度-算法标识长度)是分组长度的整数倍,字节数组的算法标识对应AES算法 - return (ciphertextBytes.length - ALGORYTHM_CODE_SIZE) % BLOCK_SIZE == 0 - && CryptoAlgorithm.match(AES, ciphertextBytes); - } - - @Override - public SymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { - if (supportCiphertext(ciphertextBytes)) { - return new SymmetricCiphertext(ciphertextBytes); - } else { - throw new CryptoException("ciphertextBytes is invalid!"); - } - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return AES; - } - - @Override - public SymmetricKey generateSymmetricKey() { - // 根据对应的标识和原始密钥生成相应的密钥数据 - return new SymmetricKey(AES, AESUtils.generateKey128_Bytes()); - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicAlgorithm.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicAlgorithm.java deleted file mode 100644 index ac3c94f4..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicAlgorithm.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoAlgorithmDefinition; - -public final class ClassicAlgorithm { - - public static final CryptoAlgorithm ED25519 = CryptoAlgorithmDefinition.defineSignature("ED25519", false, - (byte) 21); - - public static final CryptoAlgorithm ECDSA = CryptoAlgorithmDefinition.defineSignature("ECDSA", false, - (byte) 22); - - public static final CryptoAlgorithm RSA = CryptoAlgorithmDefinition.defineSignature("RSA", true, - (byte) 23); - - public static final CryptoAlgorithm SHA256 = CryptoAlgorithmDefinition.defineHash("SHA256", - (byte) 24); - - public static final CryptoAlgorithm RIPEMD160 = CryptoAlgorithmDefinition.defineHash("RIPEMD160", - (byte) 25); - - public static final CryptoAlgorithm AES = CryptoAlgorithmDefinition.defineSymmetricEncryption("AES", - (byte) 26); - - public static final CryptoAlgorithm JVM_SECURE_RANDOM = CryptoAlgorithmDefinition.defineRandom("JVM-SECURE-RANDOM", - (byte) 27); - - private ClassicAlgorithm() { - - } - -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicCryptoService.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicCryptoService.java deleted file mode 100644 index e47edd21..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicCryptoService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import com.jd.blockchain.crypto.CryptoFunction; -import com.jd.blockchain.crypto.CryptoService; -import com.jd.blockchain.provider.NamedProvider; - -@NamedProvider("CLASSIC") -public class ClassicCryptoService implements CryptoService { - - - public static final AESEncryptionFunction AES = new AESEncryptionFunction(); - - public static final ED25519SignatureFunction ED25519 = new ED25519SignatureFunction(); - - public static final RIPEMD160HashFunction RIPEMD160 = new RIPEMD160HashFunction(); - - public static final SHA256HashFunction SHA256 = new SHA256HashFunction(); - - public static final JVMSecureRandomFunction JVM_SECURE_RANDOM = new JVMSecureRandomFunction(); - - public static final ECDSASignatureFunction ECDSA = new ECDSASignatureFunction(); - - public static final RSACryptoFunction RSA = new RSACryptoFunction(); - - private static final Collection FUNCTIONS; - - static { - List funcs = Arrays.asList(AES, ED25519, ECDSA, RSA, RIPEMD160, SHA256, JVM_SECURE_RANDOM); - FUNCTIONS = Collections.unmodifiableList(funcs); - } - - @Override - public Collection getFunctions() { - return FUNCTIONS; - } - -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunction.java deleted file mode 100644 index d7ebe0b7..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunction.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.utils.classic.ECDSAUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; - -import java.math.BigInteger; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; - -public class ECDSASignatureFunction implements SignatureFunction { - - private static final CryptoAlgorithm ECDSA = ClassicAlgorithm.ECDSA; - - private static final int PUBKEY_SIZE = 65; - private static final int PRIVKEY_SIZE = 32; - private static final int SIGNATUREDIGEST_SIZE = 64; - - private static final int PUBKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PUBKEY_SIZE; - private static final int PRIVKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PRIVKEY_SIZE; - private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_CODE_SIZE + SIGNATUREDIGEST_SIZE; - - ECDSASignatureFunction() { - } - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - // 验证原始私钥长度为256比特,即32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应ECDSA签名算法 - if (privKey.getAlgorithm() != ECDSA.code()) { - throw new CryptoException("This key is not ECDSA private key!"); - } - - // 调用ECDSA签名算法计算签名结果 - return new SignatureDigest(ECDSA, ECDSAUtils.sign(data, rawPrivKeyBytes)); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - // 验证原始公钥长度为256比特,即32字节 - if (rawPubKeyBytes.length != PUBKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应ECDSA签名算法 - if (pubKey.getAlgorithm() != ECDSA.code()) { - throw new CryptoException("This key is not ECDSA public key!"); - } - - // 验证签名数据的算法标识对应ECDSA签名算法,并且原始摘要长度为64字节 - if (digest.getAlgorithm() != ECDSA.code() || rawDigestBytes.length != SIGNATUREDIGEST_SIZE) { - throw new CryptoException("This is not ECDSA signature digest!"); - } - - // 调用ECDSA验签算法验证签名结果 - return ECDSAUtils.verify(data, rawPubKeyBytes, rawDigestBytes); - } - - @Override - public PubKey retrievePubKey(PrivKey privKey) { - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawPubKeyBytes = ECDSAUtils.retrievePublicKey(rawPrivKeyBytes); - return new PubKey(ECDSA, rawPubKeyBytes); - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应ECDSA签名算法,并且密钥类型是私钥 - return privKeyBytes.length == PRIVKEY_LENGTH && CryptoAlgorithm.match(ECDSA, privKeyBytes) - && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIVATE.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - if (supportPrivKey(privKeyBytes)) { - return new PrivKey(privKeyBytes); - } else { - throw new CryptoException("privKeyBytes are invalid!"); - } - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应ECDSA签名算法,并且密钥类型是公钥 - return pubKeyBytes.length == PUBKEY_LENGTH && CryptoAlgorithm.match(ECDSA, pubKeyBytes) - && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUBLIC.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - if (supportPubKey(pubKeyBytes)) { - return new PubKey(pubKeyBytes); - } else { - throw new CryptoException("pubKeyBytes are invalid!"); - } - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,字节数组的算法标识对应ECDSA算法 - return digestBytes.length == SIGNATUREDIGEST_LENGTH && CryptoAlgorithm.match(ECDSA, digestBytes); - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - if (supportDigest(digestBytes)) { - return new SignatureDigest(digestBytes); - } else { - throw new CryptoException("digestBytes are invalid!"); - } - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return ClassicAlgorithm.ECDSA; - } - - @Override - public AsymmetricKeypair generateKeypair() { - - // 调用ECDSA算法的密钥生成算法生成公私钥对priKey和pubKey,返回密钥对 - AsymmetricCipherKeyPair keyPair = ECDSAUtils.generateKeyPair(); - ECPrivateKeyParameters privKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate(); - ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytes = BigIntegerTo32Bytes(privKeyParams.getD()); - byte[] pubKeyBytes = pubKeyParams.getQ().getEncoded(false); - - return new AsymmetricKeypair(new PubKey(ECDSA, pubKeyBytes), new PrivKey(ECDSA, privKeyBytes)); - } - - // To convert BigInteger to byte[] whose length is 32 - private static byte[] BigIntegerTo32Bytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[32]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunction.java deleted file mode 100644 index 555586b5..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunction.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.utils.classic.ED25519Utils; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; -import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; - -public class ED25519SignatureFunction implements SignatureFunction { - - private static final CryptoAlgorithm ED25519 = ClassicAlgorithm.ED25519; - - private static final int PUBKEY_SIZE = 32; - private static final int PRIVKEY_SIZE = 32; - private static final int SIGNATUREDIGEST_SIZE = 64; - - private static final int PUBKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PUBKEY_SIZE; - private static final int PRIVKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PRIVKEY_SIZE; - private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_CODE_SIZE + SIGNATUREDIGEST_SIZE; - - ED25519SignatureFunction() { - } - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - // 验证原始私钥长度为256比特,即32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应ED25519签名算法 - if (privKey.getAlgorithm() != ED25519.code()) { - throw new CryptoException("This key is not ED25519 private key!"); - } - - // 调用ED25519签名算法计算签名结果 - return new SignatureDigest(ED25519, ED25519Utils.sign(data, rawPrivKeyBytes)); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - // 验证原始公钥长度为256比特,即32字节 - if (rawPubKeyBytes.length != PUBKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应ED25519签名算法 - if (pubKey.getAlgorithm() != ED25519.code()) { - throw new CryptoException("This key is not ED25519 public key!"); - } - - // 验证签名数据的算法标识对应ED25519签名算法,并且原始摘要长度为64字节 - if (digest.getAlgorithm() != ED25519.code() || rawDigestBytes.length != SIGNATUREDIGEST_SIZE) { - throw new CryptoException("This is not ED25519 signature digest!"); - } - - // 调用ED25519验签算法验证签名结果 - return ED25519Utils.verify(data, rawPubKeyBytes, rawDigestBytes); - } - - @Override - public PubKey retrievePubKey(PrivKey privKey) { - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawPubKeyBytes = ED25519Utils.retrievePublicKey(rawPrivKeyBytes); - return new PubKey(ED25519, rawPubKeyBytes); - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应ED25519签名算法,并且密钥类型是私钥 - return privKeyBytes.length == PRIVKEY_LENGTH && CryptoAlgorithm.match(ED25519, privKeyBytes) - && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIVATE.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - if (supportPrivKey(privKeyBytes)) { - return new PrivKey(privKeyBytes); - } else { - throw new CryptoException("privKeyBytes are invalid!"); - } - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应ED25519签名算法,并且密钥类型是公钥 - return pubKeyBytes.length == PUBKEY_LENGTH && CryptoAlgorithm.match(ED25519, pubKeyBytes) - && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUBLIC.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - if (supportPubKey(pubKeyBytes)) { - return new PubKey(pubKeyBytes); - } else { - throw new CryptoException("pubKeyBytes are invalid!"); - } - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,字节数组的算法标识对应ED25519算法 - return digestBytes.length == SIGNATUREDIGEST_LENGTH && CryptoAlgorithm.match(ED25519, digestBytes); - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - if (supportDigest(digestBytes)) { - return new SignatureDigest(digestBytes); - } else { - throw new CryptoException("digestBytes are invalid!"); - } - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return ED25519; - } - - @Override - public AsymmetricKeypair generateKeypair() { - - // 调用ED25519算法的密钥生成算法生成公私钥对priKey和pubKey,返回密钥对 - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair(); - Ed25519PrivateKeyParameters privKeyParams = (Ed25519PrivateKeyParameters) keyPair.getPrivate(); - Ed25519PublicKeyParameters pubKeyParams = (Ed25519PublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytes = privKeyParams.getEncoded(); - byte[] pubKeyBytes = pubKeyParams.getEncoded(); - return new AsymmetricKeypair(new PubKey(ED25519, pubKeyBytes), new PrivKey(ED25519, privKeyBytes)); - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/JVMSecureRandomFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/JVMSecureRandomFunction.java deleted file mode 100644 index fe120951..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/JVMSecureRandomFunction.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import java.security.SecureRandom; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.RandomFunction; -import com.jd.blockchain.crypto.RandomGenerator; - -public class JVMSecureRandomFunction implements RandomFunction { - - private static final CryptoAlgorithm JVM_SECURE_RANDOM = ClassicAlgorithm.JVM_SECURE_RANDOM; - - - JVMSecureRandomFunction() { - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return JVM_SECURE_RANDOM; - } - - @Override - public RandomGenerator generate(byte[] seed) { - return new SecureRandomGenerator(seed); - } - - - private static class SecureRandomGenerator implements RandomGenerator{ - - private SecureRandom sr; - - public SecureRandomGenerator(byte[] seed) { - if (seed == null || seed.length == 0) { - // 随机; - sr = new SecureRandom(); - } else { - sr = new SecureRandom(seed); - } - } - - @Override - public byte[] nextBytes(int size) { - byte[] randomBytes = new byte[size]; - sr.nextBytes(randomBytes); - return randomBytes; - } - - @Override - public void nextBytes(byte[] buffer) { - sr.nextBytes(buffer); - } - - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunction.java deleted file mode 100644 index bddbc99b..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunction.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; - -import java.util.Arrays; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.utils.classic.RIPEMD160Utils; - -public class RIPEMD160HashFunction implements HashFunction { - - private static final CryptoAlgorithm RIPEMD160 = ClassicAlgorithm.RIPEMD160; - - private static final int DIGEST_BYTES = 160 / 8; - - private static final int DIGEST_LENGTH = ALGORYTHM_CODE_SIZE + DIGEST_BYTES; - - RIPEMD160HashFunction() { - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return RIPEMD160; - } - - @Override - public HashDigest hash(byte[] data) { - if (data == null) { - throw new CryptoException("data is null!"); - } - - byte[] digestBytes = RIPEMD160Utils.hash(data); - return new HashDigest(RIPEMD160, digestBytes); - } - - @Override - public HashDigest hash(byte[] data, int offset, int len) { - if (data == null) { - throw new CryptoException("data is null!"); - } - - byte[] digestBytes = RIPEMD160Utils.hash(data, offset, len); - return new HashDigest(RIPEMD160, digestBytes); - } - - @Override - public boolean verify(HashDigest digest, byte[] data) { - HashDigest hashDigest = hash(data); - return Arrays.equals(hashDigest.toBytes(), digest.toBytes()); - } - - @Override - public boolean supportHashDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,以及算法标识; - return DIGEST_LENGTH == digestBytes.length && CryptoAlgorithm.match(RIPEMD160, digestBytes); - } - - @Override - public HashDigest resolveHashDigest(byte[] digestBytes) { - if (supportHashDigest(digestBytes)) { - return new HashDigest(digestBytes); - } else { - throw new CryptoException("digestBytes is invalid!"); - } - } - -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RSACryptoFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RSACryptoFunction.java deleted file mode 100644 index ab078bfb..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RSACryptoFunction.java +++ /dev/null @@ -1,212 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.utils.classic.RSAUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.RSAKeyParameters; -import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; - -/** - * @author zhanglin33 - * @title: RSACryptoFunction - * @description: Interfaces for RSA crypto functions, including key generation, encryption, signature, and so on - * @date 2019-03-25, 17:28 - */ -public class RSACryptoFunction implements AsymmetricEncryptionFunction, SignatureFunction { - - private static final CryptoAlgorithm RSA = ClassicAlgorithm.RSA; - - // modulus.length = 256, publicExponent.length = 3 - private static final int PUBKEY_SIZE = 259; - // modulus.length = 256, publicExponent.length = 3, privateExponent.length = 256, p.length = 128, q.length =128, - // dP.length = 128, dQ.length = 128, qInv.length = 128 - private static final int PRIVKEY_SIZE = 1155; - - private static final int SIGNATUREDIGEST_SIZE = 256; - private static final int CIPHERTEXTBLOCK_SIZE = 256; - - private static final int PUBKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PUBKEY_SIZE; - private static final int PRIVKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PRIVKEY_SIZE; - private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_CODE_SIZE + SIGNATUREDIGEST_SIZE; - @Override - public Ciphertext encrypt(PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - - // 验证原始公钥长度为257字节 - if (rawPubKeyBytes.length != PUBKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应RSA算法 - if (pubKey.getAlgorithm() != RSA.code()) { - throw new CryptoException("The is not RSA public key!"); - } - - // 调用RSA加密算法计算密文 - return new AsymmetricCiphertext(RSA, RSAUtils.encrypt(data, rawPubKeyBytes)); - } - - @Override - public byte[] decrypt(PrivKey privKey, Ciphertext ciphertext) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - // 验证原始私钥长度为1153字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应RSA算法 - if (privKey.getAlgorithm() != RSA.code()) { - throw new CryptoException("This key is not RSA private key!"); - } - - // 验证密文数据的算法标识对应RSA算法,并且密文是分组长度的整数倍 - if (ciphertext.getAlgorithm() != RSA.code() - || rawCiphertextBytes.length % CIPHERTEXTBLOCK_SIZE != 0) { - throw new CryptoException("This is not RSA ciphertext!"); - } - - // 调用RSA解密算法得到明文结果 - return RSAUtils.decrypt(rawCiphertextBytes, rawPrivKeyBytes); - } - - @Override - public PubKey retrievePubKey(PrivKey privKey) { - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawPubKeyBytes = RSAUtils.retrievePublicKey(rawPrivKeyBytes); - return new PubKey(RSA, rawPubKeyBytes); - } - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - // 验证原始私钥长度为1153字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应RSA签名算法 - if (privKey.getAlgorithm() != RSA.code()) { - throw new CryptoException("This key is not RSA private key!"); - } - - // 调用RSA签名算法计算签名结果 - return new SignatureDigest(RSA, RSAUtils.sign(data, rawPrivKeyBytes)); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - // 验证原始公钥长度为257字节 - if (rawPubKeyBytes.length != PUBKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应RSA签名算法 - if (pubKey.getAlgorithm() != RSA.code()) { - throw new CryptoException("This key is not RSA public key!"); - } - - // 验证签名数据的算法标识对应RSA签名算法,并且原始签名长度为256字节 - if (digest.getAlgorithm() != RSA.code() || rawDigestBytes.length != SIGNATUREDIGEST_SIZE) { - throw new CryptoException("This is not RSA signature digest!"); - } - - // 调用RSA验签算法验证签名结果 - return RSAUtils.verify(data, rawPubKeyBytes, rawDigestBytes); - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应RSA算法,并且密钥类型是私钥 - return privKeyBytes.length == PRIVKEY_LENGTH && CryptoAlgorithm.match(RSA, privKeyBytes) - && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIVATE.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - if (supportPrivKey(privKeyBytes)) { - return new PrivKey(privKeyBytes); - } else { - throw new CryptoException("privKeyBytes are invalid!"); - } - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+椭圆曲线点长度,密钥数据的算法标识对应RSA算法,并且密钥类型是公钥 - return pubKeyBytes.length == PUBKEY_LENGTH && CryptoAlgorithm.match(RSA, pubKeyBytes) - && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUBLIC.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - if (supportPubKey(pubKeyBytes)) { - return new PubKey(pubKeyBytes); - } else { - throw new CryptoException("pubKeyBytes are invalid!"); - } - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+签名长度,字节数组的算法标识对应RSA算法 - return digestBytes.length == SIGNATUREDIGEST_LENGTH && CryptoAlgorithm.match(RSA, digestBytes); - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - if (supportDigest(digestBytes)) { - return new SignatureDigest(digestBytes); - } else { - throw new CryptoException("digestBytes are invalid!"); - } - } - - @Override - public boolean supportCiphertext(byte[] ciphertextBytes) { - // 验证输入字节数组长度=密文分组的整数倍,字节数组的算法标识对应RSA算法 - return (ciphertextBytes.length % CIPHERTEXTBLOCK_SIZE == ALGORYTHM_CODE_SIZE) - && CryptoAlgorithm.match(RSA, ciphertextBytes); - } - - @Override - public AsymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { - if (supportCiphertext(ciphertextBytes)) { - return new AsymmetricCiphertext(ciphertextBytes); - } else { - throw new CryptoException("ciphertextBytes are invalid!"); - } - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return RSA; - } - - @Override - public AsymmetricKeypair generateKeypair() { - - AsymmetricCipherKeyPair keyPair = RSAUtils.generateKeyPair(); - RSAKeyParameters pubKey = (RSAKeyParameters) keyPair.getPublic(); - RSAPrivateCrtKeyParameters privKey = (RSAPrivateCrtKeyParameters) keyPair.getPrivate(); - - byte[] pubKeyBytes = RSAUtils.pubKey2Bytes_RawKey(pubKey); - byte[] privKeyBytes = RSAUtils.privKey2Bytes_RawKey(privKey); - - return new AsymmetricKeypair(new PubKey(RSA, pubKeyBytes), new PrivKey(RSA, privKeyBytes)); - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/SHA256HashFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/SHA256HashFunction.java deleted file mode 100644 index 307a85e1..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/SHA256HashFunction.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jd.blockchain.crypto.service.classic; - -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; - -import java.util.Arrays; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.utils.classic.SHA256Utils; - -public class SHA256HashFunction implements HashFunction { - - private static final CryptoAlgorithm SHA256 = ClassicAlgorithm.SHA256; - - private static final int DIGEST_BYTES = 256 / 8; - - private static final int DIGEST_LENGTH = ALGORYTHM_CODE_SIZE + DIGEST_BYTES; - - SHA256HashFunction() { - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return SHA256; - } - - @Override - public HashDigest hash(byte[] data) { - if (data == null) { - throw new CryptoException("data is null!"); - } - - byte[] digestBytes = SHA256Utils.hash(data); - return new HashDigest(SHA256, digestBytes); - } - - @Override - public HashDigest hash(byte[] data, int offset, int len) { - if (data == null) { - throw new CryptoException("data is null!"); - } - - byte[] digestBytes = SHA256Utils.hash(data, offset, len); - return new HashDigest(SHA256, digestBytes); - } - - @Override - public boolean verify(HashDigest digest, byte[] data) { - HashDigest hashDigest = hash(data); - return Arrays.equals(hashDigest.toBytes(), digest.toBytes()); - } - - @Override - public boolean supportHashDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,以及算法标识; - return DIGEST_LENGTH == digestBytes.length && CryptoAlgorithm.match(SHA256, digestBytes); - } - - @Override - public HashDigest resolveHashDigest(byte[] digestBytes) { - if (supportHashDigest(digestBytes)) { - return new HashDigest(digestBytes); - } else { - throw new CryptoException("digestBytes is invalid!"); - } - } - -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/AESUtils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/AESUtils.java deleted file mode 100644 index e1b3eaf4..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/AESUtils.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.CryptoException; -import org.bouncycastle.crypto.CipherKeyGenerator; -import org.bouncycastle.crypto.KeyGenerationParameters; -import org.bouncycastle.crypto.engines.AESEngine; -import org.bouncycastle.crypto.modes.CBCBlockCipher; -import org.bouncycastle.crypto.paddings.PKCS7Padding; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; - -import java.security.SecureRandom; -import java.util.Arrays; - -/** - * @author zhanglin33 - * @title: AESUtils - * @description: AES128/CBC/PKCS7Padding symmetric encryption algorithm - * @date 2019-04-22, 09:37 - */ -public class AESUtils { - - // AES128 supports 128-bit(16 bytes) secret key - private static final int KEY_SIZE = 128 / 8; - // One block contains 16 bytes - private static final int BLOCK_SIZE = 16; - // Initial vector's size is 16 bytes - private static final int IV_SIZE = 16; - - /** - * key generation - * - * @return secret key - */ - public static byte[] generateKey(){ - - CipherKeyGenerator keyGenerator = new CipherKeyGenerator(); - - // To provide secure randomness and key length as input - // to prepare generate private key - keyGenerator.init(new KeyGenerationParameters(new SecureRandom(), KEY_SIZE * 8)); - - // To generate key - return keyGenerator.generateKey(); - } - - public static byte[] generateKey(byte[] seed){ - byte[] hash = SHA256Utils.hash(seed); - return Arrays.copyOf(hash, KEY_SIZE); - } - - - /** - * encryption - * - * @param plainBytes plaintext - * @param secretKey symmetric key - * @param iv initial vector - * @return ciphertext - */ - public static byte[] encrypt(byte[] plainBytes, byte[] secretKey, byte[] iv){ - - // To ensure that plaintext is not null - if (plainBytes == null) - { - throw new CryptoException("plaintext is null!"); - } - - if (secretKey.length != KEY_SIZE) - { - throw new CryptoException("secretKey's length is wrong!"); - } - - if (iv.length != IV_SIZE) - { - throw new CryptoException("iv's length is wrong!"); - } - - // To get the value padded into input - int padding = 16 - plainBytes.length % BLOCK_SIZE; - // The plaintext with padding value - byte[] plainBytesWithPadding = new byte[plainBytes.length + padding]; - System.arraycopy(plainBytes,0,plainBytesWithPadding,0,plainBytes.length); - // The padder adds PKCS7 padding to the input, which makes its length to - // become an integral multiple of 16 bytes - PKCS7Padding padder = new PKCS7Padding(); - // To add padding - padder.addPadding(plainBytesWithPadding, plainBytes.length); - - CBCBlockCipher encryptor = new CBCBlockCipher(new AESEngine()); - // To provide key and initialisation vector as input - encryptor.init(true,new ParametersWithIV(new KeyParameter(secretKey),iv)); - byte[] output = new byte[plainBytesWithPadding.length + IV_SIZE]; - // To encrypt the input_p in CBC mode - for(int i = 0 ; i < plainBytesWithPadding.length/BLOCK_SIZE; i++) { - encryptor.processBlock(plainBytesWithPadding, i * BLOCK_SIZE, output, (i + 1) * BLOCK_SIZE); - } - - // The IV locates on the first block of ciphertext - System.arraycopy(iv,0,output,0,BLOCK_SIZE); - return output; - } - - public static byte[] encrypt(byte[] plainBytes, byte[] secretKey){ - - byte[] iv = new byte[IV_SIZE]; - SecureRandom random = new SecureRandom(); - random.nextBytes(iv); - return encrypt(plainBytes,secretKey,iv); - } - - /** - * decryption - * - * @param cipherBytes ciphertext - * @param secretKey symmetric key - * @return plaintext - */ - public static byte[] decrypt(byte[] cipherBytes, byte[] secretKey){ - - // To ensure that the ciphertext is not null - if (cipherBytes == null) - { - throw new CryptoException("ciphertext is null!"); - } - - // To ensure that the ciphertext's length is integral multiples of 16 bytes - if (cipherBytes.length % BLOCK_SIZE != 0) - { - throw new CryptoException("ciphertext's length is wrong!"); - } - - if (secretKey.length != KEY_SIZE) - { - throw new CryptoException("secretKey's length is wrong!"); - } - - byte[] iv = new byte[IV_SIZE]; - System.arraycopy(cipherBytes,0,iv,0,BLOCK_SIZE); - - CBCBlockCipher decryptor = new CBCBlockCipher(new AESEngine()); - // To prepare the decryption - decryptor.init(false,new ParametersWithIV(new KeyParameter(secretKey),iv)); - byte[] outputWithPadding = new byte[cipherBytes.length-BLOCK_SIZE]; - // To decrypt the input in CBC mode - for(int i = 1 ; i < cipherBytes.length/BLOCK_SIZE ; i++) { - decryptor.processBlock(cipherBytes, i * BLOCK_SIZE, outputWithPadding, (i - 1) * BLOCK_SIZE); - } - - int p = outputWithPadding[outputWithPadding.length-1]; - // To ensure that the padding of output_p is valid - if(p > BLOCK_SIZE || p < 0x01) - { - throw new CryptoException("There no exists such padding!"); - - } - for(int i = 0 ; i < p ; i++) - { - if(outputWithPadding[outputWithPadding.length - i -1] != p) - { - throw new CryptoException("Padding is invalid!"); - } - } - - // To remove the padding from output and obtain plaintext - byte[] output = new byte[outputWithPadding.length - p]; - System.arraycopy(outputWithPadding, 0, output, 0, output.length); - return output; - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ECDSAUtils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ECDSAUtils.java deleted file mode 100644 index 73b9e7b3..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ECDSAUtils.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import org.bouncycastle.asn1.sec.SECNamedCurves; -import org.bouncycastle.asn1.x9.X9ECParameters; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.generators.ECKeyPairGenerator; -import org.bouncycastle.crypto.params.*; -import org.bouncycastle.crypto.signers.ECDSASigner; -import org.bouncycastle.jce.ECNamedCurveTable; -import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.math.ec.ECMultiplier; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.math.ec.FixedPointCombMultiplier; - -import java.math.BigInteger; -import java.security.SecureRandom; - -/** - * @author zhanglin33 - * @title: ECDSAUtils - * @description: ECDSA signature algorithm based on Curve secp256k1 with SHA256 - * @date 2019-03-25, 17:21 - */ -public class ECDSAUtils { - - private static final int R_SIZE =32; - private static final int S_SIZE =32; - - // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 - // the curve equation is y^2 = x^3 + 7. - private static final ECNamedCurveParameterSpec PARAMS = ECNamedCurveTable.getParameterSpec("secp256k1"); - private static final ECCurve CURVE = PARAMS.getCurve(); - private static final ECDomainParameters DOMAIN_PARAMS = new ECDomainParameters( - CURVE, PARAMS.getG(), PARAMS.getN(), PARAMS.getH()); - - - //-----------------Key Generation Algorithm----------------- - - /** - * key generation - * - * @return key pair - */ - public static AsymmetricCipherKeyPair generateKeyPair(){ - SecureRandom random = new SecureRandom(); - return generateKeyPair(random); - } - - public static AsymmetricCipherKeyPair generateKeyPair(SecureRandom random){ - - ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS,random); - ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); - - // To generate the key pair - keyPairGenerator.init(keyGenerationParams); - return keyPairGenerator.generateKeyPair(); - } - - /** - * public key retrieval - * - * @param privateKey private key - * @return publicKey - */ - public static byte[] retrievePublicKey(byte[] privateKey) { - ECPoint publicKeyPoint = DOMAIN_PARAMS.getG().multiply(new BigInteger(1,privateKey)).normalize(); - return publicKeyPoint.getEncoded(false); - } - - - //-----------------Digital Signature Algorithm----------------- - - /** - * signature generation - * - * @param data data to be signed - * @param privateKey private key - * @return signature - */ - public static byte[] sign(byte[] data, byte[] privateKey){ - - SecureRandom random = new SecureRandom(); - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); - CipherParameters params = new ParametersWithRandom(privKey,random); - - return sign(data,params); - } - - public static byte[] sign(byte[] data, byte[] privateKey, SecureRandom random){ - - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); - CipherParameters params = new ParametersWithRandom(privKey,random); - - return sign(data,params); - } - - public static byte[] sign(byte[] data, CipherParameters params){ - - byte[] hashedMsg = SHA256Utils.hash(data); - return sign(params,hashedMsg); - } - - public static byte[] sign(CipherParameters params, byte[] hashedMsg){ - ECDSASigner signer = new ECDSASigner(); - signer.init(true, params); - BigInteger[] signature = signer.generateSignature(hashedMsg); - - byte[] rBytes = BigIntegerTo32Bytes(signature[0]); - byte[] sBytes = BigIntegerTo32Bytes(signature[1]); - - byte[] result = new byte[R_SIZE + S_SIZE]; - System.arraycopy(rBytes,0,result,0,R_SIZE); - System.arraycopy(sBytes,0,result,R_SIZE,S_SIZE); - - return result; - } - - - /** - * verification - * - * @param data data to be signed - * @param publicKey public key - * @param signature signature to be verified - * @return true or false - */ - public static boolean verify(byte[] data, byte[] publicKey, byte[] signature){ - - ECPoint pubKeyPoint = resolvePubKeyBytes(publicKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint, DOMAIN_PARAMS); - - return verify(data,pubKey,signature); - } - - public static boolean verify(byte[] data, CipherParameters params, byte[] signature){ - - byte[] hashedMsg = SHA256Utils.hash(data); - return verify(params,signature,hashedMsg); - } - - public static boolean verify(CipherParameters params, byte[] signature, byte[] hashedMsg){ - - byte[] rBytes = new byte[R_SIZE]; - byte[] sBytes = new byte[S_SIZE]; - System.arraycopy(signature,0,rBytes,0,R_SIZE); - System.arraycopy(signature,R_SIZE,sBytes,0,S_SIZE); - - BigInteger r = new BigInteger(1,rBytes); - BigInteger s = new BigInteger(1,sBytes); - - ECDSASigner verifier = new ECDSASigner(); - verifier.init(false,params); - return verifier.verifySignature(hashedMsg,r,s); - } - - // To convert BigInteger to byte[] whose length is 32 - private static byte[] BigIntegerTo32Bytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[32]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } - - // To retrieve the public key point from publicKey in byte array mode - private static ECPoint resolvePubKeyBytes(byte[] publicKey){ - return CURVE.decodePoint(publicKey); - } - - public static ECCurve getCurve(){return CURVE;} - - public static ECDomainParameters getDomainParams(){return DOMAIN_PARAMS;} -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ED25519Utils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ED25519Utils.java deleted file mode 100644 index d3f45e65..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ED25519Utils.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; -import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; -import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; -import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; -import org.bouncycastle.crypto.signers.Ed25519Signer; - -import java.security.SecureRandom; - -/** - * @author zhanglin33 - * @title: ED25519Utils - * @description: ED25519 signature algorithm - * @date 2019-04-04, 20:01 - */ -public class ED25519Utils { - - //-----------------Key Generation Algorithm----------------- - - /** - * key pair generation - * - * @return key pair - */ - public static AsymmetricCipherKeyPair generateKeyPair(){ - SecureRandom random = new SecureRandom(); - return generateKeyPair(random); - } - - public static AsymmetricCipherKeyPair generateKeyPair(SecureRandom random){ - Ed25519KeyPairGenerator keyPairGenerator = new Ed25519KeyPairGenerator(); - keyPairGenerator.init(new Ed25519KeyGenerationParameters(random)); - return keyPairGenerator.generateKeyPair(); - } - - /** - * public key retrieval - * - * @param privateKey private key - * @return publicKey - */ - public static byte[] retrievePublicKey(byte[] privateKey){ - Ed25519PrivateKeyParameters privKeyParams = new Ed25519PrivateKeyParameters(privateKey,0); - return privKeyParams.generatePublicKey().getEncoded(); - } - - - //-----------------Digital Signature Algorithm----------------- - - /** - * signature generation - * - * @param data data to be signed - * @param privateKey private key - * @return signature - */ - public static byte[] sign(byte[] data, byte[] privateKey){ - Ed25519PrivateKeyParameters privKeyParams = new Ed25519PrivateKeyParameters(privateKey,0); - return sign(data,privKeyParams); - } - - public static byte[] sign(byte[] data, CipherParameters params){ - Ed25519Signer signer = new Ed25519Signer(); - signer.init(true, params); - signer.update(data,0,data.length); - return signer.generateSignature(); - } - - /** - * verification - * - * @param data data to be signed - * @param publicKey public key - * @param signature signature to be verified - * @return true or false - */ - public static boolean verify(byte[] data, byte[] publicKey, byte[] signature){ - Ed25519PublicKeyParameters pubKeyParams = new Ed25519PublicKeyParameters(publicKey,0); - return verify(data,pubKeyParams,signature); - } - - public static boolean verify(byte[] data, CipherParameters params, byte[] signature){ - Ed25519Signer verifier = new Ed25519Signer(); - verifier.init(false, params); - verifier.update(data,0,data.length); - return verifier.verifySignature(signature); - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RIPEMD160Utils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RIPEMD160Utils.java deleted file mode 100644 index 0ce73eab..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RIPEMD160Utils.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import org.bouncycastle.crypto.digests.RIPEMD160Digest; - -/** - * @author zhanglin33 - * @title: RIPEMD160Utils - * @description: RIPEMD160 hash algorithm - * @date 2019-04-10, 16:51 - */ -public class RIPEMD160Utils { - - // The length of RIPEMD160 output is 20 bytes - public static final int RIPEMD160DIGEST_LENGTH = 160 / 8; - - public static byte[] hash(byte[] data) { - - byte[] result = new byte[RIPEMD160DIGEST_LENGTH]; - RIPEMD160Digest ripemd160Digest = new RIPEMD160Digest(); - - ripemd160Digest.update(data, 0, data.length); - ripemd160Digest.doFinal(result, 0); - return result; - } - - public static byte[] hash(byte[] data, int offset, int len) { - - byte[] result = new byte[RIPEMD160DIGEST_LENGTH]; - RIPEMD160Digest ripemd160Digest = new RIPEMD160Digest(); - - ripemd160Digest.update(data, offset, len); - ripemd160Digest.doFinal(result, 0); - return result; - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RSAUtils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RSAUtils.java deleted file mode 100644 index a787b655..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RSAUtils.java +++ /dev/null @@ -1,536 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.RSAPrivateKey; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.crypto.AsymmetricBlockCipher; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.encodings.PKCS1Encoding; -import org.bouncycastle.crypto.engines.RSAEngine; -import org.bouncycastle.crypto.generators.RSAKeyPairGenerator; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; -import org.bouncycastle.crypto.params.RSAKeyParameters; -import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; -import org.bouncycastle.crypto.signers.RSADigestSigner; -import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil; - -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * @author zhanglin33 - * @title: RSAUtils - * @description: RSA2048 encryption(RSA/ECB/PKCS1Padding) and signature(SHA256withRSA) algorithms, - * and keys are output in raw, PKCS1v2 and PKCS8 formats - * @date 2019-03-25, 17:20 - */ -public class RSAUtils { - - private static final int KEYSIZEBITS = 2048; - private static final int CERTAINTY = 100; - - private static final int MODULUS_LENGTH = 2048 / 8; - private static final int PRIVEXP_LENGTH = 2048 / 8; - private static final int P_LENGTH = 1024 / 8; - private static final int Q_LENGTH = 1024 / 8; - private static final int DP_LENGTH = 1024 / 8; - private static final int DQ_LENGTH = 1024 / 8; - private static final int QINV_LENGTH = 1024 / 8; - - private static final BigInteger PUBEXP_0X03 = BigInteger.valueOf(0x03); - private static final BigInteger PUBEXP_0X010001 = BigInteger.valueOf(0x010001); - - private static final BigInteger VERSION_2PRIMES = BigInteger.valueOf(0); - - private static final AlgorithmIdentifier RSA_ALGORITHM_IDENTIFIER = - new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); - - private static final int PLAINTEXT_BLOCKSIZE = 256 - 11; - private static final int CIPHERTEXT_BLOCKSIZE = 256; - - - //-----------------Key Generation Algorithm----------------- - - /** - * key pair generation - * - * @return key pair - */ - public static AsymmetricCipherKeyPair generateKeyPair(){ - return generateKeyPair(new SecureRandom()); - } - - public static AsymmetricCipherKeyPair generateKeyPair(SecureRandom random){ - AsymmetricCipherKeyPairGenerator kpGen = new RSAKeyPairGenerator(); - kpGen.init(new RSAKeyGenerationParameters(PUBEXP_0X010001, random, KEYSIZEBITS, CERTAINTY)); - return kpGen.generateKeyPair(); - } - - /** - * key pair generation with short public exponent, resulting in verifying and encrypting more efficiently - * - * @return key pair - */ - public static AsymmetricCipherKeyPair generateKeyPair_shortExp(){ - return generateKeyPair_shortExp(new SecureRandom()); - } - - public static AsymmetricCipherKeyPair generateKeyPair_shortExp(SecureRandom random){ - AsymmetricCipherKeyPairGenerator kpGen = new RSAKeyPairGenerator(); - kpGen.init(new RSAKeyGenerationParameters(PUBEXP_0X03, random, KEYSIZEBITS, CERTAINTY)); - return kpGen.generateKeyPair(); - } - - // Retrieve public key in raw keys form - public static byte[] retrievePublicKey(byte[] privateKey) { - - RSAPrivateCrtKeyParameters privKey = bytes2PrivKey_RawKey(privateKey); - - BigInteger modulus = privKey.getModulus(); - BigInteger exponent = privKey.getPublicExponent(); - - RSAKeyParameters pubKey = new RSAKeyParameters(false, modulus, exponent); - - return pubKey2Bytes_RawKey(pubKey); - } - - - //-----------------Digital Signature Algorithm----------------- - - /** - * signature generation - * - * @param data data to be signed - * @param privateKey private key - * @return signature - */ - public static byte[] sign(byte[] data, byte[] privateKey){ - RSAPrivateCrtKeyParameters privKey = bytes2PrivKey_RawKey(privateKey); - return sign(data,privKey); - } - - public static byte[] sign(byte[] data, CipherParameters params){ - - SHA256Digest digest = new SHA256Digest(); - RSADigestSigner signer = new RSADigestSigner(digest); - signer.init(true, params); - signer.update(data, 0, data.length); - try { - return signer.generateSignature(); - } catch (CryptoException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - } - - /** - * verification - * - * @param data data to be signed - * @param publicKey public key - * @param signature signature to be verified - * @return true or false - */ - public static boolean verify(byte[] data, byte[] publicKey, byte[] signature){ - RSAKeyParameters pubKey = bytes2PubKey_RawKey(publicKey); - return verify(data,pubKey,signature); - } - - public static boolean verify(byte[] data, CipherParameters params, byte[] signature){ - - SHA256Digest digest = new SHA256Digest(); - RSADigestSigner signer = new RSADigestSigner(digest); - - signer.init(false, params); - signer.update(data, 0, data.length); - return signer.verifySignature(signature); - } - - - //-----------------Public Key Encryption Algorithm----------------- - - /** - * encryption - * - * @param plainBytes plaintext - * @param publicKey public key - * @return ciphertext - */ - public static byte[] encrypt(byte[] plainBytes, byte[] publicKey){ - RSAKeyParameters pubKey = bytes2PubKey_RawKey(publicKey); - return encrypt(plainBytes,pubKey); - } - - public static byte[] encrypt(byte[] plainBytes, byte[] publicKey, SecureRandom random){ - - RSAKeyParameters pubKey = bytes2PubKey_RawKey(publicKey); - ParametersWithRandom params = new ParametersWithRandom(pubKey,random); - - return encrypt(plainBytes,params); - } - - public static byte[] encrypt(byte[] plainBytes, CipherParameters params){ - - int blockNum = (plainBytes.length % PLAINTEXT_BLOCKSIZE == 0) ? (plainBytes.length / PLAINTEXT_BLOCKSIZE) - : (plainBytes.length / PLAINTEXT_BLOCKSIZE + 1); - int inputLength; - byte[] result = new byte[blockNum * CIPHERTEXT_BLOCKSIZE]; - byte[] buffer; - - AsymmetricBlockCipher encryptor = new PKCS1Encoding(new RSAEngine()); - encryptor.init(true, params); - try { - for (int i= 0; i < blockNum; i++) { - inputLength = ((plainBytes.length - i * PLAINTEXT_BLOCKSIZE) > PLAINTEXT_BLOCKSIZE)? - PLAINTEXT_BLOCKSIZE : (plainBytes.length - i * PLAINTEXT_BLOCKSIZE); - buffer = encryptor.processBlock(plainBytes, i * PLAINTEXT_BLOCKSIZE, inputLength); - System.arraycopy(buffer,0, - result, i * CIPHERTEXT_BLOCKSIZE, CIPHERTEXT_BLOCKSIZE); - } - } catch (InvalidCipherTextException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - return result; - } - - /** - * decryption - * - * @param cipherBytes ciphertext - * @param privateKey private key - * @return plaintext - */ - public static byte[] decrypt(byte[] cipherBytes, byte[] privateKey){ - RSAPrivateCrtKeyParameters privKey = bytes2PrivKey_RawKey(privateKey); - return decrypt(cipherBytes,privKey); - } - - public static byte[] decrypt(byte[] cipherBytes, CipherParameters params){ - - if (cipherBytes.length % CIPHERTEXT_BLOCKSIZE != 0) - { - throw new com.jd.blockchain.crypto.CryptoException("ciphertext's length is wrong!"); - } - - int blockNum = cipherBytes.length / CIPHERTEXT_BLOCKSIZE; - int count = 0; - byte[] buffer; - byte[] plaintextWithZeros = new byte[blockNum * PLAINTEXT_BLOCKSIZE]; - byte[] result; - - AsymmetricBlockCipher decryptor = new PKCS1Encoding(new RSAEngine()); - decryptor.init(false,params); - try { - for (int i = 0; i < blockNum; i++){ - buffer = decryptor.processBlock(cipherBytes,i * CIPHERTEXT_BLOCKSIZE, CIPHERTEXT_BLOCKSIZE); - count += buffer.length; - System.arraycopy(buffer,0,plaintextWithZeros, i * PLAINTEXT_BLOCKSIZE, buffer.length); - } - } catch (InvalidCipherTextException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - - result = new byte[count]; - System.arraycopy(plaintextWithZeros,0,result,0,result.length); - - return result; - } - - - /** - * This outputs the key in PKCS1v2 format. - * RSAPublicKey ::= SEQUENCE { - * modulus INTEGER, -- n - * publicExponent INTEGER, -- e - * } - */ - public static byte[] pubKey2Bytes_PKCS1(RSAKeyParameters pubKey) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(new ASN1Integer(pubKey.getModulus())); - v.add(new ASN1Integer(pubKey.getExponent())); - - DERSequence pubKeySequence = new DERSequence(v); - - byte[] result; - - try { - result = pubKeySequence.getEncoded(ASN1Encoding.DER); - } catch (IOException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - - return result; - } - - public static byte[] pubKey2Bytes_PKCS8(RSAKeyParameters pubKey){ - - BigInteger modulus = pubKey.getModulus(); - BigInteger exponent = pubKey.getExponent(); - - return KeyUtil.getEncodedSubjectPublicKeyInfo(RSA_ALGORITHM_IDENTIFIER, - new org.bouncycastle.asn1.pkcs.RSAPublicKey(modulus, exponent)); - } - - public static byte[] pubKey2Bytes_RawKey(RSAKeyParameters pubKey){ - - BigInteger modulus = pubKey.getModulus(); - BigInteger exponent = pubKey.getExponent(); - - byte[] exponentBytes = exponent.toByteArray(); - byte[] modulusBytes = bigInteger2Bytes(modulus,MODULUS_LENGTH); - - return BytesUtils.concat(modulusBytes,exponentBytes); - } - - public static RSAKeyParameters bytes2PubKey_PKCS1(byte[] pubKeyBytes) { - - ASN1Sequence pubKeySequence = ASN1Sequence.getInstance(pubKeyBytes); - - BigInteger modulus = ASN1Integer.getInstance(pubKeySequence.getObjectAt(0)).getValue(); - BigInteger exponent = ASN1Integer.getInstance(pubKeySequence.getObjectAt(1)).getValue(); - - return new RSAKeyParameters(false, modulus, exponent); - } - - public static RSAKeyParameters bytes2PubKey_PKCS8(byte[] pubKeyBytes) { - - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKeyBytes); - - KeyFactory keyFactory; - RSAPublicKey publicKey; - - try { - keyFactory = KeyFactory.getInstance("RSA"); - publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec); - } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - - BigInteger exponent = publicKey.getPublicExponent(); - BigInteger modulus = publicKey.getModulus(); - - return new RSAKeyParameters(false,modulus,exponent); - } - - public static RSAKeyParameters bytes2PubKey_RawKey(byte[] pubKeyBytes) { - - byte[] modulusBytes = new byte[MODULUS_LENGTH]; - byte[] exponentBytes = new byte[pubKeyBytes.length - MODULUS_LENGTH]; - - System.arraycopy(pubKeyBytes,0, modulusBytes,0, MODULUS_LENGTH); - - System.arraycopy(pubKeyBytes,MODULUS_LENGTH, exponentBytes,0,exponentBytes.length); - - BigInteger modulus = new BigInteger(1, modulusBytes); - BigInteger exponent = new BigInteger(1, exponentBytes); - - return new RSAKeyParameters(false,modulus,exponent); - } - - /** - * This outputs the key in PKCS1v2 format. - * RSAPrivateKey ::= SEQUENCE { - * VERSION_2PRIMES Version, - * modulus INTEGER, -- n - * publicExponent INTEGER, -- e - * privateExponent INTEGER, -- d - * prime1 INTEGER, -- p - * prime2 INTEGER, -- q - * exponent1 INTEGER, -- d mod (p-1) - * exponent2 INTEGER, -- d mod (q-1) - * coefficient INTEGER, -- (inverse of q) mod p - * otherPrimeInfos OtherPrimeInfos OPTIONAL - * } - * - * Version ::= INTEGER { two-prime(0), multi(1) } - * (CONSTRAINED BY {-- version must be multi if otherPrimeInfos present --}) - * - * This routine is written to output PKCS1 version 2.1, private keys. - */ - public static byte[] privKey2Bytes_PKCS1(RSAPrivateCrtKeyParameters privKey) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(new ASN1Integer(VERSION_2PRIMES)); // version - v.add(new ASN1Integer(privKey.getModulus())); - v.add(new ASN1Integer(privKey.getPublicExponent())); - v.add(new ASN1Integer(privKey.getExponent())); - v.add(new ASN1Integer(privKey.getP())); - v.add(new ASN1Integer(privKey.getQ())); - v.add(new ASN1Integer(privKey.getDP())); - v.add(new ASN1Integer(privKey.getDQ())); - v.add(new ASN1Integer(privKey.getQInv())); - - DERSequence privKeySequence = new DERSequence(v); - - byte[] result; - - try { - result = privKeySequence.getEncoded(ASN1Encoding.DER); - } catch (IOException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - - return result; - } - - public static byte[] privKey2Bytes_PKCS8(RSAPrivateCrtKeyParameters privKey){ - - BigInteger modulus = privKey.getModulus(); - BigInteger pubExp = privKey.getPublicExponent(); - BigInteger privExp = privKey.getExponent(); - BigInteger p = privKey.getP(); - BigInteger q = privKey.getQ(); - BigInteger dP = privKey.getDP(); - BigInteger dQ = privKey.getDQ(); - BigInteger qInv = privKey.getQInv(); - - return KeyUtil.getEncodedPrivateKeyInfo(RSA_ALGORITHM_IDENTIFIER, - new RSAPrivateKey(modulus, pubExp, privExp, p, q, dP, dQ, qInv)); - } - - public static byte[] privKey2Bytes_RawKey(RSAPrivateCrtKeyParameters privKey){ - - BigInteger modulus = privKey.getModulus(); - BigInteger pubExp = privKey.getPublicExponent(); - BigInteger privExp = privKey.getExponent(); - BigInteger p = privKey.getP(); - BigInteger q = privKey.getQ(); - BigInteger dP = privKey.getDP(); - BigInteger dQ = privKey.getDQ(); - BigInteger qInv = privKey.getQInv(); - - byte[] modulusBytes = bigInteger2Bytes(modulus,MODULUS_LENGTH); - byte[] pubExpBytes = pubExp.toByteArray(); - byte[] privExpBytes = bigInteger2Bytes(privExp,PRIVEXP_LENGTH); - byte[] pBytes = bigInteger2Bytes(p,P_LENGTH); - byte[] qBytes = bigInteger2Bytes(q,Q_LENGTH); - byte[] dPBytes = bigInteger2Bytes(dP,DP_LENGTH); - byte[] dQBytes = bigInteger2Bytes(dQ,DQ_LENGTH); - byte[] qInvBytes = bigInteger2Bytes(qInv,QINV_LENGTH); - - - return BytesUtils.concat(modulusBytes,pubExpBytes,privExpBytes,pBytes,qBytes,dPBytes,dQBytes,qInvBytes); - } - - public static RSAPrivateCrtKeyParameters bytes2PrivKey_PKCS1(byte[] privKeyBytes){ - - ASN1Sequence priKeySequence = ASN1Sequence.getInstance(privKeyBytes); - - BigInteger modulus = ASN1Integer.getInstance(priKeySequence.getObjectAt(1)).getValue(); - BigInteger pubExp = ASN1Integer.getInstance(priKeySequence.getObjectAt(2)).getValue(); - BigInteger privExp = ASN1Integer.getInstance(priKeySequence.getObjectAt(3)).getValue(); - BigInteger p = ASN1Integer.getInstance(priKeySequence.getObjectAt(4)).getValue(); - BigInteger q = ASN1Integer.getInstance(priKeySequence.getObjectAt(5)).getValue(); - BigInteger dP = ASN1Integer.getInstance(priKeySequence.getObjectAt(6)).getValue(); - BigInteger dQ = ASN1Integer.getInstance(priKeySequence.getObjectAt(7)).getValue(); - BigInteger qInv = ASN1Integer.getInstance(priKeySequence.getObjectAt(8)).getValue(); - - return new RSAPrivateCrtKeyParameters(modulus, pubExp, privExp, p, q, dP, dQ, qInv); - } - - public static RSAPrivateCrtKeyParameters bytes2PrivKey_PKCS8(byte[] privKeyBytes){ - - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyBytes); - - KeyFactory keyFactory; - RSAPrivateCrtKey privateKey; - - try { - keyFactory = KeyFactory.getInstance("RSA"); - privateKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(keySpec); - } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - - BigInteger modulus = privateKey.getModulus(); - BigInteger pubExp = privateKey.getPublicExponent(); - BigInteger privExp = privateKey.getPrivateExponent(); - BigInteger p = privateKey.getPrimeP(); - BigInteger q = privateKey.getPrimeQ(); - BigInteger dP = privateKey.getPrimeExponentP(); - BigInteger dQ = privateKey.getPrimeExponentQ(); - BigInteger qInv = privateKey.getCrtCoefficient(); - - return new RSAPrivateCrtKeyParameters(modulus, pubExp, privExp, p, q, dP, dQ, qInv); - } - - public static RSAPrivateCrtKeyParameters bytes2PrivKey_RawKey(byte[] privKeyBytes){ - - byte[] modulusBytes = new byte[MODULUS_LENGTH]; - byte[] pubExpBytes = new byte[privKeyBytes.length - MODULUS_LENGTH - PRIVEXP_LENGTH - P_LENGTH - Q_LENGTH - - DP_LENGTH - DQ_LENGTH - QINV_LENGTH]; - byte[] privExpBytes = new byte[PRIVEXP_LENGTH]; - byte[] pBytes = new byte[P_LENGTH]; - byte[] qBytes = new byte[Q_LENGTH]; - byte[] dPBytes = new byte[DP_LENGTH]; - byte[] dQBytes = new byte[DQ_LENGTH]; - byte[] qInvBytes = new byte[QINV_LENGTH]; - - System.arraycopy(privKeyBytes,0, modulusBytes,0, MODULUS_LENGTH); - System.arraycopy(privKeyBytes, MODULUS_LENGTH, pubExpBytes,0,pubExpBytes.length); - System.arraycopy(privKeyBytes,MODULUS_LENGTH + pubExpBytes.length, - privExpBytes,0,PRIVEXP_LENGTH); - System.arraycopy(privKeyBytes,MODULUS_LENGTH + pubExpBytes.length + PRIVEXP_LENGTH, - pBytes,0,P_LENGTH); - System.arraycopy(privKeyBytes,MODULUS_LENGTH + pubExpBytes.length + PRIVEXP_LENGTH + P_LENGTH, - qBytes,0,Q_LENGTH); - System.arraycopy(privKeyBytes,MODULUS_LENGTH + pubExpBytes.length + PRIVEXP_LENGTH + P_LENGTH + - Q_LENGTH, dPBytes,0,DP_LENGTH); - System.arraycopy(privKeyBytes,MODULUS_LENGTH + pubExpBytes.length + PRIVEXP_LENGTH + P_LENGTH + - Q_LENGTH + DP_LENGTH, dQBytes,0,DQ_LENGTH); - System.arraycopy(privKeyBytes,MODULUS_LENGTH + pubExpBytes.length + PRIVEXP_LENGTH + P_LENGTH + - Q_LENGTH + DP_LENGTH + DQ_LENGTH, qInvBytes,0,QINV_LENGTH); - - BigInteger modulus = new BigInteger(1, modulusBytes); - BigInteger pubExp = new BigInteger(1, pubExpBytes); - BigInteger privExp = new BigInteger(1, privExpBytes); - BigInteger p = new BigInteger(1, pBytes); - BigInteger q = new BigInteger(1, qBytes); - BigInteger dP = new BigInteger(1, dPBytes); - BigInteger dQ = new BigInteger(1, dQBytes); - BigInteger qInv = new BigInteger(1, qInvBytes); - - return new RSAPrivateCrtKeyParameters(modulus, pubExp, privExp, p, q, dP, dQ, qInv); - } - - private static byte[] bigInteger2Bytes(BigInteger src, int length){ - - byte[] result = new byte[length]; - byte[] srcBytes = src.toByteArray(); - int srcLength = srcBytes.length; - - if (srcLength > length) { - System.arraycopy(srcBytes,srcLength - length, - result,0, length); - } else { - System.arraycopy(srcBytes,0, - result,length - srcLength, srcLength); - } - - return result; - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SHA256Utils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SHA256Utils.java deleted file mode 100644 index 017a2b7a..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SHA256Utils.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import org.bouncycastle.crypto.digests.SHA256Digest; - -/** - * @author zhanglin33 - * @title: SHA256Utils - * @description: SHA256 hash algorithm - * @date 2019-04-09, 14:28 - */ -public class SHA256Utils { - - // The length of SHA256 output is 32 bytes - public static final int SHA256DIGEST_LENGTH = 256 / 8; - - public static byte[] hash(byte[] data){ - - byte[] result = new byte[SHA256DIGEST_LENGTH]; - SHA256Digest sha256Digest = new SHA256Digest(); - - sha256Digest.update(data,0,data.length); - sha256Digest.doFinal(result,0); - return result; - } - - public static byte[] hash(byte[] data, int offset, int len){ - - byte[] result = new byte[SHA256DIGEST_LENGTH]; - SHA256Digest sha256Digest = new SHA256Digest(); - - sha256Digest.update(data, offset, len); - sha256Digest.doFinal(result,0); - return result; - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SSHKeyParser.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SSHKeyParser.java deleted file mode 100644 index 055699c7..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SSHKeyParser.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.CryptoException; -import org.bouncycastle.asn1.sec.SECNamedCurves; -import org.bouncycastle.asn1.x9.X9ECParameters; -import org.bouncycastle.crypto.params.*; -import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil; -import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil; -import org.bouncycastle.jce.spec.OpenSSHPrivateKeySpec; -import org.bouncycastle.jce.spec.OpenSSHPublicKeySpec; -import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.io.pem.PemReader; - -import java.io.IOException; -import java.io.StringReader; -import java.math.BigInteger; - -import static java.math.BigInteger.ONE; - -/** - * @author zhanglin33 - * @title: SSHKeyParser - * @description: a parser for parsing asymmetric keys in Base64 format - * @date 2019-05-17, 17:52 - */ -public class SSHKeyParser { - - private String keyFormat; - private String keyType; - private String identity; - - public AsymmetricKeyParameter pubKeyParse(String pubKeyStr) { - - byte[] pubKeyBytes; - pubKeyStr = pubKeyStr.replaceAll("\\n", ""); - - if (pubKeyStr.startsWith("ssh") || pubKeyStr.startsWith("ecdsa")) { - String[] algoAndKeyAndLocal = pubKeyStr.split(" "); - pubKeyBytes = Base64.decode(algoAndKeyAndLocal[1]); - identity = algoAndKeyAndLocal[2]; - } else { - pubKeyBytes = Base64.decode(pubKeyStr); - } - - OpenSSHPublicKeySpec pubKeySpec = new OpenSSHPublicKeySpec(pubKeyBytes); - - keyFormat = pubKeySpec.getFormat(); - keyType = pubKeySpec.getType(); - - return OpenSSHPublicKeyUtil.parsePublicKey(pubKeyBytes); - } - - public AsymmetricKeyParameter privKeyParse(String privKeyStr) { - - byte[] privKeyBytes; - try { - privKeyBytes = new PemReader(new StringReader(privKeyStr)).readPemObject().getContent(); - } catch (IOException e) { - throw new CryptoException(e.getMessage(), e); - } - - OpenSSHPrivateKeySpec privKeySpec = new OpenSSHPrivateKeySpec(privKeyBytes); - keyFormat = privKeySpec.getFormat(); - - if (!keyFormat.equals("OpenSSH")) { - return OpenSSHPrivateKeyUtil.parsePrivateKeyBlob(privKeyBytes); - } - else - { - byte[] AUTH_MAGIC = Strings.toByteArray("openssh-key-v1\0"); - SSHKeyReader keyReader = new SSHKeyReader(AUTH_MAGIC, privKeyBytes); - - byte[] buffer = keyReader.readBytes(); - String cipherName = Strings.fromByteArray(buffer); - if (!cipherName.equals("none")) - { - throw new CryptoException("encrypted keys are not supported!"); - } - - String kdfName = Strings.fromByteArray(keyReader.readBytes()); - if (!kdfName.equals("none")) - { - throw new CryptoException("KDFs are not supported!"); - } - - int kdfLength = keyReader.read32Bits(); - if (kdfLength != 0) { - throw new CryptoException("KDF's length should be 0!"); - } - - int keysNum = keyReader.read32Bits(); - if (keysNum != 1) { - throw new CryptoException("Number of keys should be 1!"); - } - - byte[] pubKeyBytes = keyReader.readBytes(); - OpenSSHPublicKeySpec pubKeySpec = new OpenSSHPublicKeySpec(pubKeyBytes); - keyType = pubKeySpec.getType(); - - byte[] privKeyWithCmt = keyReader.readBytes(); - SSHKeyReader privKeyReader = new SSHKeyReader(privKeyWithCmt); - - int rnd1 = privKeyReader.read32Bits(); - int rnd2 = privKeyReader.read32Bits(); - if (rnd1 != rnd2) { - throw new CryptoException("Two random values for checking are not same!"); - } - - String privKeyType = Strings.fromByteArray(privKeyReader.readBytes()); - if (!privKeyType.equals(keyType)) { - throw new CryptoException("Two key types in public/private keys are not same!"); - } - - AsymmetricKeyParameter result = null; - - switch (privKeyType) { - - case "ssh-rsa": { - BigInteger n = new BigInteger(1, privKeyReader.readBytes()); - BigInteger e = new BigInteger(1, privKeyReader.readBytes()); - BigInteger d = new BigInteger(1, privKeyReader.readBytes()); - BigInteger qInv = new BigInteger(1, privKeyReader.readBytes()); - BigInteger p = new BigInteger(1, privKeyReader.readBytes()); - BigInteger q = new BigInteger(1, privKeyReader.readBytes()); - - BigInteger dP = d.remainder(p.subtract(ONE)); - BigInteger dQ = d.remainder(q.subtract(ONE)); - - result = new RSAPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv); - break; - } - - case "ssh-dss": { - BigInteger p = new BigInteger(1, privKeyReader.readBytes()); - BigInteger q = new BigInteger(1, privKeyReader.readBytes()); - BigInteger g = new BigInteger(1, privKeyReader.readBytes()); - privKeyReader.readBytes(); // y - BigInteger x = new BigInteger(1, privKeyReader.readBytes()); - - result = new DSAPrivateKeyParameters(x, new DSAParameters(p, q, g)); - break; - } - - case "ecdsa-sha2-nistp256": { - privKeyReader.readBytes(); // nistp256 - privKeyReader.readBytes(); // Q - BigInteger d = new BigInteger(1, privKeyReader.readBytes()); - X9ECParameters x9Params = SECNamedCurves.getByName("secp256r1"); - result = new ECPrivateKeyParameters(d, new ECDomainParameters( - x9Params.getCurve(), - x9Params.getG(), - x9Params.getN(), - x9Params.getH(), - x9Params.getSeed())); - break; - } - - case "ssh-ed25519": { - privKeyReader.readBytes(); // A - byte[] key = privKeyReader.readBytes(); - result = new Ed25519PrivateKeyParameters(key, 0); - break; - } - } - identity = Strings.fromByteArray(privKeyReader.readBytes()); - return result; - } - } - - public String getKeyFormat() { - return keyFormat; - } - - public String getKeyType() { - return keyType; - } - - public String getIdentity() { - return identity; - } -} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SSHKeyReader.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SSHKeyReader.java deleted file mode 100644 index 26dcd71f..00000000 --- a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/SSHKeyReader.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.CryptoException; - -/** - * @author zhanglin33 - * @title: SSHKeyReader - * @description: TODO - * @date 2019-05-20, 15:56 - */ -public class SSHKeyReader { - - private byte[] input; - private int pos = 0; - private byte[] magic; - - public SSHKeyReader(byte[] magicBytes, byte[] keyBytes) { - - magic = magicBytes; - input = keyBytes; - - for (int i = 0; i < magic.length; i++) { - if (magic[i] != keyBytes[i]) { - throw new CryptoException("Magic bytes are inconsistent!"); - } - } - pos += magic.length; - } - - public SSHKeyReader(byte[] keyBytes) { - magic = null; - input = keyBytes; - } - - public int read32Bits() { - return (input[pos++] & 0xFF) << 24 | - (input[pos++] & 0xFF) << 16 | - (input[pos++] & 0xFF) << 8 | - (input[pos++] & 0xFF); - } - - public byte[] readBytes() { - int count = read32Bits(); - byte[] result = new byte[count]; - System.arraycopy(input, pos, result, 0, result.length); - pos += count; - return result; - } - - public byte[] getMagic() { - return magic; - } -} diff --git a/source/crypto/crypto-classic/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService b/source/crypto/crypto-classic/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService deleted file mode 100644 index 75d86390..00000000 --- a/source/crypto/crypto-classic/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService +++ /dev/null @@ -1 +0,0 @@ -com.jd.blockchain.crypto.service.classic.ClassicCryptoService \ No newline at end of file diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/AESEncryptionFunctionTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/AESEncryptionFunctionTest.java deleted file mode 100644 index e250da7b..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/AESEncryptionFunctionTest.java +++ /dev/null @@ -1,292 +0,0 @@ -package test.com.jd.blockchain.crypto.service.classic; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.ENCRYPTION_ALGORITHM; -import static com.jd.blockchain.crypto.CryptoAlgorithm.SYMMETRIC_KEY; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Random; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.SymmetricKey; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * @author zhanglin33 - * @title: AESEncryptionFunctionTest - * @description: JunitTest for AESAESEncryptionFunction in SPI mode - * @date 2019-04-01, 13:57 - */ -public class AESEncryptionFunctionTest { - - @Test - public void getAlgorithmTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - assertEquals(symmetricEncryptionFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(symmetricEncryptionFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("AES"); - assertNotNull(algorithm); - - assertEquals(symmetricEncryptionFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(symmetricEncryptionFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("aess"); - assertNull(algorithm); - } - - @Test - public void generateSymmetricKeyTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - assertEquals(SYMMETRIC.CODE, symmetricKey.getKeyType().CODE); - assertEquals(128 / 8, symmetricKey.getRawKeyBytes().length); - - assertEquals(algorithm.code(), symmetricKey.getAlgorithm()); - - assertEquals(2 + 1 + 128 / 8, symmetricKey.toBytes().length); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] keyTypeBytes = new byte[] { SYMMETRIC.CODE }; - byte[] rawKeyBytes = symmetricKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, keyTypeBytes, rawKeyBytes), symmetricKey.toBytes()); - } - - @Test - public void encryptTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - assertEquals(2 + 16 + 1024, ciphertextBytes.length); - assertEquals(ClassicAlgorithm.AES.code(), ciphertext.getAlgorithm()); - assertEquals((short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | ((byte) 26 & 0x00FF)), ciphertext.getAlgorithm()); - - byte[] algoBytes = BytesUtils.toBytes(ciphertext.getAlgorithm()); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawCiphertextBytes), ciphertextBytes); - } - - @Test - public void decryptTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] decryptedPlaintext = symmetricEncryptionFunction.decrypt(symmetricKey, ciphertext); - - assertArrayEquals(data, decryptedPlaintext); - } - - // @Test - // public void streamEncryptTest(){ - // - // byte[] data = new byte[1024]; - // Random random = new Random(); - // random.nextBytes(data); - // - // - // InputStream inputStream = new ByteArrayInputStream(data); - // OutputStream outputStream = new ByteArrayOutputStream(); - // - // CryptoAlgorithm algorithm = CryptoServiceProviders.getAlgorithm("aes"); - // assertNotNull(algorithm); - // - // SymmetricEncryptionFunction symmetricEncryptionFunction = - // CryptoServiceProviders.getSymmetricEncryptionFunction(algorithm); - // - // SymmetricKey symmetricKey = (SymmetricKey) - // symmetricEncryptionFunction.generateSymmetricKey(); - // - // symmetricEncryptionFunction.encrypt(symmetricKey,inputStream,outputStream); - // - // assertNotNull(outputStream); - // - // - // } - - @Test - public void supportSymmetricKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - byte[] symmetricKeyBytes = symmetricKey.toBytes(); - - assertTrue(symmetricEncryptionFunction.supportSymmetricKey(symmetricKeyBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = symmetricKey.getRawKeyBytes(); - byte[] ripemd160KeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - assertFalse(symmetricEncryptionFunction.supportSymmetricKey(ripemd160KeyBytes)); - } - - @Test - public void resolveSymmetricKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - byte[] symmetricKeyBytes = symmetricKey.toBytes(); - - SymmetricKey resolvedKey = symmetricEncryptionFunction.resolveSymmetricKey(symmetricKeyBytes); - - assertEquals(SYMMETRIC.CODE, resolvedKey.getKeyType().CODE); - assertEquals(128 / 8, resolvedKey.getRawKeyBytes().length); - assertEquals(ClassicAlgorithm.AES.code(), resolvedKey.getAlgorithm()); - assertEquals((short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | ((byte) 26 & 0x00FF)), resolvedKey.getAlgorithm()); - assertArrayEquals(symmetricKeyBytes, resolvedKey.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = symmetricKey.getRawKeyBytes(); - byte[] ripemd160KeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - symmetricEncryptionFunction.resolveSymmetricKey(ripemd160KeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportCiphertextTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - assertTrue(symmetricEncryptionFunction.supportCiphertext(ciphertextBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawCiphertextBytes = ciphertext.toBytes(); - byte[] ripemd160CiphertextBytes = BytesUtils.concat(algoBytes, rawCiphertextBytes); - - assertFalse(symmetricEncryptionFunction.supportCiphertext(ripemd160CiphertextBytes)); - } - - @Test - public void resolveCiphertextTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - - Ciphertext resolvedCiphertext = symmetricEncryptionFunction.resolveCiphertext(ciphertextBytes); - - assertEquals(1024 + 16, resolvedCiphertext.getRawCiphertext().length); - assertEquals(ClassicAlgorithm.AES.code(), resolvedCiphertext.getAlgorithm()); - assertEquals((short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | ((byte) 26 & 0x00FF)), - resolvedCiphertext.getAlgorithm()); - assertArrayEquals(ciphertextBytes, resolvedCiphertext.toBytes()); - - assertArrayEquals(ciphertext.toBytes(), resolvedCiphertext.toBytes()); - assertArrayEquals(ciphertext.getRawCiphertext(), resolvedCiphertext.getRawCiphertext()); - assertEquals(ciphertext.getAlgorithm(), resolvedCiphertext.getAlgorithm()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - byte[] ripemd160CiphertextBytes = BytesUtils.concat(algoBytes, rawCiphertextBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - symmetricEncryptionFunction.resolveCiphertext(ripemd160CiphertextBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunctionTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunctionTest.java deleted file mode 100644 index 7e1120c1..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunctionTest.java +++ /dev/null @@ -1,352 +0,0 @@ -package test.com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.ASYMMETRIC_KEY; -import static com.jd.blockchain.crypto.CryptoAlgorithm.SIGNATURE_ALGORITHM; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: ECDSASignatureFunctionTest - * @description: JunitTest for ECDSASignatureFunction in SPI mode - * @date 2019-04-23, 09:37 - */ -public class ECDSASignatureFunctionTest { - - @Test - public void getAlgorithmTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("eCDsA"); - assertNotNull(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("eedsa"); - assertNull(algorithm); - } - - @Test - public void generateKeyPairTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - assertEquals(PUBLIC.CODE, pubKey.getKeyType().CODE); - assertEquals(65, pubKey.getRawKeyBytes().length); - assertEquals(PRIVATE.CODE, privKey.getKeyType().CODE); - assertEquals(32, privKey.getRawKeyBytes().length); - - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(algorithm.code(), privKey.getAlgorithm()); - - assertEquals(2 + 1 + 65, pubKey.toBytes().length); - assertEquals(2 + 1 + 32, privKey.toBytes().length); - - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawPubKeyBytes), pubKey.toBytes()); - assertArrayEquals(BytesUtils.concat(algoBytes, privKeyTypeBytes, rawPrivKeyBytes), privKey.toBytes()); - } - - @Test - public void retrievePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - PubKey retrievedPubKey = signatureFunction.retrievePubKey(privKey); - - assertEquals(pubKey.getKeyType(), retrievedPubKey.getKeyType()); - assertEquals(pubKey.getRawKeyBytes().length, retrievedPubKey.getRawKeyBytes().length); - assertEquals(pubKey.getAlgorithm(), retrievedPubKey.getAlgorithm()); - assertArrayEquals(pubKey.toBytes(), retrievedPubKey.toBytes()); - } - - @Test - public void signTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureBytes = signatureDigest.toBytes(); - - assertEquals(2 + 64, signatureBytes.length); - assertEquals(ClassicAlgorithm.ECDSA.code(), signatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 22 & 0x00FF)), - signatureDigest.getAlgorithm()); - - byte[] algoBytes = BytesUtils.toBytes(signatureDigest.getAlgorithm()); - byte[] rawSinatureBytes = signatureDigest.getRawDigest(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawSinatureBytes), signatureBytes); - } - - @Test - public void verifyTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - assertTrue(signatureFunction.verify(signatureDigest, pubKey, data)); - } - - @Test - public void supportPrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - assertTrue(signatureFunction.supportPrivKey(privKeyBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = privKey.getRawKeyBytes(); - byte[] ripemd160PubKeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - assertFalse(signatureFunction.supportPrivKey(ripemd160PubKeyBytes)); - } - - @Test - public void resolvePrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - PrivKey resolvedPrivKey = signatureFunction.resolvePrivKey(privKeyBytes); - - assertEquals(PRIVATE.CODE, resolvedPrivKey.getKeyType().CODE); - assertEquals(32, resolvedPrivKey.getRawKeyBytes().length); - assertEquals(ClassicAlgorithm.ECDSA.code(), resolvedPrivKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 22 & 0x00FF)), - resolvedPrivKey.getAlgorithm()); - assertArrayEquals(privKeyBytes, resolvedPrivKey.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = privKey.getRawKeyBytes(); - byte[] ripemd160PubKeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolvePrivKey(ripemd160PubKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportPubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - assertTrue(signatureFunction.supportPubKey(pubKeyBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawKeyBytes = pubKey.getRawKeyBytes(); - byte[] ripemd160PrivKeyBytes = BytesUtils.concat(algoBytes, privKeyTypeBytes, rawKeyBytes); - - assertFalse(signatureFunction.supportPubKey(ripemd160PrivKeyBytes)); - } - - @Test - public void resolvePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - PubKey resolvedPubKey = signatureFunction.resolvePubKey(pubKeyBytes); - - assertEquals(PUBLIC.CODE, resolvedPubKey.getKeyType().CODE); - assertEquals(65, resolvedPubKey.getRawKeyBytes().length); - assertEquals(ClassicAlgorithm.ECDSA.code(), resolvedPubKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 22 & 0x00FF)), - resolvedPubKey.getAlgorithm()); - assertArrayEquals(pubKeyBytes, resolvedPubKey.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawKeyBytes = pubKey.getRawKeyBytes(); - byte[] ripemd160PrivKeyBytes = BytesUtils.concat(algoBytes, privKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolvePrivKey(ripemd160PrivKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertTrue(signatureFunction.supportDigest(signatureDigestBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = signatureDigest.toBytes(); - byte[] ripemd160SignatureBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - assertFalse(signatureFunction.supportDigest(ripemd160SignatureBytes)); - } - - @Test - public void resolveDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ECDSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - - SignatureDigest resolvedSignatureDigest = signatureFunction.resolveDigest(signatureDigestBytes); - - assertEquals(64, resolvedSignatureDigest.getRawDigest().length); - assertEquals(ClassicAlgorithm.ECDSA.code(), resolvedSignatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 22 & 0x00FF)), - resolvedSignatureDigest.getAlgorithm()); - assertArrayEquals(signatureDigestBytes, resolvedSignatureDigest.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = signatureDigest.getRawDigest(); - byte[] ripemd160SignatureDigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolveDigest(ripemd160SignatureDigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunctionTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunctionTest.java deleted file mode 100644 index 57a66ea6..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunctionTest.java +++ /dev/null @@ -1,365 +0,0 @@ -package test.com.jd.blockchain.crypto.service.classic; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.ASYMMETRIC_KEY; -import static com.jd.blockchain.crypto.CryptoAlgorithm.SIGNATURE_ALGORITHM; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Random; - -import org.junit.Test; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * @author zhanglin33 - * @title: ED25519SignatureFunctionTest - * @description: JunitTest for ED25519SignatureFunction in SPI mode - * @date 2019-04-01, 14:01 - */ -public class ED25519SignatureFunctionTest { - - @Test - public void getAlgorithmTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("Ed25519"); - assertNotNull(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("eddsa"); - assertNull(algorithm); - } - - @Test - public void generateKeyPairTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - assertEquals(PUBLIC.CODE, pubKey.getKeyType().CODE); - assertEquals(32, pubKey.getRawKeyBytes().length); - assertEquals(PRIVATE.CODE, privKey.getKeyType().CODE); - assertEquals(32, privKey.getRawKeyBytes().length); - - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(algorithm.code(), privKey.getAlgorithm()); - - assertEquals(2 + 1 + 32, pubKey.toBytes().length); - assertEquals(2 + 1 + 32, privKey.toBytes().length); - - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawPubKeyBytes), pubKey.toBytes()); - assertArrayEquals(BytesUtils.concat(algoBytes, privKeyTypeBytes, rawPrivKeyBytes), privKey.toBytes()); - } - - @Test - public void retrievePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - PubKey retrievedPubKey = signatureFunction.retrievePubKey(privKey); - - assertEquals(pubKey.getKeyType(), retrievedPubKey.getKeyType()); - assertEquals(pubKey.getRawKeyBytes().length, retrievedPubKey.getRawKeyBytes().length); - assertEquals(pubKey.getAlgorithm(), retrievedPubKey.getAlgorithm()); - assertArrayEquals(pubKey.toBytes(), retrievedPubKey.toBytes()); - } - - @Test - public void signTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureBytes = signatureDigest.toBytes(); - - assertEquals(2 + 64, signatureBytes.length); - assertEquals(ClassicAlgorithm.ED25519.code(), signatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 21 & 0x00FF)), - signatureDigest.getAlgorithm()); - - byte[] algoBytes = BytesUtils.toBytes(signatureDigest.getAlgorithm()); - byte[] rawSinatureBytes = signatureDigest.getRawDigest(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawSinatureBytes), signatureBytes); - } - - @Test - public void verifyTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - assertTrue(signatureFunction.verify(signatureDigest, pubKey, data)); - } - - @Test - public void supportPrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - assertTrue(signatureFunction.supportPrivKey(privKeyBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = privKey.getRawKeyBytes(); - byte[] ripemd160PubKeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - assertFalse(signatureFunction.supportPrivKey(ripemd160PubKeyBytes)); - } - - @Test - public void resolvePrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - PrivKey resolvedPrivKey = signatureFunction.resolvePrivKey(privKeyBytes); - - assertEquals(PRIVATE.CODE, resolvedPrivKey.getKeyType().CODE); - assertEquals(32, resolvedPrivKey.getRawKeyBytes().length); - assertEquals(ClassicAlgorithm.ED25519.code(), resolvedPrivKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 21 & 0x00FF)), - resolvedPrivKey.getAlgorithm()); - assertArrayEquals(privKeyBytes, resolvedPrivKey.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = privKey.getRawKeyBytes(); - byte[] ripemd160PubKeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolvePrivKey(ripemd160PubKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportPubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - assertTrue(signatureFunction.supportPubKey(pubKeyBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawKeyBytes = pubKey.getRawKeyBytes(); - byte[] ripemd160PrivKeyBytes = BytesUtils.concat(algoBytes, privKeyTypeBytes, rawKeyBytes); - - assertFalse(signatureFunction.supportPubKey(ripemd160PrivKeyBytes)); - } - - @Test - public void resolvePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - PubKey resolvedPubKey = signatureFunction.resolvePubKey(pubKeyBytes); - - assertEquals(PUBLIC.CODE, resolvedPubKey.getKeyType().CODE); - assertEquals(32, resolvedPubKey.getRawKeyBytes().length); - assertEquals(ClassicAlgorithm.ED25519.code(), resolvedPubKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 21 & 0x00FF)), - resolvedPubKey.getAlgorithm()); - assertArrayEquals(pubKeyBytes, resolvedPubKey.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawKeyBytes = pubKey.getRawKeyBytes(); - byte[] ripemd160PrivKeyBytes = BytesUtils.concat(algoBytes, privKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolvePrivKey(ripemd160PrivKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertTrue(signatureFunction.supportDigest(signatureDigestBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = signatureDigest.toBytes(); - byte[] ripemd160SignatureBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - assertFalse(signatureFunction.supportDigest(ripemd160SignatureBytes)); - } - - @Test - public void resolveDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("ed25519"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - - SignatureDigest resolvedSignatureDigest = signatureFunction.resolveDigest(signatureDigestBytes); - - assertEquals(64, resolvedSignatureDigest.getRawDigest().length); - assertEquals(ClassicAlgorithm.ED25519.code(), resolvedSignatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 21 & 0x00FF)), - resolvedSignatureDigest.getAlgorithm()); - assertArrayEquals(signatureDigestBytes, resolvedSignatureDigest.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = signatureDigest.getRawDigest(); - byte[] ripemd160SignatureDigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolveDigest(ripemd160SignatureDigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/EncodeTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/EncodeTest.java deleted file mode 100644 index a0eebbc4..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/EncodeTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package test.com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.HexUtils; -import org.junit.Assert; -import org.junit.Test; - -public class EncodeTest { - - @Test - public void test() { - String pubKey = "7VeRLdGtSz1Y91gjLTqEdnkotzUfaAqdap3xw6fQ1yKHkvVq"; - Bytes bytes = Bytes.fromBase58(pubKey); - String hexString = HexUtils.encode(bytes.toBytes()); - String code = hexString.substring(2, 4); - Assert.assertEquals(code, "15"); // 15为十六进制,对应十进制为21(ED25519) - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunctionTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunctionTest.java deleted file mode 100644 index 402f4ce6..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunctionTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package test.com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.HASH_ALGORITHM; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; - -/** - * @author zhanglin33 - * @title: RIPEMD160HashFunctionTest - * @description: JunitTest for RIPEMD160HashFunction in SPI mode - * @date 2019-04-01, 14:03 - */ -public class RIPEMD160HashFunctionTest { - - @Test - public void getAlgorithmTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("RIPEMD160"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - assertEquals(hashFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(hashFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("RIPEmd160"); - assertNotNull(algorithm); - - assertEquals(hashFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(hashFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("RIPEMD-160"); - assertNull(algorithm); - } - - @Test - public void hashTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("RIPEMD160"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - byte[] rawDigestBytes = digest.getRawDigest(); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - - byte[] digestBytes = digest.toBytes(); - assertEquals(160 / 8 + 2, digestBytes.length); - assertArrayEquals(digestBytes, BytesUtils.concat(algoBytes, rawDigestBytes)); - - assertEquals(algorithm.code(), digest.getAlgorithm()); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - data = null; - hashFunction.hash(data); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void verifyTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("RIPEMD160"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - assertTrue(hashFunction.verify(digest, data)); - } - - @Test - public void supportHashDigestTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("RIPEMD160"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - byte[] digestBytes = digest.toBytes(); - assertTrue(hashFunction.supportHashDigest(digestBytes)); - - algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - System.arraycopy(algoBytes, 0, digestBytes, 0, algoBytes.length); - assertFalse(hashFunction.supportHashDigest(digestBytes)); - } - - @Test - public void resolveHashDigestTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("RIPEMD160"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - byte[] digestBytes = digest.toBytes(); - - HashDigest resolvedDigest = hashFunction.resolveHashDigest(digestBytes); - - assertEquals(160 / 8, resolvedDigest.getRawDigest().length); - assertEquals(ClassicAlgorithm.RIPEMD160.code(), resolvedDigest.getAlgorithm()); - assertEquals((short) (HASH_ALGORITHM | ((byte) 25 & 0x00FF)), resolvedDigest.getAlgorithm()); - assertArrayEquals(digestBytes, resolvedDigest.toBytes()); - - algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = digest.getRawDigest(); - byte[] aesDigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - hashFunction.resolveHashDigest(aesDigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - - algorithm = Crypto.getAlgorithm("sha256"); - assertNotNull(algorithm); - algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - rawDigestBytes = digest.getRawDigest(); - byte[] ripemd160DigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - expectedException = CryptoException.class; - actualEx = null; - try { - hashFunction.resolveHashDigest(ripemd160DigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/RSACryptoFunctionTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/RSACryptoFunctionTest.java deleted file mode 100644 index 60f4d113..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/RSACryptoFunctionTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package test.com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.*; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: RSACryptoFunctionTest - * @description: JunitTest for RSACryptoFunction in SPI mode - * @date 2019-04-23, 15:30 - */ -public class RSACryptoFunctionTest { - - @Test - public void getAlgorithmTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("RSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("Rsa"); - assertNotNull(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("rsa2"); - assertNull(algorithm); - } - - @Test - public void test() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("RSA"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - assertEquals(PUBLIC.CODE, pubKey.getKeyType().CODE); - assertEquals(259, pubKey.getRawKeyBytes().length); - assertEquals(PRIVATE.CODE, privKey.getKeyType().CODE); - assertEquals(1155, privKey.getRawKeyBytes().length); - - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(algorithm.code(), privKey.getAlgorithm()); - - assertEquals(2 + 1 + 259, pubKey.toBytes().length); - assertEquals(2 + 1 + 1155, privKey.toBytes().length); - - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawPubKeyBytes), pubKey.toBytes()); - assertArrayEquals(BytesUtils.concat(algoBytes, privKeyTypeBytes, rawPrivKeyBytes), privKey.toBytes()); - - - PubKey retrievedPubKey = signatureFunction.retrievePubKey(privKey); - - assertEquals(pubKey.getKeyType(), retrievedPubKey.getKeyType()); - assertEquals(pubKey.getRawKeyBytes().length, retrievedPubKey.getRawKeyBytes().length); - assertEquals(pubKey.getAlgorithm(), retrievedPubKey.getAlgorithm()); - assertArrayEquals(pubKey.toBytes(), retrievedPubKey.toBytes()); - - - byte[] data = new byte[128]; - Random random = new Random(); - random.nextBytes(data); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureBytes = signatureDigest.toBytes(); - - assertEquals(2 + 256, signatureBytes.length); - assertEquals(algorithm.code(), signatureDigest.getAlgorithm()); - - assertEquals(ClassicAlgorithm.RSA.code(), signatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 23 & 0x00FF)), - signatureDigest.getAlgorithm()); - - byte[] rawSinatureBytes = signatureDigest.getRawDigest(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawSinatureBytes), signatureBytes); - - - assertTrue(signatureFunction.verify(signatureDigest, pubKey, data)); - - - AsymmetricEncryptionFunction asymmetricEncryptionFunction = Crypto - .getAsymmetricEncryptionFunction(algorithm); - - Ciphertext ciphertext = asymmetricEncryptionFunction.encrypt(pubKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - assertEquals(2 + 256, ciphertextBytes.length); - assertEquals(ClassicAlgorithm.RSA.code(), ciphertext.getAlgorithm()); - - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 23 & 0x00FF)), - ciphertext.getAlgorithm()); - - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawCiphertextBytes), ciphertextBytes); - - - byte[] decryptedPlaintext = asymmetricEncryptionFunction.decrypt(privKey, ciphertext); - assertArrayEquals(data, decryptedPlaintext); - - - byte[] privKeyBytes = privKey.toBytes(); - assertTrue(signatureFunction.supportPrivKey(privKeyBytes)); - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] rawKeyBytes = privKey.getRawKeyBytes(); - byte[] ripemd160PubKeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - assertFalse(signatureFunction.supportPrivKey(ripemd160PubKeyBytes)); - - - PrivKey resolvedPrivKey = signatureFunction.resolvePrivKey(privKeyBytes); - assertEquals(PRIVATE.CODE, resolvedPrivKey.getKeyType().CODE); - assertEquals(1155, resolvedPrivKey.getRawKeyBytes().length); - assertEquals(ClassicAlgorithm.RSA.code(), resolvedPrivKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 23 & 0x00FF)), - resolvedPrivKey.getAlgorithm()); - assertArrayEquals(privKeyBytes, resolvedPrivKey.toBytes()); - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolvePrivKey(ripemd160PubKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - - - - byte[] pubKeyBytes = pubKey.toBytes(); - assertTrue(signatureFunction.supportPubKey(pubKeyBytes)); - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] ripemd160PrivKeyBytes = BytesUtils.concat(algoBytes, privKeyTypeBytes, rawKeyBytes); - assertFalse(signatureFunction.supportPubKey(ripemd160PrivKeyBytes)); - - - PubKey resolvedPubKey = signatureFunction.resolvePubKey(pubKeyBytes); - assertEquals(PUBLIC.CODE, resolvedPubKey.getKeyType().CODE); - assertEquals(259, resolvedPubKey.getRawKeyBytes().length); - assertEquals(ClassicAlgorithm.RSA.code(), resolvedPubKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 23 & 0x00FF)), - resolvedPubKey.getAlgorithm()); - assertArrayEquals(pubKeyBytes, resolvedPubKey.toBytes()); - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - try { - signatureFunction.resolvePrivKey(ripemd160PrivKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertTrue(signatureFunction.supportDigest(signatureDigestBytes)); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] rawDigestBytes = signatureDigest.toBytes(); - byte[] ripemd160SignatureBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - assertFalse(signatureFunction.supportDigest(ripemd160SignatureBytes)); - - - SignatureDigest resolvedSignatureDigest = signatureFunction.resolveDigest(signatureDigestBytes); - - assertEquals(256, resolvedSignatureDigest.getRawDigest().length); - assertEquals(ClassicAlgorithm.RSA.code(), resolvedSignatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 23 & 0x00FF)), - resolvedSignatureDigest.getAlgorithm()); - assertArrayEquals(signatureDigestBytes, resolvedSignatureDigest.toBytes()); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - byte[] ripemd160SignatureDigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - try { - signatureFunction.resolveDigest(ripemd160SignatureDigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - - - assertTrue(asymmetricEncryptionFunction.supportCiphertext(ciphertextBytes)); - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] ripemd160CiphertextBytes = BytesUtils.concat(algoBytes, rawCiphertextBytes); - assertFalse(asymmetricEncryptionFunction.supportCiphertext(ripemd160CiphertextBytes)); - - - Ciphertext resolvedCiphertext = asymmetricEncryptionFunction.resolveCiphertext(ciphertextBytes); - assertEquals(256, resolvedCiphertext.getRawCiphertext().length); - assertEquals(ClassicAlgorithm.RSA.code(), resolvedCiphertext.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 23 & 0x00FF)), - resolvedCiphertext.getAlgorithm()); - assertArrayEquals(ciphertextBytes, resolvedCiphertext.toBytes()); - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - try { - asymmetricEncryptionFunction.resolveCiphertext(ripemd160CiphertextBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/SHA256HashFunctionTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/SHA256HashFunctionTest.java deleted file mode 100644 index 0400c9f0..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/service/classic/SHA256HashFunctionTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package test.com.jd.blockchain.crypto.service.classic; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.HASH_ALGORITHM; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: SHA256HashFunctionTest - * @description: JunitTest for SHA256HashFunction in SPI mode - * @date 2019-04-01, 14:21 - */ - -public class SHA256HashFunctionTest { - - @Test - public void getAlgorithmTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sha256"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - assertEquals(hashFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(hashFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("SHa256"); - assertNotNull(algorithm); - - assertEquals(hashFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(hashFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("sha-256"); - assertNull(algorithm); - } - - @Test - public void hashTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sha256"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - byte[] rawDigestBytes = digest.getRawDigest(); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - - byte[] digestBytes = digest.toBytes(); - assertEquals(256 / 8 + 2, digestBytes.length); - assertArrayEquals(digestBytes, BytesUtils.concat(algoBytes, rawDigestBytes)); - - assertEquals(algorithm.code(), digest.getAlgorithm()); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - data = null; - hashFunction.hash(data); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void verifyTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sha256"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - assertTrue(hashFunction.verify(digest, data)); - } - - @Test - public void supportHashDigestTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sha256"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - byte[] digestBytes = digest.toBytes(); - assertTrue(hashFunction.supportHashDigest(digestBytes)); - - algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - System.arraycopy(algoBytes, 0, digestBytes, 0, algoBytes.length); - assertFalse(hashFunction.supportHashDigest(digestBytes)); - } - - @Test - public void resolveHashDigestTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sha256"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - byte[] digestBytes = digest.toBytes(); - - HashDigest resolvedDigest = hashFunction.resolveHashDigest(digestBytes); - - assertEquals(256 / 8, resolvedDigest.getRawDigest().length); - assertEquals(ClassicAlgorithm.SHA256.code(), resolvedDigest.getAlgorithm()); - assertEquals((short) (HASH_ALGORITHM | ((byte) 24 & 0x00FF)), resolvedDigest.getAlgorithm()); - assertArrayEquals(digestBytes, resolvedDigest.toBytes()); - - algorithm = Crypto.getAlgorithm("aes"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = digest.getRawDigest(); - byte[] aesDigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - hashFunction.resolveHashDigest(aesDigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - - algorithm = Crypto.getAlgorithm("ripemd160"); - assertNotNull(algorithm); - algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - rawDigestBytes = digest.getRawDigest(); - byte[] ripemd160DigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - expectedException = CryptoException.class; - actualEx = null; - try { - hashFunction.resolveHashDigest(ripemd160DigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/AESUtilsTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/AESUtilsTest.java deleted file mode 100644 index 78f36df5..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/AESUtilsTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package test.com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.utils.classic.AESUtils; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import java.util.Random; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -/** - * @author zhanglin33 - * @title: AESUtilsTest - * @description: Tests for methods in AESUtils - * @date 2019-04-22, 16:06 - */ -public class AESUtilsTest { - - @Test - public void generateKeyTest(){ - byte[] key = AESUtils.generateKey(); - assertEquals(16,key.length); - key = AESUtils.generateKey(BytesUtils.toBytes("abc")); - assertArrayEquals( - Hex.decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".substring(0,32)),key); - } - - - @Test - public void encryptTest(){ - String plaintext = "abc"; - String key = "1234567890123456"; - String iv = "1234567890123456"; - String expectedCiphertextIn2ndBlock = "f479efae2d41d23227f61e675fced95c"; - - byte[] ciphertext = AESUtils.encrypt(BytesUtils.toBytes(plaintext), - BytesUtils.toBytes(key), BytesUtils.toBytes(iv)); - byte[] expectedCiphertext = BytesUtils.concat(BytesUtils.toBytes(iv),Hex.decode(expectedCiphertextIn2ndBlock)); - assertArrayEquals(expectedCiphertext,ciphertext); - } - - - @Test - public void decryptTest(){ - - Random random = new Random(); - byte[] data = new byte[1024]; - random.nextBytes(data); - - byte[] key = AESUtils.generateKey(); - - byte[] ciphertext = AESUtils.encrypt(data,key); - byte[] plaintext = AESUtils.decrypt(ciphertext,key); - - assertArrayEquals(data,plaintext); - } - - - public void encryptingPerformance() { - - byte[] data = new byte[1000]; - Random random = new Random(); - random.nextBytes(data); - - byte[] aesCiphertext = null; - - int count = 100000; - - - byte[] aesKey = AESUtils.generateKey(); - - System.out.println("=================== do AES encrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - aesCiphertext = AESUtils.encrypt(data, aesKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("AES Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do AES decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - AESUtils.decrypt(aesCiphertext, aesKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("AES Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/ECDSAUtilsTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/ECDSAUtilsTest.java deleted file mode 100644 index 71ccbee9..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/ECDSAUtilsTest.java +++ /dev/null @@ -1,203 +0,0 @@ -package test.com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.utils.classic.ECDSAUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.math.ec.ECMultiplier; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.math.ec.FixedPointCombMultiplier; -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.util.test.FixedSecureRandom; -import org.junit.Test; - -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.Random; - -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: ECDSAUtilsTest - * @description: Tests for methods in ECDSAUtils - * @date 2019-04-09, 14:58 - */ -public class ECDSAUtilsTest { - - @Test - public void generateKeyPairTest(){ - - AsymmetricCipherKeyPair keyPair = ECDSAUtils.generateKeyPair(); - ECPrivateKeyParameters privKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate(); - ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytes = BigIntegerTo32Bytes(privKeyParams.getD()); - byte[] pubKeyBytes = pubKeyParams.getQ().getEncoded(false); - - assertEquals(32,privKeyBytes.length); - assertEquals(65,pubKeyBytes.length); - } - - @Test - public void retrievePublicKeyTest(){ - - AsymmetricCipherKeyPair keyPair = ECDSAUtils.generateKeyPair(); - ECPrivateKeyParameters privKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate(); - ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytes = BigIntegerTo32Bytes(privKeyParams.getD()); - byte[] pubKeyBytes = pubKeyParams.getQ().getEncoded(false); - - byte[] retrievedPubKeyBytes = ECDSAUtils.retrievePublicKey(privKeyBytes); - - assertArrayEquals(pubKeyBytes,retrievedPubKeyBytes); - } - - @Test - public void signTest(){ - - AsymmetricCipherKeyPair keyPair = ECDSAUtils.generateKeyPair(); - ECPrivateKeyParameters privKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate(); - - byte[] privKeyBytes = BigIntegerTo32Bytes(privKeyParams.getD()); - - Random random = new Random(); - byte[] data = new byte[1024]; - random.nextBytes(data); - - byte[] signatureDigestFromBytes = ECDSAUtils.sign(data,privKeyBytes); - byte[] signatureDigestFromParams = ECDSAUtils.sign(data,privKeyBytes); - - assertEquals(64,signatureDigestFromParams.length); - assertEquals(64,signatureDigestFromBytes.length); - } - - @Test - public void verifyTest(){ - - AsymmetricCipherKeyPair keyPair = ECDSAUtils.generateKeyPair(); - ECPrivateKeyParameters privKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate(); - ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic(); - - byte[] pubKeyBytes = pubKeyParams.getQ().getEncoded(false); - - Random random = new Random(); - byte[] data = new byte[1024]; - random.nextBytes(data); - - byte[] signatureDigest = ECDSAUtils.sign(data,privKeyParams); - - assertTrue(ECDSAUtils.verify(data,pubKeyParams,signatureDigest)); - assertTrue(ECDSAUtils.verify(data,pubKeyBytes,signatureDigest)); - } - - @Test - public void checkParams(){ - // https://crypto.stackexchange.com/questions/784/are-there-any-secp256k1-ecdsa-test-examples-available - ECDomainParameters params = ECDSAUtils.getDomainParams(); - ECPoint ECDSA_G = params.getG(); - - BigInteger scalar = new BigInteger("AA5E28D6A97A2479A65527F7290311A3624D4CC0FA1578598EE3C2613BF99522",16); - - String xCoord = "34F9460F0E4F08393D192B3C5133A6BA099AA0AD9FD54EBCCFACDFA239FF49C6"; - String yCoord = "0B71EA9BD730FD8923F6D25A7A91E7DD7728A960686CB5A901BB419E0F2CA232"; - - - ECMultiplier createBasePointMultiplier = new FixedPointCombMultiplier(); - ECPoint point = createBasePointMultiplier.multiply(ECDSA_G,scalar).normalize(); - byte[] result = point.getEncoded(false); - - assertEquals("04" + xCoord + yCoord,Hex.toHexString(result).toUpperCase()); - } - - @Test - public void checkDeterministicValues(){ - // https://crypto.stackexchange.com/questions/41316/complete-set-of-test-vectors-for-ecdsa-secp256k1 - ECDomainParameters domainParams = ECDSAUtils.getDomainParams(); - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( - new BigInteger("ebb2c082fd7727890a28ac82f6bdf97bad8de9f5d7c9028692de1a255cad3e0f", 16), - domainParams); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters( - domainParams.getCurve().decodePoint(Hex.decode("04" + - "779dd197a5df977ed2cf6cb31d82d43328b790dc6b3b7d4437a427bd5847dfcd" + - "e94b724a555b6d017bb7607c3e3281daf5b1699d6ef4124975c9237b917d426f")), - domainParams); - - byte[] privKeyBytes = BigIntegerTo32Bytes(privKey.getD()); - byte[] pubKeyBytes = ECDSAUtils.retrievePublicKey(privKeyBytes); - - assertArrayEquals(pubKeyBytes,pubKey.getQ().getEncoded(false)); - - SecureRandom k = new FixedSecureRandom(Hex.decode("49a0d7b786ec9cde0d0721d72804befd06571c974b191efb42ecf322ba9ddd9a")); - CipherParameters params = new ParametersWithRandom(privKey,k); - - byte[] hashedMsg = Hex.decode("4b688df40bcedbe641ddb16ff0a1842d9c67ea1c3bf63f3e0471baa664531d1a"); - - byte[] signature = ECDSAUtils.sign(params,hashedMsg); - - String r = "241097efbf8b63bf145c8961dbdf10c310efbb3b2676bbc0f8b08505c9e2f795"; - String s = "021006b7838609339e8b415a7f9acb1b661828131aef1ecbc7955dfb01f3ca0e"; - assertEquals(Hex.toHexString(signature),r + s); - - assertTrue(ECDSAUtils.verify(pubKey,signature,hashedMsg)); - } - -// @Test - public void performanceTest(){ - - int count = 10000; - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - AsymmetricCipherKeyPair keyPair = ECDSAUtils.generateKeyPair(); - ECPrivateKeyParameters privKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate(); - ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic(); - - byte[] signatureDigest = ECDSAUtils.sign(data,privKeyParams); - - assertTrue(ECDSAUtils.verify(data,pubKeyParams,signatureDigest)); - - System.out.println("=================== do ECDSA sign test ==================="); - - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ECDSAUtils.sign(data,privKeyParams); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ECDSA Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do ECDSA verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ECDSAUtils.verify(data,pubKeyParams,signatureDigest); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ECDSA Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } - - // To convert BigInteger to byte[] whose length is 32 - private static byte[] BigIntegerTo32Bytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[32]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/ED25519UtilsTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/ED25519UtilsTest.java deleted file mode 100644 index 75b824d2..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/ED25519UtilsTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package test.com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.utils.classic.ED25519Utils; -import com.jd.blockchain.utils.security.Ed25519Utils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; -import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; -import org.junit.Test; - -import java.util.Random; - -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: ED25519UtilsTest - * @description: Tests for methods in ED25519Utils - * @date 2019-04-08, 16:32 - */ -public class ED25519UtilsTest { - - @Test - public void generateKeyPairTest(){ - - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair(); - Ed25519PrivateKeyParameters privKeyParams = (Ed25519PrivateKeyParameters) keyPair.getPrivate(); - Ed25519PublicKeyParameters pubKeyParams = (Ed25519PublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytes = privKeyParams.getEncoded(); - byte[] pubKeyBytes = pubKeyParams.getEncoded(); - - assertEquals(32,privKeyBytes.length); - assertEquals(32,pubKeyBytes.length); - } - - @Test - public void retrievePublicKeyTest(){ - - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair(); - Ed25519PrivateKeyParameters privKeyParams = (Ed25519PrivateKeyParameters) keyPair.getPrivate(); - Ed25519PublicKeyParameters pubKeyParams = (Ed25519PublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytes = privKeyParams.getEncoded(); - byte[] pubKeyBytes = pubKeyParams.getEncoded(); - - byte[] retrievedPubKeyBytes = ED25519Utils.retrievePublicKey(privKeyBytes); - - assertArrayEquals(pubKeyBytes,retrievedPubKeyBytes); - } - - @Test - public void signTest(){ - - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair(); - Ed25519PrivateKeyParameters privKeyParams = (Ed25519PrivateKeyParameters) keyPair.getPrivate(); - - byte[] privKeyBytes = privKeyParams.getEncoded(); - - Random random = new Random(); - byte[] data = new byte[1024]; - random.nextBytes(data); - - byte[] signatureDigestFromBytes = ED25519Utils.sign(data,privKeyBytes); - byte[] signatureDigestFromParams = ED25519Utils.sign(data,privKeyBytes); - - assertArrayEquals(signatureDigestFromBytes,signatureDigestFromParams); - assertEquals(64,signatureDigestFromBytes.length); - } - - @Test - public void verifyTest(){ - - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair(); - Ed25519PrivateKeyParameters privKeyParams = (Ed25519PrivateKeyParameters) keyPair.getPrivate(); - Ed25519PublicKeyParameters pubKeyParams = (Ed25519PublicKeyParameters) keyPair.getPublic(); - - byte[] pubKeyBytes = pubKeyParams.getEncoded(); - - Random random = new Random(); - byte[] data = new byte[1024]; - random.nextBytes(data); - - byte[] signatureDigest = ED25519Utils.sign(data,privKeyParams); - - assertTrue(ED25519Utils.verify(data,pubKeyParams,signatureDigest)); - assertTrue(ED25519Utils.verify(data,pubKeyBytes,signatureDigest)); - } - - @Test - public void consistencyTest(){ - - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair(); - Ed25519PrivateKeyParameters privKeyParams = (Ed25519PrivateKeyParameters) keyPair.getPrivate(); - Ed25519PublicKeyParameters pubKeyParams = (Ed25519PublicKeyParameters) keyPair.getPublic(); - - byte[] pubKeyBytes = pubKeyParams.getEncoded(); - byte[] privKeyBytes = privKeyParams.getEncoded(); - - Random random = new Random(); - byte[] data = new byte[1024]; - random.nextBytes(data); - - byte[] signatureDigest = ED25519Utils.sign(data,privKeyParams); - - byte[] signatureDigestFromOlderVersion = Ed25519Utils.sign_512(data,privKeyBytes); - - assertArrayEquals(signatureDigest,signatureDigestFromOlderVersion); - assertTrue(Ed25519Utils.verify(data,pubKeyBytes,signatureDigest)); - - } - -// @Test - public void performanceTest(){ - - int count = 10000; - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair(); - Ed25519PrivateKeyParameters privKeyParams = (Ed25519PrivateKeyParameters) keyPair.getPrivate(); - Ed25519PublicKeyParameters pubKeyParams = (Ed25519PublicKeyParameters) keyPair.getPublic(); - - byte[] pubKeyBytes = pubKeyParams.getEncoded(); - byte[] privKeyBytes = privKeyParams.getEncoded(); - - byte[] signatureDigest = ED25519Utils.sign(data,privKeyParams); - - assertTrue(ED25519Utils.verify(data,pubKeyParams,signatureDigest)); - - System.out.println("=================== do ED25519 sign test ==================="); - - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ED25519Utils.sign(data,privKeyParams); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do ED25519 verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ED25519Utils.verify(data,pubKeyParams,signatureDigest); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do ED25519 sign test ==================="); - - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - Ed25519Utils.sign_512(data,privKeyBytes); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do ED25519 verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - Ed25519Utils.verify(data,pubKeyBytes,signatureDigest); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - } - -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/RIPEMD160UtilsTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/RIPEMD160UtilsTest.java deleted file mode 100644 index a3baef5d..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/RIPEMD160UtilsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package test.com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.utils.classic.RIPEMD160Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author zhanglin33 - * @title: RIPEMD160UtilsTest - * @description: Tests for the hash method in RIPEMD160Utils - * @date 2019-04-10, 16:54 - */ -public class RIPEMD160UtilsTest { - - @Test - public void hashTest() { - - byte[] data1 = BytesUtils.toBytes("a"); - byte[] data2 = BytesUtils.toBytes("abc"); - - byte[] result1 = RIPEMD160Utils.hash(data1); - byte[] result2 = RIPEMD160Utils.hash(data2); - - String respectedResult1 = "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe"; - String respectedResult2 = "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"; - - assertEquals(respectedResult1, Hex.toHexString(result1)); - assertEquals(respectedResult2, Hex.toHexString(result2)); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/RSAUtilsTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/RSAUtilsTest.java deleted file mode 100644 index 68f78549..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/RSAUtilsTest.java +++ /dev/null @@ -1,388 +0,0 @@ -package test.com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.utils.classic.RSAUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; -import org.bouncycastle.crypto.params.RSAKeyParameters; -import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; -import org.junit.Test; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import java.security.*; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Random; - -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: RSAUtilsTest - * @description: Tests for methods in RSAUtils - * @date 2019-04-11, 17:10 - */ -public class RSAUtilsTest { - - @Test - public void generateKeyPairTest() { - AsymmetricCipherKeyPair kp = RSAUtils.generateKeyPair(); - keyPairTest(kp); - } - - @Test - public void generateKeyPair_ShortExpTest() { - AsymmetricCipherKeyPair kp = RSAUtils.generateKeyPair_shortExp(); - keyPairTest(kp); - } - - private void keyPairTest(AsymmetricCipherKeyPair keyPair) { - RSAKeyParameters pubKey = (RSAKeyParameters) keyPair.getPublic(); - RSAPrivateCrtKeyParameters privKey = (RSAPrivateCrtKeyParameters) keyPair.getPrivate(); - - byte[] pubKeyBytes_RawKey = RSAUtils.pubKey2Bytes_RawKey(pubKey); - byte[] pubKeyBytesConverted_RawKey = - RSAUtils.pubKey2Bytes_RawKey(RSAUtils.bytes2PubKey_RawKey(pubKeyBytes_RawKey)); - assertArrayEquals(pubKeyBytes_RawKey,pubKeyBytesConverted_RawKey); - - byte[] privKeyBytes_RawKey = RSAUtils.privKey2Bytes_RawKey(privKey); - byte[] privKeyBytesConverted_RawKey = - RSAUtils.privKey2Bytes_RawKey(RSAUtils.bytes2PrivKey_RawKey(privKeyBytes_RawKey)); - assertArrayEquals(privKeyBytes_RawKey,privKeyBytesConverted_RawKey); - - byte[] pubKeyBytes_PKCS1 = RSAUtils.pubKey2Bytes_PKCS1(pubKey); - byte[] pubKeyBytesConverted_PKCS1 = - RSAUtils.pubKey2Bytes_PKCS1(RSAUtils.bytes2PubKey_PKCS1(pubKeyBytes_PKCS1)); - assertArrayEquals(pubKeyBytes_PKCS1,pubKeyBytesConverted_PKCS1); - - byte[] privKeyBytes_PKCS1 = RSAUtils.privKey2Bytes_PKCS1(privKey); - byte[] privKeyBytesConverted_PKCS1 = - RSAUtils.privKey2Bytes_PKCS1(RSAUtils.bytes2PrivKey_PKCS1(privKeyBytes_PKCS1)); - assertArrayEquals(privKeyBytes_PKCS1,privKeyBytesConverted_PKCS1); - - byte[] pubKeyBytes_PKCS8 = RSAUtils.pubKey2Bytes_PKCS8(pubKey); - byte[] pubKeyBytesConverted_PKCS8 = - RSAUtils.pubKey2Bytes_PKCS8(RSAUtils.bytes2PubKey_PKCS8(pubKeyBytes_PKCS8)); - assertArrayEquals(pubKeyBytes_PKCS8,pubKeyBytesConverted_PKCS8); - - byte[] privKeyBytes_PKCS8 = RSAUtils.privKey2Bytes_PKCS8(privKey); - byte[] privKeyBytesConverted_PKCS8 = - RSAUtils.privKey2Bytes_PKCS8(RSAUtils.bytes2PrivKey_PKCS8(privKeyBytes_PKCS8)); - assertArrayEquals(privKeyBytes_PKCS8,privKeyBytesConverted_PKCS8); - } - - @Test - public void test(){ - - AsymmetricCipherKeyPair kp = RSAUtils.generateKeyPair(); - RSAKeyParameters pubKey = (RSAKeyParameters) kp.getPublic(); - RSAPrivateCrtKeyParameters privKey = (RSAPrivateCrtKeyParameters) kp.getPrivate(); - - byte[] privKeyBytes = RSAUtils.privKey2Bytes_RawKey(privKey); - byte[] pubKeyBytes = RSAUtils.pubKey2Bytes_RawKey(pubKey); - byte[] retrievedPubKeyBytes = RSAUtils.retrievePublicKey(privKeyBytes); - - assertArrayEquals(pubKeyBytes,retrievedPubKeyBytes); - - byte[] data = new byte[128]; - Random random = new Random(); - random.nextBytes(data); - - byte[] signatureFromPrivKey = RSAUtils.sign(data, privKey); - byte[] signatureFromPrivKeyBytes = RSAUtils.sign(data, privKeyBytes); - - assertNotNull(signatureFromPrivKey); - assertEquals(2048 / 8, signatureFromPrivKey.length); - assertArrayEquals(signatureFromPrivKeyBytes,signatureFromPrivKey); - - byte[] signature = RSAUtils.sign(data,privKey); - - boolean isValidFromPubKey = RSAUtils.verify(data, pubKey, signature); - boolean isValidFromPubKeyBytes = RSAUtils.verify(data, pubKeyBytes, signature); - - assertTrue(isValidFromPubKey); - assertTrue(isValidFromPubKeyBytes); - - byte[] ciphertextFromPubKey = RSAUtils.encrypt(data,pubKey); - byte[] ciphertextFromPubKeyBytes = RSAUtils.encrypt(data,pubKeyBytes); - - assertEquals(256,ciphertextFromPubKey.length); - assertEquals(256,ciphertextFromPubKeyBytes.length); - - - data = new byte[1024]; - random.nextBytes(data); - byte[] ciphertext = RSAUtils.encrypt(data, pubKey); - - byte[] plaintextFromPrivKey = RSAUtils.decrypt(ciphertext, privKey); - byte[] plaintextFromPrivKeyBytes = RSAUtils.decrypt(ciphertext, privKeyBytes); - - assertArrayEquals(data, plaintextFromPrivKey); - assertArrayEquals(data, plaintextFromPrivKeyBytes); - } - - -// @Test - public void performanceTest(){ - - int count = 10000; - byte[] data = new byte[128]; - Random random = new Random(); - random.nextBytes(data); - - AsymmetricCipherKeyPair keyPair = RSAUtils.generateKeyPair(); - AsymmetricKeyParameter privKey = keyPair.getPrivate(); - AsymmetricKeyParameter pubKey = keyPair.getPublic(); - - byte[] signature = RSAUtils.sign(data,privKey); - byte[] ciphertext = RSAUtils.encrypt(data,pubKey); - - System.out.println("=================== do RSA sign test ==================="); - - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - RSAUtils.sign(data,privKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("RSA Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do RSA verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - RSAUtils.verify(data,pubKey,signature); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("RSA Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do RSA encrypt test ==================="); - - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - RSAUtils.encrypt(data,pubKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("RSA Encrypting Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do RSA decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - RSAUtils.decrypt(ciphertext,privKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("RSA Decrypting Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } - -// @Test - public void encryptionConsistencyTest(){ - - int count = 10000; - byte[] data = new byte[222]; - Random random = new Random(); - random.nextBytes(data); - - KeyPairGenerator keyPairGen = null; - try { - keyPairGen = KeyPairGenerator.getInstance("RSA"); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - assert keyPairGen != null; - keyPairGen.initialize(2048, new SecureRandom()); - KeyPair keyPair = keyPairGen.generateKeyPair(); - RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); - RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); - - byte[] publicKeyBytes = publicKey.getEncoded(); - byte[] privateKeyBytes = privateKey.getEncoded(); - - RSAKeyParameters pubKey = RSAUtils.bytes2PubKey_PKCS8(publicKeyBytes); - RSAPrivateCrtKeyParameters privKey = RSAUtils.bytes2PrivKey_PKCS8(privateKeyBytes); - - Cipher cipher; - byte[] ciphertext = null; - byte[] plaintext = null; - - System.out.println("=================== do BouncyCastle-based RSA encrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ciphertext = RSAUtils.encrypt(data,pubKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("BouncyCastle-based RSA Encrypting Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - assert ciphertext != null; - System.out.println("=================== do BouncyCastle-based RSA decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - plaintext = RSAUtils.decrypt(ciphertext,privKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("BouncyCastle-based RSA Decrypting Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do JDK-based RSA encrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - try { - cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - ciphertext = cipher.doFinal(data); - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException - | IllegalBlockSizeException | BadPaddingException e) { - e.printStackTrace(); - } - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("JDK-based RSA Encrypting Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do JDK-based RSA decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - try { - cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); - cipher.init(Cipher.DECRYPT_MODE, privateKey); - plaintext = cipher.doFinal(ciphertext); - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException - | IllegalBlockSizeException | BadPaddingException e) { - e.printStackTrace(); - } - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("JDK-based RSA Decrypting Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - - assertArrayEquals(data,plaintext); - assertArrayEquals(data,plaintext); - } - -// @Test - public void signatureConsistencyTest() { - - int count = 10000; - byte[] data = new byte[222]; - Random random = new Random(); - random.nextBytes(data); - - KeyPairGenerator keyPairGen = null; - try { - keyPairGen = KeyPairGenerator.getInstance("RSA"); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - assert keyPairGen != null; - keyPairGen.initialize(2048, new SecureRandom()); - KeyPair keyPair = keyPairGen.generateKeyPair(); - RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); - RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); - - byte[] publicKeyBytes = publicKey.getEncoded(); - byte[] privateKeyBytes = privateKey.getEncoded(); - - byte[] signature = null; - boolean isValid = false; - - RSAKeyParameters pubKey = RSAUtils.bytes2PubKey_PKCS8(publicKeyBytes); - RSAPrivateCrtKeyParameters privKey = RSAUtils.bytes2PrivKey_PKCS8(privateKeyBytes); - - System.out.println("=================== do BouncyCastle-based RSA sign test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - signature = RSAUtils.sign(data,privKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("BouncyCastle-based RSA Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do BouncyCastle-based RSA verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - isValid = RSAUtils.verify(data,pubKey,signature); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("BouncyCastle-based RSA Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - - - - System.out.println("=================== do JDK-based RSA sign test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - try { - Signature signer = Signature.getInstance("SHA256withRSA"); - signer.initSign(privateKey); - signer.update(data); - signature = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("JDK-based RSA Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do JDK-based RSA verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - try { - Signature verifier = Signature.getInstance("SHA256withRSA"); - verifier.initVerify(publicKey); - verifier.update(data); - isValid = verifier.verify(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("JDK-based RSA Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println(isValid); - - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/SHA256UtilsTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/SHA256UtilsTest.java deleted file mode 100644 index f8a40d78..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/SHA256UtilsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package test.com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.utils.classic.SHA256Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author zhanglin33 - * @title: SHA256UtilsTest - * @description: Tests for the hash method in SHA256Utils - * @date 2019-04-09, 16:18 - */ -public class SHA256UtilsTest { - - @Test - public void hashTest() { - - byte[] data1 = BytesUtils.toBytes("abc"); - byte[] data2 = BytesUtils.toBytes("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); - byte[] data3 = BytesUtils.toBytes("aaaaaaaaaa"); - - byte[] result1 = SHA256Utils.hash(data1); - byte[] result2 = SHA256Utils.hash(data2); - byte[] result3 = SHA256Utils.hash(data3); - - String respectedResult1 = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; - String respectedResult2 = "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"; - String respectedResult3 = "bf2cb58a68f684d95a3b78ef8f661c9a4e5b09e82cc8f9cc88cce90528caeb27"; - - assertEquals(respectedResult1,Hex.toHexString(result1)); - assertEquals(respectedResult2,Hex.toHexString(result2)); - assertEquals(respectedResult3,Hex.toHexString(result3)); - } -} diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/SSHKeyUtilsTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/SSHKeyUtilsTest.java deleted file mode 100644 index 88a747bd..00000000 --- a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/utils/classic/SSHKeyUtilsTest.java +++ /dev/null @@ -1,422 +0,0 @@ -package test.com.jd.blockchain.crypto.utils.classic; - -import com.jd.blockchain.crypto.utils.classic.RSAUtils; -import com.jd.blockchain.crypto.utils.classic.SSHKeyParser; -import org.bouncycastle.crypto.params.*; -import org.bouncycastle.crypto.signers.DSASigner; -import org.bouncycastle.crypto.signers.ECDSASigner; -import org.bouncycastle.crypto.signers.Ed25519Signer; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.math.ec.custom.sec.SecP256R1Curve; -import org.junit.Test; - -import java.math.BigInteger; -import java.security.SecureRandom; - -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: SSHKeyUtilsTest - * @description: Tests for methods in SSHKeyUtils - * @date 2019-05-07, 15:14 - */ -public class SSHKeyUtilsTest { - - private static SecureRandom secureRandom = new SecureRandom(); - private static SSHKeyParser parser = new SSHKeyParser(); - - private static final String rsaPubKeyWithHead = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCYwLN4EXy7g0Xugv4lQfou" + - "jbARi48gPSxVuptGsSoGqsS00e9rA7v0qzFKa9Zhnw1WkjCnEXRYAMiCAJYkM/mGI8mb3qkcdNhGWZm" + - "PnopV+D46CTFB14yeR9mjoOPXs4pjX3zGveKx5Nx8jvdoFewbTCtdN0x1XWTjNT5bXqP/4gXkLENEU5" + - "tLsWVAOu0ME/Ne/9gMujAtDoolJ181a9P06bvEpIw5cLtUnsm5CtvBuiL7WBXxDJ/IASJrKNGBdK8xi" + - "b1+Kb8tNLAT6Dj25BwylqiRNhb5l1Ni4aKrE2FqSEc5Nx5+csQMEl9MBJ3pEsLHBNbohDL+jbwLguRV" + - "D6CJ zhanglin33@zhanglin33.local\n"; - private static final String rsaPrivKeyWithHead = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + - "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn\n" + - "NhAAAAAwEAAQAAAQEAmMCzeBF8u4NF7oL+JUH6Lo2wEYuPID0sVbqbRrEqBqrEtNHvawO7\n" + - "9KsxSmvWYZ8NVpIwpxF0WADIggCWJDP5hiPJm96pHHTYRlmZj56KVfg+OgkxQdeMnkfZo6\n" + - "Dj17OKY198xr3iseTcfI73aBXsG0wrXTdMdV1k4zU+W16j/+IF5CxDRFObS7FlQDrtDBPz\n" + - "Xv/YDLowLQ6KJSdfNWvT9Om7xKSMOXC7VJ7JuQrbwboi+1gV8QyfyAEiayjRgXSvMYm9fi\n" + - "m/LTSwE+g49uQcMpaokTYW+ZdTYuGiqxNhakhHOTcefnLEDBJfTASd6RLCxwTW6IQy/o28\n" + - "C4LkVQ+giQAAA9AaxHf6GsR3+gAAAAdzc2gtcnNhAAABAQCYwLN4EXy7g0Xugv4lQfoujb\n" + - "ARi48gPSxVuptGsSoGqsS00e9rA7v0qzFKa9Zhnw1WkjCnEXRYAMiCAJYkM/mGI8mb3qkc\n" + - "dNhGWZmPnopV+D46CTFB14yeR9mjoOPXs4pjX3zGveKx5Nx8jvdoFewbTCtdN0x1XWTjNT\n" + - "5bXqP/4gXkLENEU5tLsWVAOu0ME/Ne/9gMujAtDoolJ181a9P06bvEpIw5cLtUnsm5CtvB\n" + - "uiL7WBXxDJ/IASJrKNGBdK8xib1+Kb8tNLAT6Dj25BwylqiRNhb5l1Ni4aKrE2FqSEc5Nx\n" + - "5+csQMEl9MBJ3pEsLHBNbohDL+jbwLguRVD6CJAAAAAwEAAQAAAQARfhfPSylei9TpUGTs\n" + - "PVb6F82u5K16QqceFiWL/ePTKaEnF9d0CNRwW15kqF6/hShQ3qLlrvEE1uofQRPwh2cuvl\n" + - "BrIh95m8PcoowcT0qGN8xgdwcGBDodMhsxSs5suCnD4X53f+1C8/Nv7CtW5xPHuHxKy3dd\n" + - "BVn1TvaaHgdn2PwJVKtZp+WVG3/UHr25nFHd8mYgpeHZqK9AW16N0UEMXMM1u8ZCubVOoS\n" + - "IGuMAXpTug0xA+BXHo17FcDGKSzcXFzh+urIz5glRp5zFioHBqxNmkKfQkG6C7UxnPGyS/\n" + - "/J+3lL2lvl0G8kO/5EDFMBhTMEy1NeR2b629S4G1qUxVAAAAgHDwE9kPiVETcxSzI4wotT\n" + - "1Ee9nKVVD3oGdRqefvX7EUR8bvdv4nCqHPNBx8C6l8zo7fsQD81YL85F4eWbtrdxEijRHX\n" + - "5m7J/muh/laY1Hq43WCkZGboO4fZ2HHi7oN096FqrKRpvbQGQi1FLbcISUdsitwrs6ywn3\n" + - "fNx3q+X3V6AAAAgQDJRo9v+0QvldI33cpJKPKiaop5QvfIDzMatD3vLA1qqycgIi4KOtb5\n" + - "+LP/jgIpCYah/sk+JpKNz/vsZmZmrfaVu9D3Le2LLBgMpEoSO8jOe9WGI4Ew75C7w7AZCa\n" + - "SyUnHIVX/9D8Y5tx4cKx6Im9AGbNF35XZoKO4KCk5VMTXhnwAAAIEAwkjKIpTYdeAQVTRf\n" + - "C13kg84Bu5n4WkiLnp1WOCg2GN5RekqprINtpjIMZoB9Fv292Np99La8yvmRoy5qzNHGdm\n" + - "Q6AMku8jP123jF2J+wDvF714VtZHNvdCYBGJS+rZ81xtJfHhKtZqRAVtbPertOWZeuRm9V\n" + - "o+/rEuEzgGYGXNcAAAAbemhhbmdsaW4zM0B6aGFuZ2xpbjMzLmxvY2Fs\n" + - "-----END OPENSSH PRIVATE KEY-----"; - - private static final String dsaPubKeyWithHead = "ssh-dss AAAAB3NzaC1kc3MAAACBAIOpp3qEY9zVOxQFgLS+2sOqXT+lnJVc" + - "Nr68eAE/iYG02kYKs/BrJYBbr0nb10ERdQv6Yte9tQilpJTMKPhNuTVIHTK2xbV0nfChN4wePY+XJyb" + - "Ima/m41FnIlfp2ov54ePLsNgY41qYWxuKzxURV67DgPxbMqMZmBV2Ccpb5+t/AAAAFQCcyJjOhDH3Ck" + - "Lbs9dHx/gUtmsh0wAAAIB3MyVR817NTbaRA4pO0AVnk4jC7JKVeKDlZaBBLt1CzyMKY7OzNgioqZmBX" + - "tffkHXBXxd75AdiBLeurmAPLKsZ50O+lRQI8QwGL5ne0dkGP+sRFdqTEA2BMjWyvlx6xwJD14/cKpgg" + - "fLt+FBt5nhwmbewxt9uWXENfzD/84Z7aOQAAAIA0DOAIv6SqSEPOyzPMHVWGGiqNFFgQ0gOH7BhrLD/" + - "hNqFz5vuKQd5rhKCVXxzANTQ8WrINMIk3aYIRgp96oxI3xsL1w7rYODoQmkx4JFHfvU/Sls40r1h09D" + - "OWSbqE99mo41RIZMauVFlYlhYnusziX1QyGAabHMcz73Y19vrKCg== zhanglin33@JRMVP10WHTD5"; - private static final String dsaPrivKeyWithHead = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + - "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABsQAAAAdzc2gtZH\n" + - "NzAAAAgQCDqad6hGPc1TsUBYC0vtrDql0/pZyVXDa+vHgBP4mBtNpGCrPwayWAW69J29dB\n" + - "EXUL+mLXvbUIpaSUzCj4Tbk1SB0ytsW1dJ3woTeMHj2PlycmyJmv5uNRZyJX6dqL+eHjy7\n" + - "DYGONamFsbis8VEVeuw4D8WzKjGZgVdgnKW+frfwAAABUAnMiYzoQx9wpC27PXR8f4FLZr\n" + - "IdMAAACAdzMlUfNezU22kQOKTtAFZ5OIwuySlXig5WWgQS7dQs8jCmOzszYIqKmZgV7X35\n" + - "B1wV8Xe+QHYgS3rq5gDyyrGedDvpUUCPEMBi+Z3tHZBj/rERXakxANgTI1sr5cescCQ9eP\n" + - "3CqYIHy7fhQbeZ4cJm3sMbfbllxDX8w//OGe2jkAAACANAzgCL+kqkhDzsszzB1VhhoqjR\n" + - "RYENIDh+wYayw/4Tahc+b7ikHea4SglV8cwDU0PFqyDTCJN2mCEYKfeqMSN8bC9cO62Dg6\n" + - "EJpMeCRR371P0pbONK9YdPQzlkm6hPfZqONUSGTGrlRZWJYWJ7rM4l9UMhgGmxzHM+92Nf\n" + - "b6ygoAAAHwI0abUyNGm1MAAAAHc3NoLWRzcwAAAIEAg6mneoRj3NU7FAWAtL7aw6pdP6Wc\n" + - "lVw2vrx4AT+JgbTaRgqz8GslgFuvSdvXQRF1C/pi1721CKWklMwo+E25NUgdMrbFtXSd8K\n" + - "E3jB49j5cnJsiZr+bjUWciV+nai/nh48uw2BjjWphbG4rPFRFXrsOA/FsyoxmYFXYJylvn\n" + - "638AAAAVAJzImM6EMfcKQtuz10fH+BS2ayHTAAAAgHczJVHzXs1NtpEDik7QBWeTiMLskp\n" + - "V4oOVloEEu3ULPIwpjs7M2CKipmYFe19+QdcFfF3vkB2IEt66uYA8sqxnnQ76VFAjxDAYv\n" + - "md7R2QY/6xEV2pMQDYEyNbK+XHrHAkPXj9wqmCB8u34UG3meHCZt7DG325ZcQ1/MP/zhnt\n" + - "o5AAAAgDQM4Ai/pKpIQ87LM8wdVYYaKo0UWBDSA4fsGGssP+E2oXPm+4pB3muEoJVfHMA1\n" + - "NDxasg0wiTdpghGCn3qjEjfGwvXDutg4OhCaTHgkUd+9T9KWzjSvWHT0M5ZJuoT32ajjVE\n" + - "hkxq5UWViWFie6zOJfVDIYBpscxzPvdjX2+soKAAAAFEJXzZu8UDkISU8DCj/KY7Fq31R8\n" + - "AAAAF3poYW5nbGluMzNASlJNVlAxMFdIVEQ1AQIDBA==\n" + - "-----END OPENSSH PRIVATE KEY-----\n"; - - private static final String ecdsaPubKeyWithHead = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbml" + - "zdHAyNTYAAABBBEi5T13AMBMBthe7a6GwSoK5JK8mVEMXztIA6kUGRuNefoRtY0lPx3kmeIW4GGFVK" + - "ct+Kcc6vtNKuUhn8fVqEZU= zhanglin33@JRMVP10WHTD5"; - private static final String ecdsaPrivKeyWithHead = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + - "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS\n" + - "1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQRIuU9dwDATAbYXu2uhsEqCuSSvJlRD\n" + - "F87SAOpFBkbjXn6EbWNJT8d5JniFuBhhVSnLfinHOr7TSrlIZ/H1ahGVAAAAsGEuQiRhLk\n" + - "IkAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEi5T13AMBMBthe7\n" + - "a6GwSoK5JK8mVEMXztIA6kUGRuNefoRtY0lPx3kmeIW4GGFVKct+Kcc6vtNKuUhn8fVqEZ\n" + - "UAAAAhAPEgd42vUGT8APac9sNgj7zIkE4m9/r8+7tATePBXucRAAAAF3poYW5nbGluMzNA\n" + - "SlJNVlAxMFdIVEQ1\n" + - "-----END OPENSSH PRIVATE KEY-----"; - - private static final String ed25519PubKeyWithHead = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICWVU6JcJ3k/ZM9FxKY5h" + - "kxWSi1EEZaYwCChiJ00wwps zhanglin33@JRMVP10WHTD5"; - private static final String ed25519PrivKeyWithHead = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + - "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n" + - "QyNTUxOQAAACAllVOiXCd5P2TPRcSmOYZMVkotRBGWmMAgoYidNMMKbAAAAKB9rg8cfa4P\n" + - "HAAAAAtzc2gtZWQyNTUxOQAAACAllVOiXCd5P2TPRcSmOYZMVkotRBGWmMAgoYidNMMKbA\n" + - "AAAEBK22Wm3Hb4mV3qKkAZ/eG2y7go3Wc0xMbCFrqfvZJghiWVU6JcJ3k/ZM9FxKY5hkxW\n" + - "Si1EEZaYwCChiJ00wwpsAAAAF3poYW5nbGluMzNASlJNVlAxMFdIVEQ1AQIDBAUG\n" + - "-----END OPENSSH PRIVATE KEY-----"; - - - @Test - public void parseRSAPublicKeyTest() { - - BigInteger exponent = new BigInteger("010001",16); - BigInteger modulus = new BigInteger("0098c0b378117cbb8345ee82fe2541fa2e8db0118b8f2" + - "03d2c55ba9b46b12a06aac4b4d1ef6b03bbf4ab314a6bd6619f0d569230a711745800c88200962" + - "433f98623c99bdea91c74d84659998f9e8a55f83e3a093141d78c9e47d9a3a0e3d7b38a635f7cc" + - "6bde2b1e4dc7c8ef76815ec1b4c2b5d374c755d64e3353e5b5ea3ffe205e42c4344539b4bb1654" + - "03aed0c13f35effd80cba302d0e8a25275f356bd3f4e9bbc4a48c3970bb549ec9b90adbc1ba22f" + - "b5815f10c9fc801226b28d18174af3189bd7e29bf2d34b013e838f6e41c3296a8913616f997536" + - "2e1a2ab13616a484739371e7e72c40c125f4c049de912c2c704d6e88432fe8dbc0b82e4550fa089",16); - String pubKeyFormat = "OpenSSH"; - String pubKeyType = "ssh-rsa"; - String id = "zhanglin33@zhanglin33.local"; - - RSAKeyParameters pubKey = (RSAKeyParameters) parser.pubKeyParse(rsaPubKeyWithHead); - BigInteger e = pubKey.getExponent(); - BigInteger n = pubKey.getModulus(); - assertEquals(exponent,e); - assertEquals(modulus,n); - - assertEquals(pubKeyFormat,parser.getKeyFormat()); - assertEquals(pubKeyType,parser.getKeyType()); - assertEquals(id, parser.getIdentity()); - } - - @Test - public void parseRSAPrivateKeyTest() { - - BigInteger pubExponent = new BigInteger("010001",16); - BigInteger modulus = new BigInteger("0098c0b378117cbb8345ee82fe2541fa2e8db0118b8f2" + - "03d2c55ba9b46b12a06aac4b4d1ef6b03bbf4ab314a6bd6619f0d569230a711745800c88200962" + - "433f98623c99bdea91c74d84659998f9e8a55f83e3a093141d78c9e47d9a3a0e3d7b38a635f7cc" + - "6bde2b1e4dc7c8ef76815ec1b4c2b5d374c755d64e3353e5b5ea3ffe205e42c4344539b4bb1654" + - "03aed0c13f35effd80cba302d0e8a25275f356bd3f4e9bbc4a48c3970bb549ec9b90adbc1ba22f" + - "b5815f10c9fc801226b28d18174af3189bd7e29bf2d34b013e838f6e41c3296a8913616f997536" + - "2e1a2ab13616a484739371e7e72c40c125f4c049de912c2c704d6e88432fe8dbc0b82e4550fa089",16); - BigInteger privExponent = new BigInteger("117e17cf4b295e8bd4e95064ec3d56fa17cdaee4" + - "ad7a42a71e16258bfde3d329a12717d77408d4705b5e64a85ebf852850dea2e5aef104d6ea1f41" + - "13f087672ebe506b221f799bc3dca28c1c4f4a8637cc60770706043a1d321b314ace6cb829c3e1" + - "7e777fed42f3f36fec2b56e713c7b87c4acb775d0559f54ef69a1e0767d8fc0954ab59a7e5951b" + - "7fd41ebdb99c51ddf26620a5e1d9a8af405b5e8dd1410c5cc335bbc642b9b54ea12206b8c017a5" + - "3ba0d3103e0571e8d7b15c0c6292cdc5c5ce1faeac8cf9825469e73162a0706ac4d9a429f4241b" + - "a0bb5319cf1b24bffc9fb794bda5be5d06f243bfe440c5301853304cb535e4766fadbd4b81b5a94c55",16); - BigInteger p = new BigInteger("c9468f6ffb442f95d237ddca4928f2a26a8a7942f7c80f331ab" + - "43def2c0d6aab2720222e0a3ad6f9f8b3ff8e02290986a1fec93e26928dcffbec666666adf695b" + - "bd0f72ded8b2c180ca44a123bc8ce7bd586238130ef90bbc3b01909a4b25271c8557ffd0fc639b" + - "71e1c2b1e889bd0066cd177e5766828ee0a0a4e553135e19f",16); - BigInteger q = new BigInteger("c248ca2294d875e01055345f0b5de483ce01bb99f85a488b9e9" + - "d5638283618de517a4aa9ac836da6320c66807d16fdbdd8da7df4b6bccaf991a32e6accd1c6766" + - "43a00c92ef233f5db78c5d89fb00ef17bd7856d64736f7426011894bead9f35c6d25f1e12ad66a" + - "44056d6cf7abb4e5997ae466f55a3efeb12e1338066065cd7",16); - BigInteger dP = new BigInteger("4bff095fa5c6cc14cca7ed6558944e70c6bb7c27adf8eacc47f" + - "3f042a32679b51ff3c1141326be4ee9f9c4af30df9fca26d655d3d2aa99430382f1f30e27f727f" + - "81f618504e0fc882415d025ec4ed8afe7225bbb86e79d8557d0e0d3444d5455c3e78c88d770e80" + - "fdd1d93a656bc462276e9ec54468df38e555a28d37fde314f", 16); - BigInteger dQ = new BigInteger("187ee2f57f3cd787dba752861541ce590bf54df8f8c63155613" + - "74732a76742b56d22751d7581d0a65eb30f8d6db8235ff7627cf508c13efa3e718b9dad9b59617" + - "dfb8e33cf767c34a86a4ecfa43aa777acfc9c77116e3884357277edf128a4e53bdf345cef4feb9" + - "c13fc9ef2e3ef8fce5e007c22f7724702a58bbd5998037f5b", 16); - BigInteger qInv = new BigInteger("70f013d90f8951137314b3238c28b53d447bd9ca5550f7a06" + - "751a9e7ef5fb11447c6ef76fe270aa1cf341c7c0ba97cce8edfb100fcd582fce45e1e59bb6b771" + - "1228d11d7e66ec9fe6ba1fe5698d47ab8dd60a46466e83b87d9d871e2ee8374f7a16aaca469bdb" + - "406422d452db70849476c8adc2bb3acb09f77cdc77abe5f757a", 16); - - String privKeyFormat = "OpenSSH"; - String privKeyType = "ssh-rsa"; - String id = "zhanglin33@zhanglin33.local"; - - RSAPrivateCrtKeyParameters privKey = (RSAPrivateCrtKeyParameters) parser.privKeyParse(rsaPrivKeyWithHead); - assertEquals(pubExponent,privKey.getPublicExponent()); - assertEquals(modulus,privKey.getModulus()); - assertEquals(privExponent,privKey.getExponent()); - assertEquals(p,privKey.getP()); - assertEquals(q,privKey.getQ()); - assertEquals(dP,privKey.getDP()); - assertEquals(dQ,privKey.getDQ()); - assertEquals(qInv,privKey.getQInv()); - - assertEquals(privKeyFormat,parser.getKeyFormat()); - assertEquals(privKeyType,parser.getKeyType()); - assertEquals(id,parser.getIdentity()); - } - - @Test - public void parseDSAPublicKeyTest() { - - BigInteger p = new BigInteger("83a9a77a8463dcd53b140580b4bedac3aa5d3fa59c955c36bebc" + - "78013f8981b4da460ab3f06b25805baf49dbd74111750bfa62d7bdb508a5a494cc28f84db93548" + - "1d32b6c5b5749df0a1378c1e3d8f972726c899afe6e351672257e9da8bf9e1e3cbb0d818e35a98" + - "5b1b8acf151157aec380fc5b32a31998157609ca5be7eb7f", 16); - BigInteger q = new BigInteger("9cc898ce8431f70a42dbb3d747c7f814b66b21d3", 16); - BigInteger g = new BigInteger("77332551f35ecd4db691038a4ed005679388c2ec929578a0e565" + - "a0412edd42cf230a63b3b33608a8a999815ed7df9075c15f177be4076204b7aeae600f2cab19e7" + - "43be951408f10c062f99ded1d9063feb1115da93100d813235b2be5c7ac70243d78fdc2a98207c" + - "bb7e141b799e1c266dec31b7db965c435fcc3ffce19eda39", 16); - BigInteger y = new BigInteger("340ce008bfa4aa4843cecb33cc1d55861a2a8d145810d20387ec" + - "186b2c3fe136a173e6fb8a41de6b84a0955f1cc035343c5ab20d308937698211829f7aa31237c6" + - "c2f5c3bad8383a109a4c782451dfbd4fd296ce34af5874f4339649ba84f7d9a8e3544864c6ae54" + - "5958961627bacce25f543218069b1cc733ef7635f6faca0a", 16); - - String pubKeyFormat = "OpenSSH"; - String pubKeyType = "ssh-dss"; - String id = "zhanglin33@JRMVP10WHTD5"; - - DSAPublicKeyParameters pubKey = (DSAPublicKeyParameters) parser.pubKeyParse(dsaPubKeyWithHead); - DSAParameters parameters = pubKey.getParameters(); - assertEquals(p, parameters.getP()); - assertEquals(q, parameters.getQ()); - assertEquals(g, parameters.getG()); - assertEquals(y, pubKey.getY()); - - assertEquals(pubKeyFormat,parser.getKeyFormat()); - assertEquals(pubKeyType,parser.getKeyType()); - assertEquals(id, parser.getIdentity()); - } - - @Test - public void parseDSAPrivateKeyTest() { - - BigInteger p = new BigInteger("83a9a77a8463dcd53b140580b4bedac3aa5d3fa59c955c36bebc" + - "78013f8981b4da460ab3f06b25805baf49dbd74111750bfa62d7bdb508a5a494cc28f84db93548" + - "1d32b6c5b5749df0a1378c1e3d8f972726c899afe6e351672257e9da8bf9e1e3cbb0d818e35a98" + - "5b1b8acf151157aec380fc5b32a31998157609ca5be7eb7f", 16); - BigInteger q = new BigInteger("9cc898ce8431f70a42dbb3d747c7f814b66b21d3", 16); - BigInteger g = new BigInteger("77332551f35ecd4db691038a4ed005679388c2ec929578a0e565" + - "a0412edd42cf230a63b3b33608a8a999815ed7df9075c15f177be4076204b7aeae600f2cab19e7" + - "43be951408f10c062f99ded1d9063feb1115da93100d813235b2be5c7ac70243d78fdc2a98207c" + - "bb7e141b799e1c266dec31b7db965c435fcc3ffce19eda39", 16); - BigInteger y = new BigInteger("340ce008bfa4aa4843cecb33cc1d55861a2a8d145810d20387ec" + - "186b2c3fe136a173e6fb8a41de6b84a0955f1cc035343c5ab20d308937698211829f7aa31237c6" + - "c2f5c3bad8383a109a4c782451dfbd4fd296ce34af5874f4339649ba84f7d9a8e3544864c6ae54" + - "5958961627bacce25f543218069b1cc733ef7635f6faca0a", 16); - - BigInteger x = new BigInteger("4257cd9bbc503908494f030a3fca63b16adf547c", 16); - - String privKeyFormat = "OpenSSH"; - String privKeyType = "ssh-dss"; - String id = "zhanglin33@JRMVP10WHTD5"; - - DSAPrivateKeyParameters privKey = (DSAPrivateKeyParameters) parser.privKeyParse(dsaPrivKeyWithHead); - assertEquals(x,privKey.getX()); - assertEquals(y,g.modPow(x,p)); - - DSAParameters parameters = privKey.getParameters(); - assertEquals(p, parameters.getP()); - assertEquals(q, parameters.getQ()); - assertEquals(g, parameters.getG()); - assertEquals(x, privKey.getX()); - - assertEquals(privKeyFormat,parser.getKeyFormat()); - assertEquals(privKeyType,parser.getKeyType()); - assertEquals(id, parser.getIdentity()); - } - - @Test - public void parseECDSAPublicKeyTest() { - - BigInteger gX = new BigInteger("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",16); - BigInteger gY = new BigInteger("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5",16); - - BigInteger QX = new BigInteger("48b94f5dc0301301b617bb6ba1b04a82b924af26544317ced200ea450646e35e",16); - BigInteger QY = new BigInteger("7e846d63494fc779267885b818615529cb7e29c73abed34ab94867f1f56a1195",16); - - String pubKeyFormat = "OpenSSH"; - String pubKeyType = "ecdsa-sha2-nistp256"; - String id = "zhanglin33@JRMVP10WHTD5"; - - ECPublicKeyParameters pubKey = (ECPublicKeyParameters) parser.pubKeyParse(ecdsaPubKeyWithHead); - SecP256R1Curve curve = new SecP256R1Curve(); - ECPoint g = curve.createPoint(gX,gY); - ECPoint Q = curve.createPoint(QX,QY); - assertEquals(g,pubKey.getParameters().getG()); - assertEquals(Q,pubKey.getQ()); - - assertEquals(pubKeyFormat,parser.getKeyFormat()); - assertEquals(pubKeyType,parser.getKeyType()); - assertEquals(id, parser.getIdentity()); - } - - @Test - public void parseECDSAPrivateKeyTest() { - - BigInteger gX = new BigInteger("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",16); - BigInteger gY = new BigInteger("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5",16); - - BigInteger QX = new BigInteger("48b94f5dc0301301b617bb6ba1b04a82b924af26544317ced200ea450646e35e",16); - BigInteger QY = new BigInteger("7e846d63494fc779267885b818615529cb7e29c73abed34ab94867f1f56a1195",16); - BigInteger d = new BigInteger("00f120778daf5064fc00f69cf6c3608fbcc8904e26f7fafcfbbb404de3c15ee711",16); - - String privKeyFormat = "OpenSSH"; - String privKeyType = "ecdsa-sha2-nistp256"; - String id = "zhanglin33@JRMVP10WHTD5"; - - ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) parser.privKeyParse(ecdsaPrivKeyWithHead); - - SecP256R1Curve curve = new SecP256R1Curve(); - ECPoint g = curve.createPoint(gX,gY); - ECPoint Q = curve.createPoint(QX,QY); - assertEquals(g,privKey.getParameters().getG()); - assertEquals(d,privKey.getD()); - assertEquals(Q,g.multiply(d)); - - assertEquals(privKeyFormat,parser.getKeyFormat()); - assertEquals(privKeyType,parser.getKeyType()); - assertEquals(id, parser.getIdentity()); - } - - - @Test - public void parseED25519PublicKeyTest() { - - byte[] A = Hex.decode("259553a25c27793f64cf45c4a639864c564a2d44119698c020a1889d34c30a6c"); - - String pubKeyFormat = "OpenSSH"; - String pubKeyType = "ssh-ed25519"; - String id = "zhanglin33@JRMVP10WHTD5"; - - Ed25519PublicKeyParameters pubKey = (Ed25519PublicKeyParameters) parser.pubKeyParse(ed25519PubKeyWithHead); - assertArrayEquals(A,pubKey.getEncoded()); - - assertEquals(pubKeyFormat,parser.getKeyFormat()); - assertEquals(pubKeyType,parser.getKeyType()); - assertEquals(id, parser.getIdentity()); - } - - @Test - public void parseED25519PrivateKeyTest() { - - byte[] A = Hex.decode("259553a25c27793f64cf45c4a639864c564a2d44119698c020a1889d34c30a6c"); - - byte[] s = Hex.decode("4adb65a6dc76f8995dea2a4019fde1b6cbb828dd6734c4c6c216ba9fbd926086"); - - String privKeyFormat = "OpenSSH"; - String privKeyType = "ssh-ed25519"; - String id = "zhanglin33@JRMVP10WHTD5"; - - Ed25519PrivateKeyParameters privKey = (Ed25519PrivateKeyParameters) parser.privKeyParse(ed25519PrivKeyWithHead); - assertArrayEquals(s, privKey.getEncoded()); - assertArrayEquals(A, privKey.generatePublicKey().getEncoded()); - - assertEquals(privKeyFormat,parser.getKeyFormat()); - assertEquals(privKeyType,parser.getKeyType()); - assertEquals(id, parser.getIdentity()); - } - - @Test - public void rsaTest() { - - byte[] msg = new byte[128]; - secureRandom.nextBytes(msg); - - byte[] signature = RSAUtils.sign(msg,parser.privKeyParse(rsaPrivKeyWithHead)); - boolean isValid = RSAUtils.verify(msg,parser.pubKeyParse(rsaPubKeyWithHead),signature); - assertTrue(isValid); - } - - @Test - public void dsaTest() { - - byte[] msg = new byte[128]; - secureRandom.nextBytes(msg); - - DSASigner signer = new DSASigner(); - signer.init(true, parser.privKeyParse(dsaPrivKeyWithHead)); - BigInteger[] signature = signer.generateSignature(msg); - - signer.init(false, parser.pubKeyParse(dsaPubKeyWithHead)); - boolean isValid = signer.verifySignature(msg, signature[0], signature[1]); - assertTrue(isValid); - } - - @Test - public void ecdsaTest() { - - byte[] msg = new byte[128]; - secureRandom.nextBytes(msg); - - ECDSASigner signer = new ECDSASigner(); - signer.init(true, parser.privKeyParse(ecdsaPrivKeyWithHead)); - BigInteger[] signature = signer.generateSignature(msg); - - signer.init(false, parser.pubKeyParse(ecdsaPubKeyWithHead)); - boolean isValid = signer.verifySignature(msg, signature[0], signature[1]); - assertTrue(isValid); - } - - @Test - public void ed25519Test() { - - byte[] msg = new byte[128]; - secureRandom.nextBytes(msg); - - Ed25519Signer signer = new Ed25519Signer(); - signer.init(true, parser.privKeyParse(ed25519PrivKeyWithHead)); - signer.update(msg, 0, msg.length); - byte[] signature = signer.generateSignature(); - - signer.init(false, parser.pubKeyParse(ed25519PubKeyWithHead)); - signer.update(msg, 0, msg.length); - - boolean isValid = signer.verifySignature(signature); - assertTrue(isValid); - } -} diff --git a/source/crypto/crypto-composite/src/test/java/com/jd/blockchain/AppTest.java b/source/crypto/crypto-composite/src/test/java/com/jd/blockchain/AppTest.java deleted file mode 100644 index 941b907f..00000000 --- a/source/crypto/crypto-composite/src/test/java/com/jd/blockchain/AppTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -/** - * Unit test for simple App. - */ -public class AppTest -{ - /** - * Rigorous Test :-) - */ - @Test - public void shouldAnswerWithTrue() - { - assertTrue( true ); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricCiphertext.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricCiphertext.java deleted file mode 100644 index 279d9c60..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricCiphertext.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.crypto; - -public class AsymmetricCiphertext extends BaseCryptoBytes implements Ciphertext { - - public AsymmetricCiphertext(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { - super(algorithm, rawCryptoBytes); - } - - public AsymmetricCiphertext(byte[] cryptoBytes) { - super(cryptoBytes); - } - - @Override - protected boolean support(short algorithm) { - return CryptoAlgorithm.isAsymmetricEncryptionAlgorithm(algorithm); - } - - @Override - public byte[] getRawCiphertext() { - return getRawCryptoBytes().getBytesCopy(); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricEncryptionFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricEncryptionFunction.java deleted file mode 100644 index fef57412..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricEncryptionFunction.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jd.blockchain.crypto; - -public interface AsymmetricEncryptionFunction extends AsymmetricKeypairGenerator, CryptoFunction { - - /** - * 加密; - * - * @param data - * @return - */ - Ciphertext encrypt(PubKey pubKey, byte[] data); - - /** - * 解密; - * - * @param privKey - * @param ciphertext - * @return - */ - byte[] decrypt(PrivKey privKey, Ciphertext ciphertext); - - /** - * 使用私钥恢复公钥; - * - * @param privKey PrivKey形式的私钥信息 - * @return PubKey形式的公钥信息 - */ - PubKey retrievePubKey(PrivKey privKey); - - /** - * 校验私钥格式是否满足要求; - * - * @param privKeyBytes 包含算法标识、密钥掩码和私钥的字节数组 - * @return 是否满足指定算法的私钥格式 - */ - boolean supportPrivKey(byte[] privKeyBytes); - - /** - * 将字节数组形式的私钥转换成PrivKey格式; - * - * @param privKeyBytes 包含算法标识和私钥的字节数组 - * @return PrivKey形式的私钥 - */ - PrivKey resolvePrivKey(byte[] privKeyBytes); - - /** - * 校验公钥格式是否满足要求; - * - * @param pubKeyBytes 包含算法标识、密钥掩码和公钥的字节数组 - * @return 是否满足指定算法的公钥格式 - */ - boolean supportPubKey(byte[] pubKeyBytes); - - /** - * 将字节数组形式的密钥转换成PubKey格式; - * - * @param pubKeyBytes 包含算法标识和公钥的字节数组 - * @return PubKey形式的公钥 - */ - PubKey resolvePubKey(byte[] pubKeyBytes); - - /** - * 校验密文格式是否满足要求; - * - * @param ciphertextBytes 包含算法标识和密文的字节数组 - * @return 是否满足指定算法的密文格式 - */ - boolean supportCiphertext(byte[] ciphertextBytes); - - /** - * 将字节数组形式的密文转换成AsymmetricCiphertext格式; - * - * @param ciphertextBytes 包含算法标识和密文的字节数组 - * @return AsymmetricCiphertext形式的签名摘要 - */ - AsymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricKeypair.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricKeypair.java deleted file mode 100644 index 7a454021..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricKeypair.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.crypto; - -/** - * 非对称密钥对; - * - * @author huanghaiquan - * - */ -public class AsymmetricKeypair { - - private PubKey pubKey; - - private PrivKey privKey; - - public short getAlgorithm() { - return pubKey.getAlgorithm(); - } - - public PubKey getPubKey() { - return pubKey; - } - - public PrivKey getPrivKey() { - return privKey; - } - - public AsymmetricKeypair(PubKey pubKey, PrivKey privKey) { - if (pubKey.getAlgorithm() != privKey.getAlgorithm()) { - throw new IllegalArgumentException("The algorithms of PubKey and PrivKey don't match!"); - } - this.pubKey = pubKey; - this.privKey = privKey; - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricKeypairGenerator.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricKeypairGenerator.java deleted file mode 100644 index 964ec048..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AsymmetricKeypairGenerator.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jd.blockchain.crypto; - -public interface AsymmetricKeypairGenerator { - - /** - * 返回密钥对; - */ - AsymmetricKeypair generateKeypair(); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoBytes.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoBytes.java deleted file mode 100644 index 9761e3db..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoBytes.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.util.Arrays; - -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesSlice; - -public abstract class BaseCryptoBytes extends Bytes implements CryptoBytes { - - private short algorithm; - - public BaseCryptoBytes() { - super(); - } - - public BaseCryptoBytes(short algorithm, byte[] rawCryptoBytes) { - super(CryptoBytesEncoding.encodeBytes(algorithm, rawCryptoBytes)); - this.algorithm = algorithm; - } - - public BaseCryptoBytes(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { - super(CryptoBytesEncoding.encodeBytes(algorithm, rawCryptoBytes)); - this.algorithm = algorithm.code(); - } - - public BaseCryptoBytes(byte[] cryptoBytes) { - super(cryptoBytes); - short algorithm = CryptoBytesEncoding.decodeAlgorithm(cryptoBytes); - if (!support(algorithm)) { - throw new CryptoException("Not supported algorithm [code:" + algorithm + "]!"); - } - this.algorithm = algorithm; - } - - protected abstract boolean support(short algorithm); - - protected byte[] resolveRawCryptoBytes(byte[] cryptoBytes) { - return Arrays.copyOfRange(cryptoBytes, 1, cryptoBytes.length); - } - - @Override - public short getAlgorithm() { - return algorithm; - } - - protected BytesSlice getRawCryptoBytes() { - return new BytesSlice(getDirectBytes(), CryptoAlgorithm.CODE_SIZE); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoKey.java deleted file mode 100644 index 95cfee3d..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoKey.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.io.Serializable; - -public abstract class BaseCryptoKey extends BaseCryptoBytes implements CryptoKey, Serializable { - - public static final int KEY_TYPE_BYTES = 1; - private static final long serialVersionUID = 4543074827807908363L; - - public BaseCryptoKey() { - super(); - } - - protected BaseCryptoKey(short algorithm, byte[] rawKeyBytes, CryptoKeyType keyType) { - super(algorithm, CryptoBytesEncoding.encodeKeyBytes(rawKeyBytes, keyType)); - } - - protected BaseCryptoKey(CryptoAlgorithm algorithm, byte[] rawKeyBytes, CryptoKeyType keyType) { - super(algorithm, CryptoBytesEncoding.encodeKeyBytes(rawKeyBytes, keyType)); - } - - public BaseCryptoKey(byte[] cryptoBytes) { - super(cryptoBytes); - CryptoKeyType keyType = CryptoBytesEncoding.decodeKeyType(getRawCryptoBytes()); - if (getKeyType() != keyType) { - throw new CryptoException("CryptoKey doesn't support keyType[" + keyType + "]!"); - } - } - - @Override - protected boolean support(short algorithm) { - return CryptoAlgorithm.hasAsymmetricKey(algorithm) || CryptoAlgorithm.hasSymmetricKey(algorithm); - } - - @Override - public byte[] getRawKeyBytes() { - return getRawCryptoBytes().getBytesCopy(1); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/Ciphertext.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/Ciphertext.java deleted file mode 100644 index 98b136dc..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/Ciphertext.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jd.blockchain.crypto; - -/** - * 密文; - * - * @author huanghaiquan - * - */ -public interface Ciphertext extends CryptoBytes { - - /** - * 原始的密文数据; - * - * @return - */ - byte[] getRawCiphertext(); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/Crypto.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/Crypto.java deleted file mode 100644 index 2bca057a..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/Crypto.java +++ /dev/null @@ -1,349 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jd.blockchain.provider.Provider; -import com.jd.blockchain.provider.ProviderManager; - -/** - * 密码服务提供者的管理器; - * - * @author huanghaiquan - * - */ -public final class Crypto { - - private static Logger LOGGER = LoggerFactory.getLogger(Crypto.class); - - private static Map functions = new ConcurrentHashMap<>(); - - private static Map algorithms = new ConcurrentHashMap<>(); - - private static Map names = new ConcurrentHashMap<>(); - - private static ProviderManager pm = new ProviderManager(); - - static { - loadDefaultProviders(); - } - - private static void loadDefaultProviders() { - ClassLoader cl = Crypto.class.getClassLoader(); - pm.installAllProviders(CryptoService.class, cl); - - Iterable> providers = pm.getAllProviders(CryptoService.class); - for (Provider provider : providers) { - register(provider); - } - } - - private static void register(Provider provider) { - for (CryptoFunction cryptoFunction : provider.getService().getFunctions()) { - - String name = cryptoFunction.getAlgorithm().name().toUpperCase(); - short code = cryptoFunction.getAlgorithm().code(); - CryptoAlgorithm algorithm = new CryptoAlgorithmDefinition(name, code); - if (CryptoAlgorithm.isRandomAlgorithm(algorithm) && !(cryptoFunction instanceof RandomFunction)) { - LOGGER.error(String.format( - "The random algorithm \"%s\" declared by provider[%s] does not implement the interface \"%s\"!", - algorithm.toString(), provider.getFullName(), RandomFunction.class.getName())); - continue; - } - if (CryptoAlgorithm.isAsymmetricEncryptionAlgorithm(algorithm) - && !(cryptoFunction instanceof AsymmetricEncryptionFunction)) { - LOGGER.error(String.format( - "The asymmetric encryption algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", - algorithm.toString(), provider.getFullName(), AsymmetricEncryptionFunction.class.getName())); - continue; - } - if (CryptoAlgorithm.isSignatureAlgorithm(algorithm) && !(cryptoFunction instanceof SignatureFunction)) { - LOGGER.error(String.format( - "The signature algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", - algorithm.toString(), provider.getFullName(), SignatureFunction.class.getName())); - continue; - } - if (CryptoAlgorithm.isSymmetricEncryptionAlgorithm(algorithm) - && !(cryptoFunction instanceof SymmetricEncryptionFunction)) { - LOGGER.error(String.format( - "The symmetric encryption algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", - algorithm.toString(), provider.getFullName(), SymmetricEncryptionFunction.class.getName())); - continue; - } - if (CryptoAlgorithm.isHashAlgorithm(algorithm) && !(cryptoFunction instanceof HashFunction)) { - LOGGER.error(String.format( - "The hash encryption algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", - algorithm.toString(), provider.getFullName(), HashFunction.class.getName())); - continue; - } - if (CryptoAlgorithm.isExtAlgorithm(algorithm) && (cryptoFunction instanceof RandomFunction - || cryptoFunction instanceof AsymmetricEncryptionFunction - || cryptoFunction instanceof SignatureFunction - || cryptoFunction instanceof SymmetricEncryptionFunction - || cryptoFunction instanceof HashFunction)) { - LOGGER.error(String.format( - "The ext algorithm \"%s\" declared by the provider[%s] can not implement the standard algorithm interface!", - algorithm.toString(), provider.getFullName())); - continue; - } - - if (functions.containsKey(algorithm.code()) || names.containsKey(algorithm.name())) { - LOGGER.error(String.format("The algorithm \"%s\" declared by the provider[%s] already exists!", - algorithm.toString(), provider.getFullName())); - continue; - } - - functions.put(algorithm.code(), cryptoFunction); - algorithms.put(algorithm.code(), algorithm); - names.put(algorithm.name(), algorithm.code()); - } - } - - private Crypto() { - } - - public static CryptoProvider[] getProviders() { - Collection> providers = pm.getAllProviders(CryptoService.class); - CryptoProvider[] infos = new CryptoProvider[providers.size()]; - - int i = 0; - for (Provider pd : providers) { - CryptoProviderInfo info = getProviderInfo(pd); - infos[i] = info; - } - - return infos; - } - - private static CryptoProviderInfo getProviderInfo(Provider pd) { - Collection functions = pd.getService().getFunctions(); - CryptoAlgorithm[] algorithms = new CryptoAlgorithm[functions.size()]; - int i = 0; - for (CryptoFunction function : functions) { - algorithms[i] = function.getAlgorithm(); - i++; - } - return new CryptoProviderInfo(pd.getFullName(), algorithms); - } - - /** - * 返回指定名称的密码服务提供者;如果不存在,则返回 null ; - * - * @param providerFullName - * @return - */ - public static CryptoProvider getProvider(String providerFullName) { - Provider pd = pm.getProvider(CryptoService.class, providerFullName); - if (pd == null) { - throw new CryptoException("Crypto service provider named [" + providerFullName + "] does not exist!"); - } - return getProviderInfo(pd); - } - - public static Collection getAllAlgorithms() { - return algorithms.values(); - } - - /** - * 返回指定编码的算法;
- * 如果不存在,则返回 null; - * - * @param code - * @return - */ - public static CryptoAlgorithm getAlgorithm(short code) { - return algorithms.get(code); - } - - /** - * Return the CryptoAlogrithm object of the specified name ,or null if none; - * - * @param name - * @return - */ - public static CryptoAlgorithm getAlgorithm(String name) { - Short code = names.get(name.toUpperCase()); - return code == null ? null : algorithms.get(code); - } - - public static RandomFunction getRandomFunction(short algorithmCode) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmCode); - if (algorithm == null) { - throw new CryptoException("Algorithm [code:" + algorithmCode + "] has no service provider!"); - } - return getRandomFunction(algorithm); - } - - public static RandomFunction getRandomFunction(String algorithmName) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmName); - if (algorithm == null) { - throw new CryptoException("Algorithm " + algorithmName + " has no service provider!"); - } - return getRandomFunction(algorithm); - } - - public static RandomFunction getRandomFunction(CryptoAlgorithm algorithm) { - if (!CryptoAlgorithm.isRandomAlgorithm(algorithm)) { - throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() - + "] is not a random function!"); - } - CryptoFunction func = functions.get(algorithm.code()); - if (func == null) { - throw new CryptoException( - "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); - } - - return (RandomFunction) func; - } - - public static HashFunction getHashFunction(short algorithmCode) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmCode); - if (algorithm == null) { - throw new CryptoException("Algorithm [code:" + algorithmCode + "] has no service provider!"); - } - return getHashFunction(algorithm); - } - - public static HashFunction getHashFunction(String algorithmName) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmName); - if (algorithm == null) { - throw new CryptoException("Algorithm " + algorithmName + " has no service provider!"); - } - return getHashFunction(algorithm); - } - - public static HashFunction getHashFunction(CryptoAlgorithm algorithm) { - if (!CryptoAlgorithm.isHashAlgorithm(algorithm)) { - throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() - + "] is not a hash function!"); - } - CryptoFunction func = functions.get(algorithm.code()); - if (func == null) { - throw new CryptoException( - "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); - } - - return (HashFunction) func; - } - - public static AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(short algorithmCode) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmCode); - if (algorithm == null) { - throw new CryptoException("Algorithm [code:" + algorithmCode + "] has no service provider!"); - } - return getAsymmetricEncryptionFunction(algorithm); - } - - public static AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(String algorithmName) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmName); - if (algorithm == null) { - throw new CryptoException("Algorithm " + algorithmName + " has no service provider!"); - } - return getAsymmetricEncryptionFunction(algorithm); - } - - public static AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(CryptoAlgorithm algorithm) { - if (!CryptoAlgorithm.isAsymmetricEncryptionAlgorithm(algorithm)) { - throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() - + "] is not a asymmetric encryption function!"); - } - CryptoFunction func = functions.get(algorithm.code()); - if (func == null) { - throw new CryptoException( - "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); - } - - return (AsymmetricEncryptionFunction) func; - } - - public static SignatureFunction getSignatureFunction(Short algorithmCode) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmCode); - if (algorithm == null) { - throw new CryptoException("Algorithm [code:" + algorithmCode + "] has no service provider!"); - } - return getSignatureFunction(algorithm); - } - - public static SignatureFunction getSignatureFunction(String algorithmName) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmName); - if (algorithm == null) { - throw new CryptoException("Algorithm " + algorithmName + " has no service provider!"); - } - return getSignatureFunction(algorithm); - } - - public static SignatureFunction getSignatureFunction(CryptoAlgorithm algorithm) { - if (!CryptoAlgorithm.isSignatureAlgorithm(algorithm)) { - throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() - + "] is not a signature function!"); - } - CryptoFunction func = functions.get(algorithm.code()); - if (func == null) { - throw new CryptoException( - "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); - } - - return (SignatureFunction) func; - } - - public static SymmetricEncryptionFunction getSymmetricEncryptionFunction(short algorithmCode) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmCode); - if (algorithm == null) { - throw new CryptoException("Algorithm [code:" + algorithmCode + "] has no service provider!"); - } - return getSymmetricEncryptionFunction(algorithm); - } - - public static SymmetricEncryptionFunction getSymmetricEncryptionFunction(String algorithmName) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmName); - if (algorithm == null) { - throw new CryptoException("Algorithm " + algorithmName + " has no service provider!"); - } - return getSymmetricEncryptionFunction(algorithm); - } - - public static SymmetricEncryptionFunction getSymmetricEncryptionFunction(CryptoAlgorithm algorithm) { - if (!CryptoAlgorithm.isSymmetricEncryptionAlgorithm(algorithm)) { - throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() - + "] is not a symmetric encryption function!"); - } - CryptoFunction func = functions.get(algorithm.code()); - if (func == null) { - throw new CryptoException( - "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); - } - - return (SymmetricEncryptionFunction) func; - } - - public static CryptoFunction getCryptoFunction(short algorithmCode) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmCode); - if (algorithm == null) { - throw new CryptoException("Algorithm [code:" + algorithmCode + "] has no service provider!"); - } - return getCryptoFunction(algorithm); - } - - public static CryptoFunction getCryptoFunction(String algorithmName) { - CryptoAlgorithm algorithm = getAlgorithm(algorithmName); - if (algorithm == null) { - throw new CryptoException("Algorithm " + algorithmName + " has no service provider!"); - } - return getCryptoFunction(algorithm); - } - - public static CryptoFunction getCryptoFunction(CryptoAlgorithm algorithm) { - CryptoFunction func = functions.get(algorithm.code()); - if (func == null) { - throw new CryptoException( - "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); - } - - return func; - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm.java deleted file mode 100644 index b501626f..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.io.InputStream; -import java.io.OutputStream; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.io.BytesUtils; - -@DataContract(code = DataCodes.CRYPTO_ALGORITHM) -public interface CryptoAlgorithm { - - /** - * 随机数算法标识; - */ - static final int RANDOM_ALGORITHM = 0x1000; - - /** - * 哈希数算法标识; - */ - static final int HASH_ALGORITHM = 0x2000; - - /** - * 签名算法标识; - */ - static final int SIGNATURE_ALGORITHM = 0x4000; - - /** - * 加密算法标识; - */ - static final int ENCRYPTION_ALGORITHM = 0x8000; - - /** - * 扩展密码算法标识;
- * 表示除了 - * {@link #RANDOM_ALGORITHM}、{@link #HASH_ALGORITHM}、{@link #SIGNATURE_ALGORITHM}、{@link #ENCRYPTION_ALGORITHM} - * 之外的其它非标准分类的密码算法,诸如加法同态算法、多方求和算法等; - */ - static final int EXT_ALGORITHM = 0x0000; - - /** - * 非对称密钥标识; - */ - static final int ASYMMETRIC_KEY = 0x0100; - - /** - * 对称密钥标识; - */ - static final int SYMMETRIC_KEY = 0x0200; - - /** - * 算法编码的字节长度;等同于 {@link #getCodeBytes(CryptoAlgorithm)} 返回的字节数组的长度; - */ - static final int CODE_SIZE = 2; - - /** - * 密码算法的唯一编码; - *

- * 长度16位,高4位标识算法类型(包括: {@link #RANDOM_ALGORITHM}, {@link #HASH_ALGORITHM}, - * {@link #SIGNATURE_ALGORITHM}, {@link #ENCRYPTION_ALGORITHM}, - * {@link #EXT_ALGORITHM}) 5 种); 接下来4位标识密钥类型(包括:{@link #SYMMETRIC_KEY}, - * {@link #ASYMMETRIC_KEY}); 最后8位是算法唯一ID; - */ - @DataField(order = 0, primitiveType = PrimitiveType.INT16) - short code(); - - /** - * 算法名称; - *

- * - * 实现者应该遵循“英文字符大写”的命名规范,并确保唯一性;
- * 例如,sha256 和 SHA256 将被视为相同的名称; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.TEXT) - String name(); - - - public static String getString(CryptoAlgorithm algorithm) { - return String.format("%s[%s]", algorithm.name(), (algorithm.code() & 0xFFFF)); - } - - /** - * - * @return - */ - static byte[] getCodeBytes(CryptoAlgorithm algorithm) { - return BytesUtils.toBytes(algorithm.code()); - } - - static short resolveCode(byte[] codeBytes) { - return BytesUtils.toShort(codeBytes, 0); - } - - static short resolveCode(byte[] codeBytes, int offset) { - return BytesUtils.toShort(codeBytes, offset); - } - - static short resolveCode(InputStream in) { - return BytesUtils.readShort(in); - } - - static int writeCode(short code, OutputStream out) { - return BytesUtils.writeShort(code, out); - } - - static boolean match(CryptoAlgorithm algorithm, byte[] algorithmBytes) { - return algorithm.code() == BytesUtils.toShort(algorithmBytes, 0); - } - - static boolean match(CryptoAlgorithm algorithm, byte[] algorithmBytes, int offset) { - return algorithm.code() == BytesUtils.toShort(algorithmBytes, offset); - } - - /** - * 是否属于随机数算法; - * - * @return - */ - static boolean isRandomAlgorithm(CryptoAlgorithm algorithm) { - return RANDOM_ALGORITHM == (algorithm.code() & RANDOM_ALGORITHM); - } - - /** - * 是否属于摘要算法; - * - * @return - */ - static boolean isHashAlgorithm(CryptoAlgorithm algorithm) { - return HASH_ALGORITHM == (algorithm.code() & HASH_ALGORITHM); - } - - /** - * 是否属于摘要算法; - * - * @return - */ - static boolean isHashAlgorithm(short algorithm) { - return HASH_ALGORITHM == (algorithm & HASH_ALGORITHM); - } - - /** - * 是否属于签名算法; - * - * @return - */ - static boolean isSignatureAlgorithm(short algorithm) { - return SIGNATURE_ALGORITHM == (algorithm & SIGNATURE_ALGORITHM); - } - - /** - * 是否属于签名算法; - * - * @return - */ - static boolean isSignatureAlgorithm(CryptoAlgorithm algorithm) { - return SIGNATURE_ALGORITHM == (algorithm.code() & SIGNATURE_ALGORITHM); - } - - /** - * 是否属于加密算法; - * - * @return - */ - static boolean isEncryptionAlgorithm(short algorithm) { - return ENCRYPTION_ALGORITHM == (algorithm & ENCRYPTION_ALGORITHM); - } - - /** - * 是否属于加密算法; - * - * @return - */ - static boolean isEncryptionAlgorithm(CryptoAlgorithm algorithm) { - return ENCRYPTION_ALGORITHM == (algorithm.code() & ENCRYPTION_ALGORITHM); - } - - /** - * 是否属于扩展密码算法; - * - * @return - */ - static boolean isExtAlgorithm(CryptoAlgorithm algorithm) { - return EXT_ALGORITHM == (algorithm.code() & 0xF000); - } - - /** - * 算法是否包含非对称密钥; - * - * @return - */ - static boolean hasAsymmetricKey(short algorithm) { - return ASYMMETRIC_KEY == (algorithm & ASYMMETRIC_KEY); - } - - /** - * 算法是否包含非对称密钥; - * - * @return - */ - static boolean hasAsymmetricKey(CryptoAlgorithm algorithm) { - return ASYMMETRIC_KEY == (algorithm.code() & ASYMMETRIC_KEY); - } - - /** - * 算法是否包含对称密钥; - * - * @return - */ - static boolean hasSymmetricKey(short algorithm) { - return SYMMETRIC_KEY == (algorithm & SYMMETRIC_KEY); - } - - /** - * 算法是否包含对称密钥; - * - * @return - */ - static boolean hasSymmetricKey(CryptoAlgorithm algorithm) { - return SYMMETRIC_KEY == (algorithm.code() & SYMMETRIC_KEY); - } - - /** - * 是否属于对称加密算法; - * - * @param algorithm - * @return - */ - static boolean isSymmetricEncryptionAlgorithm(CryptoAlgorithm algorithm) { - return isEncryptionAlgorithm(algorithm) && hasSymmetricKey(algorithm); - } - - /** - * 是否属于非对称加密算法; - * - * @param algorithm - * @return - */ - static boolean isAsymmetricEncryptionAlgorithm(short algorithm) { - return isEncryptionAlgorithm(algorithm) && hasAsymmetricKey(algorithm); - } - - /** - * 是否属于非对称加密算法; - * - * @param algorithm - * @return - */ - static boolean isAsymmetricEncryptionAlgorithm(CryptoAlgorithm algorithm) { - return isEncryptionAlgorithm(algorithm) && hasAsymmetricKey(algorithm); - } - - static boolean equals(CryptoAlgorithm algorithm1, CryptoAlgorithm algorithm2) { - return algorithm1.code() == algorithm2.code(); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmDefinition.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmDefinition.java deleted file mode 100644 index 4e9f94b0..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmDefinition.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.jd.blockchain.crypto; - -public final class CryptoAlgorithmDefinition implements CryptoAlgorithm { - - private short code; - - private String name; - - CryptoAlgorithmDefinition(String name, short code) { - this.code = code; - this.name = name; - } - - @Override - public short code() { - return this.code; - } - - @Override - public String name() { - return name; - } - - @Override - public String toString() { - return CryptoAlgorithm.getString(this); - } - - /** - * 声明一项哈希算法; - * - * @param name 算法名称; - * @param uid 算法ID;需要在同类算法中保持唯一性; - * @return - */ - public static CryptoAlgorithm defineHash(String name, byte uid) { - short code = (short) (HASH_ALGORITHM | (uid & 0x00FF)); - return new CryptoAlgorithmDefinition(name, code); - } - - /** - * 声明一项非对称密码算法; - * - * @param name 算法名称; - * @param uid 算法ID;需要在同类算法中保持唯一性; - * @return - */ - public static CryptoAlgorithm defineSignature(String name, boolean encryptable, byte uid) { - short code; - if (encryptable) { - code = (short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | (uid & 0x00FF)); - } else { - code = (short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | (uid & 0x00FF)); - } - return new CryptoAlgorithmDefinition(name, code); - } - - /** - * 声明一项非对称加密算法; - * - * @param name 算法名称; - * @param uid 算法ID;需要在同类算法中保持唯一性; - * @return - */ - public static CryptoAlgorithm defineAsymmetricEncryption(String name, byte uid) { - short code = (short) (ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | (uid & 0x00FF)); - return new CryptoAlgorithmDefinition(name, code); - } - - /** - * 声明一项对称密码算法; - * - * @param name 算法名称; - * @param uid 算法ID;需要在同类算法中保持唯一性; - * @return - */ - public static CryptoAlgorithm defineSymmetricEncryption(String name, byte uid) { - short code = (short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | (uid & 0x00FF)); - return new CryptoAlgorithmDefinition(name, code); - } - - /** - * 声明一项随机数算法; - * - * @param name 算法名称; - * @param uid 算法ID;需要在同类算法中保持唯一性; - * @return - */ - public static CryptoAlgorithm defineRandom(String name, byte uid) { - short code = (short) (RANDOM_ALGORITHM | (uid & 0x00FF)); - return new CryptoAlgorithmDefinition(name, code); - } - - /** - * 声明一项扩展的密码算法; - * - * @param name 算法名称; - * @param uid 算法ID;需要在同类算法中保持唯一性; - * @return - */ - public static CryptoAlgorithm definExt(String name, byte uid) { - short code = (short) (EXT_ALGORITHM | (uid & 0x00FF)); - return new CryptoAlgorithmDefinition(name, code); - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytes.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytes.java deleted file mode 100644 index 6397f1f3..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytes.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jd.blockchain.crypto; - -import com.jd.blockchain.utils.io.BytesSerializable; - -/** - * {@link CryptoBytes} 表示与特定密码算法相关的编码数据; - * - * @author huanghaiquan - * - */ -public interface CryptoBytes extends BytesSerializable { - - /** - * 算法标识符的长度; - */ - int ALGORYTHM_CODE_SIZE = CryptoAlgorithm.CODE_SIZE; - - /** - * 算法; - * - * @return - */ - short getAlgorithm(); - - /** - * 返回编码后的摘要信息;
- * - * 这是算法标识 {@link #getAlgorithm()} 与原始的摘要数据 - * 按照特定的编码方式合并后的结果; - */ - @Override - byte[] toBytes(); - - - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytesEncoding.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytesEncoding.java deleted file mode 100644 index 9bfd4567..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytesEncoding.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jd.blockchain.crypto; - -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public final class CryptoBytesEncoding { - - static byte[] encodeBytes(short algorithm, byte[] rawCryptoBytes) { - return BytesUtils.concat(BytesUtils.toBytes(algorithm), rawCryptoBytes); - } - - static byte[] encodeBytes(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { - return BytesUtils.concat(CryptoAlgorithm.getCodeBytes(algorithm), rawCryptoBytes); - } - - public static short decodeAlgorithm(byte[] cryptoBytes) { - return CryptoAlgorithm.resolveCode(cryptoBytes); - } - - static byte[] encodeKeyBytes(byte[] rawKeyBytes, CryptoKeyType keyType) { - return BytesUtils.concat(new byte[] { keyType.CODE }, rawKeyBytes); - } - - static CryptoKeyType decodeKeyType(BytesSlice cryptoBytes) { - return CryptoKeyType.valueOf(cryptoBytes.getByte()); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoDigest.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoDigest.java deleted file mode 100644 index da7e9e07..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoDigest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jd.blockchain.crypto; - -/** - * 摘要; - * - * @author huanghaiquan - * - */ -public interface CryptoDigest extends CryptoBytes { - - /** - * 原始的摘要数据; - * - * @return - */ - byte[] getRawDigest(); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoException.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoException.java deleted file mode 100644 index f4daf036..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoException.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.crypto; - -public class CryptoException extends RuntimeException { - - private static final long serialVersionUID = 1044893802336696205L; - - - public CryptoException(String message) { - super(message); - } - - public CryptoException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoFunction.java deleted file mode 100644 index bbade357..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoFunction.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.crypto; - -/** - * CryptoFunction represents the cryptographic function of a particular - * algorithm; - * - * @author huanghaiquan - * - */ -public interface CryptoFunction { - - /** - * The cryptographic algorithm supported by this CryptoFunction; - * - * @return - */ - CryptoAlgorithm getAlgorithm(); - -// /** -// * Resolve ciphertext from byte array to CyptoBytes object, and check if its -// * algorithm matches this function. -// * -// * @param bytes -// * ciphertext -// * @return Return {@link CryptoBytes} object, or throw {@link CryptoException} -// * if its algorithm does not match. -// */ -// CryptoBytes resolveCryptoBytes(byte[] bytes); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyType.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyType.java deleted file mode 100644 index 2416e815..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyType.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jd.blockchain.crypto; - -public enum CryptoKeyType { - - /** - * 非对称密钥的公钥 - */ - PUBLIC((byte)0x01), - - /** - * 非对称密钥的私钥; - */ - PRIVATE((byte)0x02), - - /** - * 对称密钥; - */ - SYMMETRIC((byte)0x03); - - public final byte CODE; - - CryptoKeyType(byte code) { - CODE = code; - } - - public static CryptoKeyType valueOf(byte code) { - for (CryptoKeyType alg : CryptoKeyType.values()) { - if (alg.CODE == code) { - return alg; - } - } - throw new CryptoException("CryptoKeyType doesn't support enum code[" + code + "]!"); - } - - public byte getCODE() { - return CODE; - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoProvider.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoProvider.java deleted file mode 100644 index 57b06831..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoProvider.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.crypto; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code = DataCodes.METADATA_CRYPTO_SETTING_PROVIDER) -public interface CryptoProvider { - - @DataField(order = 0, primitiveType = PrimitiveType.TEXT) - String getName(); - - @DataField(order = 1, list = true, refContract = true) - CryptoAlgorithm[] getAlgorithms(); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoProviderInfo.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoProviderInfo.java deleted file mode 100644 index b0b17231..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoProviderInfo.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.crypto; - -class CryptoProviderInfo implements CryptoProvider { - - private String name; - - private CryptoAlgorithm[] algorithms; - - public CryptoProviderInfo(String name, CryptoAlgorithm[] algorithms) { - this.name = name; - this.algorithms = algorithms; - } - - @Override - public String getName() { - return name; - } - - @Override - public CryptoAlgorithm[] getAlgorithms() { - return algorithms.clone(); - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoService.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoService.java deleted file mode 100644 index 4a835a83..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.util.Collection; - -public interface CryptoService { - - Collection getFunctions(); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoUtils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoUtils.java deleted file mode 100644 index 5bea9f61..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoUtils.java +++ /dev/null @@ -1,73 +0,0 @@ -//package com.jd.blockchain.crypto; -// -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -// -//import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; -//import com.jd.blockchain.crypto.asymmetric.AsymmetricEncryptionFunction; -//import com.jd.blockchain.crypto.asymmetric.SignatureFunction; -//import com.jd.blockchain.crypto.hash.HashCryptography; -//import com.jd.blockchain.crypto.hash.HashFunction; -//import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; -//import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; -// -//public class CryptoUtils { -// -// private static Logger LOGGER = LoggerFactory.getLogger(CryptoUtils.class); -// -// private static final Object MUTEX = new Object(); -// -// private static final String STD = "com.jd.blockchain.crypto.impl.CryptoFactoryImpl"; -// -// private static volatile CryptoFactory STD_FACTORY; -// -// public static CryptoFactory crypto() { -// if (STD_FACTORY == null) { -// synchronized (MUTEX) { -// if (STD_FACTORY == null) { -// try { -// Class stdFactoryClass = Class.forName(STD); -// STD_FACTORY = (CryptoFactory) stdFactoryClass.newInstance(); -// } catch (ClassNotFoundException e) { -// LOGGER.error("STD crypto provider is not found!", e); -// throw new CryptoException("STD crypto provider is not found!", e); -// } catch (InstantiationException | IllegalAccessException e) { -// LOGGER.error("Fail to init STD crypto provider!", e); -// throw new CryptoException("Fail to init STD crypto provider!", e); -// } -// } -// return STD_FACTORY; -// } -// } -// return STD_FACTORY; -// } -// -// public static HashCryptography hashCrypto() { -// return crypto().hashCryptography(); -// } -// -// public static HashFunction hash(CryptoAlgorithm alg) { -// return hashCrypto().getFunction(alg); -// } -// -// public static AsymmetricCryptography asymmCrypto() { -// return crypto().asymmetricCryptography(); -// } -// -// public static SignatureFunction sign(CryptoAlgorithm alg) { -// return asymmCrypto().getSignatureFunction(alg); -// } -// -// public static AsymmetricEncryptionFunction asymmEncrypt(CryptoAlgorithm alg) { -// return asymmCrypto().getAsymmetricEncryptionFunction(alg); -// } -// -// public static SymmetricCryptography symmCrypto() { -// return crypto().symmetricCryptography(); -// } -// -// public static SymmetricEncryptionFunction symmEncrypt(CryptoAlgorithm alg) { -// return symmCrypto().getSymmetricEncryptionFunction(alg); -// } -// -//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/HashDigest.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/HashDigest.java deleted file mode 100644 index 761dfb9e..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/HashDigest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.io.Serializable; - -public class HashDigest extends BaseCryptoBytes implements CryptoDigest,Serializable { - - private static final long serialVersionUID = 693895170514236428L; - - public HashDigest(CryptoAlgorithm algorithm, byte[] rawDigestBytes) { - super(algorithm, rawDigestBytes); - } - - public HashDigest() { - super(); - } - - public HashDigest(byte[] cryptoBytes) { - super(cryptoBytes); - } - - @Override - protected boolean support(short algorithm) { - return CryptoAlgorithm.isHashAlgorithm(algorithm); - } - - @Override - public byte[] getRawDigest() { - return getRawCryptoBytes().getBytesCopy(); - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/HashFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/HashFunction.java deleted file mode 100644 index 26afa778..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/HashFunction.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jd.blockchain.crypto; - -public interface HashFunction extends CryptoFunction { - - /** - * 计算指定数据的 hash; - * - * @param data - * @return - */ - HashDigest hash(byte[] data); - - /** - * 计算指定数据的 hash; - * - * @param data - * @return - */ - HashDigest hash(byte[] data, int offset, int len); - - - /** - * 校验 hash 摘要与指定的数据是否匹配; - * - * @param digest - * @param data - * @return - */ - boolean verify(HashDigest digest, byte[] data); - - /** - * 校验字节数组形式的hash摘要的格式是否满足要求; - * - * @param digestBytes 包含算法标识和hash摘要的字节数组 - * @return 是否满足指定算法的hash摘要格式 - */ - boolean supportHashDigest(byte[] digestBytes); - - /** - * 将字节数组形式的hash摘要转换成HashDigest格式; - * - * @param digestBytes 包含算法标识和hash摘要的字节数组 - * @return HashDigest形式的hash摘要 - */ - HashDigest resolveHashDigest(byte[] digestBytes); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/KeyGenUtils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/KeyGenUtils.java deleted file mode 100644 index 717c813c..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/KeyGenUtils.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.util.Arrays; - -import javax.crypto.SecretKey; - -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.security.AESUtils; -import com.jd.blockchain.utils.security.DecryptionException; -import com.jd.blockchain.utils.security.ShaUtils; - -public class KeyGenUtils { - - private static final byte[] PUB_KEY_FILE_MAGICNUM = { (byte) 0xFF, 112, 117, 98 }; - - private static final byte[] PRIV_KEY_FILE_MAGICNUM = { (byte) 0x00, 112, 114, 118 }; - - /** - * 公钥编码输出为 Base58 字符; - * - * @param pubKey - * @return - */ - public static String encodePubKey(PubKey pubKey) { - byte[] pubKeyBytes = BytesUtils.concat(PUB_KEY_FILE_MAGICNUM, pubKey.toBytes()); - String base58PubKey = Base58Utils.encode(pubKeyBytes); - return base58PubKey; - } - - public static PubKey decodePubKey(String base58PubKey) { - byte[] keyBytes = Base58Utils.decode(base58PubKey); - return decodePubKey(keyBytes); - } - - public static String encodePrivKey(PrivKey privKey, String base58Pwd) { - byte[] pwdBytes = Base58Utils.decode(base58Pwd); - return encodePrivKey(privKey, pwdBytes); - } - - public static String encodePrivKey(PrivKey privKey, byte[] pwdBytes) { - byte[] encodedPrivKeyBytes = encryptPrivKey(privKey, pwdBytes); - String base58PrivKey = Base58Utils.encode(encodedPrivKeyBytes); - return base58PrivKey; - } - - public static byte[] encryptPrivKey(PrivKey privKey, byte[] pwdBytes) { - SecretKey userKey = AESUtils.generateKey128(pwdBytes); - byte[] encryptedPrivKeyBytes = AESUtils.encrypt(privKey.toBytes(), userKey); - return BytesUtils.concat(PRIV_KEY_FILE_MAGICNUM, encryptedPrivKeyBytes); - } - - /** - * @param encodedPubKeyBytes - * @return - */ - private static PubKey decodePubKeyBytes(byte[] encodedPubKeyBytes) { - byte[] pubKeyBytes = Arrays.copyOfRange(encodedPubKeyBytes, PUB_KEY_FILE_MAGICNUM.length, - encodedPubKeyBytes.length); - return new PubKey(pubKeyBytes); - } - - public static PrivKey decryptedPrivKeyBytes(byte[] encodedPrivKeyBytes, byte[] pwdBytes) { - // Read privKye; - SecretKey userKey = AESUtils.generateKey128(pwdBytes); - byte[] encryptedKeyBytes = Arrays.copyOfRange(encodedPrivKeyBytes, PRIV_KEY_FILE_MAGICNUM.length, - encodedPrivKeyBytes.length); - try { - byte[] plainKeyBytes = AESUtils.decrypt(encryptedKeyBytes, userKey); - return new PrivKey(plainKeyBytes); - } catch (DecryptionException e) { - throw new DecryptionException("Invalid password!", e); - } - } - - public static PubKey readPubKey(String keyFile) { - String base58KeyString = FileUtils.readText(keyFile); - return decodePubKey(base58KeyString); - } - - /** - * 解码公钥; - * - * @param encodedPubKeyBytes 从公钥; - * @return - */ - public static PubKey decodePubKey(byte[] encodedPubKeyBytes) { - if (BytesUtils.startsWith(encodedPubKeyBytes, PUB_KEY_FILE_MAGICNUM)) { - // Read pubKey; - return decodePubKeyBytes(encodedPubKeyBytes); - } - - throw new IllegalArgumentException("The specified bytes is not valid PubKey generated by the KeyGen tool!"); - } - - /** - * 从控制台读取加密口令,以二进制数组形式返回原始口令的一次SHA256的结果; - * - * @return - */ - public static byte[] readPassword() { - byte[] pwdBytes = ConsoleUtils.readPassword(); - return ShaUtils.hash_256(pwdBytes); - } - - /** - * 对指定的原始密码进行编码生成用于加解密的密码; - * - * @param rawPassword - * @return - */ - public static byte[] encodePassword(String rawPassword) { - byte[] pwdBytes = BytesUtils.toBytes(rawPassword, "UTF-8"); - return ShaUtils.hash_256(pwdBytes); - } - - /** - * 对指定的原始密码进行编码生成用于加解密的密码; - * - * @param rawPassword - * @return - */ - public static String encodePasswordAsBase58(String rawPassword) { - return Base58Utils.encode(encodePassword(rawPassword)); - } - - /** - * 从控制台读取加密口令,以Base58字符串形式返回口令的一次SHA256的结果; - * - * @return - */ - public static String readPasswordString() { - return Base58Utils.encode(readPassword()); - } - - public static PrivKey readPrivKey(String keyFile, String base58Pwd) { - return readPrivKey(keyFile, Base58Utils.decode(base58Pwd)); - } - - /** - * 从文件读取私钥; - * - * @param keyFile - * @param pwdBytes - * @return - */ - public static PrivKey readPrivKey(String keyFile, byte[] pwdBytes) { - String base58KeyString = FileUtils.readText(keyFile); - byte[] keyBytes = Base58Utils.decode(base58KeyString); - if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { - throw new IllegalArgumentException("The specified file is not a private key file!"); - } - return decryptedPrivKeyBytes(keyBytes, pwdBytes); - } - - public static PrivKey decodePrivKey(String base58Key, String base58Pwd) { - byte[] decryptedKey = Base58Utils.decode(base58Pwd); - return decodePrivKey(base58Key, decryptedKey); - } - - public static PrivKey decodePrivKey(String base58Key, byte[] pwdBytes) { - byte[] keyBytes = Base58Utils.decode(base58Key); - if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { - throw new IllegalArgumentException("The specified file is not a private key file!"); - } - return decryptedPrivKeyBytes(keyBytes, pwdBytes); - } - - public static PrivKey decodePrivKeyWithRawPassword(String base58Key, String rawPassword) { - byte[] pwdBytes = encodePassword(rawPassword); - byte[] keyBytes = Base58Utils.decode(base58Key); - if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { - throw new IllegalArgumentException("The specified file is not a private key file!"); - } - return decryptedPrivKeyBytes(keyBytes, pwdBytes); - } - - public static boolean isPubKeyBytes(byte[] keyBytes) { - return BytesUtils.startsWith(keyBytes, PUB_KEY_FILE_MAGICNUM); - } - - public static boolean isPrivKeyBytes(byte[] keyBytes) { - return BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PubKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PubKey.java deleted file mode 100644 index 3d59dd3a..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PubKey.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.crypto; - -/** - * 公钥; - * - * @author huanghaiquan - * - */ -public class PubKey extends BaseCryptoKey { - - private static final long serialVersionUID = -2055071197736385328L; - - public PubKey() { - super(); - } - - public PubKey(short algorithm, byte[] rawCryptoBytes) { - super(algorithm, rawCryptoBytes, CryptoKeyType.PUBLIC); - } - - public PubKey(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { - super(algorithm, rawCryptoBytes, CryptoKeyType.PUBLIC); - } - - public PubKey(byte[] cryptoBytes) { - super(cryptoBytes); - } - - @Override - public CryptoKeyType getKeyType() { - return CryptoKeyType.PUBLIC; - } -} \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomFunction.java deleted file mode 100644 index a4aa748c..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomFunction.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jd.blockchain.crypto; - -public interface RandomFunction extends CryptoFunction { - - RandomGenerator generate(byte[] seed); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomGenerator.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomGenerator.java deleted file mode 100644 index 92421570..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomGenerator.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.crypto; - -public interface RandomGenerator { - - byte[] nextBytes(int size); - - void nextBytes(byte[] buffer); - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SignatureDigest.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SignatureDigest.java deleted file mode 100644 index f4164931..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SignatureDigest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.crypto; - -public class SignatureDigest extends BaseCryptoBytes implements CryptoDigest { - public SignatureDigest() { - super(); - } - - public SignatureDigest(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { - super(algorithm, rawCryptoBytes); - } - - public SignatureDigest(byte[] cryptoBytes) { - super(cryptoBytes); - } - - @Override - protected boolean support(short algorithm) { - return CryptoAlgorithm.isSignatureAlgorithm(algorithm); - } - - /** - * 返回原始签名摘要; - * - * @return - */ - @Override - public byte[] getRawDigest() { - return getRawCryptoBytes().getBytesCopy(); - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SignatureFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SignatureFunction.java deleted file mode 100644 index f1978424..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SignatureFunction.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jd.blockchain.crypto; - -public interface SignatureFunction extends AsymmetricKeypairGenerator, CryptoFunction { - - /** - * 计算指定数据的 hash; - * - * @param data 被签名消息 - * @return SignatureDigest形式的签名摘要 - */ - SignatureDigest sign(PrivKey privKey, byte[] data); - - /** - * 校验签名摘要和数据是否一致; - * - * @param digest 待验证的签名摘要 - * @param data 被签名信息 - * @return 是否验证通过 - */ - boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data); - - /** - * 使用私钥恢复公钥; - * - * @param privKey PrivKey形式的私钥信息 - * @return PubKey形式的公钥信息 - */ - PubKey retrievePubKey(PrivKey privKey); - - /** - * 校验私钥格式是否满足要求; - * - * @param privKeyBytes 包含算法标识、密钥掩码和私钥的字节数组 - * @return 是否满足指定算法的私钥格式 - */ - boolean supportPrivKey(byte[] privKeyBytes); - - /** - * 将字节数组形式的私钥转换成PrivKey格式; - * - * @param privKeyBytes 包含算法标识、密钥掩码和私钥的字节数组 - * @return PrivKey形式的私钥 - */ - PrivKey resolvePrivKey(byte[] privKeyBytes); - - /** - * 校验公钥格式是否满足要求; - * - * @param pubKeyBytes 包含算法标识、密钥掩码和公钥的字节数组 - * @return 是否满足指定算法的公钥格式 - */ - boolean supportPubKey(byte[] pubKeyBytes); - - /** - * 将字节数组形式的密钥转换成PubKey格式; - * - * @param pubKeyBytes 包含算法标识、密钥掩码和公钥的字节数组 - * @return PubKey形式的公钥 - */ - PubKey resolvePubKey(byte[] pubKeyBytes); - - /** - * 校验字节数组形式的签名摘要的格式是否满足要求; - * - * @param digestBytes 包含算法标识和签名摘要的字节数组 - * @return 是否满足指定算法的签名摘要格式 - */ - - boolean supportDigest(byte[] digestBytes); - - /** - * 将字节数组形式的签名摘要转换成SignatureDigest格式; - * - * @param digestBytes 包含算法标识和签名摘要的字节数组 - * @return SignatureDigest形式的签名摘要 - */ - SignatureDigest resolveDigest(byte[] digestBytes); -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricCiphertext.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricCiphertext.java deleted file mode 100644 index 1f811478..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricCiphertext.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.crypto; - -public class SymmetricCiphertext extends BaseCryptoBytes implements Ciphertext { - - public SymmetricCiphertext(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { - super(algorithm, rawCryptoBytes); - } - - public SymmetricCiphertext(byte[] cryptoBytes) { - super(cryptoBytes); - } - - @Override - protected boolean support(short algorithm) { - return CryptoAlgorithm.isEncryptionAlgorithm(algorithm) && CryptoAlgorithm.hasSymmetricKey(algorithm); - } - - @Override - public byte[] getRawCiphertext() { - return getRawCryptoBytes().getBytesCopy(); - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricEncryptionFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricEncryptionFunction.java deleted file mode 100644 index 4ae72162..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricEncryptionFunction.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jd.blockchain.crypto; - -import java.io.InputStream; -import java.io.OutputStream; - -public interface SymmetricEncryptionFunction extends SymmetricKeyGenerator, CryptoFunction { - - /** - * 加密; - * - * @param key 密钥; - * @param data 明文; - * @return - */ - Ciphertext encrypt(SymmetricKey key, byte[] data); - - /** - * 加密明文的输入流,把密文写入输出流; - * - * @param key 密钥; - * @param in 明文的输入流; - * @param out 密文的输出流; - */ - void encrypt(SymmetricKey key, InputStream in, OutputStream out); - - /** - * 解密; - * - * @param key 密钥; - * @param ciphertext 密文; - * @return - */ - byte[] decrypt(SymmetricKey key, Ciphertext ciphertext); - - /** - * 解密密文的输入流,把明文写入输出流;
- * - * 注:实现者不应在方法内部关闭参数指定的输入输出流; - * - * @param key 密钥; - * @param in 密文的输入流; - * @param out 明文的输出流; - */ - void decrypt(SymmetricKey key, InputStream in, OutputStream out); - - /** - * 校验对称密钥格式是否满足要求; - * - * @param symmetricKeyBytes 包含算法标识、密钥掩码和对称密钥的字节数组 - * @return 是否满足指定算法的对称密钥格式 - */ - boolean supportSymmetricKey(byte[] symmetricKeyBytes); - - /** - * 将字节数组形式的密钥转换成SymmetricKey格式; - * - * @param symmetricKeyBytes 包含算法标识、密钥掩码和对称密钥的字节数组 - * @return SymmetricKey形式的对称密钥 - */ - SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes); - - /** - * 校验密文格式是否满足要求; - * - * @param ciphertextBytes 包含算法标识和密文的字节数组 - * @return 是否满足指定算法的密文格式 - */ - boolean supportCiphertext(byte[] ciphertextBytes); - - /** - * 将字节数组形式的密文转换成SymmetricCiphertext格式; - * - * @param ciphertextBytes 包含算法标识和密文的字节数组 - * @return SymmetricCiphertext形式的签名摘要 - */ - SymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes); - - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKey.java deleted file mode 100644 index 84ffd898..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKey.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.crypto; - -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC; - -/** - * 对称密钥; - * - * @author huanghaiquan - * - */ -public class SymmetricKey extends BaseCryptoKey { - - private static final long serialVersionUID = 5055547663903904933L; - - public SymmetricKey(CryptoAlgorithm algorithm, byte[] rawKeyBytes) { - super(algorithm, rawKeyBytes, SYMMETRIC); - } - - public SymmetricKey(byte[] keyBytes) { - super(keyBytes); - } - - @Override - public CryptoKeyType getKeyType() { - return SYMMETRIC; - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKeyGenerator.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKeyGenerator.java deleted file mode 100644 index 727df9ff..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKeyGenerator.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.crypto; - -public interface SymmetricKeyGenerator { - - /** - * 返回对称密钥; - */ - SymmetricKey generateSymmetricKey(); -} diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/CryptoKeySerializationTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/CryptoKeySerializationTest.java deleted file mode 100644 index d2d1d314..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/CryptoKeySerializationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package test.com.jd.blockchain.crypto; - -import static org.junit.Assert.*; - -import java.util.UUID; - -import org.junit.Test; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoAlgorithmDefinition; -import com.jd.blockchain.crypto.CryptoKeyType; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.io.BytesUtils; - -public class CryptoKeySerializationTest { - - /** - * Test the equivalence of serialization and deserialization of PubKey; - */ - @Test - public void testPubKey() { - CryptoAlgorithm algorithm = CryptoAlgorithmDefinition.defineSignature("TEST", false, (byte) 123); - - // Simulate a public key with a random number; - byte[] rawBytes = BytesUtils.toBytes(UUID.randomUUID().toString()); - - PubKey pubKey = new PubKey(algorithm, rawBytes); - - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(CryptoKeyType.PUBLIC, pubKey.getKeyType()); - - // serialize; - byte[] keyBytes = pubKey.toBytes(); - - // deserialize; - PubKey desPubKey = new PubKey(keyBytes); - - assertEquals(algorithm.code(), desPubKey.getAlgorithm()); - assertEquals(CryptoKeyType.PUBLIC, desPubKey.getKeyType()); - byte[] desRawBytes = desPubKey.getRawKeyBytes(); - assertTrue(BytesUtils.equals(rawBytes, desRawBytes)); - - } - - /** - * Test the equivalence of serialization and deserialization of PrivKey; - */ - @Test - public void testPrivKey() { - CryptoAlgorithm algorithm = CryptoAlgorithmDefinition.defineSignature("TEST", false, (byte) 123); - - // Simulate a public key with a random number; - byte[] rawBytes = BytesUtils.toBytes(UUID.randomUUID().toString()); - - PrivKey privKey = new PrivKey(algorithm, rawBytes); - - assertEquals(algorithm.code(), privKey.getAlgorithm()); - assertEquals(CryptoKeyType.PRIVATE, privKey.getKeyType()); - - // serialize; - byte[] keyBytes = privKey.toBytes(); - - // deserialize; - PrivKey desPrivKey = new PrivKey(keyBytes); - - assertEquals(algorithm.code(), desPrivKey.getAlgorithm()); - assertEquals(CryptoKeyType.PRIVATE, desPrivKey.getKeyType()); - byte[] desRawBytes = desPrivKey.getRawKeyBytes(); - assertTrue(BytesUtils.equals(rawBytes, desRawBytes)); - - } - -} diff --git a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/PKIAlgorithm.java b/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/PKIAlgorithm.java deleted file mode 100644 index 0aff4c6b..00000000 --- a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/PKIAlgorithm.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoAlgorithmDefinition; - -/** - * @author zhanglin33 - * @title: PKIAlgorithm - * @description: TODO - * @date 2019-05-15, 16:34 - */ -public class PKIAlgorithm { - - public static final CryptoAlgorithm SHA1WITHRSA2048 = CryptoAlgorithmDefinition.defineSignature("SHA1WITHRSA2048", - false, (byte) 31); - - public static final CryptoAlgorithm SHA1WITHRSA4096 = CryptoAlgorithmDefinition.defineSignature("SHA1WITHRSA4096", - false, (byte) 32); - - public static final CryptoAlgorithm SM3WITHSM2 = CryptoAlgorithmDefinition.defineSignature("SM3WITHSM2", - false, (byte) 33); - - private PKIAlgorithm() { - } - -} diff --git a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/PKICryptoService.java b/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/PKICryptoService.java deleted file mode 100644 index 940d3168..00000000 --- a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/PKICryptoService.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.CryptoFunction; -import com.jd.blockchain.crypto.CryptoService; -import com.jd.blockchain.provider.NamedProvider; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** - * @author zhanglin33 - * @title: PKICryptoService - * @description: TODO - * @date 2019-05-15, 16:35 - */ -@NamedProvider("PKI-SOFTWARE") -public class PKICryptoService implements CryptoService { - - public static final SHA1WITHRSA2048SignatureFunction SHA1WITHRSA2048 = new SHA1WITHRSA2048SignatureFunction(); - - public static final SHA1WITHRSA4096SignatureFunction SHA1WITHRSA4096 = new SHA1WITHRSA4096SignatureFunction(); - - public static final SM3WITHSM2SignatureFunction SM3WITHSM2 = new SM3WITHSM2SignatureFunction(); - - private static final Collection FUNCTIONS; - - static { - List funcs = Arrays.asList(SHA1WITHRSA2048, SHA1WITHRSA4096, SM3WITHSM2); - FUNCTIONS = Collections.unmodifiableList(funcs); - } - - @Override - public Collection getFunctions() { - return FUNCTIONS; - } -} diff --git a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA2048SignatureFunction.java b/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA2048SignatureFunction.java deleted file mode 100644 index e8eafdad..00000000 --- a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA2048SignatureFunction.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.*; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil; -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -import java.math.BigInteger; -import java.security.*; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static com.jd.blockchain.crypto.service.pki.PKIAlgorithm.SHA1WITHRSA2048; - -/** - * @author zhanglin33 - * @title: SHA1WITHRSA2048SignatureFunction - * @description: TODO - * @date 2019-05-15, 16:37 - */ -public class SHA1WITHRSA2048SignatureFunction implements SignatureFunction { - - private static final int RAW_PUBKEY_SIZE = 259; - private static final int RAW_PRIVKEY_SIZE = 1155; - - private static final int RAW_SIGNATUREDIGEST_SIZE = 256; - - private static final AlgorithmIdentifier RSA_ALGORITHM_IDENTIFIER = - new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - if (rawPrivKeyBytes.length < RAW_PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (privKey.getAlgorithm() != SHA1WITHRSA2048.code()) { - throw new CryptoException("This key is not SHA1WITHRSA2048 private key!"); - } - - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivKeyBytes); - - KeyFactory keyFactory; - RSAPrivateCrtKey rawPrivKey; - Signature signer; - byte[] signature; - - try { - keyFactory = KeyFactory.getInstance("RSA"); - rawPrivKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(keySpec); - signer = Signature.getInstance("SHA1withRSA"); - signer.initSign(rawPrivKey); - signer.update(data); - signature = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | InvalidKeySpecException e) { - throw new CryptoException(e.getMessage(), e); - } - - return new SignatureDigest(SHA1WITHRSA2048, signature); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - if (rawPubKeyBytes.length < RAW_PUBKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (pubKey.getAlgorithm() != SHA1WITHRSA2048.code()) { - throw new CryptoException("This key is not SHA1WITHRSA2048 public key!"); - } - - if (digest.getAlgorithm() != SHA1WITHRSA2048.code() || rawDigestBytes.length != RAW_SIGNATUREDIGEST_SIZE) { - throw new CryptoException("This is not SHA1WITHRSA2048 signature digest!"); - } - - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(rawPubKeyBytes); - - KeyFactory keyFactory; - RSAPublicKey rawPubKey; - Signature verifier; - boolean isValid; - - try { - keyFactory = KeyFactory.getInstance("RSA"); - rawPubKey = (RSAPublicKey) keyFactory.generatePublic(keySpec); - verifier = Signature.getInstance("SHA1withRSA"); - verifier.initVerify(rawPubKey); - verifier.update(data); - isValid = verifier.verify(rawDigestBytes); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | InvalidKeySpecException e) { - throw new CryptoException(e.getMessage(), e); - } - - return isValid; - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - return pubKeyBytes.length > (ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + RAW_PUBKEY_SIZE) - && CryptoAlgorithm.match(SHA1WITHRSA2048, pubKeyBytes) - && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUBLIC.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - if (supportPubKey(pubKeyBytes)) { - return new PubKey(pubKeyBytes); - } else { - throw new CryptoException("pubKeyBytes are invalid!"); - } - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - return privKeyBytes.length > (ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + RAW_PRIVKEY_SIZE) - && CryptoAlgorithm.match(SHA1WITHRSA2048, privKeyBytes) - && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIVATE.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - if (supportPrivKey(privKeyBytes)) { - return new PrivKey(privKeyBytes); - } else { - throw new CryptoException("privKeyBytes are invalid!"); - } - } - - @Override - public PubKey retrievePubKey(PrivKey privKey) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - if (rawPrivKeyBytes.length < RAW_PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (privKey.getAlgorithm() != SHA1WITHRSA2048.code()) { - throw new CryptoException("This key is not SHA1WITHRSA2048 private key!"); - } - - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivKeyBytes); - - KeyFactory keyFactory; - RSAPrivateCrtKey rawPrivKey; - byte[] rawPubKeyBytes; - try { - keyFactory = KeyFactory.getInstance("RSA"); - rawPrivKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(keySpec); - BigInteger modulus = rawPrivKey.getModulus(); - BigInteger exponent = rawPrivKey.getPublicExponent(); - rawPubKeyBytes = KeyUtil.getEncodedSubjectPublicKeyInfo(RSA_ALGORITHM_IDENTIFIER, - new org.bouncycastle.asn1.pkcs.RSAPublicKey(modulus, exponent)); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - throw new CryptoException(e.getMessage(), e); - } - - return new PubKey(SHA1WITHRSA2048, rawPubKeyBytes); - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - return digestBytes.length == (RAW_SIGNATUREDIGEST_SIZE + ALGORYTHM_CODE_SIZE) - && CryptoAlgorithm.match(SHA1WITHRSA2048, digestBytes); - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - if (supportDigest(digestBytes)) { - return new SignatureDigest(digestBytes); - } else { - throw new CryptoException("digestBytes are invalid!"); - } - } - - @Override - public AsymmetricKeypair generateKeypair() { - - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - KeyPairGenerator generator; - PublicKey pubKey; - PrivateKey privKey; - try { - generator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); - generator.initialize(2048); - KeyPair keyPair = generator.generateKeyPair(); - pubKey = keyPair.getPublic(); - privKey = keyPair.getPrivate(); - } catch (NoSuchAlgorithmException | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - - byte[] pubKeyBytes = pubKey.getEncoded(); - byte[] privKeyBytes = privKey.getEncoded(); - - return new AsymmetricKeypair(new PubKey(SHA1WITHRSA2048, pubKeyBytes), - new PrivKey(SHA1WITHRSA2048, privKeyBytes)); - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return SHA1WITHRSA2048; - } -} diff --git a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA4096SignatureFunction.java b/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA4096SignatureFunction.java deleted file mode 100644 index 486096bb..00000000 --- a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA4096SignatureFunction.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.*; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil; -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -import java.math.BigInteger; -import java.security.*; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static com.jd.blockchain.crypto.service.pki.PKIAlgorithm.SHA1WITHRSA4096; - -/** - * @author zhanglin33 - * @title: SHA1WITHRSA4096SignatureFunction - * @description: TODO - * @date 2019-05-15, 17:13 - */ -public class SHA1WITHRSA4096SignatureFunction implements SignatureFunction { - private static final int RAW_PUBKEY_SIZE = 515; - private static final int RAW_PRIVKEY_SIZE = 2307; - - private static final int RAW_SIGNATUREDIGEST_SIZE = 512; - - private static final AlgorithmIdentifier RSA_ALGORITHM_IDENTIFIER = - new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - if (rawPrivKeyBytes.length < RAW_PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (privKey.getAlgorithm() != SHA1WITHRSA4096.code()) { - throw new CryptoException("This key is not SHA1WITHRSA4096 private key!"); - } - - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivKeyBytes); - - KeyFactory keyFactory; - RSAPrivateCrtKey rawPrivKey; - Signature signer; - byte[] signature; - - try { - keyFactory = KeyFactory.getInstance("RSA"); - rawPrivKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(keySpec); - signer = Signature.getInstance("SHA1withRSA"); - signer.initSign(rawPrivKey); - signer.update(data); - signature = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | InvalidKeySpecException e) { - throw new CryptoException(e.getMessage(), e); - } - - return new SignatureDigest(SHA1WITHRSA4096, signature); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - if (rawPubKeyBytes.length < RAW_PUBKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (pubKey.getAlgorithm() != SHA1WITHRSA4096.code()) { - throw new CryptoException("This key is not SHA1WITHRSA4096 public key!"); - } - - if (digest.getAlgorithm() != SHA1WITHRSA4096.code() || rawDigestBytes.length != RAW_SIGNATUREDIGEST_SIZE) { - throw new CryptoException("This is not SHA1WITHRSA4096 signature digest!"); - } - - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(rawPubKeyBytes); - - KeyFactory keyFactory; - RSAPublicKey rawPubKey; - Signature verifier; - boolean isValid; - - try { - keyFactory = KeyFactory.getInstance("RSA"); - rawPubKey = (RSAPublicKey) keyFactory.generatePublic(keySpec); - verifier = Signature.getInstance("SHA1withRSA"); - verifier.initVerify(rawPubKey); - verifier.update(data); - isValid = verifier.verify(rawDigestBytes); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | InvalidKeySpecException e) { - throw new CryptoException(e.getMessage(), e); - } - - return isValid; - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - return pubKeyBytes.length > (ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + RAW_PUBKEY_SIZE) - && CryptoAlgorithm.match(SHA1WITHRSA4096, pubKeyBytes) - && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUBLIC.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - if (supportPubKey(pubKeyBytes)) { - return new PubKey(pubKeyBytes); - } else { - throw new CryptoException("pubKeyBytes are invalid!"); - } - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - return privKeyBytes.length > (ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + RAW_PRIVKEY_SIZE) - && CryptoAlgorithm.match(SHA1WITHRSA4096, privKeyBytes) - && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIVATE.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - if (supportPrivKey(privKeyBytes)) { - return new PrivKey(privKeyBytes); - } else { - throw new CryptoException("privKeyBytes are invalid!"); - } - } - - @Override - public PubKey retrievePubKey(PrivKey privKey) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - if (rawPrivKeyBytes.length < RAW_PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (privKey.getAlgorithm() != SHA1WITHRSA4096.code()) { - throw new CryptoException("This key is not SHA1WITHRSA4096 private key!"); - } - - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivKeyBytes); - - KeyFactory keyFactory; - RSAPrivateCrtKey rawPrivKey; - byte[] rawPubKeyBytes; - try { - keyFactory = KeyFactory.getInstance("RSA"); - rawPrivKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(keySpec); - BigInteger modulus = rawPrivKey.getModulus(); - BigInteger exponent = rawPrivKey.getPublicExponent(); - rawPubKeyBytes = KeyUtil.getEncodedSubjectPublicKeyInfo(RSA_ALGORITHM_IDENTIFIER, - new org.bouncycastle.asn1.pkcs.RSAPublicKey(modulus, exponent)); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - throw new CryptoException(e.getMessage(), e); - } - - return new PubKey(SHA1WITHRSA4096, rawPubKeyBytes); - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - return digestBytes.length == (RAW_SIGNATUREDIGEST_SIZE + ALGORYTHM_CODE_SIZE) - && CryptoAlgorithm.match(SHA1WITHRSA4096, digestBytes); - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - if (supportDigest(digestBytes)) { - return new SignatureDigest(digestBytes); - } else { - throw new CryptoException("digestBytes are invalid!"); - } - } - - @Override - public AsymmetricKeypair generateKeypair() { - - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - KeyPairGenerator generator; - PublicKey pubKey; - PrivateKey privKey; - try { - generator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); - generator.initialize(4096); - KeyPair keyPair = generator.generateKeyPair(); - pubKey = keyPair.getPublic(); - privKey = keyPair.getPrivate(); - } catch (NoSuchAlgorithmException | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - - byte[] pubKeyBytes = pubKey.getEncoded(); - byte[] privKeyBytes = privKey.getEncoded(); - - return new AsymmetricKeypair(new PubKey(SHA1WITHRSA4096, pubKeyBytes), - new PrivKey(SHA1WITHRSA4096, privKeyBytes)); - } - - - @Override - public CryptoAlgorithm getAlgorithm() { - return SHA1WITHRSA4096; - } -} diff --git a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SM3WITHSM2SignatureFunction.java b/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SM3WITHSM2SignatureFunction.java deleted file mode 100644 index 5b9978d7..00000000 --- a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/service/pki/SM3WITHSM2SignatureFunction.java +++ /dev/null @@ -1,236 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.*; -import org.bouncycastle.asn1.gm.GMObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.math.ec.custom.gm.SM2P256V1Curve; - -import java.math.BigInteger; -import java.security.*; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static com.jd.blockchain.crypto.service.pki.PKIAlgorithm.SM3WITHSM2; - -/** - * @author zhanglin33 - * @title: SM3WITHSM2SignatureFunction - * @description: TODO - * @date 2019-05-15, 16:39 - */ -public class SM3WITHSM2SignatureFunction implements SignatureFunction { - private static final int RAW_PUBKEY_SIZE = 65; - private static final int RAW_PRIVKEY_SIZE = 32 + 65; - - private static final int RAW_SIGNATUREDIGEST_SIZE = 64; - - private static final SM2P256V1Curve CURVE = new SM2P256V1Curve(); - private static final BigInteger GX = new BigInteger("32C4AE2C1F1981195F9904466A39C994" + - "8FE30BBFF2660BE1715A4589334C74C7", 16); - private static final BigInteger GY = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153" + - "D0A9877CC62A474002DF32E52139F0A0", 16); - private static final ECPoint G = CURVE.createPoint(GX, GY); - - private static final AlgorithmIdentifier SM2_ALGORITHM_IDENTIFIER = new AlgorithmIdentifier( - X9ObjectIdentifiers.id_ecPublicKey, GMObjectIdentifiers.sm2p256v1); - - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - Security.addProvider(new BouncyCastleProvider()); - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - if (rawPrivKeyBytes.length < RAW_PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (privKey.getAlgorithm() != SM3WITHSM2.code()) { - throw new CryptoException("This key is not SM3WITHSM2 private key!"); - } - - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivKeyBytes); - - KeyFactory keyFactory; - ECPrivateKey rawPrivKey; - Signature signer; - byte[] signature; - - try { - keyFactory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); - rawPrivKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec); - signer = Signature.getInstance("SM3withSM2", BouncyCastleProvider.PROVIDER_NAME); - - signer.initSign(rawPrivKey); - signer.update(data); - signature = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | - InvalidKeySpecException | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - - return new SignatureDigest(SM3WITHSM2, signature); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - Security.addProvider(new BouncyCastleProvider()); - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - if (rawPubKeyBytes.length < RAW_PUBKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (pubKey.getAlgorithm() != SM3WITHSM2.code()) { - throw new CryptoException("This key is not SM3WITHSM2 public key!"); - } - - if (digest.getAlgorithm() != SM3WITHSM2.code() || rawDigestBytes.length < RAW_SIGNATUREDIGEST_SIZE) { - throw new CryptoException("This is not SM3WITHSM2 signature digest!"); - } - - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(rawPubKeyBytes); - - KeyFactory keyFactory; - ECPublicKey rawPubKey; - Signature verifier; - boolean isValid; - - try { - keyFactory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); - rawPubKey = (ECPublicKey) keyFactory.generatePublic(keySpec); - verifier = Signature.getInstance("SM3withSM2", BouncyCastleProvider.PROVIDER_NAME); - verifier.initVerify(rawPubKey); - verifier.update(data); - isValid = verifier.verify(rawDigestBytes); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | InvalidKeySpecException - | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - - return isValid; - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - return pubKeyBytes.length > (ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + RAW_PUBKEY_SIZE) - && CryptoAlgorithm.match(SM3WITHSM2, pubKeyBytes) - && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUBLIC.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - if (supportPubKey(pubKeyBytes)) { - return new PubKey(pubKeyBytes); - } else { - throw new CryptoException("pubKeyBytes are invalid!"); - } - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - return privKeyBytes.length > (ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + RAW_PRIVKEY_SIZE) - && CryptoAlgorithm.match(SM3WITHSM2, privKeyBytes) - && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIVATE.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - if (supportPrivKey(privKeyBytes)) { - return new PrivKey(privKeyBytes); - } else { - throw new CryptoException("privKeyBytes are invalid!"); - } - } - - @Override - public PubKey retrievePubKey(PrivKey privKey) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - if (rawPrivKeyBytes.length < RAW_PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - if (privKey.getAlgorithm() != SM3WITHSM2.code()) { - throw new CryptoException("This key is not SM3WITHSM2 private key!"); - } - - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivKeyBytes); - - KeyFactory keyFactory; - ECPrivateKey rawPrivKey; - byte[] rawPubKeyBytes; - try { - keyFactory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); - rawPrivKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec); - BigInteger d = rawPrivKey.getS(); - ECPoint Q = G.multiply(d).normalize(); - rawPubKeyBytes = KeyUtil.getEncodedSubjectPublicKeyInfo(SM2_ALGORITHM_IDENTIFIER, - Q.getEncoded(false)); - } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - - return new PubKey(SM3WITHSM2, rawPubKeyBytes); - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - return digestBytes.length > (RAW_SIGNATUREDIGEST_SIZE + ALGORYTHM_CODE_SIZE) - && CryptoAlgorithm.match(SM3WITHSM2, digestBytes); - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - if (supportDigest(digestBytes)) { - return new SignatureDigest(digestBytes); - } else { - throw new CryptoException("digestBytes are invalid!"); - } - } - - @Override - public AsymmetricKeypair generateKeypair() { - - Security.addProvider(new BouncyCastleProvider()); - KeyPairGenerator generator; - PublicKey pubKey; - PrivateKey privKey; - try { - generator = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); - generator.initialize(new ECNamedCurveGenParameterSpec("sm2p256v1")); - KeyPair keyPair = generator.generateKeyPair(); - pubKey = keyPair.getPublic(); - privKey = keyPair.getPrivate(); - } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) { - throw new CryptoException(e.getMessage(), e); - } - - byte[] pubKeyBytes = pubKey.getEncoded(); - byte[] privKeyBytes = privKey.getEncoded(); - - return new AsymmetricKeypair(new PubKey(SM3WITHSM2, pubKeyBytes), - new PrivKey(SM3WITHSM2, privKeyBytes)); - } - @Override - public CryptoAlgorithm getAlgorithm() { - return SM3WITHSM2; - } -} diff --git a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/utils/CSRBuilder.java b/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/utils/CSRBuilder.java deleted file mode 100644 index 3de606db..00000000 --- a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/utils/CSRBuilder.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.jd.blockchain.crypto.utils; - -import com.jd.blockchain.crypto.CryptoException; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.X500NameBuilder; -import org.bouncycastle.asn1.x500.style.BCStrictStyle; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; -import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import org.bouncycastle.util.encoders.Base64; - -import java.io.IOException; -import java.security.*; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -/** - * @author zhanglin33 - * @title: CSRBuilder - * @description: A builder for certificate signing request, supporting rsa and sm2 - * @date 2019-05-10, 15:10 - */ -public class CSRBuilder { - - private final String BC = BouncyCastleProvider.PROVIDER_NAME; - - private PublicKey pubKey; - private PrivateKey privKey; - - private String algoName; - private int keyLength; - - public void init() { - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - algoName = "SHA1withRSA"; - keyLength = 2048; - KeyPairGenerator generator; - try { - generator = KeyPairGenerator.getInstance("RSA", BC); - generator.initialize(2048); - KeyPair keyPair = generator.generateKeyPair(); - pubKey = keyPair.getPublic(); - privKey = keyPair.getPrivate(); - } catch (NoSuchAlgorithmException | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - } - - public void init(String algoName, int keyLength) { - - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - this.algoName = algoName; - this.keyLength = keyLength; - - KeyPairGenerator generator; - KeyPair keyPair; - String[] hashAndSignature = algoName.split("with"); - - try { - switch (hashAndSignature[1]) { - case "RSA": { - generator = KeyPairGenerator.getInstance("RSA", BC); - generator.initialize(keyLength); - break; - } - - case "SM2": { - generator = KeyPairGenerator.getInstance("EC", BC); - if (keyLength != 256) { - throw new CryptoException("SM3withSM2 with unsupported key length [" + - keyLength +"] in CSR!"); - } - generator.initialize(new ECNamedCurveGenParameterSpec("sm2p256v1")); - break; - } - - default: throw new CryptoException("Unsupported algorithm [" + algoName + "] with key length [" + - keyLength +"] in CSR!"); - } - keyPair = generator.generateKeyPair(); - pubKey = keyPair.getPublic(); - privKey = keyPair.getPrivate(); - } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) { - throw new CryptoException(e.getMessage(), e); - } - } - - public void init(String algoName, byte[] pubKeyBytes, byte[] privKeyBytes) { - - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - this.algoName = algoName; - String[] hashAndSignature = algoName.split("with"); - - X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes); - PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes); - - KeyFactory keyFactory; - - try { - switch (hashAndSignature[1]) { - case "RSA": { - keyFactory = KeyFactory.getInstance("RSA"); - privKey = keyFactory.generatePrivate(privKeySpec); - pubKey = keyFactory.generatePublic(pubKeySpec); - keyLength = (pubKey.getEncoded().length < 4096 / 8)? 2048: 4096; - break; - } - - case "SM2": { - keyFactory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); - privKey = keyFactory.generatePrivate(privKeySpec); - pubKey = keyFactory.generatePublic(pubKeySpec); - keyLength = 256; - break; - } - - default: throw new CryptoException("Unsupported algorithm [" + algoName + "] with the given key pair!"); - } - } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - - - } - - public String buildRequest(String countryName, String stateName, String cityName, - String organizationName, String departmentName, String domainName, - String emailName) { - - String result; - X500NameBuilder nameBuilder = new X500NameBuilder(BCStrictStyle.INSTANCE); - - nameBuilder.addRDN(BCStyle.C, countryName); // a country name, and China is short as CN - nameBuilder.addRDN(BCStyle.ST, stateName); // a state or province name - nameBuilder.addRDN(BCStyle.L, cityName); // a city name - nameBuilder.addRDN(BCStyle.O, organizationName); // an organization or corporation name - nameBuilder.addRDN(BCStyle.OU, departmentName); // a division of your organization name - nameBuilder.addRDN(BCStyle.CN, domainName); // a fully qualified domain name - nameBuilder.addRDN(BCStyle.E, emailName); // an email address - - try { - X500Name x500Name = nameBuilder.build(); - - PKCS10CertificationRequestBuilder requestBuilder - = new JcaPKCS10CertificationRequestBuilder(x500Name, pubKey); - PKCS10CertificationRequest request - = requestBuilder.build(new JcaContentSignerBuilder(algoName).setProvider(BC).build(privKey)); - byte[] csrBytes = request.getEncoded(); - result = Base64.toBase64String(csrBytes); - } catch (OperatorCreationException | IOException e) { - throw new CryptoException(e.getMessage(), e); - } - - return result; - } - - public PublicKey getPubKey() { - return pubKey; - } - - public PrivateKey getPrivKey() { - return privKey; - } - - public String getAlgoName() { - return algoName; - } - - public int getKeyLength() { - return keyLength; - } -} diff --git a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/utils/CertParser.java b/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/utils/CertParser.java deleted file mode 100644 index e54c17db..00000000 --- a/source/crypto/crypto-pki/src/main/java/com/jd/blockchain/crypto/utils/CertParser.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.jd.blockchain.crypto.utils; - -import com.jd.blockchain.crypto.CryptoException; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.io.pem.PemReader; - -import javax.security.auth.x500.X500Principal; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.StringReader; -import java.security.*; -import java.security.cert.*; -import java.util.Date; - -/** - * @author zhanglin33 - * @title: CertParser - * @description: A parser for standard certificate, along with validation process - * @date 2019-05-10, 15:17 - */ -public class CertParser { - - private PublicKey pubKey; - private String sigAlgName; - private String userName; - private String issuerName; - private int keyLength; - - private Date startTime; - private Date endTime; - - public void parse(String userCertificate, String issuerCertificate) { - - X509Certificate issuerCert = parseWithoutValidationProcess(issuerCertificate); - - // ensure that the certificate is within the validity period - try { - issuerCert.checkValidity(); - } catch (CertificateExpiredException | CertificateNotYetValidException e) { - throw new CryptoException(e.getMessage(), e); - } - PublicKey issuerPubKey = issuerCert.getPublicKey(); - X500Principal issuerPrincipal = issuerCert.getSubjectX500Principal(); - - X509Certificate userCert = parseWithoutValidationProcess(userCertificate); - - // check consistency between issuer's names in userCertificate and issuerCertificate - if (!userCert.getIssuerX500Principal().equals(issuerPrincipal)) { - throw new CryptoException("Issuer in the targeted certificate is not " + - "compliance with the parent certificate!"); - } - - try { - userCert.checkValidity(); - } catch (CertificateExpiredException | CertificateNotYetValidException e) { - throw new CryptoException(e.getMessage(), e); - } - - // verify the signature in certificate with issuer's public key - try { - userCert.verify(issuerPubKey); - } catch (CertificateException | NoSuchAlgorithmException - | InvalidKeyException | NoSuchProviderException | SignatureException e) { - throw new CryptoException(e.getMessage(), e); - } - - startTime = userCert.getNotBefore(); - endTime = userCert.getNotAfter(); - - pubKey = userCert.getPublicKey(); - sigAlgName = userCert.getSigAlgName(); - issuerName = userCert.getIssuerX500Principal().getName(); - userName = userCert.getSubjectX500Principal().getName(); - - switch (sigAlgName) { - case "SM3WITHSM2": { - keyLength = 256; - break; - } - case "SHA1WITHRSA": { - keyLength = (pubKey.getEncoded().length < 4096 / 8)? 2048: 4096; - break; - } - } - } - - // certificate string in Base64 format - public X509Certificate parseWithoutValidationProcess(String certificate) { - - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - - byte[] certificateBytes; - String BEGIN = "-----BEGIN CERTIFICATE-----"; - String END = "-----END CERTIFICATE-----"; - if (!certificate.startsWith(BEGIN)) { - certificate = certificate.replaceAll("\\n", ""); - certificate = certificate.replaceAll(END, ""); - certificateBytes = Base64.decode(certificate); - } else { - try { - certificateBytes = new PemReader(new StringReader(certificate)).readPemObject().getContent(); - } catch (IOException e) { - throw new CryptoException(e.getMessage(), e); - } - } - - ByteArrayInputStream bytesIn = new ByteArrayInputStream(certificateBytes); - CertificateFactory factory; - X509Certificate cert; - try { - factory = CertificateFactory.getInstance("X509", BouncyCastleProvider.PROVIDER_NAME); - cert = (X509Certificate) factory.generateCertificate(bytesIn); - } catch (CertificateException | NoSuchProviderException e) { - throw new CryptoException(e.getMessage(), e); - } - return cert; - } - - public PublicKey getPubKey() { - return pubKey; - } - - public String getSigAlgName() { - return sigAlgName; - } - - public String getUserName() { - return userName; - } - - public String getIssuerName() { - return issuerName; - } - - public int getKeyLength() { - return keyLength; - } - - public Date getStartTime() { - return startTime; - } - - public Date getEndTime() { - return endTime; - } -} diff --git a/source/crypto/crypto-pki/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService b/source/crypto/crypto-pki/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService deleted file mode 100644 index 14a8682f..00000000 --- a/source/crypto/crypto-pki/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService +++ /dev/null @@ -1 +0,0 @@ -com.jd.blockchain.crypto.service.pki.PKICryptoService \ No newline at end of file diff --git a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA2048SignatureFunctionTest.java b/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA2048SignatureFunctionTest.java deleted file mode 100644 index 64ca7eb5..00000000 --- a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA2048SignatureFunctionTest.java +++ /dev/null @@ -1,273 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.utils.CSRBuilder; -import com.jd.blockchain.crypto.utils.CertParser; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import java.security.*; -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.*; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: SHA1WITHRSA2048SignatureFunctionTest - * @description: TODO - * @date 2019-05-16, 10:49 - */ -public class SHA1WITHRSA2048SignatureFunctionTest { - - @Test - public void getAlgorithmTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SHA1WITHRSA2048"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("SHA1withRsa2048"); - assertNotNull(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("rsa2048"); - assertNull(algorithm); - } - - @Test - public void test() { - - // generateKeyPairTest - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SHA1WITHRSA2048"); - assertNotNull(algorithm); - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - assertEquals(PUBLIC.CODE, pubKey.getKeyType().CODE); - assertTrue(pubKey.getRawKeyBytes().length > 259); - assertEquals(PRIVATE.CODE, privKey.getKeyType().CODE); - assertTrue(privKey.getRawKeyBytes().length > 1155); - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(algorithm.code(), privKey.getAlgorithm()); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawPubKeyBytes), pubKey.toBytes()); - assertArrayEquals(BytesUtils.concat(algoBytes, privKeyTypeBytes, rawPrivKeyBytes), privKey.toBytes()); - - // retrievePubKeyTest - PubKey retrievedPubKey = signatureFunction.retrievePubKey(privKey); - assertEquals(pubKey.getKeyType(), retrievedPubKey.getKeyType()); - assertEquals(pubKey.getRawKeyBytes().length, retrievedPubKey.getRawKeyBytes().length); - assertEquals(pubKey.getAlgorithm(), retrievedPubKey.getAlgorithm()); - assertArrayEquals(pubKey.toBytes(), retrievedPubKey.toBytes()); - - // signTest - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - byte[] signatureBytes = signatureDigest.toBytes(); - assertEquals(2 + 256, signatureBytes.length); - assertEquals(algorithm.code(), signatureDigest.getAlgorithm()); - assertEquals(PKIAlgorithm.SHA1WITHRSA2048.code(), signatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 31 & 0x00FF)), - signatureDigest.getAlgorithm()); - - byte[] rawSinatureBytes = signatureDigest.getRawDigest(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawSinatureBytes), signatureBytes); - - // verifyTest - assertTrue(signatureFunction.verify(signatureDigest, pubKey, data)); - - // supportPrivKeyTest - byte[] privKeyBytes = privKey.toBytes(); - assertTrue(signatureFunction.supportPrivKey(privKeyBytes)); - - // resolvePrivKeyTest - PrivKey resolvedPrivKey = signatureFunction.resolvePrivKey(privKeyBytes); - assertEquals(PRIVATE.CODE, resolvedPrivKey.getKeyType().CODE); - assertEquals(PKIAlgorithm.SHA1WITHRSA2048.code(), resolvedPrivKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 31 & 0x00FF)), - resolvedPrivKey.getAlgorithm()); - assertArrayEquals(privKeyBytes, resolvedPrivKey.toBytes()); - - // supportPubKeyTest - byte[] pubKeyBytes = pubKey.toBytes(); - assertTrue(signatureFunction.supportPubKey(pubKeyBytes)); - - // resolvedPubKeyTest - PubKey resolvedPubKey = signatureFunction.resolvePubKey(pubKeyBytes); - assertEquals(PUBLIC.CODE, resolvedPubKey.getKeyType().CODE); - assertEquals(PKIAlgorithm.SHA1WITHRSA2048.code(), resolvedPubKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 31 & 0x00FF)), - resolvedPubKey.getAlgorithm()); - assertArrayEquals(pubKeyBytes, resolvedPubKey.toBytes()); - - //supportDigestTest - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertTrue(signatureFunction.supportDigest(signatureDigestBytes)); - - // resolveDigestTest - SignatureDigest resolvedSignatureDigest = signatureFunction.resolveDigest(signatureDigestBytes); - assertEquals(256, resolvedSignatureDigest.getRawDigest().length); - assertEquals(PKIAlgorithm.SHA1WITHRSA2048.code(), resolvedSignatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 31 & 0x00FF)), - resolvedSignatureDigest.getAlgorithm()); - assertArrayEquals(signatureDigestBytes, resolvedSignatureDigest.toBytes()); - } - - @Test - public void testWithCSRAndCert() { - - String countryName = "CN"; - String stateName = "Beijing"; - String cityName = "Beijing"; - String organizationName = "JD.com"; - String departmentName = "Blockchain Department"; - String domainName = "ledger.jd.com"; - String emailName = "zhanglin33@jd.com"; - - - String publicKeyStr = "30820122300d06092a864886f70d01010105000382010f003082010a0282010100c91e978897a36b" + - "30a57d265807441b0eff40c5572ecf029cd0cb2999b715edd2d5345c7b60c003075b1352629d03b943d08b25bfc5245" + - "a400f9ecbc1757394eac452d6316bf90cfcff5edfc427e277aa5266e89b1b2daa2e69dad5575515f49417c9ff332c83" + - "0dcd5537381f08e00b11123ad947bb11b18666d264ab5d8cdc92d0967fd7e0e6677746e2f01270d0594f74cda4e9d77" + - "4c6f3824499896bfb6424684af260d71b57a1366b741104fc647d9e38de055568daad60c116686e4afa1e9c83e9e30c" + - "7216e61353da2f75b2dde2c0ae870cf0ccc90490d1e22ecccbf3985d30933689847e6faf946993f930f83ac5b816075" + - "793a9a6df20727552a21be30203010001"; - - String privateKeyStr = "308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100c91e" + - "978897a36b30a57d265807441b0eff40c5572ecf029cd0cb2999b715edd2d5345c7b60c003075b1352629d03b943d08" + - "b25bfc5245a400f9ecbc1757394eac452d6316bf90cfcff5edfc427e277aa5266e89b1b2daa2e69dad5575515f49417" + - "c9ff332c830dcd5537381f08e00b11123ad947bb11b18666d264ab5d8cdc92d0967fd7e0e6677746e2f01270d0594f7" + - "4cda4e9d774c6f3824499896bfb6424684af260d71b57a1366b741104fc647d9e38de055568daad60c116686e4afa1e" + - "9c83e9e30c7216e61353da2f75b2dde2c0ae870cf0ccc90490d1e22ecccbf3985d30933689847e6faf946993f930f83" + - "ac5b816075793a9a6df20727552a21be30203010001028201003975637e93300d8a2ee573e47762f6461117cca96d46" + - "982cfc1be6ed3318f142a845d6dc2ad680a703d69fd56b9d6a3b1d23fbeb6f63c4e303736f2bfca5c2585631825f494" + - "534783d6f3a07bd0b5efbcaa1faf7814ac9118c8d8820f4be9a8b0ac6db819fc86b538bf284369d9f009a667668a82d" + - "224f7122041eddb492ef5b02d462aa11bc550bf3785a5d7538043586cfb0cd5c313a4746f22a5d4a89a412b279a7517" + - "176b1858a9677a1a60605aa0b2a7d260cf2e9e23a0e67c4a23ac046c62973239e84874c3695cc3f34073a62bd50b597" + - "ee06092a93fa6e41303ab4d2293ffad4c8db06e6516ae0a26a4d681305c3b7d535b540a638ca6cff1ce483750281810" + - "0e39967c5b287bd319b448255a1033591c74f4d688eb71f89a674cdb1be999e9abcf40e6b7f0bb3054262d7625002da" + - "7d34e56055ee130b66d682a0b9f8ea240a7e2dd1ff3f4b32f3bd352ba0a5dffc0315da34922493c267597787222213b" + - "f87d99fbd2a809c2647a1937cd1e303d746373db7c409a2ef33f8c06bb838bc612702818100e2374c71db5f0b4a199f" + - "f9d646a1785a84383a14aceb506f515b380c69ff45b51d0e941f55f0a234d8a3ee30bed656142bb5b985e462c44d234" + - "cfd424ecd6ca5fc70503862978ffe42b45bd698a99091d6fc65e2d85652e0ef56c52e8e05a6c5e879922c1d794e22f3" + - "51998217b5c6637a6abb716bf90cd1f23a2eedcdfface50281805d28a872224e2f2183e539d7e4ccd47b73f240c4004" + - "e72493c69e8dbcd2141eb22565f249edee20ad00e770c95a5655b0470b2cad964d030eab293292bfa62802cff824a10" + - "d52de8d8545024346106dd186fb53ef05bcea1d0dbfce2fac1cc8ec583fdc0ccdd9d498a983cea081ac55dc734aae84" + - "1ed802d6caf0e285c88b6d702818068b2a752daf1364c6967bd3e0b1a98956c3489cd1feb19232c4847bc97226aa4d4" + - "79f6dc39ee51649c0fe321f471470db6dd38ac5b73caded8c3bd437f2d5c67c65a450693bb0a0de7d989d7dc783e4d0" + - "16f77c871d02233b1123bd8bc2aa97157934cafd6445a819a93ddb4743cd141215b5cbdb5f7629398c48d0bcb17d671" + - "028181009282554329b89bcb2236a7e2a5bff53627e3ca7cc792d65236085741bc62a3f5767654722af561eff175664" + - "1af60e3d3959f63f0fec00cb29443ffca4ff751a76ecc6fa192ebe08ec9f643b9bb0d11bc90c1e850f0528ef223ea5f" + - "e4b4c107cc3a9eb26e6b84d74d87acbf7cc760cd788cbc30f95f8399077b25cdd924604c01"; - - String expectedCSR = "MIIC4jCCAcoCAQAwgZwxCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW" + - "5nMQ8wDQYDVQQKDAZKRC5jb20xHjAcBgNVBAsMFUJsb2NrY2hhaW4gRGVwYXJ0bWVudDEWMBQGA1UEAwwNbGVkZ2VyLmpkL" + - "mNvbTEgMB4GCSqGSIb3DQEJARYRemhhbmdsaW4zM0BqZC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDJ" + - "HpeIl6NrMKV9JlgHRBsO/0DFVy7PApzQyymZtxXt0tU0XHtgwAMHWxNSYp0DuUPQiyW/xSRaQA+ey8F1c5TqxFLWMWv5DPz" + - "/Xt/EJ+J3qlJm6JsbLaouadrVV1UV9JQXyf8zLIMNzVU3OB8I4AsREjrZR7sRsYZm0mSrXYzcktCWf9fg5md3RuLwEnDQWU" + - "90zaTp13TG84JEmYlr+2QkaEryYNcbV6E2a3QRBPxkfZ443gVVaNqtYMEWaG5K+h6cg+njDHIW5hNT2i91st3iwK6HDPDMy" + - "QSQ0eIuzMvzmF0wkzaJhH5vr5Rpk/kw+DrFuBYHV5Oppt8gcnVSohvjAgMBAAGgADANBgkqhkiG9w0BAQUFAAOCAQEALKHw" + - "BrlppbN+CSJwHxO99rv2XVD7L8lwwiMqdMzoNHxZUoob4AcGS3Iyxy6obX8fZh7DCA4nN0AmvrJCmWD3hCLclWKlwXTwvFe" + - "WIeB4xEB9MVPV6/Hs/QaI9Rjhd+O/Alfzov8y+KyYHEWmwxHj2RtQm1ZeulELzMvRjsqP+m5tOM1hLnPMU+AF1tZ9Fc7Jbm" + - "7Dwh6TAPpmaH1aVbHsnlZyCp8K4nMozVogcXJqg3qsbeJ6c/TofL0fURqiTJxLKMC0aD0TwVcNwDWEmc8cpqGheG1g6UF5l" + - "QBpeR2Br4f3LXJgr1Op1RxRy6I+X7h1IL38Q3jAOoU4y04O/+an7g=="; - - String expectedUserCert = "MIIERjCCAy6gAwIBAgIFIChmYJgwDQYJKoZIhvcNAQEFBQAwWTELMAkGA1UEBhMCQ04xMDAuBgNVB" + - "AoTJ0NoaW5hIEZpbmFuY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEYMBYGA1UEAxMPQ0ZDQSBURVNUIE9DQTExMB4X" + - "DTE5MDgyODA2MzEyNVoXDTIxMDgyODA2MzEyNVoweDELMAkGA1UEBhMCQ04xGDAWBgNVBAoTD0NGQ0EgVEVTVCBPQ0ExMTE" + - "RMA8GA1UECxMITG9jYWwgUkExFTATBgNVBAsTDEluZGl2aWR1YWwtMTElMCMGA1UEAxQcMDUxQHpoYW5nbGluIUBaMTg2MT" + - "IyMjkyOTVANTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMkel4iXo2swpX0mWAdEGw7/QMVXLs8CnNDLKZm3F" + - "e3S1TRce2DAAwdbE1JinQO5Q9CLJb/FJFpAD57LwXVzlOrEUtYxa/kM/P9e38Qn4neqUmbomxstqi5p2tVXVRX0lBfJ/zMs" + - "gw3NVTc4HwjgCxESOtlHuxGxhmbSZKtdjNyS0JZ/1+DmZ3dG4vAScNBZT3TNpOnXdMbzgkSZiWv7ZCRoSvJg1xtXoTZrdBE" + - "E/GR9njjeBVVo2q1gwRZobkr6HpyD6eMMchbmE1PaL3Wy3eLArocM8MzJBJDR4i7My/OYXTCTNomEfm+vlGmT+TD4OsW4Fg" + - "dXk6mm3yBydVKiG+MCAwEAAaOB9TCB8jAfBgNVHSMEGDAWgBT8C7xEmg4xoYOpgYcnHgVCxr9W+DBIBgNVHSAEQTA/MD0GC" + - "GCBHIbvKgECMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuY2ZjYS5jb20uY24vdXMvdXMtMTUuaHRtMDoGA1UdHwQzMDEw" + - "L6AtoCuGKWh0dHA6Ly8yMTAuNzQuNDIuMy9PQ0ExMS9SU0EvY3JsMjY2NTAuY3JsMAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQ" + - "UOTy45HymVDivPwA83lRoMpShasQwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMA0GCSqGSIb3DQEBBQUAA4IBAQ" + - "A7NFkDMV1mRV/07DJUdZJzvkm+QihhpLp7D2dUblCCEt0jjY5RdLiWG7HvJnlPTThiSkiejEO0Fy1cQzA5jYRhwp+70X8X9" + - "bt5jEBP/V4PyRXKKEvKZMdppLIeVI6rZk/gJzPh2FQYv3qWaINilxLOBP8Qa0kdMBwo6D6/MYwnSGv5zP4NLFUysLUJiKoM" + - "lAzEQSPNnkYRX6nogpkdN91/xgH3GA7fiihrjm5oxMAupCli9LQqvlUvRtv5EKIN9c+ixCAYFagG9IIjMDXbDne77n15i01" + - "420N8sjfTlr9v3W0v1gBSzjzFOT+TTTUtrjfO/Vm8iqq+z22QKIXgYjSF"; - - String issuerCert = - "-----BEGIN CERTIFICATE-----\n" + - "MIIDzzCCAregAwIBAgIKUalCR1Mt5ZSK8jANBgkqhkiG9w0BAQUFADBZMQswCQYD\n" + - "VQQGEwJDTjEwMC4GA1UEChMnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24g\n" + - "QXV0aG9yaXR5MRgwFgYDVQQDEw9DRkNBIFRFU1QgQ1MgQ0EwHhcNMTIwODI5MDU1\n" + - "NDM2WhcNMzIwODI0MDU1NDM2WjBZMQswCQYDVQQGEwJDTjEwMC4GA1UEChMnQ2hp\n" + - "bmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRgwFgYDVQQDEw9D\n" + - "RkNBIFRFU1QgT0NBMTEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC8\n" + - "jn0n8Fp6hcRdACdn1+Y6GAkC6KGgNdKyHPrmsdmhCjnd/i4qUFwnG8cp3D4lFw1G\n" + - "jmjSO5yVYbik/NbS6lbNpRgTK3fDfMFvLJpRIC+IFhG9SdAC2hwjsH9qTpL9cK2M\n" + - "bSdrC6pBdDgnbzaM9AGBF4Y6vXhj5nah4ZMsBvDp19LzXjlGuTPLuAgv9ZlWknsd\n" + - "RN70PIAmvomd10uqX4GIJ4Jq/FdKXOLZ2DNK/NhRyN6Yq71L3ham6tutXeZow5t5\n" + - "0254AnUlo1u6SeH9F8itER653o/oMLFwp+63qXAcqrHUlOQPX+JI8fkumSqZ4F2F\n" + - "t/HfVMnqdtFNCnh5+eIBAgMBAAGjgZgwgZUwHwYDVR0jBBgwFoAUdN7FjQp9EBqq\n" + - "aYNbTSHOhpvMcTgwDAYDVR0TBAUwAwEB/zA4BgNVHR8EMTAvMC2gK6AphidodHRw\n" + - "Oi8vMjEwLjc0LjQyLjMvdGVzdHJjYS9SU0EvY3JsMS5jcmwwCwYDVR0PBAQDAgEG\n" + - "MB0GA1UdDgQWBBT8C7xEmg4xoYOpgYcnHgVCxr9W+DANBgkqhkiG9w0BAQUFAAOC\n" + - "AQEAb7W0K9fZPA+JPw6lRiMDaUJ0oh052yEXreMBfoPulxkBj439qombDiFggRLc\n" + - "3g8wIEKzMOzOKXTWtnzYwN3y/JQSuJb/M1QqOEEM2PZwCxI4AkBuH6jg03RjlkHg\n" + - "/kTtuIFp9ItBCC2/KkKlp0ENfn4XgVg2KtAjZ7lpyVU0LPnhEqqUVY/xthjlCSa7\n" + - "/XHNStRxsfCTIBUWJ8n2FZyQhfV/UkMNHDBIiJR0v6C4Ai0/290WvbPEIAq+03Si\n" + - "fsHzBeA0C8lP5VzfAr6wWePaZMCpStpLaoXNcAqReKxQllElOqAhRxC5VKH+rnIQ\n" + - "OMRZvB7FRyE9IfwKApngcZbA5g==\n" + - "-----END CERTIFICATE-----"; - - byte[] rawPublicKeyBytes = Hex.decode(publicKeyStr); - byte[] rawPrivateKeyBytes = Hex.decode(privateKeyStr); - - CSRBuilder builder = new CSRBuilder(); - builder.init("SHA1withRSA", rawPublicKeyBytes, rawPrivateKeyBytes); - - String csr = builder.buildRequest(countryName,stateName,cityName, - organizationName,departmentName,domainName, - emailName); - - assertEquals(expectedCSR,csr); - - CertParser parser = new CertParser(); - parser.parse(expectedUserCert,issuerCert); - - PublicKey rawPublicKeyInCert = parser.getPubKey(); - // check that the public key in inputs and the public key in certificate are consistent - assertArrayEquals(rawPublicKeyBytes, rawPublicKeyInCert.getEncoded()); - - String algoName = parser.getSigAlgName(); - int keyLength = parser.getKeyLength(); - String length = String.valueOf(keyLength); - String algo = (algoName.contains("RSA")? (algoName + length).toUpperCase(): algoName.toUpperCase()); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm(algo); - assertNotNull(algorithm); - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - PubKey pubKey = new PubKey(algorithm, rawPublicKeyBytes); - PrivKey privKey = new PrivKey(algorithm, rawPrivateKeyBytes); - - // signTest - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - SignatureDigest signature = signatureFunction.sign(privKey, data); - assertTrue(signatureFunction.verify(signature, pubKey, data)); - } -} diff --git a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA4096SignatureFunctionTest.java b/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA4096SignatureFunctionTest.java deleted file mode 100644 index 466e245d..00000000 --- a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SHA1WITHRSA4096SignatureFunctionTest.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.utils.CSRBuilder; -import com.jd.blockchain.crypto.utils.CertParser; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import java.security.PublicKey; -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.ASYMMETRIC_KEY; -import static com.jd.blockchain.crypto.CryptoAlgorithm.SIGNATURE_ALGORITHM; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: SHA1WITHRSA4096SignatureFunctionTest - * @description: TODO - * @date 2019-05-16, 10:49 - */ -public class SHA1WITHRSA4096SignatureFunctionTest { - - @Test - public void getAlgorithmTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SHA1WITHRSA4096"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("SHA1withRsa4096"); - assertNotNull(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("rsa2048"); - assertNull(algorithm); - } - - //@Test - public void generateKeyPairTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SHA1WITHRSA4096"); - assertNotNull(algorithm); - - AsymmetricKeypair keyPair = Crypto.getSignatureFunction(algorithm).generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - assertEquals(PUBLIC.CODE, pubKey.getKeyType().CODE); - assertTrue(pubKey.getRawKeyBytes().length > 515); - assertEquals(PRIVATE.CODE, privKey.getKeyType().CODE); - assertTrue(privKey.getRawKeyBytes().length > 2307); - - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(algorithm.code(), privKey.getAlgorithm()); - - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawPubKeyBytes), pubKey.toBytes()); - assertArrayEquals(BytesUtils.concat(algoBytes, privKeyTypeBytes, rawPrivKeyBytes), privKey.toBytes()); - - // retrievePubKeyTest - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - PubKey retrievedPubKey = signatureFunction.retrievePubKey(privKey); - assertEquals(pubKey.getKeyType(), retrievedPubKey.getKeyType()); - assertEquals(pubKey.getRawKeyBytes().length, retrievedPubKey.getRawKeyBytes().length); - assertEquals(pubKey.getAlgorithm(), retrievedPubKey.getAlgorithm()); - assertArrayEquals(pubKey.toBytes(), retrievedPubKey.toBytes()); - - - // signAndVerifyTest - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - byte[] signatureBytes = signatureDigest.toBytes(); - assertEquals(2 + 512, signatureBytes.length); - assertEquals(algorithm.code(), signatureDigest.getAlgorithm()); - assertEquals(PKIAlgorithm.SHA1WITHRSA4096.code(), signatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 32 & 0x00FF)), - signatureDigest.getAlgorithm()); - algoBytes = BytesUtils.toBytes(signatureDigest.getAlgorithm()); - byte[] rawSinatureBytes = signatureDigest.getRawDigest(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawSinatureBytes), signatureBytes); - assertTrue(signatureFunction.verify(signatureDigest, pubKey, data)); - - // supportAndResolvePrivKeyTest - byte[] privKeyBytes = privKey.toBytes(); - assertTrue(signatureFunction.supportPrivKey(privKeyBytes)); - PrivKey resolvedPrivKey = signatureFunction.resolvePrivKey(privKeyBytes); - assertEquals(PRIVATE.CODE, resolvedPrivKey.getKeyType().CODE); - assertEquals(PKIAlgorithm.SHA1WITHRSA4096.code(), resolvedPrivKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 32 & 0x00FF)), - resolvedPrivKey.getAlgorithm()); - assertArrayEquals(privKeyBytes, resolvedPrivKey.toBytes()); - - // supportAndResolvePubKeyTest - byte[] pubKeyBytes = pubKey.toBytes(); - assertTrue(signatureFunction.supportPubKey(pubKeyBytes)); - PubKey resolvedPubKey = signatureFunction.resolvePubKey(pubKeyBytes); - assertEquals(PUBLIC.CODE, resolvedPubKey.getKeyType().CODE); - assertEquals(PKIAlgorithm.SHA1WITHRSA4096.code(), resolvedPubKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 32 & 0x00FF)), - resolvedPubKey.getAlgorithm()); - assertArrayEquals(pubKeyBytes, resolvedPubKey.toBytes()); - - - // supportAndResolveDigestTest - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertTrue(signatureFunction.supportDigest(signatureDigestBytes)); - SignatureDigest resolvedSignatureDigest = signatureFunction.resolveDigest(signatureDigestBytes); - assertEquals(512, resolvedSignatureDigest.getRawDigest().length); - assertEquals(PKIAlgorithm.SHA1WITHRSA4096.code(), resolvedSignatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 32 & 0x00FF)), - resolvedSignatureDigest.getAlgorithm()); - assertArrayEquals(signatureDigestBytes, resolvedSignatureDigest.toBytes()); - } - - @Test - public void testWithCSRAndCert() { - - String countryName = "CN"; - String stateName = "Beijing"; - String cityName = "Beijing"; - String organizationName = "JD.com"; - String departmentName = "Blockchain Department"; - String domainName = "ledger.jd.com"; - String emailName = "zhanglin33@jd.com"; - - - String publicKeyStr = "30820222300d06092a864886f70d01010105000382020f003082020a0282020100b40edee83b609e" + - "aa001f2496f95d2f3302513306ec9a8e7fce0d2e141fce7ee357a7465314c3f5f4b08cb6c95803c368ddbfedba483cb" + - "5c45914037ceee5783fc971a12ef9b0e4158dc379b59499eee629324a9beb350c4c10e50837345be128b91f43a03381" + - "758bbefe41c45712e4b5fdd5bde780167283706b24e37dd753db65b4c6b3e49cd8be825665d9a29a24b77e76473df02" + - "2327873555aa33ba2ffcc766cbefedc46ec868d10f817822540eaf5754c074dd6d428355ce24a058a4c9ce41e48aad5" + - "92e7955cf93d779d03d3acf25ae271346a9e4255e4ed902ae016032b04efbee98f43cd767653e089b37540e537aede9" + - "dbc04f8f1a858b2764b9eedac80b6a8da5ff02aab4be94e071c70718fde7227cdefec31600a1c55bac16f4de9dea8ab" + - "7824c1ec783b818dfe005f040a3f6872b1c7a6c31a66c1b06eb8d872a23d1b4fdadf9eed58f93b2a2bc145638a79a81" + - "904d39b22128ced18a2556c21888ed1ec8ad59bd6764f1ea16eb7f3574c53166f0827b5072d23017bd725adeb63eeb2" + - "29a4e78d4d7426e936753902bb51e3cd90630314f4ab41272a9e36cb668b2ba9c2ebc02e9ef0c377c88482e839f2f4d" + - "5c8efcfbe1280e52c6bdf80aa487ae03ff9dd9fd981f78172bc1141ce6031b0b8915658d830c696662507d3cf4ddba8" + - "7daabf97c15cbef58b15e84f16f879328c7c65076d94fc6b4514549831850203010001"; - - String privateKeyStr = "30820942020100300d06092a864886f70d01010105000482092c308209280201000282020100b40e" + - "dee83b609eaa001f2496f95d2f3302513306ec9a8e7fce0d2e141fce7ee357a7465314c3f5f4b08cb6c95803c368ddb" + - "fedba483cb5c45914037ceee5783fc971a12ef9b0e4158dc379b59499eee629324a9beb350c4c10e50837345be128b9" + - "1f43a03381758bbefe41c45712e4b5fdd5bde780167283706b24e37dd753db65b4c6b3e49cd8be825665d9a29a24b77" + - "e76473df022327873555aa33ba2ffcc766cbefedc46ec868d10f817822540eaf5754c074dd6d428355ce24a058a4c9c" + - "e41e48aad592e7955cf93d779d03d3acf25ae271346a9e4255e4ed902ae016032b04efbee98f43cd767653e089b3754" + - "0e537aede9dbc04f8f1a858b2764b9eedac80b6a8da5ff02aab4be94e071c70718fde7227cdefec31600a1c55bac16f" + - "4de9dea8ab7824c1ec783b818dfe005f040a3f6872b1c7a6c31a66c1b06eb8d872a23d1b4fdadf9eed58f93b2a2bc14" + - "5638a79a81904d39b22128ced18a2556c21888ed1ec8ad59bd6764f1ea16eb7f3574c53166f0827b5072d23017bd725" + - "adeb63eeb229a4e78d4d7426e936753902bb51e3cd90630314f4ab41272a9e36cb668b2ba9c2ebc02e9ef0c377c8848" + - "2e839f2f4d5c8efcfbe1280e52c6bdf80aa487ae03ff9dd9fd981f78172bc1141ce6031b0b8915658d830c696662507" + - "d3cf4ddba87daabf97c15cbef58b15e84f16f879328c7c65076d94fc6b451454983185020301000102820200063fece" + - "3452a579f817513454d3efb842afcac077dbf689a4d89de13533e4cdfb1bb6be0b6dc0d65b29a13bf1dd7b598e67782" + - "b6204b4128e149a54c59136c6ed45c661296169a78180d54a46595c939c26ccd33a7c095de6f08b01610726ef885a26" + - "cebbad5efc14bbe1204d15be5c5de5b64a5cc279b4e6e20bded4a8126973b2ac0e9de11c6a1282f7d060693909a30e0" + - "c49cc500bedd38ed99c18830a26dd39f772aabf527410d54ed338db022d674f21f1332d3b5d5f67234a58a97300d130" + - "aed0d46effc2b4e4895665934188d0c75749e26ca5b97645957989530657b332b4ef202b3d70fe2e07d0d526240fbe1" + - "68e320357be0f54e18008a233a8137e23ca1c54074b31c57eebee49bf2f1c66ea97a2c846a8d26680b97e1240d6763e" + - "60bcd8d696c806362b18bf0504a39e4d465a9548091dbe97c36f6d8e038d95a72c0a88ff524dc81fe0ed2afd69f4251" + - "1a90687a4c632c812234a19a7312b2dea3fcd4515800eca700733b0f83509184fe8d3cd21385f0ef0cec37c433d354f" + - "aed61662a62902c8708c81e2af20898f649c1bafd600baa0409c943cf82bc90ea20a8972da7ab3a252f4f08df2509de" + - "e1dacfe787eef4d60c0c92ec7a3c6277d7be39deed7704ac721d8efd138a410d632a32535142cf977b09d9fb680bc96" + - "c538c00440d5e1ed71f8510e6524e564d69a24d03f1a9a0c326b421e32550801c890282010100e8d72f8f1fbeada724" + - "3e6df25337a2e7fc43e3d4f39877f89abb3b5e453f20f339a1f35e0a2847122f0bd835e6b43fd276f447da04f85cfca" + - "0fa8bf49b313239e36f9595ef1bfb9b8247bf01cc407dfc444421161a5b2e96d4d1d90cea185945e9447d21a2d8a461" + - "f43dff9ba58043feeb49552a3bf2472eea59b2aa8631048c76a15898065be0ef957d4802c827e30339d66ad7aed5851" + - "a5896f12d33f45800dcb10859531c590af7a75e9fa81f1d937a287fb6b066d58720584af2ae161e083681655ae77f48" + - "34bfe0accf1d12bbdd8c2644f78b207cfcb2dedf9fe7d29e1ae5c2a5623f5a1770db27d2636450c79fd39bce39f009b" + - "598e0298e1f77bf8d3d0282010100c5f7af9258a42da93204cecb71c544397bc16691cf0d41308fbd3b88eca7d101d1" + - "377dfe3b7e66707d3e5543b21033ab6c5b0de577740c6e335f512eeb2a839c3f2baeca4ce80e3fbd8fb93fa983e1719" + - "5c5fee63bc163df334a80f2767871e3434adc0bc7030dea44fce414a08da7e918e6f030cfb20b2d29033e9ef1be3e08" + - "ef1f50df0c9325a20ff01d0b7a06761403ae3498aea8bad93110d61a6386d470e630990029e2cb098de40fafa330911" + - "6c3c6de180b7fa41ae14553e891148ab53e970ce372b1777826983baaccac08290e343761d8daa2505f1dc45b8511a3" + - "6e2d0909237be9ae7ebbaa00b31de1224f32959e4e6f3428140ca8e1e5580789e902820100674075609c8d2be880940" + - "6a17cf1a1160ab1f8684895862e023fa0f60ef30da38e1d1914cca04bd3ee74ec2e0ade47a70705108fc7c0734bbbff" + - "1eed1b9cd74f00624d0d2df954bc032bd9b1ec6774f6d736f70d1c26ef2407bffee65130f6f59f99b57ba3013af40d2" + - "12926565fe8c734835276e61a6c228bddb6f3138acd1f94c3bbcbbe9623cb5a9931c3ba0aa60a9a2d5137cfd9f3aa59" + - "3aa63c8b5b8162f07ab8df1391f092827bffe400e3bb73d8a9f8e88495357f3482b2c9a7153bc01c9b88dca4e7b6975" + - "db73e2aa213daa7462cfa4c63afc67d30bcd0a1d2657da323dc0b06e45d09240cab3e0ac1436922a0ede8a79ca0519d" + - "375a7621d23269690282010100bbc1299716d2bf2b94f0d260494ada65da6596adfb3d8af24fa11d71c36175eccf4c5" + - "e065cce88c16f474afea546907aa88dc3243aa2a9976ac99fe96bc82a8269b738534d9558ce432ea87724829bb26a66" + - "1a56a99dc4e6cf727dd17762cc40ca759934e24e9747f49e14832bb2ade97960adb4dd86f2eaa5d719f10d3d6d00742" + - "9b33d98638671a9c40507f9775f4da41ff86a465c68b9ccbb371458086c3b9755c8064bb378f55ac94dc73a72b96869" + - "cd969e1f69b36e7af091a024d8e2a4faf3af999811904937f171c58fd028fd272786cf1a286180f074fee1fdd6b8b5a" + - "9a8c42e0f3b95ef4474fbace54dbc887865467b0524e64dfda3be7b117e34e1028201001a7e846231c34400c1f704e7" + - "fec6e46c87d61f269b71942bc9cc72005ba30eea3db5d0e5b0b754f7a00b96c883399982b5b3a9916765c5ed9129e44" + - "a791ce6892f85758c637bc040da132b8f0cd0ac36ba3aae9334414a77f0b50c0aa03643bfd59b9a621342a4807e46fc" + - "52a5a12fd3ff6762e181c40c2baf3653043c836b14700463af5d68a2a2897897edb5f217d655d5bcd24e7910062f40e" + - "00f19e2f94b45efbbf60cbf734830756baf72dcfca8d2858ca5df63336999474945f3744a96e4ce23f9067bbca849ef" + - "1048cba3a4aad73ed73b0fcd8c2e9f6d06aa768548d7107aa58d9d296f853543f6569e4dd33270540d983460773794f" + - "e9196fc5a54cd"; - - String expectedCSR = "MIIE4jCCAsoCAQAwgZwxCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW" + - "5nMQ8wDQYDVQQKDAZKRC5jb20xHjAcBgNVBAsMFUJsb2NrY2hhaW4gRGVwYXJ0bWVudDEWMBQGA1UEAwwNbGVkZ2VyLmpkL" + - "mNvbTEgMB4GCSqGSIb3DQEJARYRemhhbmdsaW4zM0BqZC5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC0" + - "Dt7oO2CeqgAfJJb5XS8zAlEzBuyajn/ODS4UH85+41enRlMUw/X0sIy2yVgDw2jdv+26SDy1xFkUA3zu5Xg/yXGhLvmw5BW" + - "Nw3m1lJnu5ikySpvrNQxMEOUINzRb4Si5H0OgM4F1i77+QcRXEuS1/dW954AWcoNwayTjfddT22W0xrPknNi+glZl2aKaJL" + - "d+dkc98CIyeHNVWqM7ov/Mdmy+/txG7IaNEPgXgiVA6vV1TAdN1tQoNVziSgWKTJzkHkiq1ZLnlVz5PXedA9Os8lricTRqn" + - "kJV5O2QKuAWAysE777pj0PNdnZT4ImzdUDlN67enbwE+PGoWLJ2S57trIC2qNpf8CqrS+lOBxxwcY/ecifN7+wxYAocVbrB" + - "b03p3qireCTB7Hg7gY3+AF8ECj9ocrHHpsMaZsGwbrjYcqI9G0/a357tWPk7KivBRWOKeagZBNObIhKM7RiiVWwhiI7R7Ir" + - "Vm9Z2Tx6hbrfzV0xTFm8IJ7UHLSMBe9clretj7rIppOeNTXQm6TZ1OQK7UePNkGMDFPSrQScqnjbLZosrqcLrwC6e8MN3yI" + - "SC6Dny9NXI78++EoDlLGvfgKpIeuA/+d2f2YH3gXK8EUHOYDGwuJFWWNgwxpZmJQfTz03bqH2qv5fBXL71ixXoTxb4eTKMf" + - "GUHbZT8a0UUVJgxhQIDAQABoAAwDQYJKoZIhvcNAQEFBQADggIBAKowJTG9mZLbDHRndmDUd7PWrq1AiCdk6DStV39B/REF" + - "OrMYcW9X4Ak69fhXQDtD4gu2lKtumDY0oJ8xleM2FHUSzdooTWb7P/QtCIBy27sH6nvlefRWi7ngSTNJlDmwgr0l07UzZU1" + - "Yl/ZULn0XlNAFal+qt+4ZNdiulNwkL6IofXV/8vqOeQw5iICDBYHItyY/mqD8IIaClVd8yNpEuE/W9GdJIDNXQjpug+BxL/" + - "FbjAs6P3ZzJboedJE5urbru2jjb7atl3w/eDo4r6+XNSD8d1PgVmVhzN2WpUWsZNeH2jd9AA6436GjsBssgSRKEc3FTJ+lO" + - "0Jw2d8GewXXkIv8CT4L3BFwqZhGQt27wlb87+W4dIC05JIaJx52869dvu1ky1CL73GROXeS8rVYJsPwVmK2xy3QTaeHGEQh" + - "kiVNeV1cc3mll2z7fgbkjPD8zDNBWUdzSXQMzecY1CBD02iz6LaHfvkI7gXXoiIf1cJrnLtYhv3lG45jKr0E45/Wn7oXmYk" + - "RM4/zHO4KnY7Pp3b3QTgkRJaPnZiG7aiCrdnTIopDSGpTWSPWDLjgwgaCPPz5Pd2Fk+SAE98o7Cu8O0vxMASpd4liaedASE" + - "n6hnrvcTkFLLG2ecZzJZ0aEqPi4es0FqlqVZrLPH2UYpECgfhkGQQKAx4eRTAZFhz1GSkd"; - - String expectedUserCert = "MIIFRjCCBC6gAwIBAgIFIChmYWIwDQYJKoZIhvcNAQEFBQAwWTELMAkGA1UEBhMCQ04xMDAuBgNVB" + - "AoTJ0NoaW5hIEZpbmFuY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEYMBYGA1UEAxMPQ0ZDQSBURVNUIE9DQTExMB4X" + - "DTE5MDgyODA4MDAxMVoXDTIxMDgyODA4MDAxMVoweDELMAkGA1UEBhMCQ04xGDAWBgNVBAoTD0NGQ0EgVEVTVCBPQ0ExMTE" + - "RMA8GA1UECxMITG9jYWwgUkExFTATBgNVBAsTDEluZGl2aWR1YWwtMTElMCMGA1UEAxQcMDUxQHpoYW5nbGluIUBaMTg2MT" + - "IyMjkyOTVANzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALQO3ug7YJ6qAB8klvldLzMCUTMG7JqOf84NLhQfz" + - "n7jV6dGUxTD9fSwjLbJWAPDaN2/7bpIPLXEWRQDfO7leD/JcaEu+bDkFY3DebWUme7mKTJKm+s1DEwQ5Qg3NFvhKLkfQ6Az" + - "gXWLvv5BxFcS5LX91b3ngBZyg3BrJON911PbZbTGs+Sc2L6CVmXZopokt352Rz3wIjJ4c1Vaozui/8x2bL7+3Ebsho0Q+Be" + - "CJUDq9XVMB03W1Cg1XOJKBYpMnOQeSKrVkueVXPk9d50D06zyWuJxNGqeQlXk7ZAq4BYDKwTvvumPQ812dlPgibN1QOU3rt" + - "6dvAT48ahYsnZLnu2sgLao2l/wKqtL6U4HHHBxj95yJ83v7DFgChxVusFvTeneqKt4JMHseDuBjf4AXwQKP2hyscemwxpmw" + - "bBuuNhyoj0bT9rfnu1Y+TsqK8FFY4p5qBkE05siEoztGKJVbCGIjtHsitWb1nZPHqFut/NXTFMWbwgntQctIwF71yWt62Pu" + - "simk541NdCbpNnU5ArtR482QYwMU9KtBJyqeNstmiyupwuvALp7ww3fIhILoOfL01cjvz74SgOUsa9+Aqkh64D/53Z/Zgfe" + - "BcrwRQc5gMbC4kVZY2DDGlmYlB9PPTduofaq/l8FcvvWLFehPFvh5Mox8ZQdtlPxrRRRUmDGFAgMBAAGjgfUwgfIwHwYDVR" + - "0jBBgwFoAU/Au8RJoOMaGDqYGHJx4FQsa/VvgwSAYDVR0gBEEwPzA9BghggRyG7yoBAjAxMC8GCCsGAQUFBwIBFiNodHRwO" + - "i8vd3d3LmNmY2EuY29tLmNuL3VzL3VzLTE1Lmh0bTA6BgNVHR8EMzAxMC+gLaArhilodHRwOi8vMjEwLjc0LjQyLjMvT0NB" + - "MTEvUlNBL2NybDI2NjU1LmNybDALBgNVHQ8EBAMCA+gwHQYDVR0OBBYEFBl1Gmb89bqbEKyFcTU3eOY/5NmKMB0GA1UdJQQ" + - "WMBQGCCsGAQUFBwMCBggrBgEFBQcDBDANBgkqhkiG9w0BAQUFAAOCAQEADEU//9rnWN1s3/ariMHIUmgzRUdz3fWYiDRzGC" + - "mcnnETlXDstGmoYmwCM+QwHw6cyKXkwkg9zV7c7CgM471ZuF00gq115d432Ps3RXGCpfQ2fn3gs+91ky/YqJOOyBb8KL0IP" + - "r/Zh56/y3XX0gORn4GLqaj+oVZrFcmKrPtVhySlXNiD5BRMq39mUbuLBweGsgNVQ9VxiWc8ZBGjlJ6OVsngbvWrtl3zgkKb" + - "X9lhr8Bxq3G+jOV8jvr1Dkn4a65g2TWcFquxmPvRc5UwN29CimbC7RViCL3Jp+zrGasqbjycuqu5eSXb6gG4/aV0/K9yn5k" + - "YlZMIBlbsXSEi5J26pg=="; - - String issuerCert = - "-----BEGIN CERTIFICATE-----\n" + - "MIIDzzCCAregAwIBAgIKUalCR1Mt5ZSK8jANBgkqhkiG9w0BAQUFADBZMQswCQYD\n" + - "VQQGEwJDTjEwMC4GA1UEChMnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24g\n" + - "QXV0aG9yaXR5MRgwFgYDVQQDEw9DRkNBIFRFU1QgQ1MgQ0EwHhcNMTIwODI5MDU1\n" + - "NDM2WhcNMzIwODI0MDU1NDM2WjBZMQswCQYDVQQGEwJDTjEwMC4GA1UEChMnQ2hp\n" + - "bmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRgwFgYDVQQDEw9D\n" + - "RkNBIFRFU1QgT0NBMTEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC8\n" + - "jn0n8Fp6hcRdACdn1+Y6GAkC6KGgNdKyHPrmsdmhCjnd/i4qUFwnG8cp3D4lFw1G\n" + - "jmjSO5yVYbik/NbS6lbNpRgTK3fDfMFvLJpRIC+IFhG9SdAC2hwjsH9qTpL9cK2M\n" + - "bSdrC6pBdDgnbzaM9AGBF4Y6vXhj5nah4ZMsBvDp19LzXjlGuTPLuAgv9ZlWknsd\n" + - "RN70PIAmvomd10uqX4GIJ4Jq/FdKXOLZ2DNK/NhRyN6Yq71L3ham6tutXeZow5t5\n" + - "0254AnUlo1u6SeH9F8itER653o/oMLFwp+63qXAcqrHUlOQPX+JI8fkumSqZ4F2F\n" + - "t/HfVMnqdtFNCnh5+eIBAgMBAAGjgZgwgZUwHwYDVR0jBBgwFoAUdN7FjQp9EBqq\n" + - "aYNbTSHOhpvMcTgwDAYDVR0TBAUwAwEB/zA4BgNVHR8EMTAvMC2gK6AphidodHRw\n" + - "Oi8vMjEwLjc0LjQyLjMvdGVzdHJjYS9SU0EvY3JsMS5jcmwwCwYDVR0PBAQDAgEG\n" + - "MB0GA1UdDgQWBBT8C7xEmg4xoYOpgYcnHgVCxr9W+DANBgkqhkiG9w0BAQUFAAOC\n" + - "AQEAb7W0K9fZPA+JPw6lRiMDaUJ0oh052yEXreMBfoPulxkBj439qombDiFggRLc\n" + - "3g8wIEKzMOzOKXTWtnzYwN3y/JQSuJb/M1QqOEEM2PZwCxI4AkBuH6jg03RjlkHg\n" + - "/kTtuIFp9ItBCC2/KkKlp0ENfn4XgVg2KtAjZ7lpyVU0LPnhEqqUVY/xthjlCSa7\n" + - "/XHNStRxsfCTIBUWJ8n2FZyQhfV/UkMNHDBIiJR0v6C4Ai0/290WvbPEIAq+03Si\n" + - "fsHzBeA0C8lP5VzfAr6wWePaZMCpStpLaoXNcAqReKxQllElOqAhRxC5VKH+rnIQ\n" + - "OMRZvB7FRyE9IfwKApngcZbA5g==\n" + - "-----END CERTIFICATE-----"; - - byte[] rawPublicKeyBytes = Hex.decode(publicKeyStr); - byte[] rawPrivateKeyBytes = Hex.decode(privateKeyStr); - - CSRBuilder builder = new CSRBuilder(); - builder.init("SHA1withRSA", rawPublicKeyBytes, rawPrivateKeyBytes); - - String csr = builder.buildRequest(countryName,stateName,cityName, - organizationName,departmentName,domainName, - emailName); - - assertEquals(expectedCSR,csr); - - CertParser parser = new CertParser(); - parser.parse(expectedUserCert,issuerCert); - - PublicKey rawPublicKeyInCert = parser.getPubKey(); - // check that the public key in inputs and the public key in certificate are consistent - assertArrayEquals(rawPublicKeyBytes, rawPublicKeyInCert.getEncoded()); - - String algoName = parser.getSigAlgName(); - int keyLength = parser.getKeyLength(); - String length = String.valueOf(keyLength); - String algo = (algoName.contains("RSA")? (algoName + length).toUpperCase(): algoName.toUpperCase()); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm(algo); - assertNotNull(algorithm); - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - PubKey pubKey = new PubKey(algorithm, rawPublicKeyBytes); - PrivKey privKey = new PrivKey(algorithm, rawPrivateKeyBytes); - - // signTest - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - SignatureDigest signature = signatureFunction.sign(privKey, data); - assertTrue(signatureFunction.verify(signature, pubKey, data)); - } -} diff --git a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SM3WITHSM2SignatureFunctionTest.java b/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SM3WITHSM2SignatureFunctionTest.java deleted file mode 100644 index 54969745..00000000 --- a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/service/pki/SM3WITHSM2SignatureFunctionTest.java +++ /dev/null @@ -1,353 +0,0 @@ -package com.jd.blockchain.crypto.service.pki; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.utils.CSRBuilder; -import com.jd.blockchain.crypto.utils.CertParser; -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import java.security.PublicKey; -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.ASYMMETRIC_KEY; -import static com.jd.blockchain.crypto.CryptoAlgorithm.SIGNATURE_ALGORITHM; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: SM3WITHSM2SignatureFunctionTest - * @description: TODO - * @date 2019-05-16, 17:04 - */ -public class SM3WITHSM2SignatureFunctionTest { - - @Test - public void getAlgorithmTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("sm3withsm2"); - assertNotNull(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("sm3withs"); - assertNull(algorithm); - } - - @Test - public void generateKeyPairTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - assertEquals(PUBLIC.CODE, pubKey.getKeyType().CODE); - assertTrue(pubKey.getRawKeyBytes().length > 32); - assertEquals(PRIVATE.CODE, privKey.getKeyType().CODE); - assertTrue(privKey.getRawKeyBytes().length > 65 + 32); - - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(algorithm.code(), privKey.getAlgorithm()); - - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawPubKeyBytes), pubKey.toBytes()); - assertArrayEquals(BytesUtils.concat(algoBytes, privKeyTypeBytes, rawPrivKeyBytes), privKey.toBytes()); - } - - @Test - public void retrievePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - PubKey retrievedPubKey = signatureFunction.retrievePubKey(privKey); - - assertEquals(pubKey.getKeyType(), retrievedPubKey.getKeyType()); - assertEquals(pubKey.getRawKeyBytes().length, retrievedPubKey.getRawKeyBytes().length); - assertEquals(pubKey.getAlgorithm(), retrievedPubKey.getAlgorithm()); - assertArrayEquals(pubKey.toBytes(), retrievedPubKey.toBytes()); - } - - @Test - public void signTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureBytes = signatureDigest.toBytes(); - - assertTrue(signatureBytes.length > 2 + 64); - assertEquals(algorithm.code(), signatureDigest.getAlgorithm()); - - assertEquals(PKIAlgorithm.SM3WITHSM2.code(), signatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 33 & 0x00FF)), - signatureDigest.getAlgorithm()); - - byte[] algoBytes = BytesUtils.toBytes(signatureDigest.getAlgorithm()); - byte[] rawSinatureBytes = signatureDigest.getRawDigest(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawSinatureBytes), signatureBytes); - } - - @Test - public void verifyTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - System.out.println(signatureDigest.getRawDigest().length); - assertTrue(signatureFunction.verify(signatureDigest, pubKey, data)); - } - - @Test - public void supportPrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - assertTrue(signatureFunction.supportPrivKey(privKeyBytes)); - } - - @Test - public void resolvePrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - PrivKey resolvedPrivKey = signatureFunction.resolvePrivKey(privKeyBytes); - - assertEquals(PRIVATE.CODE, resolvedPrivKey.getKeyType().CODE); - assertEquals(PKIAlgorithm.SM3WITHSM2.code(), resolvedPrivKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 33 & 0x00FF)), - resolvedPrivKey.getAlgorithm()); - assertArrayEquals(privKeyBytes, resolvedPrivKey.toBytes()); - } - - @Test - public void supportPubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - assertTrue(signatureFunction.supportPubKey(pubKeyBytes)); - } - - @Test - public void resolvePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - PubKey resolvedPubKey = signatureFunction.resolvePubKey(pubKeyBytes); - - assertEquals(PUBLIC.CODE, resolvedPubKey.getKeyType().CODE); - assertEquals(PKIAlgorithm.SM3WITHSM2.code(), resolvedPubKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 33 & 0x00FF)), - resolvedPubKey.getAlgorithm()); - assertArrayEquals(pubKeyBytes, resolvedPubKey.toBytes()); - } - - @Test - public void supportDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertTrue(signatureFunction.supportDigest(signatureDigestBytes)); - } - - @Test - public void resolveDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SM3WITHSM2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - - SignatureDigest resolvedSignatureDigest = signatureFunction.resolveDigest(signatureDigestBytes); - - assertTrue(resolvedSignatureDigest.getRawDigest().length > 64); - assertEquals(PKIAlgorithm.SM3WITHSM2.code(), resolvedSignatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | ((byte) 33 & 0x00FF)), - resolvedSignatureDigest.getAlgorithm()); - assertArrayEquals(signatureDigestBytes, resolvedSignatureDigest.toBytes()); - } - - - @Test - public void testWithCSRAndCert() { - - String publicKeyStr = "3059301306072a8648ce3d020106082a811ccf5501822d03420004aa6586478be879504fdd02892f" + - "b4cf2bdb3d96a316f41ff7bcadfabef4ea836678984f9ba6931a609391426ca7164592f5fccd062be56fc32b3eec3a5" + - "0400971"; - - String privateKeyStr = "308193020100301306072a8648ce3d020106082a811ccf5501822d0479307702010104207abd2953" + - "84f193abe4f3715c26bc15225061f007131755d94ca12c7e0ce0b3a0a00a06082a811ccf5501822da14403420004aa6" + - "586478be879504fdd02892fb4cf2bdb3d96a316f41ff7bcadfabef4ea836678984f9ba6931a609391426ca7164592f5" + - "fccd062be56fc32b3eec3a50400971"; - - String expectedUserCert = "MIICwjCCAmWgAwIBAgIFIChnMlIwDAYIKoEcz1UBg3UFADBdMQswCQYDVQQGEwJDTjEwMC4GA1UEC" + - "gwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRwwGgYDVQQDDBNDRkNBIFRFU1QgU00yIE9DQTEx" + - "MB4XDTE5MDgyODA4MTUzNloXDTIxMDgyODA4MTUzNloweDELMAkGA1UEBhMCQ04xGDAWBgNVBAoMD0NGQ0EgVEVTVCBPQ0E" + - "xMTERMA8GA1UECwwITG9jYWwgUkExFTATBgNVBAsMDEluZGl2aWR1YWwtMTElMCMGA1UEAwwcMDUxQHpoYW5nbGluIUBaMT" + - "g2MTIyMjkyOTVAODBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IABKplhkeL6HlQT90CiS+0zyvbPZajFvQf97yt+r706oNme" + - "JhPm6aTGmCTkUJspxZFkvX8zQYr5W/DKz7sOlBACXGjgfQwgfEwHwYDVR0jBBgwFoAUvqZ+TT18j6BV5sEvCS4sIEOzQn8w" + - "SAYDVR0gBEEwPzA9BghggRyG7yoBAjAxMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmNmY2EuY29tLmNuL3VzL3VzLTE1Lmh" + - "0bTA5BgNVHR8EMjAwMC6gLKAqhihodHRwOi8vMjEwLjc0LjQyLjMvT0NBMTEvU00yL2NybDI0OTkuY3JsMAsGA1UdDwQEAw" + - "ID6DAdBgNVHQ4EFgQU07tMtbs5PWkwN33OQVH116xd1kowHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMAwGCCqBH" + - "M9VAYN1BQADSQAwRgIhAPuuInppVhugw6EIG4wgkouxX/MX2dTLe478wx7LFXSQAiEAneiz51vrurICNCfeecaBHgzaj7+3" + - "kmrdIZJBoxYGbso="; - - String issuerCert = - "-----BEGIN CERTIFICATE-----\n" + - "MIICTzCCAfOgAwIBAgIKJFSZ4SRVDndYUTAMBggqgRzPVQGDdQUAMF0xCzAJBgNV\n" + - "BAYTAkNOMTAwLgYDVQQKDCdDaGluYSBGaW5hbmNpYWwgQ2VydGlmaWNhdGlvbiBB\n" + - "dXRob3JpdHkxHDAaBgNVBAMME0NGQ0EgVEVTVCBDUyBTTTIgQ0EwHhcNMTIwODI5\n" + - "MDU0ODQ3WhcNMzIwODI0MDU0ODQ3WjBdMQswCQYDVQQGEwJDTjEwMC4GA1UECgwn\n" + - "Q2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRwwGgYDVQQD\n" + - "DBNDRkNBIFRFU1QgU00yIE9DQTExMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE\n" + - "L1mx4wriQUojGsIkNL14kslv9nwiqsiVpELOZauzghrbccNlPYKNYKZOCvXwIIqU\n" + - "9QY02d4weqKqo/JMcNsKEaOBmDCBlTAfBgNVHSMEGDAWgBS12JBvXPDYM9JjvX6y\n" + - "w43GTxJ6YTAMBgNVHRMEBTADAQH/MDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly8y\n" + - "MTAuNzQuNDIuMy90ZXN0cmNhL1NNMi9jcmwxLmNybDALBgNVHQ8EBAMCAQYwHQYD\n" + - "VR0OBBYEFL6mfk09fI+gVebBLwkuLCBDs0J/MAwGCCqBHM9VAYN1BQADSAAwRQIh\n" + - "AKuk7s3eYCZDck5NWU0eNQmLhBN/1zmKs517qFrDrkJWAiAP4cVfLtdza/OkwU9P\n" + - "PrIDl+E4aL3FypntFXHG3T+Keg==\n" + - "-----END CERTIFICATE-----"; - - byte[] rawPublicKeyBytes = Hex.decode(publicKeyStr); - byte[] rawPrivateKeyBytes = Hex.decode(privateKeyStr); - - CSRBuilder builder = new CSRBuilder(); - builder.init("SM3withSM2", rawPublicKeyBytes, rawPrivateKeyBytes); - - CertParser parser = new CertParser(); - parser.parse(expectedUserCert,issuerCert); - - PublicKey rawPublicKeyInCert = parser.getPubKey(); - // check that the public key in inputs and the public key in certificate are consistent - assertArrayEquals(rawPublicKeyBytes, rawPublicKeyInCert.getEncoded()); - - String algoName = parser.getSigAlgName(); - int keyLength = parser.getKeyLength(); - String length = String.valueOf(keyLength); - String algo = (algoName.contains("RSA")? (algoName + length).toUpperCase(): algoName.toUpperCase()); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm(algo); - assertNotNull(algorithm); - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - PubKey pubKey = new PubKey(algorithm, rawPublicKeyBytes); - PrivKey privKey = new PrivKey(algorithm, rawPrivateKeyBytes); - - // signTest - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - SignatureDigest signature = signatureFunction.sign(privKey, data); - assertTrue(signatureFunction.verify(signature, pubKey, data)); - } -} diff --git a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/utils/CSRBuilderTest.java b/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/utils/CSRBuilderTest.java deleted file mode 100644 index 62dc4dc2..00000000 --- a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/utils/CSRBuilderTest.java +++ /dev/null @@ -1,396 +0,0 @@ -package com.jd.blockchain.crypto.utils; - -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.pkcs.CertificationRequestInfo; -import org.bouncycastle.asn1.x500.RDN; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.util.encoders.Base64; -import org.junit.Test; - -import java.io.IOException; -import java.security.*; - -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: CSRBuilderTest - * @description: TODO - * @date 2019-05-10, 17:22 - */ -public class CSRBuilderTest { - - @Test - public void defaultCSRTest(){ - - String countryName = "CN"; - String stateName = "Beijing"; - String cityName = "Beijing"; - String organizationName = "JD.com"; - String departmentName = "Blockchain Department"; - String domainName = "ledger.jd.com"; - String emailName = "zhanglin33@jd.com"; - - CSRBuilder builder = new CSRBuilder(); - - builder.init(); - String csr = builder.buildRequest(countryName,stateName,cityName, - organizationName,departmentName,domainName, - emailName); - - PublicKey pubKey = builder.getPubKey(); - PrivateKey privKey = builder.getPrivKey(); - - byte[] crsBytes = Base64.decode(csr); - PKCS10CertificationRequest request = null; - try { - request = new PKCS10CertificationRequest(crsBytes); - } catch (IOException e) { - e.printStackTrace(); - } - assertNotNull(request); - assertEquals("1.2.840.113549.1.1.5",request.getSignatureAlgorithm().getAlgorithm().getId()); - byte[] pubKeyBytes = new byte[0]; - try { - pubKeyBytes = request.getSubjectPublicKeyInfo().getEncoded(); - } catch (IOException e) { - e.printStackTrace(); - } - assertArrayEquals(pubKeyBytes,pubKey.getEncoded()); - - RDN[] rdns = request.getSubject().getRDNs(); - assertEquals(BCStyle.C, rdns[0].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.ST, rdns[1].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.L, rdns[2].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.O, rdns[3].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.OU, rdns[4].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.CN, rdns[5].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.E, rdns[6].getFirst().getType().toASN1Primitive()); - - assertEquals("CN", rdns[0].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[1].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[2].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("JD.com", rdns[3].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Blockchain Department", rdns[4].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("ledger.jd.com", rdns[5].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("zhanglin33@jd.com", rdns[6].getFirst().getValue().toASN1Primitive().toString()); - - byte[] signature = request.getSignature(); - - CertificationRequestInfo requestInfo = new CertificationRequestInfo(request.getSubject(),request.getSubjectPublicKeyInfo(),new DERSet()); - byte[] message = new byte[0]; - try { - message = requestInfo.getEncoded(ASN1Encoding.DER); - } catch (IOException e) { - e.printStackTrace(); - } - - Signature signer; - byte[] result = new byte[0]; - try { - signer = Signature.getInstance("SHA1withRSA"); - signer.initSign(privKey); - signer.update(message); - result = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertArrayEquals(result,signature); - - Signature verifier; - boolean isValid = false; - try { - verifier = Signature.getInstance("SHA1withRSA"); - verifier.initVerify(pubKey); - verifier.update(message); - isValid = verifier.verify(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertTrue(isValid); - } - - @Test - public void SHA1withRSA2048CSRTest(){ - - String countryName = "CN"; - String stateName = "Beijing"; - String cityName = "Beijing"; - String organizationName = "JD.com"; - String departmentName = "Blockchain Department"; - String domainName = "ledger.jd.com"; - String emailName = "zhanglin33@jd.com"; - - CSRBuilder builder = new CSRBuilder(); - - builder.init("SHA1withRSA",2048); - String csr = builder.buildRequest(countryName,stateName,cityName, - organizationName,departmentName,domainName, - emailName); - - PublicKey pubKey = builder.getPubKey(); - PrivateKey privKey = builder.getPrivKey(); - - byte[] crsBytes = Base64.decode(csr); - PKCS10CertificationRequest request = null; - try { - request = new PKCS10CertificationRequest(crsBytes); - } catch (IOException e) { - e.printStackTrace(); - } - assertNotNull(request); - assertEquals("1.2.840.113549.1.1.5",request.getSignatureAlgorithm().getAlgorithm().getId()); - byte[] pubKeyBytes = new byte[0]; - try { - pubKeyBytes = request.getSubjectPublicKeyInfo().getEncoded(); - } catch (IOException e) { - e.printStackTrace(); - } - assertArrayEquals(pubKeyBytes,pubKey.getEncoded()); - - RDN[] rdns = request.getSubject().getRDNs(); - assertEquals(BCStyle.C, rdns[0].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.ST, rdns[1].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.L, rdns[2].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.O, rdns[3].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.OU, rdns[4].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.CN, rdns[5].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.E, rdns[6].getFirst().getType().toASN1Primitive()); - - assertEquals("CN", rdns[0].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[1].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[2].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("JD.com", rdns[3].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Blockchain Department", rdns[4].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("ledger.jd.com", rdns[5].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("zhanglin33@jd.com", rdns[6].getFirst().getValue().toASN1Primitive().toString()); - - byte[] signature = request.getSignature(); - - CertificationRequestInfo requestInfo = new CertificationRequestInfo(request.getSubject(),request.getSubjectPublicKeyInfo(),new DERSet()); - byte[] message = new byte[0]; - try { - message = requestInfo.getEncoded(ASN1Encoding.DER); - } catch (IOException e) { - e.printStackTrace(); - } - - Signature signer; - byte[] result = new byte[0]; - try { - signer = Signature.getInstance("SHA1withRSA"); - signer.initSign(privKey); - signer.update(message); - result = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertArrayEquals(result,signature); - - Signature verifier; - boolean isValid = false; - try { - verifier = Signature.getInstance("SHA1withRSA"); - verifier.initVerify(pubKey); - verifier.update(message); - isValid = verifier.verify(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertTrue(isValid); - } - - -// @Test - public void SHA1withRSA4096CSRTest(){ - - String countryName = "CN"; - String stateName = "Beijing"; - String cityName = "Beijing"; - String organizationName = "JD.com"; - String departmentName = "Blockchain Department"; - String domainName = "ledger.jd.com"; - String emailName = "zhanglin33@jd.com"; - - CSRBuilder builder = new CSRBuilder(); - - builder.init("SHA1withRSA",4096); - String csr = builder.buildRequest(countryName,stateName,cityName, - organizationName,departmentName,domainName, - emailName); - - PublicKey pubKey = builder.getPubKey(); - PrivateKey privKey = builder.getPrivKey(); - - byte[] crsBytes = Base64.decode(csr); - PKCS10CertificationRequest request = null; - try { - request = new PKCS10CertificationRequest(crsBytes); - } catch (IOException e) { - e.printStackTrace(); - } - assertNotNull(request); - assertEquals("1.2.840.113549.1.1.5",request.getSignatureAlgorithm().getAlgorithm().getId()); - byte[] pubKeyBytes = new byte[0]; - try { - pubKeyBytes = request.getSubjectPublicKeyInfo().getEncoded(); - } catch (IOException e) { - e.printStackTrace(); - } - assertArrayEquals(pubKeyBytes,pubKey.getEncoded()); - - RDN[] rdns = request.getSubject().getRDNs(); - assertEquals(BCStyle.C, rdns[0].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.ST, rdns[1].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.L, rdns[2].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.O, rdns[3].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.OU, rdns[4].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.CN, rdns[5].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.E, rdns[6].getFirst().getType().toASN1Primitive()); - - assertEquals("CN", rdns[0].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[1].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[2].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("JD.com", rdns[3].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Blockchain Department", rdns[4].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("ledger.jd.com", rdns[5].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("zhanglin33@jd.com", rdns[6].getFirst().getValue().toASN1Primitive().toString()); - - byte[] signature = request.getSignature(); - - CertificationRequestInfo requestInfo = new CertificationRequestInfo(request.getSubject(),request.getSubjectPublicKeyInfo(),new DERSet()); - byte[] message = new byte[0]; - try { - message = requestInfo.getEncoded(ASN1Encoding.DER); - } catch (IOException e) { - e.printStackTrace(); - } - - Signature signer; - byte[] result = new byte[0]; - try { - signer = Signature.getInstance("SHA1withRSA"); - signer.initSign(privKey); - signer.update(message); - result = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertArrayEquals(result,signature); - - Signature verifier; - boolean isValid = false; - try { - verifier = Signature.getInstance("SHA1withRSA"); - verifier.initVerify(pubKey); - verifier.update(message); - isValid = verifier.verify(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertTrue(isValid); - } - - - @Test - public void SM3withSM2CSRTest(){ - - String countryName = "CN"; - String stateName = "Beijing"; - String cityName = "Beijing"; - String organizationName = "JD.com"; - String departmentName = "Blockchain Department"; - String domainName = "ledger.jd.com"; - String emailName = "zhanglin33@jd.com"; - - CSRBuilder builder = new CSRBuilder(); - - builder.init("SM3withSM2",256); - String csr = builder.buildRequest(countryName,stateName,cityName, - organizationName,departmentName,domainName, - emailName); - - System.out.println(csr); - PublicKey pubKey = builder.getPubKey(); - PrivateKey privKey = builder.getPrivKey(); - - byte[] crsBytes = Base64.decode(csr); - PKCS10CertificationRequest request = null; - try { - request = new PKCS10CertificationRequest(crsBytes); - } catch (IOException e) { - e.printStackTrace(); - } - assertNotNull(request); - assertEquals("1.2.156.10197.1.501",request.getSignatureAlgorithm().getAlgorithm().getId()); - byte[] pubKeyBytes = new byte[0]; - try { - pubKeyBytes = request.getSubjectPublicKeyInfo().getEncoded(); - } catch (IOException e) { - e.printStackTrace(); - } - assertArrayEquals(pubKeyBytes,pubKey.getEncoded()); - - RDN[] rdns = request.getSubject().getRDNs(); - assertEquals(BCStyle.C, rdns[0].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.ST, rdns[1].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.L, rdns[2].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.O, rdns[3].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.OU, rdns[4].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.CN, rdns[5].getFirst().getType().toASN1Primitive()); - assertEquals(BCStyle.E, rdns[6].getFirst().getType().toASN1Primitive()); - - assertEquals("CN", rdns[0].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[1].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Beijing", rdns[2].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("JD.com", rdns[3].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("Blockchain Department", rdns[4].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("ledger.jd.com", rdns[5].getFirst().getValue().toASN1Primitive().toString()); - assertEquals("zhanglin33@jd.com", rdns[6].getFirst().getValue().toASN1Primitive().toString()); - - byte[] signature = request.getSignature(); - - CertificationRequestInfo requestInfo = new CertificationRequestInfo(request.getSubject(),request.getSubjectPublicKeyInfo(),new DERSet()); - byte[] message = new byte[0]; - try { - message = requestInfo.getEncoded(ASN1Encoding.DER); - } catch (IOException e) { - e.printStackTrace(); - } - - Signature signer; - byte[] result = new byte[0]; - try { - signer = Signature.getInstance("SM3withSM2"); - signer.initSign(privKey); - signer.update(message); - result = signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - - Signature verifier; - boolean isValid = false; - try { - verifier = Signature.getInstance("SM3withSM2"); - verifier.initVerify(pubKey); - verifier.update(message); - isValid = verifier.verify(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertTrue(isValid); - - try { - verifier = Signature.getInstance("SM3withSM2"); - verifier.initVerify(pubKey); - verifier.update(message); - isValid = verifier.verify(result); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - e.printStackTrace(); - } - assertTrue(isValid); - } -} diff --git a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/utils/CertParserTest.java b/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/utils/CertParserTest.java deleted file mode 100644 index 263d3e88..00000000 --- a/source/crypto/crypto-pki/src/test/java/com/jd/blockchain/crypto/utils/CertParserTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.jd.blockchain.crypto.utils; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author zhanglin33 - * @title: CertParserTest - * @description: TODO - * @date 2019-05-13, 10:05 - */ -public class CertParserTest { - - @Test - public void parseSHA1WITHRSA2048Test() { - CertParser parser = new CertParser(); - String issuerCert = - "-----BEGIN CERTIFICATE-----\n" + - "MIIDzzCCAregAwIBAgIKUalCR1Mt5ZSK8jANBgkqhkiG9w0BAQUFADBZMQswCQYD\n" + - "VQQGEwJDTjEwMC4GA1UEChMnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24g\n" + - "QXV0aG9yaXR5MRgwFgYDVQQDEw9DRkNBIFRFU1QgQ1MgQ0EwHhcNMTIwODI5MDU1\n" + - "NDM2WhcNMzIwODI0MDU1NDM2WjBZMQswCQYDVQQGEwJDTjEwMC4GA1UEChMnQ2hp\n" + - "bmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRgwFgYDVQQDEw9D\n" + - "RkNBIFRFU1QgT0NBMTEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC8\n" + - "jn0n8Fp6hcRdACdn1+Y6GAkC6KGgNdKyHPrmsdmhCjnd/i4qUFwnG8cp3D4lFw1G\n" + - "jmjSO5yVYbik/NbS6lbNpRgTK3fDfMFvLJpRIC+IFhG9SdAC2hwjsH9qTpL9cK2M\n" + - "bSdrC6pBdDgnbzaM9AGBF4Y6vXhj5nah4ZMsBvDp19LzXjlGuTPLuAgv9ZlWknsd\n" + - "RN70PIAmvomd10uqX4GIJ4Jq/FdKXOLZ2DNK/NhRyN6Yq71L3ham6tutXeZow5t5\n" + - "0254AnUlo1u6SeH9F8itER653o/oMLFwp+63qXAcqrHUlOQPX+JI8fkumSqZ4F2F\n" + - "t/HfVMnqdtFNCnh5+eIBAgMBAAGjgZgwgZUwHwYDVR0jBBgwFoAUdN7FjQp9EBqq\n" + - "aYNbTSHOhpvMcTgwDAYDVR0TBAUwAwEB/zA4BgNVHR8EMTAvMC2gK6AphidodHRw\n" + - "Oi8vMjEwLjc0LjQyLjMvdGVzdHJjYS9SU0EvY3JsMS5jcmwwCwYDVR0PBAQDAgEG\n" + - "MB0GA1UdDgQWBBT8C7xEmg4xoYOpgYcnHgVCxr9W+DANBgkqhkiG9w0BAQUFAAOC\n" + - "AQEAb7W0K9fZPA+JPw6lRiMDaUJ0oh052yEXreMBfoPulxkBj439qombDiFggRLc\n" + - "3g8wIEKzMOzOKXTWtnzYwN3y/JQSuJb/M1QqOEEM2PZwCxI4AkBuH6jg03RjlkHg\n" + - "/kTtuIFp9ItBCC2/KkKlp0ENfn4XgVg2KtAjZ7lpyVU0LPnhEqqUVY/xthjlCSa7\n" + - "/XHNStRxsfCTIBUWJ8n2FZyQhfV/UkMNHDBIiJR0v6C4Ai0/290WvbPEIAq+03Si\n" + - "fsHzBeA0C8lP5VzfAr6wWePaZMCpStpLaoXNcAqReKxQllElOqAhRxC5VKH+rnIQ\n" + - "OMRZvB7FRyE9IfwKApngcZbA5g==\n" + - "-----END CERTIFICATE-----"; - - String userCert = "MIIEQDCCAyigAwIBAgIFICdVYzEwDQYJKoZIhvcNAQEFBQAwWTELMAkGA1UEBhMCQ04xMDAuBgNVBAoTJ0NoaW5hIEZpbmFuY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEYMBYGA1UEAxMPQ0ZDQSBURVNUIE9DQTExMB4XDTE5MDUxMDExMjAyNFoXDTIxMDUxMDExMjAyNFowcjELMAkGA1UEBhMCQ04xGDAWBgNVBAoTD0NGQ0EgVEVTVCBPQ0ExMTERMA8GA1UECxMITG9jYWwgUkExFTATBgNVBAsTDEluZGl2aWR1YWwtMTEfMB0GA1UEAxQWMDUxQGFhYWFhQFpIMDkzNTgwMjhAMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJx3F2WD1dJPzK/nRHO7d1TJ1hTjzGTmv0PQ7ECsJAh3U3BtnGTpCB+b4+JMI4LO8nHkKIBQ3P9XnF+Bf1iXdWNAQ4aWCxa2nV7lCp4w0GliPu/EMgIfmsSDUtgqbM3cr8sR8r9m1xG3gt2TIQJ+jT7sAiguU/kyNzpjaccOUIgUFa8IDFq9UeB76MXtCuhlERRZQCl47e+9w7ZoxmE7e6IZORxPp7rQWVBHlR9ntWjJfNDTm3gMP5ehP+yIZnKx1LudxkBLQxpMmspzOyH1zqx5nkKe49AfWWpDxxRvYkriyYC3aE81qLsU/bhLwNEKOju7BGDF/mhJLZUedojM0gMCAwEAAaOB9TCB8jAfBgNVHSMEGDAWgBT8C7xEmg4xoYOpgYcnHgVCxr9W+DBIBgNVHSAEQTA/MD0GCGCBHIbvKgECMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuY2ZjYS5jb20uY24vdXMvdXMtMTUuaHRtMDoGA1UdHwQzMDEwL6AtoCuGKWh0dHA6Ly8yMTAuNzQuNDIuMy9PQ0ExMS9SU0EvY3JsMjU2OTMuY3JsMAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQU5oKGaQs7Jt5Gfbt1XhFTWAySEKswHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMA0GCSqGSIb3DQEBBQUAA4IBAQAlmPRaImZV51iKjtpMKuyLMw7dX8L0lY3tl+pVZZSxHuwsN4GCCtV0Ej50up+/6EbfL4NUTiuHVAjCroKKvb+94CrdEwdnQGM5IbGSjT78nQpeASXbIWuUwA+ImjvZOzvq/0b56AzonNzBxOMGko/bj5smM6X8jrgJ0NQppo2KNSVNC4JbuoNWI4FM94SE4DUi9H7EYl4JdOtDaDtCsq49o/A1CZyYrmoOPCgxpQQXmuB3lGq/jyoOlW2aW8uee/hYG1JJcSHLBjF0WBwdxssgbBotA5f1PebiIMSbFgjk57bd4M80hhU/rI4Hkn9pcp5R7NsX95TtyDIg90LboBnW"; - - parser.parse(userCert, issuerCert); - assertEquals("SHA1WITHRSA", parser.getSigAlgName()); - assertEquals(2048, parser.getKeyLength()); - } - - @Test - public void parseSHA1WITHRSA4096Test() { - CertParser parser = new CertParser(); - String issuerCert = - "-----BEGIN CERTIFICATE-----\n" + - "MIIDzzCCAregAwIBAgIKUalCR1Mt5ZSK8jANBgkqhkiG9w0BAQUFADBZMQswCQYD\n" + - "VQQGEwJDTjEwMC4GA1UEChMnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24g\n" + - "QXV0aG9yaXR5MRgwFgYDVQQDEw9DRkNBIFRFU1QgQ1MgQ0EwHhcNMTIwODI5MDU1\n" + - "NDM2WhcNMzIwODI0MDU1NDM2WjBZMQswCQYDVQQGEwJDTjEwMC4GA1UEChMnQ2hp\n" + - "bmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRgwFgYDVQQDEw9D\n" + - "RkNBIFRFU1QgT0NBMTEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC8\n" + - "jn0n8Fp6hcRdACdn1+Y6GAkC6KGgNdKyHPrmsdmhCjnd/i4qUFwnG8cp3D4lFw1G\n" + - "jmjSO5yVYbik/NbS6lbNpRgTK3fDfMFvLJpRIC+IFhG9SdAC2hwjsH9qTpL9cK2M\n" + - "bSdrC6pBdDgnbzaM9AGBF4Y6vXhj5nah4ZMsBvDp19LzXjlGuTPLuAgv9ZlWknsd\n" + - "RN70PIAmvomd10uqX4GIJ4Jq/FdKXOLZ2DNK/NhRyN6Yq71L3ham6tutXeZow5t5\n" + - "0254AnUlo1u6SeH9F8itER653o/oMLFwp+63qXAcqrHUlOQPX+JI8fkumSqZ4F2F\n" + - "t/HfVMnqdtFNCnh5+eIBAgMBAAGjgZgwgZUwHwYDVR0jBBgwFoAUdN7FjQp9EBqq\n" + - "aYNbTSHOhpvMcTgwDAYDVR0TBAUwAwEB/zA4BgNVHR8EMTAvMC2gK6AphidodHRw\n" + - "Oi8vMjEwLjc0LjQyLjMvdGVzdHJjYS9SU0EvY3JsMS5jcmwwCwYDVR0PBAQDAgEG\n" + - "MB0GA1UdDgQWBBT8C7xEmg4xoYOpgYcnHgVCxr9W+DANBgkqhkiG9w0BAQUFAAOC\n" + - "AQEAb7W0K9fZPA+JPw6lRiMDaUJ0oh052yEXreMBfoPulxkBj439qombDiFggRLc\n" + - "3g8wIEKzMOzOKXTWtnzYwN3y/JQSuJb/M1QqOEEM2PZwCxI4AkBuH6jg03RjlkHg\n" + - "/kTtuIFp9ItBCC2/KkKlp0ENfn4XgVg2KtAjZ7lpyVU0LPnhEqqUVY/xthjlCSa7\n" + - "/XHNStRxsfCTIBUWJ8n2FZyQhfV/UkMNHDBIiJR0v6C4Ai0/290WvbPEIAq+03Si\n" + - "fsHzBeA0C8lP5VzfAr6wWePaZMCpStpLaoXNcAqReKxQllElOqAhRxC5VKH+rnIQ\n" + - "OMRZvB7FRyE9IfwKApngcZbA5g==\n" + - "-----END CERTIFICATE-----"; - - String userCert = "MIIFRjCCBC6gAwIBAgIFICdWiDMwDQYJKoZIhvcNAQEFBQAwWTELMAkGA1UEBhMCQ04xMDAuBgNVBAoTJ0NoaW5hIEZpbmFuY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEYMBYGA1UEAxMPQ0ZDQSBURVNUIE9DQTExMB4XDTE5MDUxNjA3MDcyMloXDTIxMDUxNjA3MDcyMloweDELMAkGA1UEBhMCQ04xGDAWBgNVBAoTD0NGQ0EgVEVTVCBPQ0ExMTERMA8GA1UECxMITG9jYWwgUkExFTATBgNVBAsTDEluZGl2aWR1YWwtMTElMCMGA1UEAxQcMDUxQHpoYW5nbGluIUBaMTg2MTIyMjkyOTVAMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAL0rTOxd8rsjPtFJ0aGVh9bZPy5Xo0SADaP7BbJsG4+ykLQMZHg9hTf/6fv1OsD2HEKFoMpIkW2gwCJW2nvicHcVql/shCoktc6ZBW6Dr/DxOgbO9tpoGxZ50xdI4Q0NsrxqtbCldW4ozPHdjgRJ83i1KSFh7evNrVByN/mB+jchrVGLWyJ1uIRgUUgpRZmZPoOHaizVJqrqWJGGk6xbDLR2gUQ1hTzetQaz1OeKtelHDk9FY08XSmNGssSMpuSjrxn78S888VW5WIxyo4cwrXSXFk3J7LNTy70Oga16HZjJD/vLTM6a4riPa8+uivPinKxK38/++nlBPNwhx6n46uYkd9Zvw+SJiJgpnuPJLtMZpKpJx7V1BDVEydKPUthilTdsmJtkBFSlFw0G1aKfuciBGzzJ3SKngJF/JqJAWIonVAFBGb6Gokp1Sw+T4KqXrdbjxYxiyyjZ++8O1vydgFAkx/NjsuwJnpKETiRKFJmY7YawcUvC4ixF7XQc0luFWRDYcbxOppir+ieMqhGXyaFhLUuB4WXv+rFxfa3NmkBW8q5TPzt/PwWcXpITsYTZYla/E/grB+OeZLYgjigT5YlgytPHG6Gt1ySCCd8WXFWpkBbQfXzqcvtU27RCcAUgfXk5NLb7NZCQg7heGjgzOdYJCPsa1d3m7l04+VIKGCZdAgMBAAGjgfUwgfIwHwYDVR0jBBgwFoAU/Au8RJoOMaGDqYGHJx4FQsa/VvgwSAYDVR0gBEEwPzA9BghggRyG7yoBAjAxMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmNmY2EuY29tLmNuL3VzL3VzLTE1Lmh0bTA6BgNVHR8EMzAxMC+gLaArhilodHRwOi8vMjEwLjc0LjQyLjMvT0NBMTEvUlNBL2NybDI1NzE3LmNybDALBgNVHQ8EBAMCA+gwHQYDVR0OBBYEFMjh6AzDCuNkD+pqQfiS6bqPGpI4MB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDBDANBgkqhkiG9w0BAQUFAAOCAQEApZaLXS6/6FudPA3l2xom5U7nJUOpQ1E6DO/ic9dFGtLE0WgyAqB3JVPvXEntppX55x/dAV7rvvz9NaEdiAe8DAj7qyoPDvC8ZWQK8U4n9l8N78QwALOURxzQNs+CBatJQzbu2w1RKVwkfE6xEIVnu+wjiAtymfwdLHMagHxDIC/eOPbTnbbtITJk2ukFfoc0WJ6Awg5lW+x7nGokEn/XAjKyRHCpkRUFGQm4ww41zlrqCqQqnVGVABJtjbdtFf7nh33QHl0fkj19nfMox9eGuntPyM0bNA0XqPMA+FWSCqeDT6uLbyaOKWxlhv53U/NCJl76U3tssMEWsm9amEDDQg=="; - - parser.parse(userCert, issuerCert); - assertEquals("SHA1WITHRSA", parser.getSigAlgName()); - assertEquals(4096, parser.getKeyLength()); - } - - @Test - public void parseSM3WITHSM2Test() { - CertParser parser = new CertParser(); - String issuerCert = - "-----BEGIN CERTIFICATE-----\n" + - "MIICTzCCAfOgAwIBAgIKJFSZ4SRVDndYUTAMBggqgRzPVQGDdQUAMF0xCzAJBgNV\n" + - "BAYTAkNOMTAwLgYDVQQKDCdDaGluYSBGaW5hbmNpYWwgQ2VydGlmaWNhdGlvbiBB\n" + - "dXRob3JpdHkxHDAaBgNVBAMME0NGQ0EgVEVTVCBDUyBTTTIgQ0EwHhcNMTIwODI5\n" + - "MDU0ODQ3WhcNMzIwODI0MDU0ODQ3WjBdMQswCQYDVQQGEwJDTjEwMC4GA1UECgwn\n" + - "Q2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRwwGgYDVQQD\n" + - "DBNDRkNBIFRFU1QgU00yIE9DQTExMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE\n" + - "L1mx4wriQUojGsIkNL14kslv9nwiqsiVpELOZauzghrbccNlPYKNYKZOCvXwIIqU\n" + - "9QY02d4weqKqo/JMcNsKEaOBmDCBlTAfBgNVHSMEGDAWgBS12JBvXPDYM9JjvX6y\n" + - "w43GTxJ6YTAMBgNVHRMEBTADAQH/MDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly8y\n" + - "MTAuNzQuNDIuMy90ZXN0cmNhL1NNMi9jcmwxLmNybDALBgNVHQ8EBAMCAQYwHQYD\n" + - "VR0OBBYEFL6mfk09fI+gVebBLwkuLCBDs0J/MAwGCCqBHM9VAYN1BQADSAAwRQIh\n" + - "AKuk7s3eYCZDck5NWU0eNQmLhBN/1zmKs517qFrDrkJWAiAP4cVfLtdza/OkwU9P\n" + - "PrIDl+E4aL3FypntFXHG3T+Keg==\n" + - "-----END CERTIFICATE-----"; - - String userCert = "MIICwDCCAmWgAwIBAgIFICdWkWgwDAYIKoEcz1UBg3UFADBdMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRwwGgYDVQQDDBNDRkNBIFRFU1QgU00yIE9DQTExMB4XDTE5MDUxNjA4MTA1MVoXDTIxMDUxNjA4MTA1MVoweDELMAkGA1UEBhMCQ04xGDAWBgNVBAoMD0NGQ0EgVEVTVCBPQ0ExMTERMA8GA1UECwwITG9jYWwgUkExFTATBgNVBAsMDEluZGl2aWR1YWwtMTElMCMGA1UEAwwcMDUxQHpoYW5nbGluIUBaMTg2MTIyMjkyOTVAMzBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IABPvNXpdZ4/4g+wx5qKS94CPkMqpEDhlnXYYW7ZzsbNI4d28sVBz5Ji6dTT1Zx627Kvw4tdUaUt7BVMvZsu3BFlyjgfQwgfEwHwYDVR0jBBgwFoAUvqZ+TT18j6BV5sEvCS4sIEOzQn8wSAYDVR0gBEEwPzA9BghggRyG7yoBAjAxMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmNmY2EuY29tLmNuL3VzL3VzLTE1Lmh0bTA5BgNVHR8EMjAwMC6gLKAqhihodHRwOi8vMjEwLjc0LjQyLjMvT0NBMTEvU00yL2NybDIxMDkuY3JsMAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQUxR5C/VjASus5zrAAFS4ulMpRjKgwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMAwGCCqBHM9VAYN1BQADRwAwRAIgVBzVi/fgkknr+2BH2wXeGMXC+Pa6p7rbldUsYMOYoyUCIAmQ4KEk2U1xJZSBpOPy5jN9kmRb+0YH6x04O/2tqCgq"; - - parser.parse(userCert, issuerCert); - assertEquals("SM3WITHSM2", parser.getSigAlgName()); - assertEquals(256, parser.getKeyLength()); - } - - @Test - public void authenticateIssuerByCATest() { - CertParser parser = new CertParser(); - String CACert = - "-----BEGIN CERTIFICATE-----\n" + - "MIICFDCCAbegAwIBAgIKPYozwkCO86Nd9TAMBggqgRzPVQGDdQUAMF0xCzAJBgNV\n" + - "BAYTAkNOMTAwLgYDVQQKDCdDaGluYSBGaW5hbmNpYWwgQ2VydGlmaWNhdGlvbiBB\n" + - "dXRob3JpdHkxHDAaBgNVBAMME0NGQ0EgVEVTVCBDUyBTTTIgQ0EwHhcNMTIwODI5\n" + - "MDMyOTQ2WhcNMzIwODI5MDMyOTQ2WjBdMQswCQYDVQQGEwJDTjEwMC4GA1UECgwn\n" + - "Q2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRwwGgYDVQQD\n" + - "DBNDRkNBIFRFU1QgQ1MgU00yIENBMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE\n" + - "tTjB3O4JueYFDDOtxH678HBZbEmrsgd3BDIdGf0BekyA26n9S0/pKPnjBh/zLouS\n" + - "8+GB5EEnjbn4An24yo1Gv6NdMFswHwYDVR0jBBgwFoAUtdiQb1zw2DPSY71+ssON\n" + - "xk8SemEwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFLXYkG9c\n" + - "8Ngz0mO9frLDjcZPEnphMAwGCCqBHM9VAYN1BQADSQAwRgIhAKwuuqoBS1bwDowW\n" + - "a4IU//UsvudswJYSlltqrd/PQ9q+AiEAyTUAjFdaGI+8yPdr3A93UiA38wtGPf9e\n" + - "6B6O/6abyWE=\n" + - "-----END CERTIFICATE-----"; - - String issuerCert = "-----BEGIN CERTIFICATE-----\n" + - "MIICTzCCAfOgAwIBAgIKJFSZ4SRVDndYUTAMBggqgRzPVQGDdQUAMF0xCzAJBgNV\n" + - "BAYTAkNOMTAwLgYDVQQKDCdDaGluYSBGaW5hbmNpYWwgQ2VydGlmaWNhdGlvbiBB\n" + - "dXRob3JpdHkxHDAaBgNVBAMME0NGQ0EgVEVTVCBDUyBTTTIgQ0EwHhcNMTIwODI5\n" + - "MDU0ODQ3WhcNMzIwODI0MDU0ODQ3WjBdMQswCQYDVQQGEwJDTjEwMC4GA1UECgwn\n" + - "Q2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRwwGgYDVQQD\n" + - "DBNDRkNBIFRFU1QgU00yIE9DQTExMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE\n" + - "L1mx4wriQUojGsIkNL14kslv9nwiqsiVpELOZauzghrbccNlPYKNYKZOCvXwIIqU\n" + - "9QY02d4weqKqo/JMcNsKEaOBmDCBlTAfBgNVHSMEGDAWgBS12JBvXPDYM9JjvX6y\n" + - "w43GTxJ6YTAMBgNVHRMEBTADAQH/MDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly8y\n" + - "MTAuNzQuNDIuMy90ZXN0cmNhL1NNMi9jcmwxLmNybDALBgNVHQ8EBAMCAQYwHQYD\n" + - "VR0OBBYEFL6mfk09fI+gVebBLwkuLCBDs0J/MAwGCCqBHM9VAYN1BQADSAAwRQIh\n" + - "AKuk7s3eYCZDck5NWU0eNQmLhBN/1zmKs517qFrDrkJWAiAP4cVfLtdza/OkwU9P\n" + - "PrIDl+E4aL3FypntFXHG3T+Keg==\n" + - "-----END CERTIFICATE-----"; - parser.parse(issuerCert, CACert); - assertEquals("SM3WITHSM2", parser.getSigAlgName()); - assertEquals(256, parser.getKeyLength()); - } -} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM2CryptoFunction.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM2CryptoFunction.java deleted file mode 100644 index 344aac35..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM2CryptoFunction.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.jd.blockchain.crypto.service.sm; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; - -import com.jd.blockchain.crypto.AsymmetricCiphertext; -import com.jd.blockchain.crypto.AsymmetricEncryptionFunction; -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.utils.sm.SM2Utils; - -public class SM2CryptoFunction implements AsymmetricEncryptionFunction, SignatureFunction { - - private static final CryptoAlgorithm SM2 = SMAlgorithm.SM2; - - private static final int ECPOINT_SIZE = 65; - private static final int PRIVKEY_SIZE = 32; - private static final int SIGNATUREDIGEST_SIZE = 64; - private static final int HASHDIGEST_SIZE = 32; - - private static final int PUBKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + ECPOINT_SIZE; - private static final int PRIVKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PRIVKEY_SIZE; - private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_CODE_SIZE + SIGNATUREDIGEST_SIZE; - - SM2CryptoFunction() { - } - - @Override - public Ciphertext encrypt(PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - - // 验证原始公钥长度为65字节 - if (rawPubKeyBytes.length != ECPOINT_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应SM2算法 - if (pubKey.getAlgorithm() != SM2.code()) { - throw new CryptoException("The is not sm2 public key!"); - } - - // 调用SM2加密算法计算密文 - return new AsymmetricCiphertext(SM2, SM2Utils.encrypt(data, rawPubKeyBytes)); - } - - @Override - public byte[] decrypt(PrivKey privKey, Ciphertext ciphertext) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - // 验证原始私钥长度为32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应SM2算法 - if (privKey.getAlgorithm() != SM2.code()) { - throw new CryptoException("This key is not SM2 private key!"); - } - - // 验证密文数据的算法标识对应SM2算法,并且密文符合长度要求 - if (ciphertext.getAlgorithm() != SM2.code() - || rawCiphertextBytes.length < ECPOINT_SIZE + HASHDIGEST_SIZE) { - throw new CryptoException("This is not SM2 ciphertext!"); - } - - // 调用SM2解密算法得到明文结果 - return SM2Utils.decrypt(rawCiphertextBytes, rawPrivKeyBytes); - } - - @Override - public PubKey retrievePubKey(PrivKey privKey) { - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawPubKeyBytes = SM2Utils.retrievePublicKey(rawPrivKeyBytes); - return new PubKey(SM2, rawPubKeyBytes); - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应SM2算法,并且密钥类型是私钥 - return privKeyBytes.length == PRIVKEY_LENGTH && CryptoAlgorithm.match(SM2, privKeyBytes) - && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIVATE.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - if (supportPrivKey(privKeyBytes)) { - return new PrivKey(privKeyBytes); - } else { - throw new CryptoException("privKeyBytes are invalid!"); - } - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+椭圆曲线点长度,密钥数据的算法标识对应SM2算法,并且密钥类型是公钥 - return pubKeyBytes.length == PUBKEY_LENGTH && CryptoAlgorithm.match(SM2, pubKeyBytes) - && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUBLIC.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - if (supportPubKey(pubKeyBytes)) { - return new PubKey(pubKeyBytes); - } else { - throw new CryptoException("pubKeyBytes are invalid!"); - } - } - - @Override - public boolean supportCiphertext(byte[] ciphertextBytes) { - // 验证输入字节数组长度>=算法标识长度+椭圆曲线点长度+哈希长度,字节数组的算法标识对应SM2算法 - return ciphertextBytes.length >= ALGORYTHM_CODE_SIZE + ECPOINT_SIZE + HASHDIGEST_SIZE - && CryptoAlgorithm.match(SM2, ciphertextBytes); - } - - @Override - public AsymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { - if (supportCiphertext(ciphertextBytes)) { - return new AsymmetricCiphertext(ciphertextBytes); - } else { - throw new CryptoException("ciphertextBytes are invalid!"); - } - } - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - // 验证原始私钥长度为256比特,即32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应SM2签名算法 - if (privKey.getAlgorithm() != SM2.code()) { - throw new CryptoException("This key is not SM2 private key!"); - } - - // 调用SM2签名算法计算签名结果 - return new SignatureDigest(SM2, SM2Utils.sign(data, rawPrivKeyBytes)); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - // 验证原始公钥长度为520比特,即65字节 - if (rawPubKeyBytes.length != ECPOINT_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应SM2签名算法 - if (pubKey.getAlgorithm() != SM2.code()) { - throw new CryptoException("This key is not SM2 public key!"); - } - - // 验证签名数据的算法标识对应SM2签名算法,并且原始签名长度为64字节 - if (digest.getAlgorithm() != SM2.code() || rawDigestBytes.length != SIGNATUREDIGEST_SIZE) { - throw new CryptoException("This is not SM2 signature digest!"); - } - - // 调用SM2验签算法验证签名结果 - return SM2Utils.verify(data, rawPubKeyBytes, rawDigestBytes); - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+签名长度,字节数组的算法标识对应SM2算法 - return digestBytes.length == SIGNATUREDIGEST_LENGTH && CryptoAlgorithm.match(SM2, digestBytes); - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - if (supportDigest(digestBytes)) { - return new SignatureDigest(digestBytes); - } else { - throw new CryptoException("digestBytes are invalid!"); - } - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return SM2; - } - - @Override - public AsymmetricKeypair generateKeypair() { - - // 调用SM2算法的密钥生成算法生成公私钥对priKey和pubKey,返回密钥对 - AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); - ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); - ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytesD = ecPriv.getD().toByteArray(); - byte[] privKeyBytes = new byte[PRIVKEY_SIZE]; - if (privKeyBytesD.length > PRIVKEY_SIZE) { - System.arraycopy(privKeyBytesD, privKeyBytesD.length - PRIVKEY_SIZE, - privKeyBytes, 0, PRIVKEY_SIZE); - } - else { - System.arraycopy(privKeyBytesD, 0, - privKeyBytes, PRIVKEY_SIZE - privKeyBytesD.length, privKeyBytesD.length); - } - - byte[] pubKeyBytes = ecPub.getQ().getEncoded(false); - - return new AsymmetricKeypair(new PubKey(SM2, pubKeyBytes), new PrivKey(SM2, privKeyBytes)); - } -} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM3HashFunction.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM3HashFunction.java deleted file mode 100644 index 79893ae5..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM3HashFunction.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jd.blockchain.crypto.service.sm; - -import java.util.Arrays; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoBytes; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.utils.sm.SM3Utils; - -public class SM3HashFunction implements HashFunction { - - private static final CryptoAlgorithm SM3 = SMAlgorithm.SM3; - - private static final int DIGEST_BYTES = 256 / 8; - - private static final int DIGEST_LENGTH = CryptoBytes.ALGORYTHM_CODE_SIZE + DIGEST_BYTES; - - SM3HashFunction() { - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return SM3; - } - - @Override - public HashDigest hash(byte[] data) { - if (data == null) { - throw new CryptoException("data is null!"); - } - - byte[] digestBytes = SM3Utils.hash(data); - return new HashDigest(SM3, digestBytes); - } - - @Override - public HashDigest hash(byte[] data, int offset, int len) { - if (data == null) { - throw new CryptoException("data is null!"); - } - - byte[] digestBytes = SM3Utils.hash(data, offset, len); - return new HashDigest(SM3, digestBytes); - } - - @Override - public boolean verify(HashDigest digest, byte[] data) { - HashDigest hashDigest = hash(data); - return Arrays.equals(hashDigest.toBytes(), digest.toBytes()); - } - - @Override - public boolean supportHashDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,以及算法标识; - return CryptoAlgorithm.match(SM3, digestBytes) && DIGEST_LENGTH == digestBytes.length; - } - - @Override - public HashDigest resolveHashDigest(byte[] digestBytes) { - if (supportHashDigest(digestBytes)) { - return new HashDigest(digestBytes); - } else { - throw new CryptoException("digestBytes is invalid!"); - } - } -} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunction.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunction.java deleted file mode 100644 index 892b21f8..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunction.java +++ /dev/null @@ -1,212 +0,0 @@ -package com.jd.blockchain.crypto.service.sm; - -import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.utils.sm.SM4Utils; - -public class SM4EncryptionFunction implements SymmetricEncryptionFunction { - - private static final CryptoAlgorithm SM4 = SMAlgorithm.SM4; - - private static final int KEY_SIZE = 128 / 8; - private static final int BLOCK_SIZE = 128 / 8; - - // SM4-CBC - private static final int PLAINTEXT_BUFFER_LENGTH = 256; - private static final int CIPHERTEXT_BUFFER_LENGTH = 256 + 32 + 2; - - private static final int SYMMETRICKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + KEY_SIZE; - - SM4EncryptionFunction() { - } - - @Override - public Ciphertext encrypt(SymmetricKey key, byte[] data) { - - byte[] rawKeyBytes = key.getRawKeyBytes(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应SM4算法 - if (key.getAlgorithm() != SM4.code()) { - throw new CryptoException("The is not SM4 symmetric key!"); - } - - // 调用底层SM4算法并计算密文数据 - return new SymmetricCiphertext(SM4, SM4Utils.encrypt(data, rawKeyBytes)); - } - - @Override - public void encrypt(SymmetricKey key, InputStream in, OutputStream out) { - - // 读输入流得到明文,加密,密文数据写入输出流 - try { - byte[] buffBytes = new byte[PLAINTEXT_BUFFER_LENGTH]; - - // The final byte of plaintextWithPadding represents the length of padding in - // the first 256 bytes, - // and the padded value in hexadecimal - byte[] plaintextWithPadding = new byte[buffBytes.length + 1]; - - byte padding; - - int len; - int i; - - while ((len = in.read(buffBytes)) > 0) { - padding = (byte) (PLAINTEXT_BUFFER_LENGTH - len); - i = len; - while (i < plaintextWithPadding.length) { - plaintextWithPadding[i] = padding; - i++; - } - out.write(encrypt(key, plaintextWithPadding).toBytes()); - } - // byte[] sm4Data = new byte[in.available()]; - // in.read(sm4Data); - // in.close(); - // - // out.write(encrypt(key, sm4Data).toBytes()); - // out.close(); - } catch (IOException e) { - throw new CryptoException(e.getMessage(), e); - } - } - - @Override - public byte[] decrypt(SymmetricKey key, Ciphertext ciphertext) { - - byte[] rawKeyBytes = key.getRawKeyBytes(); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) { - throw new CryptoException("This key has wrong format!"); - } - - // 验证密钥数据的算法标识对应SM4算法 - if (key.getAlgorithm() != SM4.code()) { - throw new CryptoException("The is not SM4 symmetric key!"); - } - - // 验证原始密文长度为分组长度的整数倍 - if (rawCiphertextBytes.length % BLOCK_SIZE != 0) { - throw new CryptoException("This ciphertext has wrong format!"); - } - - // 验证密文数据算法标识对应SM4算法 - if (ciphertext.getAlgorithm() != SM4.code()) { - throw new CryptoException("This is not SM4 ciphertext!"); - } - - // 调用底层SM4算法解密,得到明文 - return SM4Utils.decrypt(rawCiphertextBytes, rawKeyBytes); - } - - @Override - public void decrypt(SymmetricKey key, InputStream in, OutputStream out) { - // 读输入流得到密文数据,解密,明文写入输出流 - try { - byte[] buffBytes = new byte[CIPHERTEXT_BUFFER_LENGTH]; - byte[] plaintextWithPadding; - - byte padding; - byte[] plaintext; - - int len, i; - while ((len = in.read(buffBytes)) > 0) { - if (len != CIPHERTEXT_BUFFER_LENGTH) { - throw new CryptoException("inputStream's length is wrong!"); - } - if (!supportCiphertext(buffBytes)) { - throw new CryptoException("InputStream is not valid SM4 ciphertext!"); - } - - plaintextWithPadding = decrypt(key, resolveCiphertext(buffBytes)); - - if (plaintextWithPadding.length != (PLAINTEXT_BUFFER_LENGTH + 1)) { - throw new CryptoException("The decrypted plaintext is invalid"); - } - - padding = plaintextWithPadding[PLAINTEXT_BUFFER_LENGTH]; - i = PLAINTEXT_BUFFER_LENGTH; - - while ((PLAINTEXT_BUFFER_LENGTH - padding) < i) { - - if (plaintextWithPadding[i] != padding) { - throw new CryptoException("The inputSteam padding is invalid!"); - } - i--; - } - plaintext = new byte[PLAINTEXT_BUFFER_LENGTH - padding]; - System.arraycopy(plaintextWithPadding, 0, plaintext, 0, plaintext.length); - out.write(plaintext); - } - // byte[] sm4Data = new byte[in.available()]; - // in.read(sm4Data); - // in.close(); - // - // if (!supportCiphertext(sm4Data)) { - // throw new CryptoException("InputStream is not valid SM4 ciphertext!"); - // } - // - // out.write(decrypt(key, resolveCiphertext(sm4Data))); - // out.close(); - } catch (IOException e) { - throw new CryptoException(e.getMessage(), e); - } - } - - @Override - public boolean supportSymmetricKey(byte[] symmetricKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,字节数组的算法标识对应SM4算法且密钥密钥类型是对称密钥 - return symmetricKeyBytes.length == SYMMETRICKEY_LENGTH && CryptoAlgorithm.match(SM4, symmetricKeyBytes) - && symmetricKeyBytes[ALGORYTHM_CODE_SIZE] == SYMMETRIC.CODE; - } - - @Override - public SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes) { - if (supportSymmetricKey(symmetricKeyBytes)) { - return new SymmetricKey(symmetricKeyBytes); - } else { - throw new CryptoException("symmetricKeyBytes is invalid!"); - } - } - - @Override - public boolean supportCiphertext(byte[] ciphertextBytes) { - // 验证(输入字节数组长度-算法标识长度)是分组长度的整数倍,字节数组的算法标识对应SM4算法 - return (ciphertextBytes.length - ALGORYTHM_CODE_SIZE) % BLOCK_SIZE == 0 - && CryptoAlgorithm.match(SM4, ciphertextBytes); - } - - @Override - public SymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { - if (supportCiphertext(ciphertextBytes)) { - return new SymmetricCiphertext(ciphertextBytes); - } else { - throw new CryptoException("ciphertextBytes is invalid!"); - } - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return SM4; - } - - @Override - public SymmetricKey generateSymmetricKey() { - // 根据对应的标识和原始密钥生成相应的密钥数据 - return new SymmetricKey(SM4, SM4Utils.generateKey()); - } -} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMAlgorithm.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMAlgorithm.java deleted file mode 100644 index 62e13a06..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMAlgorithm.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.crypto.service.sm; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoAlgorithmDefinition; - -public final class SMAlgorithm { - - public static final CryptoAlgorithm SM2 = CryptoAlgorithmDefinition.defineSignature("SM2", true, (byte) 2); - - public static final CryptoAlgorithm SM3 = CryptoAlgorithmDefinition.defineHash("SM3", (byte) 3); - - public static final CryptoAlgorithm SM4 = CryptoAlgorithmDefinition.defineSymmetricEncryption("SM4", (byte) 4); - - private SMAlgorithm() { - } - -} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMCryptoService.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMCryptoService.java deleted file mode 100644 index 001a699f..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMCryptoService.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jd.blockchain.crypto.service.sm; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import com.jd.blockchain.crypto.CryptoFunction; -import com.jd.blockchain.crypto.CryptoService; -import com.jd.blockchain.provider.NamedProvider; - -/** - * 国密软实现; - * - * @author huanghaiquan - * - */ -@NamedProvider("SM-SOFTWARE") -public class SMCryptoService implements CryptoService { - - public static final SM2CryptoFunction SM2 = new SM2CryptoFunction(); - public static final SM3HashFunction SM3 = new SM3HashFunction(); - public static final SM4EncryptionFunction SM4 = new SM4EncryptionFunction(); - - private static final Collection FUNCTIONS; - - static { - List funcs = Arrays.asList(SM2, SM3, SM4); - FUNCTIONS = Collections.unmodifiableList(funcs); - } - - @Override - public Collection getFunctions() { - return FUNCTIONS; - } - -} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM2Utils.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM2Utils.java deleted file mode 100644 index b3a65b18..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM2Utils.java +++ /dev/null @@ -1,303 +0,0 @@ -package com.jd.blockchain.crypto.utils.sm; - -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.engines.SM2Engine; -import org.bouncycastle.crypto.generators.ECKeyPairGenerator; -import org.bouncycastle.crypto.params.*; -import org.bouncycastle.crypto.signers.SM2Signer; -import org.bouncycastle.jce.ECNamedCurveTable; -import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; -import org.bouncycastle.math.ec.*; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.SecureRandom; - -public class SM2Utils { - - private static final int COORDS_SIZE = 32; - private static final int POINT_SIZE = COORDS_SIZE * 2 + 1; - private static final int R_SIZE =32; - private static final int S_SIZE =32; - - // The length of sm3 output is 32 bytes - private static final int SM3DIGEST_LENGTH = 32; - - private static final ECNamedCurveParameterSpec PARAMS = ECNamedCurveTable.getParameterSpec("sm2p256v1"); - private static final ECCurve CURVE = PARAMS.getCurve(); - private static final ECDomainParameters DOMAIN_PARAMS = new ECDomainParameters( - CURVE, PARAMS.getG(), PARAMS.getN(), PARAMS.getH()); - - - //-----------------Key Generation Algorithm----------------- - - /** - * key pair generation - * - * @return key pair - */ - public static AsymmetricCipherKeyPair generateKeyPair(){ - SecureRandom random = new SecureRandom(); - return generateKeyPair(random); - } - - public static AsymmetricCipherKeyPair generateKeyPair(SecureRandom random){ - - ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS,random); - ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); - - // To generate the key pair - keyPairGenerator.init(keyGenerationParams); - return keyPairGenerator.generateKeyPair(); - } - - /** - * public key retrieval - * - * @param privateKey private key - * @return publicKey - */ - public static byte[] retrievePublicKey(byte[] privateKey) { - ECPoint publicKeyPoint = DOMAIN_PARAMS.getG().multiply(new BigInteger(1,privateKey)).normalize(); - return publicKeyPoint.getEncoded(false); - } - - - //-----------------Digital Signature Algorithm----------------- - - /** - * signature generation - * - * @param data data to be signed - * @param privateKey private key - * @return signature - */ - public static byte[] sign(byte[] data, byte[] privateKey){ - - SecureRandom random = new SecureRandom(); - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); - CipherParameters params = new ParametersWithRandom(privKey,random); - - return sign(data,params); - } - - public static byte[] sign(byte[] data, byte[] privateKey, SecureRandom random, String ID){ - - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); - CipherParameters params = new ParametersWithID(new ParametersWithRandom(privKey,random), BytesUtils.toBytes(ID)); - - return sign(data,params); - } - - public static byte[] sign(byte[] data, CipherParameters params){ - - SM2Signer signer = new SM2Signer(); - - // To get Z_A and prepare parameters - signer.init(true,params); - // To fill the whole message to be signed - signer.update(data,0,data.length); - // To get and return the signature result; - - byte[] encodedSignature; - try { - encodedSignature = signer.generateSignature(); - } catch (CryptoException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - - // To decode the signature - ASN1Sequence sig = ASN1Sequence.getInstance(encodedSignature); - byte[] rBytes = BigIntegerTo32Bytes(ASN1Integer.getInstance(sig.getObjectAt(0)).getValue()); - byte[] sBytes = BigIntegerTo32Bytes(ASN1Integer.getInstance(sig.getObjectAt(1)).getValue()); - - byte[] signature = new byte[R_SIZE + S_SIZE]; - System.arraycopy(rBytes,0,signature,0,R_SIZE); - System.arraycopy(sBytes,0,signature,R_SIZE,S_SIZE); - - return signature; - } - - /** - * verification - * - * @param data data to be signed - * @param publicKey public key - * @param signature signature to be verified - * @return true or false - */ - public static boolean verify(byte[] data, byte[] publicKey, byte[] signature){ - - ECPoint pubKeyPoint = resolvePubKeyBytes(publicKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint, DOMAIN_PARAMS); - - return verify(data,pubKey,signature); - } - - public static boolean verify(byte[] data, byte[] publicKey, byte[] signature, String ID){ - - ECPoint pubKeyPoint = resolvePubKeyBytes(publicKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint, DOMAIN_PARAMS); - ParametersWithID params = new ParametersWithID(pubKey, BytesUtils.toBytes(ID)); - return verify(data,params,signature); - } - - public static boolean verify(byte[] data, CipherParameters params, byte[] signature){ - - - SM2Signer verifier = new SM2Signer(); - - // To get Z_A and prepare parameters - verifier.init(false,params); - // To fill the whole message - verifier.update(data,0,data.length); - // To verify the signature - - byte[] rBytes = new byte[R_SIZE]; - byte[] sBytes = new byte[S_SIZE]; - System.arraycopy(signature,0,rBytes,0,R_SIZE); - System.arraycopy(signature,R_SIZE,sBytes,0,S_SIZE); - - BigInteger r = new BigInteger(1,rBytes); - BigInteger s = new BigInteger(1,sBytes); - byte[] encodedSignature = new byte[0]; - try { - encodedSignature = new DERSequence(new ASN1Encodable[] { new ASN1Integer(r), new ASN1Integer(s)}).getEncoded(); - } catch (IOException e) { - e.printStackTrace(); - } - - return verifier.verifySignature(encodedSignature); - } - - - - - //-----------------Public Key Encryption Algorithm----------------- - - /** - * encryption - * - * @param plainBytes plaintext - * @param publicKey public key - * @return ciphertext - */ - public static byte[] encrypt(byte[] plainBytes, byte[] publicKey){ - - SecureRandom random = new SecureRandom(); - - return encrypt(plainBytes,publicKey,random); - } - - public static byte[] encrypt(byte[] plainBytes, byte[] publicKey, SecureRandom random){ - - ECPoint pubKeyPoint = resolvePubKeyBytes(publicKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint, DOMAIN_PARAMS); - ParametersWithRandom params = new ParametersWithRandom(pubKey,random); - - return encrypt(plainBytes,params); - } - - public static byte[] encrypt(byte[] plainBytes, ECPublicKeyParameters pubKey){ - - SecureRandom random = new SecureRandom(); - ParametersWithRandom params = new ParametersWithRandom(pubKey,random); - - return encrypt(plainBytes,params); - } - - public static byte[] encrypt(byte[] plainBytes, CipherParameters params){ - - SM2Engine encryptor = new SM2Engine(); - - // To prepare parameters - encryptor.init(true,params); - - // To generate the twisted ciphertext c1c2c3. - // The latest standard specification indicates that the correct ordering is c1c3c2 - byte[] c1c2c3 = new byte[0]; - try { - c1c2c3 = encryptor.processBlock(plainBytes,0,plainBytes.length); - } catch (InvalidCipherTextException e) { - e.printStackTrace(); - } - - // get correct output c1c3c2 from c1c2c3 - byte[] c1c3c2 = new byte[c1c2c3.length]; - System.arraycopy(c1c2c3,0,c1c3c2,0,POINT_SIZE); - System.arraycopy(c1c2c3,POINT_SIZE,c1c3c2,POINT_SIZE + SM3DIGEST_LENGTH, plainBytes.length); - System.arraycopy(c1c2c3,POINT_SIZE + plainBytes.length, c1c3c2,POINT_SIZE,SM3DIGEST_LENGTH); - - return c1c3c2; - } - - /** - * decryption - * - * @param cipherBytes ciphertext - * @param privateKey private key - * @return plaintext - */ - public static byte[] decrypt(byte[] cipherBytes, byte[] privateKey){ - - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); - - return decrypt(cipherBytes,privKey); - } - - public static byte[] decrypt(byte[] cipherBytes, CipherParameters params){ - - SM2Engine decryptor = new SM2Engine(); - - // To prepare parameters - decryptor.init(false,params); - - // To get c1c2c3 from ciphertext whose ordering is c1c3c2 - byte[] c1c2c3 = new byte[cipherBytes.length]; - System.arraycopy(cipherBytes,0,c1c2c3,0,POINT_SIZE); - System.arraycopy(cipherBytes,POINT_SIZE,c1c2c3,c1c2c3.length-SM3DIGEST_LENGTH, SM3DIGEST_LENGTH); - System.arraycopy(cipherBytes,SM3DIGEST_LENGTH + POINT_SIZE,c1c2c3,POINT_SIZE,c1c2c3.length-SM3DIGEST_LENGTH-POINT_SIZE); - - // To output the plaintext - try { - return decryptor.processBlock(c1c2c3,0,c1c2c3.length); - } catch (InvalidCipherTextException e) { - throw new com.jd.blockchain.crypto.CryptoException(e.getMessage(), e); - } - } - - - - // To convert BigInteger to byte[] whose length is 32 - private static byte[] BigIntegerTo32Bytes(BigInteger b){ - byte[] tmp = b.toByteArray(); - byte[] result = new byte[32]; - if (tmp.length > result.length) { - System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); - } - else { - System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); - } - return result; - } - - // To retrieve the public key point from publicKey in byte array mode - private static ECPoint resolvePubKeyBytes(byte[] publicKey){ - return CURVE.decodePoint(publicKey); - } - - public static ECCurve getCurve(){return CURVE;} - - public static ECDomainParameters getDomainParams(){return DOMAIN_PARAMS;} -} - - - diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM3Utils.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM3Utils.java deleted file mode 100644 index 282a403c..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM3Utils.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.crypto.utils.sm; - -import org.bouncycastle.crypto.digests.SM3Digest; - -public class SM3Utils { - - // The length of sm3 output is 32 bytes - public static final int SM3DIGEST_LENGTH = 32; - - public static byte[] hash(byte[] data) { - - byte[] result = new byte[SM3DIGEST_LENGTH]; - - SM3Digest sm3digest = new SM3Digest(); - - sm3digest.update(data, 0, data.length); - sm3digest.doFinal(result, 0); - - return result; - } - - public static byte[] hash(byte[] data, int offset, int len) { - - byte[] result = new byte[SM3DIGEST_LENGTH]; - - SM3Digest sm3digest = new SM3Digest(); - - sm3digest.update(data, offset, len); - sm3digest.doFinal(result, 0); - - return result; - } -} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM4Utils.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM4Utils.java deleted file mode 100644 index 323243d4..00000000 --- a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM4Utils.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.jd.blockchain.crypto.utils.sm; - -import com.jd.blockchain.crypto.CryptoException; -import org.bouncycastle.crypto.CipherKeyGenerator; -import org.bouncycastle.crypto.KeyGenerationParameters; -import org.bouncycastle.crypto.engines.SM4Engine; -import org.bouncycastle.crypto.modes.CBCBlockCipher; -import org.bouncycastle.crypto.paddings.PKCS7Padding; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; - - -import java.security.SecureRandom; -import java.util.Arrays; - -public class SM4Utils { - - // SM4 supports 128-bit(16 bytes) secret key - private static final int KEY_SIZE = 128 / 8; - // One block contains 16 bytes - private static final int BLOCK_SIZE = 16; - // Initial vector's size is 16 bytes - private static final int IV_SIZE = 16; - - - /** - * key generation - * - * @return secret key - */ - public static byte[] generateKey(){ - - CipherKeyGenerator keyGenerator = new CipherKeyGenerator(); - - // To provide secure randomness and key length as input - // to prepare generate private key - keyGenerator.init(new KeyGenerationParameters(new SecureRandom(), KEY_SIZE * 8)); - - // To generate key - return keyGenerator.generateKey(); - } - - public static byte[] generateKey(byte[] seed){ - byte[] hash = SM3Utils.hash(seed); - return Arrays.copyOf(hash, KEY_SIZE); - } - - - /** - * encryption - * - * @param plainBytes plaintext - * @param secretKey symmetric key - * @param iv initial vector - * @return ciphertext - */ - public static byte[] encrypt(byte[] plainBytes, byte[] secretKey, byte[] iv){ - - // To ensure that plaintext is not null - if (plainBytes == null) - { - throw new CryptoException("plaintext is null!"); - } - - if (secretKey.length != KEY_SIZE) - { - throw new CryptoException("secretKey's length is wrong!"); - } - - if (iv.length != IV_SIZE) - { - throw new CryptoException("iv's length is wrong!"); - } - - // To get the value padded into input - int padding = 16 - plainBytes.length % BLOCK_SIZE; - // The plaintext with padding value - byte[] plainBytesWithPadding = new byte[plainBytes.length + padding]; - System.arraycopy(plainBytes,0,plainBytesWithPadding,0,plainBytes.length); - // The padder adds PKCS7 padding to the input, which makes its length to - // become an integral multiple of 16 bytes - PKCS7Padding padder = new PKCS7Padding(); - // To add padding - padder.addPadding(plainBytesWithPadding, plainBytes.length); - - CBCBlockCipher encryptor = new CBCBlockCipher(new SM4Engine()); - // To provide key and initialisation vector as input - encryptor.init(true,new ParametersWithIV(new KeyParameter(secretKey),iv)); - byte[] output = new byte[plainBytesWithPadding.length + IV_SIZE]; - // To encrypt the input_p in CBC mode - for(int i = 0 ; i < plainBytesWithPadding.length/BLOCK_SIZE; i++) { - encryptor.processBlock(plainBytesWithPadding, i * BLOCK_SIZE, output, (i + 1) * BLOCK_SIZE); - } - - // The IV locates on the first block of ciphertext - System.arraycopy(iv,0,output,0,BLOCK_SIZE); - return output; - } - - public static byte[] encrypt(byte[] plainBytes, byte[] secretKey){ - - byte[] iv = new byte[IV_SIZE]; - SecureRandom random = new SecureRandom(); - random.nextBytes(iv); - return encrypt(plainBytes,secretKey,iv); - } - - /** - * decryption - * - * @param cipherBytes ciphertext - * @param secretKey symmetric key - * @return plaintext - */ - public static byte[] decrypt(byte[] cipherBytes, byte[] secretKey){ - - // To ensure that the ciphertext is not null - if (cipherBytes == null) - { - throw new CryptoException("ciphertext is null!"); - } - - // To ensure that the ciphertext's length is integral multiples of 16 bytes - if (cipherBytes.length % BLOCK_SIZE != 0) - { - throw new CryptoException("ciphertext's length is wrong!"); - } - - if (secretKey.length != KEY_SIZE) - { - throw new CryptoException("secretKey's length is wrong!"); - } - - byte[] iv = new byte[IV_SIZE]; - System.arraycopy(cipherBytes,0,iv,0,BLOCK_SIZE); - - CBCBlockCipher decryptor = new CBCBlockCipher(new SM4Engine()); - // To prepare the decryption - decryptor.init(false,new ParametersWithIV(new KeyParameter(secretKey),iv)); - byte[] outputWithPadding = new byte[cipherBytes.length-BLOCK_SIZE]; - // To decrypt the input in CBC mode - for(int i = 1 ; i < cipherBytes.length/BLOCK_SIZE ; i++) { - decryptor.processBlock(cipherBytes, i * BLOCK_SIZE, outputWithPadding, (i - 1) * BLOCK_SIZE); - } - - int p = outputWithPadding[outputWithPadding.length-1]; - // To ensure that the padding of output_p is valid - if(p > BLOCK_SIZE || p < 0x01) - { - throw new CryptoException("There no exists such padding!"); - - } - for(int i = 0 ; i < p ; i++) - { - if(outputWithPadding[outputWithPadding.length-i-1] != p) - { - throw new CryptoException("Padding is invalid!"); - } - } - - // To remove the padding from output and obtain plaintext - byte[] output = new byte[outputWithPadding.length-p]; - System.arraycopy(outputWithPadding, 0, output, 0, output.length); - return output; - } -} diff --git a/source/crypto/crypto-sm/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService b/source/crypto/crypto-sm/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService deleted file mode 100644 index e89073b2..00000000 --- a/source/crypto/crypto-sm/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService +++ /dev/null @@ -1 +0,0 @@ -com.jd.blockchain.crypto.service.sm.SMCryptoService \ No newline at end of file diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM2CyptoFunctionTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM2CyptoFunctionTest.java deleted file mode 100644 index 218b443d..00000000 --- a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM2CyptoFunctionTest.java +++ /dev/null @@ -1,487 +0,0 @@ -package test.com.jd.blockchain.crypto.service.sm; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.service.sm.SMAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.*; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIVATE; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: SM2CyptoFunctionTest - * @description: JunitTest for SM2CyptoFunction in SPI mode - * @date 2019-04-03, 16:32 - */ -public class SM2CyptoFunctionTest { - - @Test - public void getAlgorithmTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("sM2"); - assertNotNull(algorithm); - - assertEquals(signatureFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(signatureFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("sm22"); - assertNull(algorithm); - } - - @Test - public void generateKeyPairTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - assertEquals(PUBLIC.CODE, pubKey.getKeyType().CODE); - assertEquals(65, pubKey.getRawKeyBytes().length); - assertEquals(PRIVATE.CODE, privKey.getKeyType().CODE); - assertEquals(32, privKey.getRawKeyBytes().length); - - assertEquals(algorithm.code(), pubKey.getAlgorithm()); - assertEquals(algorithm.code(), privKey.getAlgorithm()); - - assertEquals(2 + 1 + 65, pubKey.toBytes().length); - assertEquals(2 + 1 + 32, privKey.toBytes().length); - - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawPubKeyBytes), pubKey.toBytes()); - assertArrayEquals(BytesUtils.concat(algoBytes, privKeyTypeBytes, rawPrivKeyBytes), privKey.toBytes()); - } - - @Test - public void retrievePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - PubKey retrievedPubKey = signatureFunction.retrievePubKey(privKey); - - assertEquals(pubKey.getKeyType(), retrievedPubKey.getKeyType()); - assertEquals(pubKey.getRawKeyBytes().length, retrievedPubKey.getRawKeyBytes().length); - assertEquals(pubKey.getAlgorithm(), retrievedPubKey.getAlgorithm()); - assertArrayEquals(pubKey.toBytes(), retrievedPubKey.toBytes()); - } - - @Test - public void signTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureBytes = signatureDigest.toBytes(); - - assertEquals(2 + 64, signatureBytes.length); - assertEquals(algorithm.code(), signatureDigest.getAlgorithm()); - - assertEquals(SMAlgorithm.SM2.code(), signatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 2 & 0x00FF)), - signatureDigest.getAlgorithm()); - - byte[] algoBytes = BytesUtils.toBytes(signatureDigest.getAlgorithm()); - byte[] rawSinatureBytes = signatureDigest.getRawDigest(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawSinatureBytes), signatureBytes); - } - - @Test - public void verifyTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - assertTrue(signatureFunction.verify(signatureDigest, pubKey, data)); - } - - @Test - public void encryptTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - AsymmetricEncryptionFunction asymmetricEncryptionFunction = Crypto - .getAsymmetricEncryptionFunction(algorithm); - - AsymmetricKeypair keyPair = asymmetricEncryptionFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - - Ciphertext ciphertext = asymmetricEncryptionFunction.encrypt(pubKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - assertEquals(2 + 65 + 256 / 8 + 1024, ciphertextBytes.length); - assertEquals(SMAlgorithm.SM2.code(), ciphertext.getAlgorithm()); - - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 2 & 0x00FF)), - ciphertext.getAlgorithm()); - - byte[] algoBytes = BytesUtils.toBytes(ciphertext.getAlgorithm()); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawCiphertextBytes), ciphertextBytes); - } - - @Test - public void decryptTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - AsymmetricEncryptionFunction asymmetricEncryptionFunction = Crypto - .getAsymmetricEncryptionFunction(algorithm); - - AsymmetricKeypair keyPair = asymmetricEncryptionFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - Ciphertext ciphertext = asymmetricEncryptionFunction.encrypt(pubKey, data); - - byte[] decryptedPlaintext = asymmetricEncryptionFunction.decrypt(privKey, ciphertext); - - assertArrayEquals(data, decryptedPlaintext); - } - - @Test - public void supportPrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - assertTrue(signatureFunction.supportPrivKey(privKeyBytes)); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = privKey.getRawKeyBytes(); - byte[] sm3PubKeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - assertFalse(signatureFunction.supportPrivKey(sm3PubKeyBytes)); - } - - @Test - public void resolvePrivKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - byte[] privKeyBytes = privKey.toBytes(); - - PrivKey resolvedPrivKey = signatureFunction.resolvePrivKey(privKeyBytes); - - assertEquals(PRIVATE.CODE, resolvedPrivKey.getKeyType().CODE); - assertEquals(32, resolvedPrivKey.getRawKeyBytes().length); - assertEquals(SMAlgorithm.SM2.code(), resolvedPrivKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 2 & 0x00FF)), - resolvedPrivKey.getAlgorithm()); - assertArrayEquals(privKeyBytes, resolvedPrivKey.toBytes()); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = privKey.getRawKeyBytes(); - byte[] sm3PubKeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolvePrivKey(sm3PubKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportPubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - assertTrue(signatureFunction.supportPubKey(pubKeyBytes)); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawKeyBytes = pubKey.getRawKeyBytes(); - byte[] sm3PrivKeyBytes = BytesUtils.concat(algoBytes, privKeyTypeBytes, rawKeyBytes); - - assertFalse(signatureFunction.supportPubKey(sm3PrivKeyBytes)); - } - - @Test - public void resolvePubKeyTest() { - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - byte[] pubKeyBytes = pubKey.toBytes(); - - PubKey resolvedPubKey = signatureFunction.resolvePubKey(pubKeyBytes); - - assertEquals(PUBLIC.CODE, resolvedPubKey.getKeyType().CODE); - assertEquals(65, resolvedPubKey.getRawKeyBytes().length); - assertEquals(SMAlgorithm.SM2.code(), resolvedPubKey.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 2 & 0x00FF)), - resolvedPubKey.getAlgorithm()); - assertArrayEquals(pubKeyBytes, resolvedPubKey.toBytes()); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] privKeyTypeBytes = new byte[] { PRIVATE.CODE }; - byte[] rawKeyBytes = pubKey.getRawKeyBytes(); - byte[] sm3PrivKeyBytes = BytesUtils.concat(algoBytes, privKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolvePrivKey(sm3PrivKeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertTrue(signatureFunction.supportDigest(signatureDigestBytes)); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = signatureDigest.toBytes(); - byte[] sm3SignatureBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - assertFalse(signatureFunction.supportDigest(sm3SignatureBytes)); - } - - @Test - public void resolveDigestTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - SignatureFunction signatureFunction = Crypto.getSignatureFunction(algorithm); - - AsymmetricKeypair keyPair = signatureFunction.generateKeypair(); - - PrivKey privKey = keyPair.getPrivKey(); - - SignatureDigest signatureDigest = signatureFunction.sign(privKey, data); - - byte[] signatureDigestBytes = signatureDigest.toBytes(); - - SignatureDigest resolvedSignatureDigest = signatureFunction.resolveDigest(signatureDigestBytes); - - assertEquals(64, resolvedSignatureDigest.getRawDigest().length); - assertEquals(SMAlgorithm.SM2.code(), resolvedSignatureDigest.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 2 & 0x00FF)), - resolvedSignatureDigest.getAlgorithm()); - assertArrayEquals(signatureDigestBytes, resolvedSignatureDigest.toBytes()); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = signatureDigest.getRawDigest(); - byte[] sm3SignatureDigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - signatureFunction.resolveDigest(sm3SignatureDigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportCiphertextTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - AsymmetricEncryptionFunction asymmetricEncryptionFunction = Crypto - .getAsymmetricEncryptionFunction(algorithm); - - AsymmetricKeypair keyPair = asymmetricEncryptionFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - - Ciphertext ciphertext = asymmetricEncryptionFunction.encrypt(pubKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - - assertTrue(asymmetricEncryptionFunction.supportCiphertext(ciphertextBytes)); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawCiphertextBytes = ciphertext.toBytes(); - byte[] sm3CiphertextBytes = BytesUtils.concat(algoBytes, rawCiphertextBytes); - - assertFalse(asymmetricEncryptionFunction.supportCiphertext(sm3CiphertextBytes)); - } - - @Test - public void resolveCiphertextTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm2"); - assertNotNull(algorithm); - - AsymmetricEncryptionFunction asymmetricEncryptionFunction = Crypto - .getAsymmetricEncryptionFunction(algorithm); - - AsymmetricKeypair keyPair = asymmetricEncryptionFunction.generateKeypair(); - - PubKey pubKey = keyPair.getPubKey(); - - Ciphertext ciphertext = asymmetricEncryptionFunction.encrypt(pubKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - - Ciphertext resolvedCiphertext = asymmetricEncryptionFunction.resolveCiphertext(ciphertextBytes); - - assertEquals(65 + 256 / 8 + 1024, resolvedCiphertext.getRawCiphertext().length); - assertEquals(SMAlgorithm.SM2.code(), resolvedCiphertext.getAlgorithm()); - assertEquals((short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | ((byte) 2 & 0x00FF)), - resolvedCiphertext.getAlgorithm()); - assertArrayEquals(ciphertextBytes, resolvedCiphertext.toBytes()); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - byte[] sm3CiphertextBytes = BytesUtils.concat(algoBytes, rawCiphertextBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - asymmetricEncryptionFunction.resolveCiphertext(sm3CiphertextBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM3HashFunctionTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM3HashFunctionTest.java deleted file mode 100644 index f543bc68..00000000 --- a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM3HashFunctionTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package test.com.jd.blockchain.crypto.service.sm; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.service.sm.SMAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.HASH_ALGORITHM; -import static org.junit.Assert.*; - -/** - * @author zhanglin33 - * @title: SM3HashFunctionTest - * @description: JunitTest for SM3HashFunction in SPI mode - * @date 2019-04-03, 16:33 - */ -public class SM3HashFunctionTest { - @Test - public void getAlgorithmTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - assertEquals(hashFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(hashFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("Sm3"); - assertNotNull(algorithm); - - assertEquals(hashFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(hashFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("sm3333"); - assertNull(algorithm); - } - - @Test - public void hashTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - byte[] rawDigestBytes = digest.getRawDigest(); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - - byte[] digestBytes = digest.toBytes(); - assertEquals(256 / 8 + 2, digestBytes.length); - assertArrayEquals(digestBytes, BytesUtils.concat(algoBytes, rawDigestBytes)); - - assertEquals(algorithm.code(), digest.getAlgorithm()); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - data = null; - hashFunction.hash(data); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void verifyTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - assertTrue(hashFunction.verify(digest, data)); - } - - @Test - public void supportHashDigestTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - byte[] digestBytes = digest.toBytes(); - assertTrue(hashFunction.supportHashDigest(digestBytes)); - - algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - System.arraycopy(algoBytes, 0, digestBytes, 0, algoBytes.length); - assertFalse(hashFunction.supportHashDigest(digestBytes)); - } - - @Test - public void resolveHashDigestTest() { - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - - HashFunction hashFunction = Crypto.getHashFunction(algorithm); - - HashDigest digest = hashFunction.hash(data); - - byte[] digestBytes = digest.toBytes(); - - HashDigest resolvedDigest = hashFunction.resolveHashDigest(digestBytes); - - assertEquals(256 / 8, resolvedDigest.getRawDigest().length); - assertEquals(SMAlgorithm.SM3.code(), resolvedDigest.getAlgorithm()); - assertEquals((short) (HASH_ALGORITHM | ((byte) 3 & 0x00FF)), resolvedDigest.getAlgorithm()); - assertArrayEquals(digestBytes, resolvedDigest.toBytes()); - - algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawDigestBytes = digest.getRawDigest(); - byte[] aesDigestBytes = BytesUtils.concat(algoBytes, rawDigestBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - hashFunction.resolveHashDigest(aesDigestBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunctionTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunctionTest.java deleted file mode 100644 index f2a8d3d0..00000000 --- a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunctionTest.java +++ /dev/null @@ -1,285 +0,0 @@ -package test.com.jd.blockchain.crypto.service.sm; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.ENCRYPTION_ALGORITHM; -import static com.jd.blockchain.crypto.CryptoAlgorithm.SYMMETRIC_KEY; -import static com.jd.blockchain.crypto.CryptoKeyType.PUBLIC; -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Random; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.SymmetricKey; -import com.jd.blockchain.crypto.service.sm.SMAlgorithm; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * @author zhanglin33 - * @title: SM4EncryptionFunctionTest - * @description: JunitTest for SM4EncryptionFunction in SPI mode - * @date 2019-04-03, 16:35 - */ -public class SM4EncryptionFunctionTest { - @Test - public void getAlgorithmTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - assertEquals(symmetricEncryptionFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(symmetricEncryptionFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("sM4"); - assertNotNull(algorithm); - - assertEquals(symmetricEncryptionFunction.getAlgorithm().name(), algorithm.name()); - assertEquals(symmetricEncryptionFunction.getAlgorithm().code(), algorithm.code()); - - algorithm = Crypto.getAlgorithm("smm4"); - assertNull(algorithm); - } - - @Test - public void generateSymmetricKeyTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - assertEquals(SYMMETRIC.CODE, symmetricKey.getKeyType().CODE); - assertEquals(128 / 8, symmetricKey.getRawKeyBytes().length); - - assertEquals(algorithm.code(), symmetricKey.getAlgorithm()); - - assertEquals(2 + 1 + 128 / 8, symmetricKey.toBytes().length); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] keyTypeBytes = new byte[] { SYMMETRIC.CODE }; - byte[] rawKeyBytes = symmetricKey.getRawKeyBytes(); - assertArrayEquals(BytesUtils.concat(algoBytes, keyTypeBytes, rawKeyBytes), symmetricKey.toBytes()); - } - - @Test - public void encryptTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - assertEquals(2 + 16 + 16 + 1024, ciphertextBytes.length); - assertEquals(SMAlgorithm.SM4.code(), ciphertext.getAlgorithm()); - assertEquals((short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | ((byte) 4 & 0x00FF)), ciphertext.getAlgorithm()); - - byte[] algoBytes = BytesUtils.toBytes(ciphertext.getAlgorithm()); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - assertArrayEquals(BytesUtils.concat(algoBytes, rawCiphertextBytes), ciphertextBytes); - } - - @Test - public void decryptTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] decryptedPlaintext = symmetricEncryptionFunction.decrypt(symmetricKey, ciphertext); - - assertArrayEquals(data, decryptedPlaintext); - } - - // @Test - // public void streamEncryptTest(){ - // - // byte[] data = new byte[1024]; - // Random random = new Random(); - // random.nextBytes(data); - // - // - // InputStream inputStream = new ByteArrayInputStream(data); - // OutputStream outputStream = new ByteArrayOutputStream(); - // - // CryptoAlgorithm algorithm = CryptoServiceProviders.getAlgorithm("aes"); - // assertNotNull(algorithm); - // - // SymmetricEncryptionFunction symmetricEncryptionFunction = - // CryptoServiceProviders.getSymmetricEncryptionFunction(algorithm); - // - // SymmetricKey symmetricKey = (SymmetricKey) - // symmetricEncryptionFunction.generateSymmetricKey(); - // - // symmetricEncryptionFunction.encrypt(symmetricKey,inputStream,outputStream); - // - // assertNotNull(outputStream); - // - // - // } - - @Test - public void supportSymmetricKeyTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - byte[] symmetricKeyBytes = symmetricKey.toBytes(); - - assertTrue(symmetricEncryptionFunction.supportSymmetricKey(symmetricKeyBytes)); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = symmetricKey.getRawKeyBytes(); - byte[] ripemd160KeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - assertFalse(symmetricEncryptionFunction.supportSymmetricKey(ripemd160KeyBytes)); - } - - @Test - public void resolveSymmetricKeyTest() { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - byte[] symmetricKeyBytes = symmetricKey.toBytes(); - - SymmetricKey resolvedKey = symmetricEncryptionFunction.resolveSymmetricKey(symmetricKeyBytes); - - assertEquals(SYMMETRIC.CODE, resolvedKey.getKeyType().CODE); - assertEquals(128 / 8, resolvedKey.getRawKeyBytes().length); - assertEquals(SMAlgorithm.SM4.code(), resolvedKey.getAlgorithm()); - assertEquals((short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | ((byte) 4 & 0x00FF)), resolvedKey.getAlgorithm()); - assertArrayEquals(symmetricKeyBytes, resolvedKey.toBytes()); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] pubKeyTypeBytes = new byte[] { PUBLIC.CODE }; - byte[] rawKeyBytes = symmetricKey.getRawKeyBytes(); - byte[] ripemd160KeyBytes = BytesUtils.concat(algoBytes, pubKeyTypeBytes, rawKeyBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - symmetricEncryptionFunction.resolveSymmetricKey(ripemd160KeyBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - - @Test - public void supportCiphertextTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - assertTrue(symmetricEncryptionFunction.supportCiphertext(ciphertextBytes)); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawCiphertextBytes = ciphertext.toBytes(); - byte[] sm3CiphertextBytes = BytesUtils.concat(algoBytes, rawCiphertextBytes); - - assertFalse(symmetricEncryptionFunction.supportCiphertext(sm3CiphertextBytes)); - } - - @Test - public void resolveCiphertextTest() { - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - CryptoAlgorithm algorithm = Crypto.getAlgorithm("sm4"); - assertNotNull(algorithm); - - SymmetricEncryptionFunction symmetricEncryptionFunction = Crypto - .getSymmetricEncryptionFunction(algorithm); - - SymmetricKey symmetricKey = (SymmetricKey) symmetricEncryptionFunction.generateSymmetricKey(); - - Ciphertext ciphertext = symmetricEncryptionFunction.encrypt(symmetricKey, data); - - byte[] ciphertextBytes = ciphertext.toBytes(); - - Ciphertext resolvedCiphertext = symmetricEncryptionFunction.resolveCiphertext(ciphertextBytes); - - assertEquals(1024 + 16 + 16, resolvedCiphertext.getRawCiphertext().length); - assertEquals(SMAlgorithm.SM4.code(), resolvedCiphertext.getAlgorithm()); - assertEquals((short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | ((byte) 4 & 0x00FF)), - resolvedCiphertext.getAlgorithm()); - assertArrayEquals(ciphertextBytes, resolvedCiphertext.toBytes()); - - algorithm = Crypto.getAlgorithm("sm3"); - assertNotNull(algorithm); - byte[] algoBytes = CryptoAlgorithm.getCodeBytes(algorithm); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - byte[] sm3CiphertextBytes = BytesUtils.concat(algoBytes, rawCiphertextBytes); - - Class expectedException = CryptoException.class; - Exception actualEx = null; - try { - symmetricEncryptionFunction.resolveCiphertext(sm3CiphertextBytes); - } catch (Exception e) { - actualEx = e; - } - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } -} diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM2UtilsTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM2UtilsTest.java deleted file mode 100644 index 11d6839a..00000000 --- a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM2UtilsTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package test.com.jd.blockchain.crypto.utils; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.util.test.TestRandomBigInteger; -import org.junit.Test; - -import com.jd.blockchain.crypto.utils.sm.SM2Utils; - -import java.util.Random; - -public class SM2UtilsTest { - - @Test - public void testGenerateKeyPair() { - - String expectedPrivateKey = "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8"; - String expectedPublicKey = "04"+"09f9df311e5421a150dd7d161e4bc5c672179fad1833fc076bb08ff356f35020"+"ccea490ce26775a52dc6ea718cc1aa600aed05fbf35e084a6632f6072da9ad13"; - - AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(new TestRandomBigInteger(expectedPrivateKey, 16)); - ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); - ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); - - byte[] expectedPrivateKeyBytes = Hex.decode(expectedPrivateKey); - byte[] privKeyBytes = ecPriv.getD().toByteArray(); - assertArrayEquals(expectedPrivateKeyBytes,privKeyBytes); - - byte[] pubKeyBytesX = ecPub.getQ().getAffineXCoord().getEncoded(); - byte[] pubKeyBytesY = ecPub.getQ().getAffineYCoord().getEncoded(); - assertEquals(expectedPublicKey,"04"+Hex.toHexString(pubKeyBytesX)+Hex.toHexString(pubKeyBytesY)); - - byte[] pubKeyBytes = ecPub.getQ().getEncoded(false); - assertArrayEquals(Hex.decode(expectedPublicKey),pubKeyBytes); - } - - @Test - public void testPubKeyRetrieve() { - - String expectedPrivateKey = "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8"; - String expectedPublicKey = "04"+"09f9df311e5421a150dd7d161e4bc5c672179fad1833fc076bb08ff356f35020"+"ccea490ce26775a52dc6ea718cc1aa600aed05fbf35e084a6632f6072da9ad13"; - - byte[] privateKey = Hex.decode(expectedPrivateKey); - byte[] publicKey = SM2Utils.retrievePublicKey(privateKey); - - assertEquals(expectedPublicKey,Hex.toHexString(publicKey)); - } - - @Test - public void testSign() { - - String expectedPrivateKey = "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8"; - String expectedRandomness = "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21"; - String expectedMessage = "message digest"; - String expectedIdentifier = "ALICE123@YAHOO.COM"; - String expectedR = "b0e3e7d4ac2178f833ad73fa9d1191e41c76c8bfedb5ad89040ba2e5184bde58"; - String expectedS = "cc8d096578f7dd2669ac1ac42f7e722bcfa42b9e0be0b1b5df7ca0b53fdd5750"; - - byte[] privKeyBytes = Hex.decode(expectedPrivateKey); - byte[] messageBytes = BytesUtils.toBytes(expectedMessage); - - byte[] signature = SM2Utils.sign(messageBytes,privKeyBytes,new TestRandomBigInteger(expectedRandomness, 16),expectedIdentifier); - assertArrayEquals(Hex.decode(expectedR+expectedS),signature); - } - - @Test - public void testVerify() { - - String expectedPublicKey = "04"+"09f9df311e5421a150dd7d161e4bc5c672179fad1833fc076bb08ff356f35020"+"ccea490ce26775a52dc6ea718cc1aa600aed05fbf35e084a6632f6072da9ad13"; - String expectedMessage = "message digest"; - String expectedIdentifier = "ALICE123@YAHOO.COM"; - String expectedR = "b0e3e7d4ac2178f833ad73fa9d1191e41c76c8bfedb5ad89040ba2e5184bde58"; - String expectedS = "cc8d096578f7dd2669ac1ac42f7e722bcfa42b9e0be0b1b5df7ca0b53fdd5750"; - - byte[] pubKeyBytes = Hex.decode(expectedPublicKey); - byte[] messageBytes = BytesUtils.toBytes(expectedMessage); - byte[] signatureBytes = Hex.decode(expectedR + expectedS); - - boolean isVerified = SM2Utils.verify(messageBytes,pubKeyBytes,signatureBytes,expectedIdentifier); - assertTrue(isVerified); - } - - @Test - public void testEncrypt() { - - String expectedPublicKey = "04"+"09f9df311e5421a150dd7d161e4bc5c672179fad1833fc076bb08ff356f35020"+"ccea490ce26775a52dc6ea718cc1aa600aed05fbf35e084a6632f6072da9ad13"; - String expectedMessage = "encryption standard"; - String expectedRandomness = "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21"; - String expectedC1 = "0404ebfc718e8d1798620432268e77feb6415e2ede0e073c0f4f640ecd2e149a73e858f9d81e5430a57b36daab8f950a3c64e6ee6a63094d99283aff767e124df0"; - String expectedC2 = "21886ca989ca9c7d58087307ca93092d651efa"; - String expectedC3 = "59983c18f809e262923c53aec295d30383b54e39d609d160afcb1908d0bd8766"; - - byte[] pubKeyBytes = Hex.decode(expectedPublicKey); - byte[] messageBytes = BytesUtils.toBytes(expectedMessage); - - byte[] ciphertext = SM2Utils.encrypt(messageBytes,pubKeyBytes,new TestRandomBigInteger(expectedRandomness, 16)); - assertArrayEquals(Hex.decode(expectedC1 + expectedC3 + expectedC2),ciphertext); - - - } - - @Test - public void testDecrypt() { - - String expectedPrivateKey = "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8"; - String expectedMessage = "encryption standard"; - String expectedC1 = "0404ebfc718e8d1798620432268e77feb6415e2ede0e073c0f4f640ecd2e149a73e858f9d81e5430a57b36daab8f950a3c64e6ee6a63094d99283aff767e124df0"; - String expectedC2 = "21886ca989ca9c7d58087307ca93092d651efa"; - String expectedC3 = "59983c18f809e262923c53aec295d30383b54e39d609d160afcb1908d0bd8766"; - - byte[] privKeyBytes = Hex.decode(expectedPrivateKey); - byte[] ciphertext = Hex.decode(expectedC1 + expectedC3 + expectedC2); - - byte[] plaintext = SM2Utils.decrypt(ciphertext,privKeyBytes); - assertArrayEquals(BytesUtils.toBytes(expectedMessage),plaintext); - } - -// @Test - public void encryptingPerformace(){ - - byte[] data = new byte[1000]; - Random random = new Random(); - random.nextBytes(data); - - int count = 10000; - - byte[] ciphertext = null; - - AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); - ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); - ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); - - System.out.println("=================== do SM2 encrypt test ==================="); - - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ciphertext = SM2Utils.encrypt(data,ecPub); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do SM2 decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - SM2Utils.decrypt(ciphertext,ecPriv); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } - - -// @Test - public void signingPerformace(){ - - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); - - int count = 10000; - - byte[] sm2Digest = null; - - AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); - ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); - ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); - - System.out.println("=================== do SM2 sign test ==================="); - - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sm2Digest = SM2Utils.sign(data,ecPriv); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do SM2 verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - SM2Utils.verify(data,ecPub,sm2Digest); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } -} \ No newline at end of file diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM3UtilsTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM3UtilsTest.java deleted file mode 100644 index b79c202e..00000000 --- a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM3UtilsTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package test.com.jd.blockchain.crypto.utils; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import com.jd.blockchain.utils.io.BytesUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import com.jd.blockchain.crypto.utils.sm.SM3Utils; - -public class SM3UtilsTest { - - private static final int SM3DIGEST_LENGTH = 32; - - @Test - public void testHash() { - - String testString1 = "abc"; - String testString2 = "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"; - String expectedResult1="66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0" ; - String expectedResult2="debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732"; - - byte[] testString1Bytes = BytesUtils.toBytes(testString1); - byte[] testString2Bytes = BytesUtils.toBytes(testString2); - byte[] hash1 = SM3Utils.hash(testString1Bytes); - byte[] hash2 = SM3Utils.hash(testString2Bytes); - byte[] expectedResult1Bytes = BytesUtils.toBytes(expectedResult1); - byte[] expectedResult2Bytes = BytesUtils.toBytes(expectedResult2); - assertEquals(hash1.length, SM3DIGEST_LENGTH); - assertEquals(hash2.length, SM3DIGEST_LENGTH); - assertArrayEquals(hash1, Hex.decode(expectedResult1Bytes)); - assertArrayEquals(hash2, Hex.decode(expectedResult2Bytes)); - } - -// @Test -// public void hashingPerformance() { -// -// byte[] data = new byte[1000]; -// Random random = new Random(); -// random.nextBytes(data); -// -// int count = 1000000; -// -// System.out.println("=================== do SM3 hash test ==================="); -// for (int r = 0; r < 5; r++) { -// System.out.println("------------- round[" + r + "] --------------"); -// long startTS = System.currentTimeMillis(); -// for (int i = 0; i < count; i++) { -// SM3Utils.hash(data); -// } -// long elapsedTS = System.currentTimeMillis() - startTS; -// System.out.println(String.format("SM3 hashing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, -// (count * 1000.00D) / elapsedTS)); -// } -// -// System.out.println("=================== do SHA256 hash test ==================="); -// for (int r = 0; r < 5; r++) { -// System.out.println("------------- round[" + r + "] --------------"); -// long startTS = System.currentTimeMillis(); -// for (int i = 0; i < count; i++) { -// ShaUtils.hash_256(data); -// } -// long elapsedTS = System.currentTimeMillis() - startTS; -// System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, -// (count * 1000.00D) / elapsedTS)); -// } -// } -} \ No newline at end of file diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM4UtilsTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM4UtilsTest.java deleted file mode 100644 index dd379b47..00000000 --- a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/utils/SM4UtilsTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package test.com.jd.blockchain.crypto.utils; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import com.jd.blockchain.crypto.utils.sm.SM4Utils; - -public class SM4UtilsTest { - - private static final int KEY_SIZE = 16; - private static final int BLOCK_SIZE = 16; - - @Test - public void testGenerateKey() { - byte[] key = SM4Utils.generateKey(); - assertEquals(KEY_SIZE,key.length); - } - - @Test - public void testEncrypt() { - - String plaintext = "0123456789abcdeffedcba9876543210"; - String key = "0123456789abcdeffedcba9876543210"; - String iv = "00000000000000000000000000000000"; - String expectedCiphertextIn2ndBlock = "681edf34d206965e86b3e94f536e4246"; - - byte[] plaintextBytes = Hex.decode(plaintext); - byte[] keyBytes = Hex.decode(key); - byte[] ivBytes = Hex.decode(iv); - byte[] expectedCiphertextIn2ndBlockBytes = Hex.decode(expectedCiphertextIn2ndBlock); - - - byte[] ciphertextbytes = SM4Utils.encrypt(plaintextBytes,keyBytes,ivBytes); - - assertEquals(BLOCK_SIZE*3,ciphertextbytes.length); - - byte[] ciphertextIn1stBlockBytes = new byte[BLOCK_SIZE]; - System.arraycopy(ciphertextbytes,0,ciphertextIn1stBlockBytes,0,BLOCK_SIZE); - assertArrayEquals(ivBytes,ciphertextIn1stBlockBytes); - - byte[] ciphertextIn2ndBlockBytes = new byte[BLOCK_SIZE]; - System.arraycopy(ciphertextbytes,BLOCK_SIZE,ciphertextIn2ndBlockBytes,0,BLOCK_SIZE); - assertArrayEquals(expectedCiphertextIn2ndBlockBytes,ciphertextIn2ndBlockBytes); - - - } - - @Test - public void testDecrypt() { - - String plaintext = "0123456789abcdeffedcba987654321000112233445566778899"; - String key = "0123456789abcdeffedcba9876543210"; - String iv = "0123456789abcdeffedcba9876543210"; - - byte[] plaintextBytes = Hex.decode(plaintext); - byte[] keyBytes = Hex.decode(key); - byte[] ivBytes = Hex.decode(iv); - - - byte[] ciphertext = SM4Utils.encrypt(plaintextBytes,keyBytes,ivBytes); - byte[] decryptedData = SM4Utils.decrypt(ciphertext,keyBytes); - assertArrayEquals(plaintextBytes,decryptedData); - - } - -// @Test -// public void encryptingPerformance() { -// -// byte[] data = new byte[1000]; -// Random random = new Random(); -// random.nextBytes(data); -// -// byte[] sm4Ciphertext = null; -// byte[] aesCiphertext = null; -// -// int count = 100000; -// -// byte[] sm4Key = SM4Utils.generateKey(); -// -// System.out.println("=================== do SM4 encrypt test ==================="); -// for (int r = 0; r < 5; r++) { -// System.out.println("------------- round[" + r + "] --------------"); -// long startTS = System.currentTimeMillis(); -// for (int i = 0; i < count; i++) { -// sm4Ciphertext = SM4Utils.encrypt(data, sm4Key); -// } -// long elapsedTS = System.currentTimeMillis() - startTS; -// System.out.println(String.format("SM4 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, -// (count * 1000.00D) / elapsedTS)); -// } -// -// System.out.println("=================== do SM4 decrypt test ==================="); -// for (int r = 0; r < 5; r++) { -// System.out.println("------------- round[" + r + "] --------------"); -// long startTS = System.currentTimeMillis(); -// for (int i = 0; i < count; i++) { -// SM4Utils.decrypt(sm4Ciphertext, sm4Key); -// } -// long elapsedTS = System.currentTimeMillis() - startTS; -// System.out.println(String.format("SM4 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, -// (count * 1000.00D) / elapsedTS)); -// } -// -// byte[] aesKey = AESUtils.generateKey128_Bytes(); -// -// System.out.println("=================== do AES encrypt test ==================="); -// for (int r = 0; r < 5; r++) { -// System.out.println("------------- round[" + r + "] --------------"); -// long startTS = System.currentTimeMillis(); -// for (int i = 0; i < count; i++) { -// aesCiphertext = AESUtils.encrypt(data, aesKey); -// } -// long elapsedTS = System.currentTimeMillis() - startTS; -// System.out.println(String.format("AES Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, -// (count * 1000.00D) / elapsedTS)); -// } -// -// -// System.out.println("=================== do AES decrypt test ==================="); -// for (int r = 0; r < 5; r++) { -// System.out.println("------------- round[" + r + "] --------------"); -// long startTS = System.currentTimeMillis(); -// for (int i = 0; i < count; i++) { -// AESUtils.decrypt(aesCiphertext, aesKey); -// } -// long elapsedTS = System.currentTimeMillis() - startTS; -// System.out.println(String.format("AES Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, -// (count * 1000.00D) / elapsedTS)); -// } -// } -} \ No newline at end of file diff --git a/source/gateway/.gitignore b/source/gateway/.gitignore deleted file mode 100644 index 4f496dc3..00000000 --- a/source/gateway/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/target/ -/.apt_generated_tests/ diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayConfigProperties.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayConfigProperties.java deleted file mode 100644 index 5a836a41..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayConfigProperties.java +++ /dev/null @@ -1,299 +0,0 @@ -package com.jd.blockchain.gateway; - -import java.io.File; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class GatewayConfigProperties { - // HTTP协议相关配置项的键的前缀; - public static final String HTTP_PREFIX = "http."; - // 网关的HTTP服务地址; - public static final String HTTP_HOST = HTTP_PREFIX + "host"; - // 网关的HTTP服务端口; - public static final String HTTP_PORT = HTTP_PREFIX + "port"; - // 网关的HTTP服务上下文路径,可选; - public static final String HTTP_CONTEXT_PATH = HTTP_PREFIX + "context-path"; - - // 共识相关配置项的键的前缀; - public static final String PEER_PREFIX = "peer."; - // 共识节点的服务地址; - public static final String PEER_HOST = PEER_PREFIX + "host"; - // 共识节点的服务端口; - public static final String PEER_PORT = PEER_PREFIX + "port"; - // 共识节点的服务是否启用安全证书; - public static final String PEER_SECURE = PEER_PREFIX + "secure"; - // 支持共识的Provider列表,以英文逗号分隔 - public static final String PEER_PROVIDERS = PEER_PREFIX + "providers"; - - // 数据检索服务URL地址 - public static final String DATA_RETRIEVAL_URL="data.retrieval.url"; - public static final String SCHEMA_RETRIEVAL_URL="schema.retrieval.url"; - - // 密钥相关配置项的键的前缀; - public static final String KEYS_PREFIX = "keys."; - // 默认密钥相关配置项的键的前缀; - public static final String DEFAULT_KEYS_PREFIX = KEYS_PREFIX + "default."; - // 默认私钥的内容; - public static final String DEFAULT_PUBKEY = DEFAULT_KEYS_PREFIX + "pubkey"; - // 默认私钥的文件存储路径; - public static final String DEFAULT_PRIVKEY_PATH = DEFAULT_KEYS_PREFIX + "privkey-path"; - // 默认私钥的内容; - public static final String DEFAULT_PRIVKEY = DEFAULT_KEYS_PREFIX + "privkey"; - // 默认私钥的密码; - public static final String DEFAULT_PK_PWD = DEFAULT_KEYS_PREFIX + "privkey-password"; - - - private HttpConfig http = new HttpConfig(); - - private ProviderConfig providerConfig = new ProviderConfig(); - - private NetworkAddress masterPeerAddress; - - private String dataRetrievalUrl; - private String schemaRetrievalUrl; - - private KeysConfig keys = new KeysConfig(); - - public HttpConfig http() { - return http; - } - - public NetworkAddress masterPeerAddress() { - return masterPeerAddress; - } - - public String dataRetrievalUrl() { - return this.dataRetrievalUrl; - } - - public void setDataRetrievalUrl(String dataRetrievalUrl) { - this.dataRetrievalUrl = dataRetrievalUrl; - } - - public String getSchemaRetrievalUrl() { - return schemaRetrievalUrl; - } - - public void setSchemaRetrievalUrl(String schemaRetrievalUrl) { - this.schemaRetrievalUrl = schemaRetrievalUrl; - } - - public ProviderConfig providerConfig() { - return providerConfig; - } - - public void setMasterPeerAddress(NetworkAddress peerAddress) { - if (peerAddress == null) { - throw new IllegalArgumentException("peerAddress is null!"); - } - this.masterPeerAddress = peerAddress; - } - - public KeysConfig keys() { - return keys; - } - - public GatewayConfigProperties() { - } - - public static GatewayConfigProperties resolve(String file) { - Properties props = FileUtils.readProperties(file, "UTf-8"); - return resolve(props); - } - - public static GatewayConfigProperties resolve(File file) { - Properties props = FileUtils.readProperties(file, "UTf-8"); - return resolve(props); - } - - public static GatewayConfigProperties resolve(InputStream in) { - Properties props = FileUtils.readProperties(in, "UTf-8"); - return resolve(props); - } - - public static GatewayConfigProperties resolve(Properties props) { - GatewayConfigProperties configProps = new GatewayConfigProperties(); - configProps.http.host = getProperty(props, HTTP_HOST, true); - configProps.http.port = getInt(props, HTTP_PORT, true); - configProps.http.contextPath = getProperty(props, HTTP_CONTEXT_PATH, false); - - String peerHost = getProperty(props, PEER_HOST, true); - int peerPort = getInt(props, PEER_PORT, true); - boolean peerSecure = getBoolean(props, PEER_SECURE, false); - configProps.masterPeerAddress = new NetworkAddress(peerHost, peerPort, peerSecure); - - String dataRetrievalUrl = getProperty(props, DATA_RETRIEVAL_URL, true); - configProps.dataRetrievalUrl = dataRetrievalUrl; - - String schemaRetrievalUrl = getProperty(props, SCHEMA_RETRIEVAL_URL, true); - configProps.schemaRetrievalUrl = schemaRetrievalUrl; - - String providers = getProperty(props, PEER_PROVIDERS, true); - if (providers == null || providers.length() <= 0) { - throw new IllegalArgumentException("Miss peer providers!"); - } - String[] providerArray = providers.split(","); - for (String provider : providerArray) { - configProps.providerConfig.add(provider); - } - - configProps.keys.defaultPK.pubKeyValue = getProperty(props, DEFAULT_PUBKEY, true); - configProps.keys.defaultPK.privKeyPath = getProperty(props, DEFAULT_PRIVKEY_PATH, false); - configProps.keys.defaultPK.privKeyValue = getProperty(props, DEFAULT_PRIVKEY, false); - if (configProps.keys.defaultPK.privKeyPath == null && configProps.keys.defaultPK.privKeyValue == null) { - throw new IllegalArgumentException("Miss both of pk-path and pk content!"); - } - configProps.keys.defaultPK.privKeyPassword = getProperty(props, DEFAULT_PK_PWD, true); - - return configProps; - } - - private static String getProperty(Properties props, String key, boolean required) { - String value = props.getProperty(key); - if (value != null) { - value = value.trim(); - } - if (value == null || value.length() == 0) { - if (required) { - throw new IllegalArgumentException("Miss property[" + key + "]!"); - } - return null; - } - return value; - } - - private static boolean getBoolean(Properties props, String key, boolean required) { - String strBool = getProperty(props, key, required); - if (strBool == null) { - return false; - } - return Boolean.parseBoolean(strBool); - } - - private static int getInt(Properties props, String key, boolean required) { - String strInt = getProperty(props, key, required); - if (strInt == null) { - return 0; - } - return getInt(strInt); - } - - private static int getInt(String strInt) { - return Integer.parseInt(strInt.trim()); - } - - // ------------------------------------------------------------ - - public static class ProviderConfig { - List providers = new ArrayList<>(); - - public void add(String provider) { - providers.add(provider); - } - - public List getProviders() { - return providers; - } - } - - public static class HttpConfig { - - private String host; - - private int port; - - private String contextPath; - - private HttpConfig() { - } - - private HttpConfig(String host, int port, String contextPath) { - this.host = host; - this.port = port; - this.contextPath = contextPath; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getContextPath() { - return contextPath; - } - - public void setContextPath(String contextPath) { - this.contextPath = contextPath; - } - } - - public static class KeysConfig { - - private KeyPairConfig defaultPK = new KeyPairConfig(); - - public KeyPairConfig getDefault() { - return defaultPK; - } - } - - public static class KeyPairConfig { - - private String pubKeyValue; - - private String privKeyPath; - - private String privKeyValue; - - private String privKeyPassword; - - public String getPrivKeyPath() { - return privKeyPath; - } - - public String getPrivKeyValue() { - return privKeyValue; - } - - public String getPrivKeyPassword() { - return privKeyPassword; - } - - public String getPubKeyValue() { - return pubKeyValue; - } - - public void setPubKeyValue(String pubKeyValue) { - this.pubKeyValue = pubKeyValue; - } - - public void setPrivKeyPath(String privKeyPath) { - this.privKeyPath = privKeyPath; - } - - public void setPrivKeyValue(String privKeyValue) { - this.privKeyValue = privKeyValue; - } - - public void setPrivKeyPassword(String privKeyPassword) { - this.privKeyPassword = privKeyPassword; - } - - } - -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/PeerConnector.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/PeerConnector.java deleted file mode 100644 index fafeff1e..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/PeerConnector.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.gateway; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.utils.net.NetworkAddress; - -import java.util.List; - -public interface PeerConnector { - - NetworkAddress getPeerAddress(); - - boolean isConnected(); - - void connect(NetworkAddress peerAddress, AsymmetricKeypair defaultKeyPair, List peerProviders); - - void reconnect(); - - void close(); - -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/PeerService.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/PeerService.java deleted file mode 100644 index b3fd6065..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/PeerService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.gateway; - -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.TransactionService; - -public interface PeerService { - - BlockchainQueryService getQueryService(); - - TransactionService getTransactionService(); - -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/DataRetrievalService.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/DataRetrievalService.java deleted file mode 100644 index 522f8a20..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/DataRetrievalService.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.service.DataRetrievalService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/15 下午3:08 - * Description: - */ -package com.jd.blockchain.gateway.service; - -/** - * - * @author shaozhuguang - * @create 2019/1/15 - * @since 1.0.0 - */ - -public interface DataRetrievalService { - - String retrieval(String url) throws Exception; - String retrievalPost(String url, String queryString) throws Exception; -} \ No newline at end of file diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/DataRetrievalServiceHandler.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/DataRetrievalServiceHandler.java deleted file mode 100644 index 79d9ebe3..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/DataRetrievalServiceHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.service.DeepQueryServiceImpl - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/15 下午3:09 - * Description: - */ -package com.jd.blockchain.gateway.service; - -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.utils.http.agent.HttpClientPool; -import org.springframework.stereotype.Component; - -/** - * - * @author shaozhuguang - * @create 2019/1/15 - * @since 1.0.0 - */ -@Component -public class DataRetrievalServiceHandler implements DataRetrievalService { - - @Override - public String retrieval(String url) throws Exception { - return HttpClientPool.get(url); - } - - @Override - public String retrievalPost(String url, String queryString) throws Exception { - return HttpClientPool.jsonPost(url,queryString); - } -} \ No newline at end of file diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayInterceptService.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayInterceptService.java deleted file mode 100644 index ca998b89..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayInterceptService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.jd.blockchain.gateway.service; - -import com.jd.blockchain.ledger.TransactionRequest; - -public interface GatewayInterceptService { - - void intercept(TransactionRequest txRequest); -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayInterceptServiceHandler.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayInterceptServiceHandler.java deleted file mode 100644 index a7668d8e..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayInterceptServiceHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jd.blockchain.gateway.service; - -import com.jd.blockchain.contract.ContractJarUtils; -import com.jd.blockchain.gateway.PeerService; -import com.jd.blockchain.ledger.ContractCodeDeployOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionRequest; -import org.apache.commons.io.FileUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.util.ResourceUtils; - -import java.io.File; -import java.net.URL; - -@Service -public class GatewayInterceptServiceHandler implements GatewayInterceptService { - - private static String contractsPath; - - @Autowired - private PeerService peerService; - - static { - contractsPath = jarRootDir(); - } - - @Override - public void intercept(TransactionRequest txRequest) { - // 当前仅处理合约发布的请求 - Operation[] operations = txRequest.getTransactionContent().getOperations(); - if (operations != null && operations.length > 0) { - for (Operation op : operations) { - if (ContractCodeDeployOperation.class.isAssignableFrom(op.getClass())) { - // 发布合约请求 - contractCheck((ContractCodeDeployOperation)op); - } - } - } - } - - private void contractCheck(final ContractCodeDeployOperation contractOP) { - - // 校验chainCode - ContractJarUtils.verify(contractsPath, contractOP.getChainCode()); - } - - private static String jarRootDir() { - - try { - URL url = GatewayInterceptServiceHandler.class.getProtectionDomain().getCodeSource().getLocation(); - String currPath = java.net.URLDecoder.decode(url.getPath(), "UTF-8"); - if (currPath.contains("!/")) { - currPath = currPath.substring(5, currPath.indexOf("!/")); - } - if (currPath.endsWith(".jar")) { - currPath = currPath.substring(0, currPath.lastIndexOf("/") + 1); - } - File file = new File(currPath); - - String homeDir = file.getParent(); - - String jarRootPath = homeDir + File.separator + "contracts"; - - FileUtils.forceMkdir(new File(jarRootPath)); - - return jarRootPath; - - } catch (Exception e) { - throw new IllegalStateException(e); - } - } -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryService.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryService.java deleted file mode 100644 index 8a856953..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryService.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jd.blockchain.gateway.service; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.sdk.ContractSettings; -import com.jd.blockchain.sdk.LedgerBaseSettings; - -/** - * queryService only for gateway; - * @Author zhaogw - * @Date 2019/2/22 10:37 - */ -public interface GatewayQueryService { - /** - * get all ledgers hashs; - * @param fromIndex - * @param count - */ - HashDigest[] getLedgersHash(int fromIndex, int count); - - /** - * get the participants by range; - * @param ledgerHash - * @param fromIndex - * @param count - * @return - */ - ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash, int fromIndex, int count); - - /** - * 获取账本初始化配置信息 - * - * @param ledgerHash - * 账本Hash - * @return - */ - LedgerBaseSettings getLedgerBaseSettings(HashDigest ledgerHash); - - /** - * 获取账本指定合约信息 - * - * @param ledgerHash - * 账本Hash - * @param address - * 合约地址 - * @return - */ - ContractSettings getContractSettings(HashDigest ledgerHash, String address); -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceHandler.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceHandler.java deleted file mode 100644 index aeedd64c..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceHandler.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.jd.blockchain.gateway.service; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.gateway.PeerService; -import com.jd.blockchain.ledger.ContractInfo; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.LedgerMetadata; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.sdk.ContractSettings; -import com.jd.blockchain.sdk.LedgerBaseSettings; -import com.jd.blockchain.utils.QueryUtil; -import com.jd.blockchain.utils.codec.HexUtils; -import com.jd.blockchain.utils.decompiler.utils.DecompilerUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import java.util.Arrays; - - -/** - * @Author zhaogw - * @Date 2019/2/22 10:39 - */ -@Component -public class GatewayQueryServiceHandler implements GatewayQueryService { - - @Autowired - private PeerService peerService; - - @Override - public HashDigest[] getLedgersHash(int fromIndex, int count) { - HashDigest[] ledgersHashs = peerService.getQueryService().getLedgerHashs(); - int[] indexAndCount = QueryUtil.calFromIndexAndCount(fromIndex, count, ledgersHashs.length); - return Arrays.copyOfRange(ledgersHashs, indexAndCount[0], indexAndCount[0] + indexAndCount[1]); - } - - @Override - public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash, int fromIndex, int count) { - ParticipantNode[] participantNodes = peerService.getQueryService().getConsensusParticipants(ledgerHash); - int[] indexAndCount = QueryUtil.calFromIndexAndCount(fromIndex, count, participantNodes.length); - ParticipantNode[] participantNodesNews = Arrays.copyOfRange(participantNodes, indexAndCount[0], - indexAndCount[0] + indexAndCount[1]); - return participantNodesNews; - } - - @Override - public LedgerBaseSettings getLedgerBaseSettings(HashDigest ledgerHash) { - - LedgerAdminInfo ledgerAdminInfo = peerService.getQueryService().getLedgerAdminInfo(ledgerHash); - - return initLedgerBaseSettings(ledgerAdminInfo); - } - - @Override - public ContractSettings getContractSettings(HashDigest ledgerHash, String address) { - ContractInfo contractInfo = peerService.getQueryService().getContract(ledgerHash, address); - return contractSettings(contractInfo); - } - - private ContractSettings contractSettings(ContractInfo contractInfo) { - ContractSettings contractSettings = new ContractSettings(contractInfo.getAddress(), contractInfo.getPubKey(), contractInfo.getRootHash()); - byte[] chainCodeBytes = contractInfo.getChainCode(); - // 将反编译chainCode - String mainClassJava = DecompilerUtils.decompileMainClassFromBytes(chainCodeBytes); - contractSettings.setChainCode(mainClassJava); - return contractSettings; - } - - /** - * 初始化账本的基本配置 - * - * @param ledgerAdminInfo - * 账本信息 - * - * @return - */ - private LedgerBaseSettings initLedgerBaseSettings(LedgerAdminInfo ledgerAdminInfo) { - - LedgerMetadata ledgerMetadata = ledgerAdminInfo.getMetadata(); - - LedgerBaseSettings ledgerBaseSettings = new LedgerBaseSettings(); - - // 设置参与方 - ledgerBaseSettings.setParticipantNodes(ledgerAdminInfo.getParticipants()); - - // 设置共识设置 - ledgerBaseSettings.setConsensusSettings(initConsensusSettings(ledgerAdminInfo)); - - // 设置参与方根Hash - ledgerBaseSettings.setParticipantsHash(ledgerMetadata.getParticipantsHash()); - - // 设置算法配置 - ledgerBaseSettings.setCryptoSetting(ledgerAdminInfo.getSettings().getCryptoSetting()); - - // 设置种子 - ledgerBaseSettings.setSeed(initSeed(ledgerMetadata.getSeed())); - - // 设置共识协议 - ledgerBaseSettings.setConsensusProtocol(ledgerAdminInfo.getSettings().getConsensusProvider()); - - return ledgerBaseSettings; - } - - /** - * 初始化账本种子信息 - * - * @param seedBytes - * 种子的字节数组显示 - * @return - * 种子以十六进制方式显示,为方便阅读,每隔八个字符中间以"-"分割 - */ - private String initSeed(byte[] seedBytes) { - String seedString = HexUtils.encode(seedBytes); - // 每隔八个字符中加入一个一个横线 - StringBuffer seed = new StringBuffer(); - - for( int i = 0; i < seedString.length(); i++) { - char c = seedString.charAt(i); - if (i != 0 && i % 8 == 0) { - seed.append("-"); - } - seed.append(c); - } - - return seed.toString(); - } - - /** - * 初始化共识配置 - * - * @param ledgerAdminInfo - * 账本元数据 - * @return - */ - private ConsensusSettings initConsensusSettings(LedgerAdminInfo ledgerAdminInfo) { - String consensusProvider = ledgerAdminInfo.getSettings().getConsensusProvider(); - ConsensusProvider provider = ConsensusProviders.getProvider(consensusProvider); - byte[] consensusSettingsBytes = ledgerAdminInfo.getSettings().getConsensusSetting().toBytes(); - return provider.getSettingsFactory().getConsensusSettingsEncoder().decode(consensusSettingsBytes); - } -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceImpl.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceImpl.java deleted file mode 100644 index 24433b70..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -//package com.jd.blockchain.gateway.service; -// -//import com.jd.blockchain.crypto.HashDigest; -//import com.jd.blockchain.gateway.PeerService; -//import com.jd.blockchain.ledger.ParticipantNode; -//import com.jd.blockchain.utils.QueryUtil; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Component; -//import java.util.Arrays; -// -//import static com.jd.blockchain.utils.BaseConstant.QUERY_LIST_MAX; -// -///** -// * @Author zhaogw -// * @Date 2019/2/22 10:39 -// */ -//@Component -//public class GatewayQueryServiceImpl implements GatewayQueryService { -// @Autowired -// private PeerService peerService; -// -// @Override -// public HashDigest[] getLedgersHash(int fromIndex, int count) { -// HashDigest ledgersHash[] = peerService.getQueryService().getLedgerHashs(); -// int indexAndCount[] = QueryUtil.calFromIndexAndCount(fromIndex,count,ledgersHash.length); -// HashDigest ledgersHashNew[] = Arrays.copyOfRange(ledgersHash,indexAndCount[0],indexAndCount[0]+indexAndCount[1]); -// return ledgersHashNew; -// } -// -// @Override -// public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash, int fromIndex, int count) { -// ParticipantNode participantNode[] = peerService.getQueryService().getConsensusParticipants(ledgerHash); -// int indexAndCount[] = QueryUtil.calFromIndexAndCount(fromIndex,count,participantNode.length); -// ParticipantNode participantNodesNew[] = Arrays.copyOfRange(participantNode,indexAndCount[0],indexAndCount[0]+indexAndCount[1]); -// return participantNodesNew; -// } -//} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/PeerConnectionManager.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/PeerConnectionManager.java deleted file mode 100644 index ba17036b..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/PeerConnectionManager.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jd.blockchain.gateway.service; - -import javax.annotation.PreDestroy; - -import org.springframework.stereotype.Component; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.gateway.PeerConnector; -import com.jd.blockchain.gateway.PeerService; -import com.jd.blockchain.sdk.service.PeerBlockchainServiceFactory; -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.TransactionService; -import com.jd.blockchain.utils.net.NetworkAddress; - -import java.util.List; - -@Component -public class PeerConnectionManager implements PeerService, PeerConnector { - - private volatile PeerBlockchainServiceFactory peerServiceFactory; - - private volatile NetworkAddress peerAddress; - - private volatile AsymmetricKeypair gateWayKeyPair; - - private volatile List peerProviders; - - @Override - public NetworkAddress getPeerAddress() { - return peerAddress; - } - - @Override - public boolean isConnected() { - return peerServiceFactory != null; - } - - @Override - public synchronized void connect(NetworkAddress peerAddress, AsymmetricKeypair defaultKeyPair, List peerProviders) { - if (isConnected()) { - if (this.peerAddress.equals(peerAddress)) { - return; - } - throw new IllegalArgumentException( - "This gateway has been connected to a peer, cann't be connected to another peer before closing it!"); - } - setPeerAddress(peerAddress); - setGateWayKeyPair(defaultKeyPair); - setPeerProviders(peerProviders); - // TODO: 未实现运行时出错时动态重连; - peerServiceFactory = PeerBlockchainServiceFactory.connect(defaultKeyPair, peerAddress, peerProviders); - } - - @Override - public synchronized void reconnect() { - if (!isConnected()) { - throw new IllegalArgumentException( - "This gateway has not connected to a peer, please connect it first!!!"); - } - peerServiceFactory = PeerBlockchainServiceFactory.connect(gateWayKeyPair, peerAddress, peerProviders); - } - - @Override - public void close() { - PeerBlockchainServiceFactory serviceFactory = this.peerServiceFactory; - if (serviceFactory != null) { - this.peerServiceFactory = null; - this.peerAddress = null; - serviceFactory.close(); - } - } - - @Override - public BlockchainQueryService getQueryService() { - PeerBlockchainServiceFactory serviceFactory = this.peerServiceFactory; - if (serviceFactory == null) { - throw new IllegalStateException("Peer connection was closed!"); - } - return serviceFactory.getBlockchainService(); - } - - @Override - public TransactionService getTransactionService() { - PeerBlockchainServiceFactory serviceFactory = this.peerServiceFactory; - if (serviceFactory == null) { - throw new IllegalStateException("Peer connection was closed!"); - } - - return serviceFactory.getTransactionService(); - } - - @PreDestroy - private void destroy() { - close(); - } - - public void setPeerAddress(NetworkAddress peerAddress) { - this.peerAddress = peerAddress; - } - - public void setGateWayKeyPair(AsymmetricKeypair gateWayKeyPair) { - this.gateWayKeyPair = gateWayKeyPair; - } - - public void setPeerProviders(List peerProviders) { - this.peerProviders = peerProviders; - } -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java deleted file mode 100644 index 97780f62..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java +++ /dev/null @@ -1,632 +0,0 @@ -package com.jd.blockchain.gateway.web; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.PeerService; -import com.jd.blockchain.gateway.service.DataRetrievalService; -import com.jd.blockchain.gateway.service.GatewayQueryService; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.ContractInfo; -import com.jd.blockchain.ledger.KVInfoVO; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInfo; -import com.jd.blockchain.ledger.LedgerMetadata; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.TypedKVEntry; -import com.jd.blockchain.ledger.UserInfo; -import com.jd.blockchain.sdk.BlockchainExtendQueryService; -import com.jd.blockchain.sdk.ContractSettings; -import com.jd.blockchain.sdk.LedgerBaseSettings; -import com.jd.blockchain.utils.BaseConstant; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.decompiler.utils.DecompilerUtils; - -@RestController -@RequestMapping(path = "/") -public class BlockBrowserController implements BlockchainExtendQueryService { - - private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(BlockBrowserController.class); - - @Autowired - private PeerService peerService; - - @Autowired - private GatewayQueryService gatewayQueryService; - - @Autowired - private DataRetrievalService dataRetrievalService; - - private String dataRetrievalUrl; - private String schemaRetrievalUrl; - - private static final long BLOCK_MAX_DISPLAY = 3L; - - private static final long GENESIS_BLOCK_HEIGHT = 0L; - - @RequestMapping(method = RequestMethod.GET, path = "ledgers") - @Override - public HashDigest[] getLedgerHashs() { - return peerService.getQueryService().getLedgerHashs(); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}") - @Override - public LedgerInfo getLedger(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getLedger(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/admininfo") - @Override - public LedgerAdminInfo getLedgerAdminInfo(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getLedgerAdminInfo(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants") - @Override - public ParticipantNode[] getConsensusParticipants(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getConsensusParticipants(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/metadata") - @Override - public LedgerMetadata getLedgerMetadata(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getLedgerMetadata(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/settings") - public LedgerBaseSettings getLedgerInitSettings(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return gatewayQueryService.getLedgerBaseSettings(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks") - public LedgerBlock[] getBlocks(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - List ledgerBlocks = new ArrayList<>(); - for (long blockHeight = maxBlockHeight; blockHeight > GENESIS_BLOCK_HEIGHT; blockHeight--) { - LedgerBlock ledgerBlock = peerService.getQueryService().getBlock(ledgerHash, blockHeight); - ledgerBlocks.add(0, ledgerBlock); - if (ledgerBlocks.size() == BLOCK_MAX_DISPLAY) { - break; - } - } - // 最后增加创世区块 - LedgerBlock genesisBlock = peerService.getQueryService().getBlock(ledgerHash, GENESIS_BLOCK_HEIGHT); - ledgerBlocks.add(0, genesisBlock); - LedgerBlock[] blocks = new LedgerBlock[ledgerBlocks.size()]; - ledgerBlocks.toArray(blocks); - return blocks; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}") - @Override - public LedgerBlock getBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getBlock(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}") - @Override - public LedgerBlock getBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getBlock(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/count") - @Override - public long getTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getTransactionCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/count") - @Override - public long getTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getTransactionCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/count") - @Override - public long getTransactionTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getTransactionTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/count") - @Override - public long getDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getDataAccountCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/count") - @Override - public long getDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getDataAccountCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/count") - @Override - public long getDataAccountTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getDataAccountTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/count") - @Override - public long getUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getUserCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/count") - @Override - public long getUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getUserCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/count") - @Override - public long getUserTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getUserTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/count") - @Override - public long getContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getContractCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/count") - @Override - public long getContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getContractCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/count") - @Override - public long getContractTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getContractTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs") - @Override - public LedgerTransaction[] getTransactions(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getTransactions(ledgerHash, blockHeight, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs") - @Override - public LedgerTransaction[] getTransactions(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getTransactions(ledgerHash, blockHash, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/hash/{contentHash}") - @Override - public LedgerTransaction getTransactionByContentHash(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "contentHash") HashDigest contentHash) { - return peerService.getQueryService().getTransactionByContentHash(ledgerHash, contentHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/state/{contentHash}") - @Override - public TransactionState getTransactionStateByContentHash(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "contentHash") HashDigest contentHash) { - return peerService.getQueryService().getTransactionStateByContentHash(ledgerHash, contentHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/address/{address}") - @Override - public UserInfo getUser(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - return peerService.getQueryService().getUser(ledgerHash, address); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/address/{address}") - @Override - public BlockchainIdentity getDataAccount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - - return peerService.getQueryService().getDataAccount(ledgerHash, address); - } - - @RequestMapping(method = { RequestMethod.GET, - RequestMethod.POST }, path = "ledgers/{ledgerHash}/accounts/{address}/entries") - @Override - public TypedKVEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, - @PathVariable("address") String address, @RequestParam("keys") String... keys) { - return peerService.getQueryService().getDataEntries(ledgerHash, address, keys); - } - - @RequestMapping(method = { RequestMethod.GET, - RequestMethod.POST }, path = "ledgers/{ledgerHash}/accounts/{address}/entries-version") - @Override - public TypedKVEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, - @PathVariable("address") String address, @RequestBody KVInfoVO kvInfoVO) { - return peerService.getQueryService().getDataEntries(ledgerHash, address, kvInfoVO); - } - - @RequestMapping(method = { RequestMethod.GET, - RequestMethod.POST }, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries") - @Override - public TypedKVEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, - @PathVariable("address") String address, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getDataEntries(ledgerHash, address, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries/count") - @Override - public long getDataEntriesTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - return peerService.getQueryService().getDataEntriesTotalCount(ledgerHash, address); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/address/{address}") - public ContractSettings getContractSettings(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - ContractInfo contractInfo = peerService.getQueryService().getContract(ledgerHash, address); - return contractSettings(contractInfo); - } - - private ContractSettings contractSettings(ContractInfo contractInfo) { - ContractSettings contractSettings = new ContractSettings(contractInfo.getAddress(), contractInfo.getPubKey(), - contractInfo.getRootHash()); - byte[] chainCodeBytes = contractInfo.getChainCode(); - // 将反编译chainCode - String mainClassJava = DecompilerUtils.decompileMainClassFromBytes(chainCodeBytes); - contractSettings.setChainCode(mainClassJava); - return contractSettings; - } - -// @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/address/{address}") - @Override - public ContractInfo getContract(HashDigest ledgerHash, String address) { - return peerService.getQueryService().getContract(ledgerHash, address); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/latest") - @Override - public LedgerBlock getLatestBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - long latestBlockHeight = peerService.getQueryService().getLedger(ledgerHash).getLatestBlockHeight(); - return peerService.getQueryService().getBlock(ledgerHash, latestBlockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/additional-count") - @Override - public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - // 获取某个区块的交易总数 - long currentBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentBlockTxCount; - } - long lastBlockHeight = blockHeight - 1; - long lastBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, lastBlockHeight); - // 当前区块交易数减上个区块交易数 - return currentBlockTxCount - lastBlockTxCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/additional-count") - @Override - public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockTxCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, previousHash); - // 当前区块交易数减上个区块交易数 - return currentBlockTxCount - lastBlockTxCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/additional-count") - @Override - public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getTransactionTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getTransactionCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/additional-count") - @Override - public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - long currentDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentDaCount; - } - long lastBlockHeight = blockHeight - 1; - long lastDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, lastBlockHeight); - return currentDaCount - lastDaCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/additional-count") - @Override - public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockDaCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, previousHash); - // 当前区块数据账户数量减上个区块数据账户数量 - return currentBlockDaCount - lastBlockDaCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/additional-count") - @Override - public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getDataAccountTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getDataAccountCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/additional-count") - @Override - public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - long currentUserCount = peerService.getQueryService().getUserCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentUserCount; - } - long lastBlockHeight = blockHeight - 1; - long lastUserCount = peerService.getQueryService().getUserCount(ledgerHash, lastBlockHeight); - return currentUserCount - lastUserCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/additional-count") - @Override - public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockUserCount = peerService.getQueryService().getUserCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockUserCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockUserCount = peerService.getQueryService().getUserCount(ledgerHash, previousHash); - // 当前区块用户数量减上个区块用户数量 - return currentBlockUserCount - lastBlockUserCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/additional-count") - @Override - public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getUserTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getUserCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/additional-count") - @Override - public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - long currentContractCount = peerService.getQueryService().getContractCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentContractCount; - } - long lastBlockHeight = blockHeight - 1; - long lastContractCount = peerService.getQueryService().getUserCount(ledgerHash, lastBlockHeight); - return currentContractCount - lastContractCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/additional-count") - @Override - public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockContractCount = peerService.getQueryService().getContractCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockContractCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockContractCount = peerService.getQueryService().getUserCount(ledgerHash, previousHash); - // 当前区块合约数量减上个区块合约数量 - return currentBlockContractCount - lastBlockContractCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/additional-count") - @Override - public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getContractTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getContractCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "utils/pubkey/{pubkey}/addr") - public String getAddrByPubKey(@PathVariable(name = "pubkey") String strPubKey) { - PubKey pubKey = KeyGenUtils.decodePubKey(strPubKey); - return AddressEncoding.generateAddress(pubKey).toBase58(); - } - - @RequestMapping(method = RequestMethod.GET, value = "ledgers/{ledgerHash}/**/search") - public Object dataRetrieval(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, HttpServletRequest request) { - String result; - if (dataRetrievalUrl == null || dataRetrievalUrl.length() <= 0) { - result = "{'message':'OK','data':'" + "data.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "" : request.getQueryString(); - String fullQueryUrl = new StringBuffer(dataRetrievalUrl).append(request.getRequestURI()) - .append(BaseConstant.DELIMETER_QUESTION).append(queryParams).toString(); - try { - result = dataRetrievalService.retrieval(fullQueryUrl); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'OK','data':'" + e.getMessage() + "'}"; - } - } - return result; - } - - /** - * querysql; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.POST, value = "schema/querysql") - public Object queryBySql(HttpServletRequest request,@RequestBody String queryString) { - String result; - if (schemaRetrievalUrl == null || schemaRetrievalUrl.length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(schemaRetrievalUrl) - .append(request.getRequestURI()) - .append(BaseConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrievalPost(fullQueryUrl,queryString); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return result; - } - - public void setSchemaRetrievalUrl(String schemaRetrievalUrl) { - this.schemaRetrievalUrl = schemaRetrievalUrl; - } - - public void setDataRetrievalUrl(String dataRetrievalUrl) { - this.dataRetrievalUrl = dataRetrievalUrl; - } - - /** - * get all ledgers count; - */ - @RequestMapping(method = RequestMethod.GET, path = "ledgers/count") - @Override - public int getLedgersCount() { - return peerService.getQueryService().getLedgerHashs().length; - } - - // 注: 账本的数量不会很多,不需要分页; -// /** -// * get all ledgers hashs; -// */ -// @RequestMapping(method = RequestMethod.GET, path = "ledgers") -// public HashDigest[] getLedgersHash( -// @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, -// @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { -// return gatewayQueryService.getLedgersHash(fromIndex, count); -// } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants/count") - public int getConsensusParticipantCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getConsensusParticipants(ledgerHash).length; - } - -// @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants") -// public ParticipantNode[] getConsensusParticipants(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, -// @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, -// @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { -// -// ParticipantNode participantNode[] = peerService.getQueryService().getConsensusParticipants(ledgerHash); -// int indexAndCount[] = QueryUtil.calFromIndexAndCount(fromIndex, count, participantNode.length); -// ParticipantNode participantNodesNew[] = Arrays.copyOfRange(participantNode, indexAndCount[0], -// indexAndCount[0] + indexAndCount[1]); -// return participantNodesNew; -// } - - /** - * get more users by fromIndex and count; - * - * @param ledgerHash - * @param fromIndex - * @param count - * @return - */ - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users") - @Override - public BlockchainIdentity[] getUsers(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return revertAccountHeader(peerService.getQueryService().getUsers(ledgerHash, fromIndex, count)); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts") - @Override - public BlockchainIdentity[] getDataAccounts(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return revertAccountHeader(peerService.getQueryService().getDataAccounts(ledgerHash, fromIndex, count)); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts") - @Override - public BlockchainIdentity[] getContractAccounts(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return revertAccountHeader(peerService.getQueryService().getContractAccounts(ledgerHash, fromIndex, count)); - } - - /** - * reverse the BlockchainIdentity[] content; the latest record show first; - * @return - */ - private BlockchainIdentity[] revertAccountHeader(BlockchainIdentity[] accountHeaders){ - BlockchainIdentity[] accounts = new BlockchainIdentity[accountHeaders.length]; - if(accountHeaders!=null && accountHeaders.length>0){ - for (int i = 0; i < accountHeaders.length; i++) { - accounts[accountHeaders.length-1-i] = accountHeaders[i]; - } - } - return accounts; - } -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayGlobalExceptionHandler.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayGlobalExceptionHandler.java deleted file mode 100644 index 463ad782..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayGlobalExceptionHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jd.blockchain.gateway.web; - -import javax.servlet.http.HttpServletRequest; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -import com.jd.blockchain.utils.BusinessException; -import com.jd.blockchain.utils.web.model.ErrorCode; -import com.jd.blockchain.utils.web.model.WebResponse; -import com.jd.blockchain.utils.web.model.WebResponse.ErrorMessage; - -/** - * 全局异常处理类 - */ -@RestControllerAdvice -public class GatewayGlobalExceptionHandler { - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - @ExceptionHandler(value = Exception.class) - @ResponseBody - public WebResponse json(HttpServletRequest req, Exception ex) { - ErrorMessage message = null; - String reqURL = "[" + req.getMethod() + "] " + req.getRequestURL().toString(); - if (ex instanceof BusinessException) { - logger.error("BusinessException occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "] " - + ex.getMessage(), ex); - BusinessException businessException = (BusinessException) ex; - message = new ErrorMessage(businessException.getErrorCode(), businessException.getMessage()); - } else { - logger.error("Unexpected exception occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() - + "]" + ex.getMessage(), ex); - message = new ErrorMessage(ErrorCode.UNEXPECTED.getValue(), - ErrorCode.UNEXPECTED.getDescription(ex.getMessage())); - } - WebResponse response = WebResponse.createFailureResult(message); - return response; - } - -} \ No newline at end of file diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayJsonResponseAdvice.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayJsonResponseAdvice.java deleted file mode 100644 index ec66c6cd..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayJsonResponseAdvice.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.gateway.web; - -import org.springframework.core.MethodParameter; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.server.ServerHttpRequest; -import org.springframework.http.server.ServerHttpResponse; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; - -import com.jd.blockchain.utils.web.model.WebResponse; - -@RestControllerAdvice -public class GatewayJsonResponseAdvice implements ResponseBodyAdvice { - - @Override - public boolean supports(MethodParameter returnType, Class> converterType) { - if (MappingJackson2HttpMessageConverter.class == converterType - && (returnType.getContainingClass().getName().startsWith("com.jd") - || returnType.getDeclaringClass().getName().startsWith("com.jd"))) { - return true; - } - return false; - } - - @Override - public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, - Class> selectedConverterType, ServerHttpRequest request, - ServerHttpResponse response) { - if (body == null) { - return WebResponse.createSuccessResult(null); - } - if (body instanceof ResponseEntity) { - return body; - } - // 把返回结果自动转换为 WebResponse; - if (body instanceof WebResponse) { - return body; - } - return WebResponse.createSuccessResult(body); - } - -} \ No newline at end of file diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayTimeTasks.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayTimeTasks.java deleted file mode 100644 index 9e6c249d..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayTimeTasks.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.web.GatewayTimeTasks - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/16 下午6:17 - * Description: - */ -package com.jd.blockchain.gateway.web; - -import com.jd.blockchain.consensus.service.NodeServer; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.gateway.PeerConnector; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.util.*; - -/** - * - * @author shaozhuguang - * @create 2019/1/16 - * @since 1.0.0 - */ -@Component -@EnableScheduling -public class GatewayTimeTasks { - - private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(GatewayTimeTasks.class); - - @Autowired - private PeerConnector peerConnector; - - //每30分钟执行一次 - @Scheduled(cron = "0 */8 * * * * ") - public void updateLedger(){ - try { - peerConnector.reconnect(); - } catch (Exception e) { - LOGGER.error(e.getMessage()); - } - } -} \ No newline at end of file diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java deleted file mode 100644 index cfed9081..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.jd.blockchain.gateway.web; - -import java.util.List; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.ClientIdentifications; -import com.jd.blockchain.consensus.action.ActionRequest; -import com.jd.blockchain.consensus.action.ActionResponse; -import com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.web.serializes.ByteArrayObjectUtil; -import org.springframework.context.annotation.Configuration; -import org.springframework.format.FormatterRegistry; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import com.jd.blockchain.utils.io.ByteArray; -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; -import com.jd.blockchain.utils.web.model.JsonWebResponseMessageConverter; -import com.jd.blockchain.web.converters.BinaryMessageConverter; -import com.jd.blockchain.web.converters.HashDigestInputConverter; - -/** - * @author zhuguang - * @date 2018-08-08 - */ -@Configuration -public class GatewayWebServerConfigurer implements WebMvcConfigurer { - - static { - JSONSerializeUtils.disableCircularReferenceDetect(); - JSONSerializeUtils.configStringSerializer(ByteArray.class); - DataContractRegistry.register(BftsmartNodeSettings.class); - - // 注册角色/权限相关接口 - DataContractRegistry.register(RolesConfigureOperation.class); - DataContractRegistry.register(RolesConfigureOperation.RolePrivilegeEntry.class); - DataContractRegistry.register(UserAuthorizeOperation.class); - DataContractRegistry.register(UserAuthorizeOperation.UserRolesEntry.class); - DataContractRegistry.register(PrivilegeSet.class); - DataContractRegistry.register(RoleSet.class); - DataContractRegistry.register(SecurityInitSettings.class); - DataContractRegistry.register(RoleInitSettings.class); - DataContractRegistry.register(UserAuthInitSettings.class); - DataContractRegistry.register(LedgerMetadata_V2.class); - } - - - @Override - public void extendMessageConverters(List> converters) { - int index = converters.size(); - for (int i = 0; i < converters.size(); i++) { - if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) { - index = i; - break; - } - } - - JsonWebResponseMessageConverter jsonConverter = new JsonWebResponseMessageConverter(false); - - converters.add(index, jsonConverter); - - converters.add(0, new BinaryMessageConverter()); - - initByteArrayJsonSerialize(); - } - - @Override - public void addFormatters(FormatterRegistry registry) { - registry.addConverter(new HashDigestInputConverter()); - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources"); - } - - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("web/index.html"); - } - - private void initByteArrayJsonSerialize() { - ByteArrayObjectUtil.init(); - } -} diff --git a/source/gateway/src/main/resources/application-gw.properties b/source/gateway/src/main/resources/application-gw.properties deleted file mode 100644 index e69de29b..00000000 diff --git a/source/gateway/src/main/resources/banner.txt b/source/gateway/src/main/resources/banner.txt deleted file mode 100644 index c39618bd..00000000 --- a/source/gateway/src/main/resources/banner.txt +++ /dev/null @@ -1,13 +0,0 @@ - - ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄ -▐░░░░░░░░░░░▌▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░▌ ▐░▌ - ▀▀▀▀▀█░█▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░▌░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ - ▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▐░▌ -▐░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░░▌ - ▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀ - diff --git a/source/gateway/src/main/resources/log4j2.xml b/source/gateway/src/main/resources/log4j2.xml deleted file mode 100644 index 9a3b1d39..00000000 --- a/source/gateway/src/main/resources/log4j2.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/GatewayConfigPropertiesTest.java b/source/gateway/src/test/java/test/com/jd/blockchain/gateway/GatewayConfigPropertiesTest.java deleted file mode 100644 index 1ab1340a..00000000 --- a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/GatewayConfigPropertiesTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package test.com.jd.blockchain.gateway; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.gateway.GatewayConfigProperties; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.security.ShaUtils; - -public class GatewayConfigPropertiesTest { - - @Test - public void test() { - ClassPathResource gatewayConfigResource = new ClassPathResource("gateway.conf"); - try (InputStream in = gatewayConfigResource.getInputStream()) { - GatewayConfigProperties configProps = GatewayConfigProperties.resolve(in); - assertEquals("0.0.0.0", configProps.http().getHost()); - assertEquals(8081, configProps.http().getPort()); - assertNull(configProps.http().getContextPath()); - - assertEquals("127.0.0.1", configProps.masterPeerAddress().getHost()); - assertEquals(12000, configProps.masterPeerAddress().getPort()); - assertTrue(configProps.masterPeerAddress().isSecure()); - - assertEquals("http://127.0.0.1:10001", configProps.dataRetrievalUrl()); - - assertEquals("3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", configProps.keys().getDefault().getPubKeyValue()); - assertNull(configProps.keys().getDefault().getPrivKeyPath()); - assertEquals("177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", configProps.keys().getDefault().getPrivKeyValue()); - assertEquals("DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY", configProps.keys().getDefault().getPrivKeyPassword()); - - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - - @Test - public void generateDefaultPassword() { - //generate default base58 password for gateway.conf - String password = "abc"; - String encodePassword; - byte[] pwdBytes = BytesUtils.toBytes(password, "UTF-8"); - encodePassword = Base58Utils.encode(ShaUtils.hash_256(pwdBytes)); - - return; - - } - -} diff --git a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestJSONSerializeTest.java b/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestJSONSerializeTest.java deleted file mode 100644 index 61bbcfc9..00000000 --- a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestJSONSerializeTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package test.com.jd.blockchain.gateway.data; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; - -public class HashDigestJSONSerializeTest { - - private static class TestData { - - private int id; - - private HashDigest hash; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public HashDigest getHash() { - return hash; - } - - public void setHash(HashDigest hash) { - this.hash = hash; - } - - } - - @Test - public void test() throws Exception { - JSONSerializeUtils.configSerialization(HashDigest.class, HashDigestSerializer.INSTANCE, - HashDigestDeserializer.INSTANCE); - - HashFunction hashFunc = Crypto.getHashFunction("SHA256"); - HashDigest hash = hashFunc.hash("jd-test".getBytes()); - - String hashJson = JSONSerializeUtils.serializeToJSON(hash, true); - HashDigest hashDigest = JSONSerializeUtils.deserializeFromJSON(hashJson, HashDigest.class); - - assertArrayEquals(hash.getRawDigest(), hashDigest.getRawDigest()); - assertEquals(hash.getAlgorithm(), hashDigest.getAlgorithm()); - - TestData data = new TestData(); - data.setHash(hash); - data.setId(10); - - String json = JSONSerializeUtils.serializeToJSON(data, true); - - TestData desData = JSONSerializeUtils.deserializeFromJSON(json, TestData.class); - assertEquals(data.getHash(), desData.getHash()); - assertEquals(data.getId(), desData.getId()); - } - -} diff --git a/source/gateway/src/test/resources/gateway.conf b/source/gateway/src/test/resources/gateway.conf deleted file mode 100644 index e112bf72..00000000 --- a/source/gateway/src/test/resources/gateway.conf +++ /dev/null @@ -1,31 +0,0 @@ -#网关的HTTP服务地址; -http.host=0.0.0.0 -#网关的HTTP服务端口; -http.port=8081 -#网关的HTTP服务上下文路径,可选; -#http.context-path= - -#共识节点的服务地址(与该网关节点连接的Peer节点的IP地址); -peer.host=127.0.0.1 -#共识节点的服务端口(与该网关节点连接的Peer节点的端口); -peer.port=12000 -#共识节点的服务是否启用安全证书; -peer.secure=true -#共识节点的服务提供解析器 -#BftSmart共识Provider:com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider -#简单消息共识Provider:com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider -peer.providers=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#数据检索服务对应URL,格式:http://{ip}:{port},例如:http://127.0.0.1:10001 -#若该值不配置或配置不正确,则浏览器模糊查询部分无法正常显示 -data.retrieval.url=http://127.0.0.1:10001 -schema.retrieval.url=http://192.168.151.39:8082 - -#默认公钥的内容(Base58编码数据); -keys.default.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#默认私钥的路径;在 pk-path 和 pk 之间必须设置其一; -keys.default.privkey-path= -#默认私钥的内容(加密的Base58编码数据);在 pk-path 和 pk 之间必须设置其一; -keys.default.privkey=177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x -#默认私钥的解码密码; -keys.default.privkey-password=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountAccessPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountAccessPolicy.java deleted file mode 100644 index 3ffa5536..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountAccessPolicy.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.ledger.core; - - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.utils.Bytes; - -/** - * 账户访问策略; - * - * @author huanghaiquan - * - */ -public interface AccountAccessPolicy { - - /** - * Check access policy before committing the specified account;
- * - * @param account - * @return Return true if it satisfies this policy, or false if it doesn't; - */ - boolean checkDataWriting(BlockchainIdentity account); - - boolean checkRegistering(Bytes address, PubKey pubKey); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountDecorator.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountDecorator.java deleted file mode 100644 index 399631ce..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountDecorator.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.Account; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.HashProof; -import com.jd.blockchain.ledger.MerkleSnapshot; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Dataset; - -public class AccountDecorator implements Account, HashProvable, MerkleSnapshot{ - - private CompositeAccount mklAccount; - - public AccountDecorator(CompositeAccount mklAccount) { - this.mklAccount = mklAccount; - } - - protected Dataset getHeaders() { - return mklAccount.getHeaders(); - } - - - @Override - public HashDigest getRootHash() { - return mklAccount.getRootHash(); - } - - @Override - public HashProof getProof(Bytes key) { - return mklAccount.getProof(key); - } - - @Override - public BlockchainIdentity getID() { - return mklAccount.getID(); - } - - @Override - public Dataset getDataset() { - return mklAccount.getDataset(); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountQuery.java deleted file mode 100644 index 23afd3fd..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountQuery.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.utils.Bytes; - -public interface AccountQuery extends MerkleProvable { - - /** - * 返回总数; - * - * @return - */ - long getTotal(); - - BlockchainIdentity[] getHeaders(int fromIndex, int count); - - boolean contains(Bytes address); - - /** - * get proof of specified account; - */ - @Override - MerkleProof getProof(Bytes address); - - /** - * 返回账户实例; - * - * @param address Base58 格式的账户地址; - * @return 账户实例,如果不存在则返回 null; - */ - T getAccount(String address); - - T getAccount(Bytes address); - - T getAccount(Bytes address, long version); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CompositeAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CompositeAccount.java deleted file mode 100644 index 5630917e..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CompositeAccount.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.Account; -import com.jd.blockchain.ledger.MerkleSnapshot; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.utils.Dataset; - -public interface CompositeAccount extends Account, MerkleSnapshot, HashProvable{ - - Dataset getHeaders(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ConsensusConfig.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ConsensusConfig.java deleted file mode 100644 index a947556e..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ConsensusConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.ledger.ConsensusSetting; -// -//public class ConsensusConfig implements ConsensusSetting { -// -// private byte[] value; -// -// public ConsensusConfig() { -// } -// -// public ConsensusConfig(ConsensusSetting setting) { -// if (setting != null) { -// this.value = setting.getValue(); -// } -// } -// -// -// @Override -// public byte[] getValue() { -// return value; -// } -// -// -// public void setValue(byte[] value) { this.value = value;} -// -// -//} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountQuery.java deleted file mode 100644 index 3c1d52a5..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountQuery.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public interface ContractAccountQuery extends AccountQuery { - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CryptoConfig.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CryptoConfig.java deleted file mode 100644 index 2a23f8bf..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CryptoConfig.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.HashMap; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerException; - -public class CryptoConfig implements CryptoSetting { - - private CryptoProvider[] cryptoProviders; - - private short hashAlgorithm; - - private boolean autoVerifyHash; - - HashMap providers; - HashMap nameAlgorithms; - HashMap codeAlgorithms; - - public CryptoConfig() { - } - - public CryptoConfig(CryptoSetting setting) { - setSupportedProviders(setting.getSupportedProviders()); - setHashAlgorithm(setting.getHashAlgorithm()); - this.autoVerifyHash = setting.getAutoVerifyHash(); - } - - @Override - public CryptoProvider[] getSupportedProviders() { - return cryptoProviders == null ? null : cryptoProviders.clone(); - } - - @Override - public short getHashAlgorithm() { - return hashAlgorithm; - } - - @Override - public boolean getAutoVerifyHash() { - return autoVerifyHash; - } - - public void setSupportedProviders(CryptoProvider[] supportedProviders) { - HashMap providers = new HashMap(); - HashMap nameAlgorithms = new HashMap(); - HashMap codeAlgorithms = new HashMap(); - if (supportedProviders != null) { - // 检查是否存在重复的提供者以及算法; - for (CryptoProvider cryptoProvider : supportedProviders) { - if (providers.containsKey(cryptoProvider.getName())) { - throw new LedgerException("Duplicate crypto providers [" + cryptoProvider.getName() + "]!"); - } - CryptoAlgorithm[] algorithms = cryptoProvider.getAlgorithms(); - for (CryptoAlgorithm alg : algorithms) { - if (nameAlgorithms.containsKey(alg.name())) { - throw new LedgerException("Duplicate crypto algorithms [" + alg.toString() + "] from provider " - + cryptoProvider.getName() + "!"); - } - if (codeAlgorithms.containsKey(alg.code())) { - throw new LedgerException("Duplicate crypto algorithms [" + alg.toString() + "] from provider" - + cryptoProvider.getName() + "!"); - } - nameAlgorithms.put(alg.name(), alg); - codeAlgorithms.put(alg.code(), alg); - } - providers.put(cryptoProvider.getName(), cryptoProvider); - } - } - this.providers = providers; - this.nameAlgorithms = nameAlgorithms; - this.codeAlgorithms = codeAlgorithms; - - this.cryptoProviders = supportedProviders; - } - - public void setHashAlgorithm(CryptoAlgorithm hashAlgorithm) { - setHashAlgorithm(hashAlgorithm.code()); - } - - public void setHashAlgorithm(short hashAlgorithm) { - if (codeAlgorithms == null || !codeAlgorithms.containsKey(hashAlgorithm)) { - throw new LedgerException("Current CryptoConfig has no crypto provider!"); - } - this.hashAlgorithm = hashAlgorithm; - } - - public void setAutoVerifyHash(boolean autoVerifyHash) { - this.autoVerifyHash = autoVerifyHash; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountQuery.java deleted file mode 100644 index c2bcb17d..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountQuery.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public interface DataAccountQuery extends AccountQuery { - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DefaultOperationHandleRegisteration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DefaultOperationHandleRegisteration.java deleted file mode 100644 index ae8ad40b..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DefaultOperationHandleRegisteration.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.stereotype.Component; - -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.core.handles.ContractCodeDeployOperationHandle; -import com.jd.blockchain.ledger.core.handles.DataAccountKVSetOperationHandle; -import com.jd.blockchain.ledger.core.handles.DataAccountRegisterOperationHandle; -import com.jd.blockchain.ledger.core.handles.JVMContractEventSendOperationHandle; -import com.jd.blockchain.ledger.core.handles.LedgerInitOperationHandle; -import com.jd.blockchain.ledger.core.handles.ParticipantRegisterOperationHandle; -import com.jd.blockchain.ledger.core.handles.ParticipantStateUpdateOperationHandle; -import com.jd.blockchain.ledger.core.handles.RolesConfigureOperationHandle; -import com.jd.blockchain.ledger.core.handles.UserAuthorizeOperationHandle; -import com.jd.blockchain.ledger.core.handles.UserRegisterOperationHandle; - -@Component -public class DefaultOperationHandleRegisteration implements OperationHandleRegisteration { - - private static Map, OperationHandle> DEFAULT_HANDLES = new HashMap<>(); - - private Map, OperationHandle> handles = new ConcurrentHashMap<>(); - - static { - registerDefaultHandle(new LedgerInitOperationHandle()); - - registerDefaultHandle(new RolesConfigureOperationHandle()); - - registerDefaultHandle(new UserAuthorizeOperationHandle()); - - registerDefaultHandle(new UserRegisterOperationHandle()); - - registerDefaultHandle(new DataAccountKVSetOperationHandle()); - - registerDefaultHandle(new DataAccountRegisterOperationHandle()); - - registerDefaultHandle(new ContractCodeDeployOperationHandle()); - - registerDefaultHandle(new JVMContractEventSendOperationHandle()); - - registerDefaultHandle(new ParticipantRegisterOperationHandle()); - - registerDefaultHandle(new ParticipantStateUpdateOperationHandle()); - } - - private static void registerDefaultHandle(OperationHandle handle) { - DEFAULT_HANDLES.put(handle.getOperationType(), handle); - } - - /** - * 注册操作处理器;此方法将覆盖默认的操作处理器配置; - * - * @param handle - */ - public void registerHandle(OperationHandle handle) { - List> opTypes = new ArrayList>(); - for (Class opType : handles.keySet()) { - if (opType.isAssignableFrom(handle.getOperationType())) { - opTypes.add(opType); - } - } - - for (Class opType : opTypes) { - handles.put(opType, handle); - } - handles.put(handle.getOperationType(), handle); - } - - private OperationHandle getRegisteredHandle(Class operationType) { - OperationHandle hdl = handles.get(operationType); - if (hdl == null) { - hdl = DEFAULT_HANDLES.get(operationType); - - //按“操作类型”的继承关系匹配; - if (hdl == null) { - for (Class opType : handles.keySet()) { - if (opType.isAssignableFrom(operationType)) { - hdl = handles.get(opType); - break; - } - } - } - - if (hdl == null) { - for (Class opType : DEFAULT_HANDLES.keySet()) { - if (opType.isAssignableFrom(operationType)) { - hdl = DEFAULT_HANDLES.get(opType); - break; - } - } - } - - if (hdl != null) { - handles.put(operationType, hdl); - } - } - return hdl; - } - - /* - * (non-Javadoc) - * - * @see - * com.jd.blockchain.ledger.core.impl.OperationHandleRegisteration#getHandle( - * java.lang.Class) - */ - @Override - public OperationHandle getHandle(Class operationType) { - OperationHandle hdl = getRegisteredHandle(operationType); - if (hdl == null) { - throw new LedgerException("Unsupported operation type[" + operationType.getName() + "]!"); - } - return hdl; - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyAccountSet.java deleted file mode 100644 index 8cfdd7fc..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyAccountSet.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.utils.Bytes; - -public class EmptyAccountSet implements AccountQuery { - - private static final BlockchainIdentity[] EMPTY = {}; - - @Override - public HashDigest getRootHash() { - return null; - } - - @Override - public MerkleProof getProof(Bytes key) { - return null; - } - - @Override - public BlockchainIdentity[] getHeaders(int fromIndex, int count) { - return EMPTY; - } - - @Override - public long getTotal() { - return 0; - } - - @Override - public boolean contains(Bytes address) { - return false; - } - - @Override - public T getAccount(String address) { - return null; - } - - @Override - public T getAccount(Bytes address) { - return null; - } - - @Override - public T getAccount(Bytes address, long version) { - return null; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyLedgerDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyLedgerDataset.java deleted file mode 100644 index 958ef8aa..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyLedgerDataset.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerAdminSettings; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.ParticipantDataQuery; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.utils.Bytes; - -public class EmptyLedgerDataset implements LedgerDataQuery { - - private static final LedgerAdminDataQuery EMPTY_ADMIN_DATA = new EmptyAdminData(); - - private static final UserAccountQuery EMPTY_USER_ACCOUNTS = new EmptyUserAccountSet(); - - private static final DataAccountQuery EMPTY_DATA_ACCOUNTS = new EmptyDataAccountSet(); - - private static final ContractAccountQuery EMPTY_CONTRACT_ACCOUNTS = new EmptyContractAccountSet(); - - private static final ParticipantDataQuery EMPTY_PARTICIPANTS = new EmptyParticipantData(); - - @Override - public LedgerAdminDataQuery getAdminDataset() { - return EMPTY_ADMIN_DATA; - } - - @Override - public UserAccountQuery getUserAccountSet() { - return EMPTY_USER_ACCOUNTS; - } - - @Override - public DataAccountQuery getDataAccountSet() { - return EMPTY_DATA_ACCOUNTS; - } - - @Override - public ContractAccountQuery getContractAccountset() { - return EMPTY_CONTRACT_ACCOUNTS; - } - - - private static class EmptyAdminData implements LedgerAdminDataQuery{ - - - @Override - public LedgerAdminSettings getAdminInfo() { - return null; - } - - @Override - public ParticipantDataQuery getParticipantDataset() { - return EMPTY_PARTICIPANTS; - } - - } - - private static class EmptyParticipantData implements ParticipantDataQuery{ - - @Override - public HashDigest getRootHash() { - return null; - } - - @Override - public MerkleProof getProof(Bytes key) { - return null; - } - - @Override - public long getParticipantCount() { - return 0; - } - - @Override - public boolean contains(Bytes address) { - return false; - } - - @Override - public ParticipantNode getParticipant(Bytes address) { - return null; - } - - @Override - public ParticipantNode[] getParticipants() { - return null; - } - - } - - private static class EmptyUserAccountSet extends EmptyAccountSet implements UserAccountQuery{ - - } - - private static class EmptyDataAccountSet extends EmptyAccountSet implements DataAccountQuery{ - - } - - private static class EmptyContractAccountSet extends EmptyAccountSet implements ContractAccountQuery{ - - } - - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/FullPermissionedSecurityManager.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/FullPermissionedSecurityManager.java deleted file mode 100644 index c217ee34..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/FullPermissionedSecurityManager.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Set; - -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerSecurityException; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.utils.Bytes; - -class FullPermissionedSecurityManager implements LedgerSecurityManager { - - public static final FullPermissionedSecurityManager INSTANCE = new FullPermissionedSecurityManager(); - - @Override - public SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes) { - return new FullPermissionedPolicy(endpoints, nodes); - } - - private static class FullPermissionedPolicy implements SecurityPolicy { - - private Set endpoints; - private Set nodes; - - public FullPermissionedPolicy(Set endpoints, Set nodes) { - this.endpoints = endpoints; - this.nodes = nodes; - } - - @Override - public Set getEndpoints() { - return endpoints; - } - - @Override - public Set getNodes() { - return nodes; - } - - @Override - public boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - } - - @Override - public void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - } - - @Override - public void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException { - } - - @Override - public void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - } - - @Override - public boolean isEndpointValid(MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isNodeValid(MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { - } - - @Override - public void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { - } - - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericAccountDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericAccountDataset.java deleted file mode 100644 index 76831c3e..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericAccountDataset.java +++ /dev/null @@ -1,36 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//public class GenericAccountDataset { -// -// private Class dataClazz; -// -// private AccountDataSet dataset; -// -// protected GenericAccountDataset(AccountDataSet dataset, Class dataClazz) { -// this.dataClazz = dataClazz; -// this.dataset = dataset; -// } -// -// protected T getData(String key) { -// byte[] value = dataset.getBytes(key); -// return deserialize(value); -// } -// -// protected T getData(String key, long version) { -// byte[] value = dataset.getBytes(key, version); -// return deserialize(value); -// } -// -// protected long setData(String key, T data, long version) { -// byte[] value = serialize(data); -// return dataset.setBytes(key, value, version); -// } -// -// private byte[] serialize(T data) { -// throw new IllegalStateException("Not implemented!"); -// } -// -// private T deserialize(byte[] value) { -// throw new IllegalStateException("Not implemented!"); -// } -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericAccountSet.java deleted file mode 100644 index 372163e1..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericAccountSet.java +++ /dev/null @@ -1,92 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.crypto.HashDigest; -//import com.jd.blockchain.ledger.AccountHeader; -//import com.jd.blockchain.ledger.CryptoSetting; -//import com.jd.blockchain.ledger.MerkleProof; -//import com.jd.blockchain.storage.service.ExPolicyKVStorage; -//import com.jd.blockchain.storage.service.VersioningKVStorage; -//import com.jd.blockchain.utils.Bytes; -//import com.jd.blockchain.utils.Transactional; -// -//public class GenericAccountSet> implements AccountQuery, Transactional { -// -// private Class headerType; -// -// private MerkleAccountSet merkleAccountSet; -// -// public GenericAccountSet(Class headerType, CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage exStorage, -// VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) { -// this(headerType, null, cryptoSetting, keyPrefix, exStorage, verStorage, false, accessPolicy); -// } -// -// public GenericAccountSet(Class headerType, HashDigest rootHash, CryptoSetting cryptoSetting, String keyPrefix, -// ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly, -// AccountAccessPolicy accessPolicy) { -// this.headerType = headerType; -// this.merkleAccountSet = new MerkleAccountSet(rootHash, cryptoSetting, keyPrefix, exStorage, verStorage, readonly, accessPolicy); -// } -// -// @Override -// public MerkleProof getProof(Bytes address) { -// return merkleAccountSet.getProof(address); -// } -// -// @Override -// public HashDigest getRootHash() { -// return merkleAccountSet.getRootHash(); -// } -// -// @Override -// public boolean isUpdated() { -// return merkleAccountSet.isUpdated(); -// } -// -// @Override -// public void commit() { -// merkleAccountSet.commit(); -// } -// -// @Override -// public void cancel() { -// merkleAccountSet.cancel(); -// } -// -// @Override -// public H[] getHeaders(int fromIndex, int count) { -// merkleAccountSet.getHeaders(fromIndex, count) -// return null; -// } -// -// @Override -// public long getTotal() { -// // TODO Auto-generated method stub -// return 0; -// } -// -// @Override -// public boolean contains(Bytes address) { -// // TODO Auto-generated method stub -// return false; -// } -// -// @Override -// public T getAccount(String address) { -// // TODO Auto-generated method stub -// return null; -// } -// -// @Override -// public T getAccount(Bytes address) { -// // TODO Auto-generated method stub -// return null; -// } -// -// @Override -// public T getAccount(Bytes address, long version) { -// // TODO Auto-generated method stub -// return null; -// } -// -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericDataEntry.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericDataEntry.java deleted file mode 100644 index 3e73d582..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericDataEntry.java +++ /dev/null @@ -1,11 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//public interface GenericDataEntry { -// -// String getKey(); -// -// long getVersion(); -// -// T getValue(); -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericMerkleDataEntry.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericMerkleDataEntry.java deleted file mode 100644 index 8a8c5635..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericMerkleDataEntry.java +++ /dev/null @@ -1,9 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//public interface GenericMerkleDataEntry { -// -// GenericDataEntry getData(); -// -// MerkleProof getProof(); -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericMerkleDataSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericMerkleDataSet.java deleted file mode 100644 index 31df6427..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenericMerkleDataSet.java +++ /dev/null @@ -1,259 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.binaryproto.BinaryEncodingUtils; -//import com.jd.blockchain.crypto.hash.HashDigest; -// -//import my.utils.Transactional; -//import my.utils.io.ByteArray; -//import my.utils.io.ExistentialKVStorage; -//import my.utils.io.VersioningKVEntry; -//import my.utils.io.VersioningKVStorage; -// -///** -// * @author huanghaiquan -// * -// * @param -// * @param -// */ -//public class GenericMerkleDataSet implements Transactional { -// -// /** -// * 数据契约的接口类型; -// */ -// private Class dataContractClazz; -// -// /** -// * 数据契约的实现类型; -// */ -// private Class dataClazz; -// -// private MerkleDataSet merkleDataSet; -// -// private Class[] extImplClazzes; -// -// /** -// * 创建一个新的 Merkle 数据集; -// * -// * @param defaultMerkleHashAlgorithm -// * @param verifyMerkleHashOnLoad -// * @param merkleTreeStorage -// * @param dataStorage -// * @param dataContractClazz -// * @param dataClazz -// * @param extImplClazzes -// */ -// public GenericMerkleDataSet(CryptoSetting merkleTreeSetting, ExistentialKVStorage merkleTreeStorage, -// VersioningKVStorage dataStorage, Class dataContractClazz, Class dataClazz, -// Class... extImplClazzes) { -// if (!dataContractClazz.isAssignableFrom(dataClazz)) { -// throw new IllegalArgumentException(String.format( -// "The specified data class doesn't implement the specified data contract class! --[DataContractClass=%s][DataClass=%s]", -// dataContractClazz.getName(), dataClazz.getName())); -// } -// this.merkleDataSet = new MerkleDataSet(merkleTreeSetting, merkleTreeStorage, dataStorage); -// this.dataContractClazz = dataContractClazz; -// this.dataClazz = dataClazz; -// this.extImplClazzes = extImplClazzes; -// } -// -// /** -// * 从指定的 Merkle 根创建 Merkle 数据集; -// * -// * @param defaultMerkleHashAlgorithm -// * @param verifyMerkleHashOnLoad -// * @param merkleTreeStorage -// * @param dataStorage -// * @param dataContractClazz -// * @param dataClazz -// * @param extImplClazzes -// */ -// public GenericMerkleDataSet(HashDigest merkleRootHash, CryptoSetting merkleTreeSetting, -// ExistentialKVStorage merkleTreeStorage, VersioningKVStorage dataStorage, boolean readonly, Class dataContractClazz, -// Class dataClazz, Class... extImplClazzes) { -// if (!dataContractClazz.isAssignableFrom(dataClazz)) { -// throw new IllegalArgumentException(String.format( -// "The specified data class doesn't implement the specified data contract class! --[DataContractClass=%s][DataClass=%s]", -// dataContractClazz.getName(), dataClazz.getName())); -// } -// this.merkleDataSet = new MerkleDataSet(merkleRootHash, merkleTreeSetting, merkleTreeStorage, dataStorage, readonly); -// this.dataContractClazz = dataContractClazz; -// this.dataClazz = dataClazz; -// this.extImplClazzes = extImplClazzes; -// } -// -// /** -// * @return -// */ -// public HashDigest getRootHash() { -// return merkleDataSet.getRootHash(); -// } -// -// /** -// * Get the merkle proof of the specified key;
-// * -// * The proof doesn't represent the latest changes until do -// * committing({@link #commit()}). -// * -// * @param key -// * @return Return the {@link MerkleProof} instance, or null if the key doesn't -// * exist. -// */ -// public MerkleProof getProof(String key) { -// return merkleDataSet.getProof(key); -// } -// -// /** -// * Create or update the value associated the specified key if the version -// * checking is passed.
-// * -// * The value of the key will be updated only if it's latest version equals the -// * specified version argument.
-// * If the key doesn't exist, the version checking will be ignored, and key will -// * be created with a new sequence number as id.
-// * It also could specify the version argument to -1 to ignore the version -// * checking. -// *

-// * If updating is performed, the version of the key increase by 1.
-// * If creating is performed, the version of the key initialize by 0.
-// * -// * @param key -// * The key of data; -// * @param value -// * The value of data; -// * @param version -// * The expected version of the key. -// */ -// public long setValue(String key, T value, long version) { -// byte[] bytesValue = BinaryEncodingUtils.encode(value, dataContractClazz); -// return merkleDataSet.setValue(key, bytesValue, version); -// } -// -// /** -// * -// * @param key -// * @param version -// */ -// public T getValue(String key, long version) { -// byte[] bytesValue = merkleDataSet.getValue(key, version); -// return decode(bytesValue); -// } -// -// /** -// * -// * @param version -// * @param key -// */ -// public T getValue(String key) { -// byte[] bytesValue = merkleDataSet.getValue(key); -// return decode(bytesValue); -// } -// -// public GenericDataEntry getDataEntry(String key) { -// VersioningKVEntry entry = merkleDataSet.getDataEntry(key); -// T value = decode(entry.getValue()); -// return new GenericDataEntryWrapper<>(entry, value); -// } -// -// public GenericDataEntry getDataEntry(String key, long version) { -// VersioningKVEntry entry = merkleDataSet.getDataEntry(key, version); -// T value = decode(entry.getValue()); -// return new GenericDataEntryWrapper<>(entry, value); -// } -// -// public GenericMerkleDataEntry getMerkleEntry(String key, long version) { -// GenericDataEntry data = getDataEntry(key, version); -// MerkleProof proof = merkleDataSet.getProof(key); -// return new GenericMerkleDataEntryWrapperr(data, proof); -// } -// -// public GenericMerkleDataEntry getMerkleEntry(String key) { -// GenericDataEntry data = getDataEntry(key); -// MerkleProof proof = merkleDataSet.getProof(key); -// return new GenericMerkleDataEntryWrapperr(data, proof); -// } -// -// @Override -// public boolean isUpdated() { -// return merkleDataSet.isUpdated(); -// } -// -// @Override -// public void commit() { -// merkleDataSet.commit(); -// } -// -// @Override -// public void cancel() { -// merkleDataSet.cancel(); -// } -// -// private T decode(byte[] bytesValue) { -// return BinaryEncodingUtils.decode(bytesValue, null, dataClazz); -// } -// -// /** -// * @author huanghaiquan -// * -// * @param -// * @param -// */ -// private static class GenericDataEntryWrapper implements GenericDataEntry { -// -// private String key; -// -// private long version; -// -// private T value; -// -// public GenericDataEntryWrapper(VersioningKVEntry binaryEntry, T value) { -// this.key = binaryEntry.getKey(); -// this.version = binaryEntry.getVersion(); -// this.value = value; -// } -// -// @Override -// public String getKey() { -// return key; -// } -// -// @Override -// public long getVersion() { -// return version; -// } -// -// @Override -// public T getValue() { -// return value; -// } -// -// } -// -// /** -// * @author huanghaiquan -// * -// * @param -// */ -// private static class GenericMerkleDataEntryWrapperr implements GenericMerkleDataEntry { -// -// private GenericDataEntry data; -// -// private MerkleProof proof; -// -// public GenericMerkleDataEntryWrapperr(GenericDataEntry data, MerkleProof proof) { -// this.data = data; -// this.proof = proof; -// } -// -// @Override -// public GenericDataEntry getData() { -// return data; -// } -// -// @Override -// public MerkleProof getProof() { -// return proof; -// } -// -// } -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenesisLedgerStorageProxy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenesisLedgerStorageProxy.java deleted file mode 100644 index c93e1fed..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenesisLedgerStorageProxy.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jd.blockchain.ledger.core; -//package com.jd.blockchain.ledger.core.impl; -// -//import com.jd.blockchain.storage.service.ExPolicyKVStorage; -//import com.jd.blockchain.storage.service.VersioningKVEntry; -//import com.jd.blockchain.storage.service.VersioningKVStorage; -//import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy; -// -///** -// * 账本存储代理;
-// * -// * @author huanghaiquan -// * -// */ -//class GenesisLedgerStorageProxy implements VersioningKVStorage, ExPolicyKVStorage { -// -// private VersioningKVStorage versioningStorage; -// -// private ExPolicyKVStorage exPolicyStorage; -// -// @Override -// public long getVersion(String key) { -// // Storage of genesis ledger is totally empty; -// return -1; -// } -// -// @Override -// public VersioningKVEntry getEntry(String key, long version) { -// return null; -// } -// -// @Override -// public byte[] get(String key, long version) { -// return null; -// } -// -// @Override -// public long set(String key, byte[] value, long version) { -// if (versioningStorage == null) { -// throw new IllegalStateException("The persistent storage of ledger is not ready!"); -// } -// return versioningStorage.set(key, value, version); -// } -// -// @Override -// public byte[] get(String key) { -// // Storage of genesis ledger is totally empty; -// return null; -// } -// -// @Override -// public boolean exist(String key) { -// return false; -// } -// -// @Override -// public boolean set(String key, byte[] value, ExPolicy ex) { -// if (exPolicyStorage == null) { -// throw new IllegalStateException("The persistent storage of ledger is not ready!"); -// } -// return exPolicyStorage.set(key, value, ex); -// } -// -// public void setPersistentStorage(ExPolicyKVStorage exPolicyStorage, VersioningKVStorage persistentStorage) { -// this.exPolicyStorage = exPolicyStorage; -// this.versioningStorage = persistentStorage; -// } -//} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/HashDigestList.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/HashDigestList.java deleted file mode 100644 index e2a74de7..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/HashDigestList.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.ArrayList; -import java.util.List; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.HashProof; - -/** - * - * @author huanghaiquan - * - */ -public class HashDigestList implements HashProof { - - private List proofs = new ArrayList(); - - public HashDigestList() { - } - - public HashDigestList(HashProof proof) { - concat(proof); - } - - public void concat(HashProof proof) { - int levels = proof.getLevels(); - for (int i = levels; i > -1; i--) { - proofs.add(proof.getHash(i)); - } - } - - @Override - public int getLevels() { - return proofs.size(); - } - - @Override - public HashDigest getHash(int level) { - return proofs.get(level); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/HashProvable.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/HashProvable.java deleted file mode 100644 index 88da19ae..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/HashProvable.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.HashProof; -import com.jd.blockchain.utils.Bytes; - -public interface HashProvable { - - HashProof getProof(Bytes key); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataQuery.java deleted file mode 100644 index 623a47b1..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataQuery.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.LedgerAdminSettings; -import com.jd.blockchain.ledger.ParticipantDataQuery; - -public interface LedgerAdminDataQuery { - - LedgerAdminSettings getAdminInfo(); - - ParticipantDataQuery getParticipantDataset(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminInfoData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminInfoData.java deleted file mode 100644 index a0a74190..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminInfoData.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.*; - -/** - * @author shaozhuguang - * @date 2019-09-16 - * - * LedgerAdminInfo的独立实现类,主要用于页面展示,区分 {@link LedgerAdminDataset} - */ -public class LedgerAdminInfoData implements LedgerAdminInfo { - - /** - * 元数据 - */ - private LedgerMetadata_V2 metadata; - - /** - * 账本配置 - * - */ - private LedgerSettings ledgerSettings; - - /** - * 参与方数量 - * - */ - private long participantCount; - - /** - * 参与方 - * - */ - private ParticipantNode[] participantNodes; - - /** - * 包装构造方法 - * - * @param ledgerAdminInfo - */ - public LedgerAdminInfoData(LedgerAdminInfo ledgerAdminInfo) { - this(ledgerAdminInfo.getMetadata(), ledgerAdminInfo.getSettings(), - ledgerAdminInfo.getParticipantCount(), ledgerAdminInfo.getParticipants()); - } - - public LedgerAdminInfoData(LedgerMetadata_V2 metadata, LedgerSettings ledgerSettings, long participantCount, ParticipantNode[] participantNodes) { - this.metadata = metadata; - this.ledgerSettings = ledgerSettings; - this.participantCount = participantCount; - this.participantNodes = participantNodes; - } - - /** - * 返回元数据配置信息 - * - * @return - */ - @Override - public LedgerMetadata_V2 getMetadata() { - return this.metadata; - } - - /** - * 返回当前设置的账本配置; - * - * @return - */ - @Override - public LedgerSettings getSettings() { - return this.ledgerSettings; - } - - /** - * 返回当前参与方的数量 - * - * @return - */ - @Override - public long getParticipantCount() { - return this.participantCount; - } - - /** - * 返回当前参与方列表 - * - * @return - */ - @Override - public ParticipantNode[] getParticipants() { - return this.participantNodes; - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerBlockData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerBlockData.java deleted file mode 100644 index 3c667ebe..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerBlockData.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerBlock; - -public class LedgerBlockData implements LedgerBlock { - - static { - DataContractRegistry.register(LedgerBlock.class); - } - - private HashDigest hash; - - private long height; - - private HashDigest ledgerHash; - - private HashDigest previousHash; - - private HashDigest adminAccountHash; - - private HashDigest userAccountSetHash; - - // private HashDigest userPrivilegeHash; - - private HashDigest dataAccountSetHash; - - // private HashDigest dataPrivilegeHash; - - private HashDigest contractAccountSetHash; - - // private HashDigest contractPrivilegeHash; - - private HashDigest transactionSetHash; - - private long timestamp; - - public LedgerBlockData() { - } - - public LedgerBlockData(LedgerBlock block) { - this.hash = block.getHash(); - this.height = block.getHeight(); - this.ledgerHash = block.getLedgerHash(); - this.previousHash = block.getPreviousHash(); - this.adminAccountHash = block.getAdminAccountHash(); - this.userAccountSetHash = block.getUserAccountSetHash(); - this.dataAccountSetHash = block.getDataAccountSetHash(); - this.contractAccountSetHash = block.getContractAccountSetHash(); - this.transactionSetHash = block.getTransactionSetHash(); - } - - public void setAdminAccountHash(HashDigest adminAccountHash) { - this.adminAccountHash = adminAccountHash; - } - - public void setUserAccountSetHash(HashDigest userAccountSetHash) { - this.userAccountSetHash = userAccountSetHash; - } - - // public void setUserPrivilegeHash(HashDigest userPrivilegeHash) { - // this.userPrivilegeHash = userPrivilegeHash; - // } - - public void setDataAccountSetHash(HashDigest dataAccountSetHash) { - this.dataAccountSetHash = dataAccountSetHash; - } - - // public void setDataPrivilegeHash(HashDigest dataPrivilegeHash) { - // this.dataPrivilegeHash = dataPrivilegeHash; - // } - - public void setContractAccountSetHash(HashDigest contractAccountSetHash) { - this.contractAccountSetHash = contractAccountSetHash; - } - - // public void setContractPrivilegeHash(HashDigest contractPrivilegeHash) { - // this.contractPrivilegeHash = contractPrivilegeHash; - // } - - public void setTransactionSetHash(HashDigest transactionSetHash) { - this.transactionSetHash = transactionSetHash; - } - - public LedgerBlockData(long height, HashDigest ledgerHash, HashDigest previousHash) { - this.height = height; - this.ledgerHash = ledgerHash; - this.previousHash = previousHash; - } - - @Override - public HashDigest getHash() { - return hash; - } - - @Override - public HashDigest getPreviousHash() { - return previousHash; - } - - @Override - public HashDigest getLedgerHash() { - return ledgerHash; - } - - @Override - public long getHeight() { - return height; - } - - @Override - public HashDigest getAdminAccountHash() { - return adminAccountHash; - } - - @Override - public HashDigest getUserAccountSetHash() { - return userAccountSetHash; - } - - // @Override - // public HashDigest getUserPrivilegeHash() { - // return userPrivilegeHash; - // } - - @Override - public HashDigest getDataAccountSetHash() { - return dataAccountSetHash; - } - - // @Override - // public HashDigest getDataPrivilegeHash() { - // return dataPrivilegeHash; - // } - - @Override - public HashDigest getContractAccountSetHash() { - return contractAccountSetHash; - } - - // @Override - // public HashDigest getContractPrivilegeHash() { - // return contractPrivilegeHash; - // } - - @Override - public HashDigest getTransactionSetHash() { - return transactionSetHash; - } - - public void setHash(HashDigest blockHash) { - this.hash = blockHash; - } - - public void setLedgerHash(HashDigest ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConfiguration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConfiguration.java deleted file mode 100644 index e727c5ad..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConfiguration.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerSettings; -import com.jd.blockchain.utils.Bytes; - -public class LedgerConfiguration implements LedgerSettings { - - private String consensusProvider; - - private Bytes consensusSetting; - - private CryptoConfig cryptoSetting; - - public LedgerConfiguration() { - this.cryptoSetting = new CryptoConfig(); - } - - public LedgerConfiguration(LedgerSettings origSetting) { - if (origSetting != null) { - this.consensusProvider = origSetting.getConsensusProvider(); - this.consensusSetting = origSetting.getConsensusSetting(); - this.cryptoSetting = new CryptoConfig(origSetting.getCryptoSetting()); - } else { - this.cryptoSetting = new CryptoConfig(); - } - } - - public LedgerConfiguration(String consensusProvider, Bytes consensusSetting, CryptoSetting cryptoSetting) { - this.consensusProvider = consensusProvider; - this.consensusSetting = consensusSetting; - this.cryptoSetting = new CryptoConfig(cryptoSetting); - } - - @Override - public Bytes getConsensusSetting() { - return consensusSetting; - } - - public void setConsensusSetting(Bytes consensusSetting) { - this.consensusSetting = consensusSetting; - } - - @Override - public CryptoConfig getCryptoSetting() { - return cryptoSetting; - } - - @Override - public String getConsensusProvider() { - return consensusProvider; - } - - public void setConsensusProvider(String consensusProvider) { - this.consensusProvider = consensusProvider; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConsts.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConsts.java deleted file mode 100644 index 8ba67ede..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConsts.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public class LedgerConsts { - - public static final String CHARSET= "UTF-8"; - - public static final String KEY_SEPERATOR = "/"; - - public static final int MAX_LIST_COUNT = 1000; - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataQuery.java deleted file mode 100644 index df70d0c0..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataQuery.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jd.blockchain.ledger.core; - -/** - * {@link LedgerDataset} 表示账本在某一个区块上的数据集合; - * - * @author huanghaiquan - * - */ -public interface LedgerDataQuery{ - - LedgerAdminDataQuery getAdminDataset(); - - UserAccountQuery getUserAccountSet(); - - DataAccountQuery getDataAccountSet(); - - ContractAccountQuery getContractAccountset(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataset.java deleted file mode 100644 index 9f840d35..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataset.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.utils.Transactional; - -public class LedgerDataset implements LedgerDataQuery, Transactional { - - private LedgerAdminDataset adminDataset; - - private UserAccountSet userAccountSet; - - private DataAccountSet dataAccountSet; - - private ContractAccountSet contractAccountSet; - - private boolean readonly; - - /** - * Create new block; - * - * @param adminAccount - * @param userAccountSet - * @param dataAccountSet - * @param contractAccountSet - * @param readonly - */ - public LedgerDataset(LedgerAdminDataset adminAccount, UserAccountSet userAccountSet, - DataAccountSet dataAccountSet, ContractAccountSet contractAccountSet, boolean readonly) { - this.adminDataset = adminAccount; - this.userAccountSet = userAccountSet; - this.dataAccountSet = dataAccountSet; - this.contractAccountSet = contractAccountSet; - - this.readonly = readonly; - } - - @Override - public LedgerAdminDataset getAdminDataset() { - return adminDataset; - } - - @Override - public UserAccountSet getUserAccountSet() { - return userAccountSet; - } - - @Override - public DataAccountSet getDataAccountSet() { - return dataAccountSet; - } - - @Override - public ContractAccountSet getContractAccountset() { - return contractAccountSet; - } - - @Override - public boolean isUpdated() { - return adminDataset.isUpdated() || userAccountSet.isUpdated() || dataAccountSet.isUpdated() - || contractAccountSet.isUpdated(); - } - - @Override - public void commit() { - if (readonly) { - throw new IllegalStateException("Readonly ledger dataset which cann't been committed!"); - } - if (!isUpdated()) { - return; - } - - adminDataset.commit(); - userAccountSet.commit(); - dataAccountSet.commit(); - contractAccountSet.commit(); - } - - @Override - public void cancel() { - adminDataset.cancel(); - userAccountSet.cancel(); - dataAccountSet.cancel(); - contractAccountSet.cancel(); - } - - public boolean isReadonly() { - return readonly; - } - - void setReadonly() { - this.readonly = true; - this.adminDataset.setReadonly(); - this.userAccountSet.setReadonly(); - this.dataAccountSet.setReadonly(); - this.contractAccountSet.setReadonly(); - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerEditor.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerEditor.java deleted file mode 100644 index 466dd30a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerEditor.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.TransactionRequest; - -/** - * {@link LedgerEditor} 定义了对账本的编辑视图; - *

- * - * {@link LedgerEditor} 以上一个区块作为数据编辑的起点;
- * 对账本数据({@link #getDataset()})的批量更改可以作为一个交易({@link LedgerTransaction})整体提交暂存,形成暂存点; - *
- * - * @author huanghaiquan - * - */ -public interface LedgerEditor { - - /** - * 账本Hash; - * - * @return - */ - HashDigest getLedgerHash(); - - /** - * 新区块的高度; - * - * @return - */ - long getBlockHeight(); - - /** - * 最新的账本数据集; - * - * @return - */ - LedgerDataset getLedgerDataset(); - - /** - * 最新的交易集合; - * - * @return - */ - TransactionSet getTransactionSet(); - - /** - * 开始新事务;
- * - * 方法返回之前,将会校验交易请求的用户签名列表和节点签名列表,并在后续对数据集 - * {@link LedgerTransactionContext#getDataset()} 的操作时,校验这些用户和节点是否具备权限;
- * - * 校验失败将引发异常 {@link LedgerException}; - *

- * - * 调用者通过获得的 {@link LedgerTransactionContext} 对象对账本进行操作,这些写入操作可以一起提交(通过方法 - * {@link LedgerTransactionContext#commit(com.jd.blockchain.ledger.ExecutionState)}),
- * 或者全部回滚(通过方法 {@link LedgerTransactionContext#rollback()}),以此实现原子性写入; - *

- * - * 每一次事务性的账本写入操作在提交后,都会记录该事务相关的系统全局快照,以交易对象 {@link LedgerTransaction} 进行保存; - *

- * - * - * - * 注:方法不解析、不执行交易中的操作; - *

- * - * @param txRequest 交易请求; - * @return - */ - LedgerTransactionContext newTransaction(TransactionRequest txRequest); - - /** - * 暂存当前的数据变更,并预提交生成新区块; - * - * @param txRequest - * @param result - * @return - */ - LedgerBlock prepare(); - - /** - * 提交数据; - */ - void commit(); - - /** - * 丢弃所有数据变更以及暂存的交易; - */ - void cancel(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitDecision.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitDecision.java deleted file mode 100644 index 4810d601..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitDecision.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.SignatureDigest; - -/** - * 账本初始化决定; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA_INIT_DECISION) -public interface LedgerInitDecision { - - /** - * 做出许可的参与方 ID; - * - * @return - */ - @DataField(order=1, primitiveType=PrimitiveType.INT32) - int getParticipantId(); - - /** - * 新建账本的哈希; - * @return - */ - @DataField(order=2, primitiveType = PrimitiveType.BYTES) - HashDigest getLedgerHash(); - - /** - * 参数方的签名; - * - *
- * - * 这是对“参与方ID({@link #getParticipantId()})”+“新账本的哈希({@link #getLedgerHash()})”做出的签名; - * - * @return - */ - @DataField(order=3, primitiveType = PrimitiveType.BYTES) - SignatureDigest getSignature(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposal.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposal.java deleted file mode 100644 index 2baaacbd..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposal.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.ledger.LedgerInitOperation; - -/** - * 账本初始化许可; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA_INIT_PROPOSAL) -public interface LedgerInitProposal { - - /** - * 做出许可的参与方 ID; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.INT32) - int getParticipantId(); - - /** - * 参数方对初始化交易的签名; - * - *

- * - * 初始化交易即账本的第一个交易,需要满足如下规则:
- * 1、不指定账本 hash;
- * 2、交易的第一个操作是({@link LedgerInitOperation}) ;
- * 3、后续的操作是按照参与者列表({@link LedgerInitOperation#getInitSetting()})的顺序依次注册相应的初始用户的操作; - * - *

- * 此签名将作为交易的节点签名,按照参与者列表的顺序加入到初始化交易的节点签名列表; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - SignatureDigest getTransactionSignature(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposalData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposalData.java deleted file mode 100644 index 4fa95cb7..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposalData.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.SignatureDigest; - -public class LedgerInitProposalData implements LedgerInitProposal { - - private int participantId; - - private SignatureDigest transactionSignature; - - /** - * a private contructor for deserialize; - */ - @SuppressWarnings("unused") - private LedgerInitProposalData() { - } - - public LedgerInitProposalData(int participantId, SignatureDigest initTxSignature) { - this.participantId = participantId; - this.transactionSignature = initTxSignature; - } - - @Override - public int getParticipantId() { - return participantId; - } - - @Override - public SignatureDigest getTransactionSignature() { - return transactionSignature; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitializer.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitializer.java deleted file mode 100644 index c8c04712..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitializer.java +++ /dev/null @@ -1,316 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainIdentityData; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.LedgerAdminSettings; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitException; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.RoleInitSettings; -import com.jd.blockchain.ledger.RolesConfigureOperation; -import com.jd.blockchain.ledger.SecurityInitSettings; -import com.jd.blockchain.ledger.TransactionBuilder; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.UserAuthInitSettings; -import com.jd.blockchain.ledger.UserAuthorizeOperation; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.service.TransactionBatchResultHandle; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.transaction.SignatureUtils; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.transaction.TxRequestBuilder; - -public class LedgerInitializer { - - private static final FullPermissionedSecurityManager FULL_PERMISSION_SECURITY_MANAGER = new FullPermissionedSecurityManager(); - - private static final LedgerQuery EMPTY_LEDGER =new EmptyLedgerQuery(); - - private static final LedgerDataQuery EMPTY_LEDGER_DATA_QUERY = new EmptyLedgerDataset(); - - private static final OperationHandleRegisteration DEFAULT_OP_HANDLE_REG = new DefaultOperationHandleRegisteration(); - -// private LedgerService EMPTY_LEDGERS = new LedgerManager(); - - private LedgerInitSetting initSetting; - - private TransactionContent initTxContent; - - private volatile LedgerBlock genesisBlock; - - private volatile LedgerEditor ledgerEditor; - - private volatile boolean committed = false; - - private volatile boolean canceled = false; - - private TransactionBatchResultHandle txResultsHandle; - - /** - * 初始化生成的账本hash;
- * - * 在成功执行 {@link #prepareLedger(KVStorageService, DigitalSignature...)} 之前总是返回 - * null; - * - * @return - */ - public HashDigest getLedgerHash() { - return genesisBlock == null ? null : genesisBlock.getHash(); - } - - /** - * @param initSetting - * @param initTxContent - */ - private LedgerInitializer(LedgerInitSetting initSetting, TransactionContent initTxContent) { - this.initSetting = initSetting; - this.initTxContent = initTxContent; - } - - public TransactionContent getTransactionContent() { - return initTxContent; - } - - public static LedgerInitializer create(LedgerInitSetting initSetting, SecurityInitSettings securityInitSettings) { - // 生成创世交易; - TransactionContent initTxContent = buildGenesisTransaction(initSetting, securityInitSettings); - - return new LedgerInitializer(initSetting, initTxContent); - } - - /** - * 根据初始化配置,生成创始交易; - *

- * - * “创世交易”按顺序由以下操作组成:
- * (1) 账本初始化 {@link LedgerInitOperation}:此操作仅用于锚定了原始的交易配置,对应的 - * {@link OperationHandle} 执行空操作,由“创世交易”其余的操作来表达对账本的实际修改;
- * (2) 注册用户 {@link UserRegisterOperation}:有一项或者多项;
- * (3) 配置角色 {@link RolesConfigureOperation}:有一项或者多项;
- * (4) 授权用户 {@link UserAuthorizeOperation}:有一项或者多项;
- * - * @param initSetting - * @param securityInitSettings - * @return - */ - public static TransactionContent buildGenesisTransaction(LedgerInitSetting initSetting, - SecurityInitSettings securityInitSettings) { - // 账本初始化交易的账本 hash 为 null; - TransactionBuilder initTxBuilder = new TxBuilder(null); - - // 定义账本初始化操作; - initTxBuilder.ledgers().create(initSetting); - - // TODO: 注册参与方; 目前由 LedgerInitSetting 定义,在 LedgerAdminDataset 中解释执行; - - //  注册用户; - for (ParticipantNode p : initSetting.getConsensusParticipants()) { - // TODO:暂时只支持注册用户的初始化操作; - BlockchainIdentity superUserId = new BlockchainIdentityData(p.getPubKey()); - initTxBuilder.users().register(superUserId); - } - - // 配置角色; - for (RoleInitSettings roleSettings : securityInitSettings.getRoles()) { - initTxBuilder.security().roles().configure(roleSettings.getRoleName()) - .enable(roleSettings.getLedgerPermissions()).enable(roleSettings.getTransactionPermissions()); - } - - // 授权用户; - for (UserAuthInitSettings userAuthSettings : securityInitSettings.getUserAuthorizations()) { - initTxBuilder.security().authorziations().forUser(userAuthSettings.getUserAddress()) - .authorize(userAuthSettings.getRoles()) - .setPolicy(userAuthSettings.getPolicy()); - } - - // 账本初始化配置声明的创建时间来初始化交易时间戳;注:不能用本地时间,因为共识节点之间的本地时间系统不一致; - return initTxBuilder.prepareContent(initSetting.getCreatedTime()); - } - - public SignatureDigest signTransaction(PrivKey privKey) { - return SignatureUtils.sign(initTxContent, privKey); - } - - public DigitalSignature signTransaction(BlockchainKeypair key) { - return SignatureUtils.sign(initTxContent, key); - } - - /** - * 准备创建账本; - * - * @param storageService 存储服务; - * @param nodeSignatures 节点签名列表; - * @return - */ - public LedgerBlock prepareLedger(KVStorageService storageService, DigitalSignature... nodeSignatures) { - if (genesisBlock != null) { - throw new LedgerInitException("The ledger has been prepared!"); - } - // 生成账本; - this.ledgerEditor = createLedgerEditor(this.initSetting, storageService); - this.genesisBlock = prepareLedger(ledgerEditor, nodeSignatures); - - return genesisBlock; - } - - public void commit() { - if (committed) { - throw new LedgerInitException("The ledger has been committed!"); - } - if (canceled) { - throw new LedgerInitException("The ledger has been canceled!"); - } - committed = true; - this.txResultsHandle.commit(); - } - - public void cancel() { - if (canceled) { - throw new LedgerInitException("The ledger has been canceled!"); - } - if (committed) { - throw new LedgerInitException("The ledger has been committed!"); - } - this.ledgerEditor.cancel(); - } - - public static LedgerEditor createLedgerEditor(LedgerInitSetting initSetting, KVStorageService storageService) { - LedgerEditor genesisBlockEditor = LedgerTransactionalEditor.createEditor(initSetting, - LedgerManage.LEDGER_PREFIX, storageService.getExPolicyKVStorage(), - storageService.getVersioningKVStorage()); - return genesisBlockEditor; - } - - /** - * 初始化账本数据,返回创始区块; - * - * @param ledgerEditor - * @return - */ - private LedgerBlock prepareLedger(LedgerEditor ledgerEditor, DigitalSignature... nodeSignatures) { - // 初始化时,自动将参与方注册为账本的用户; - TxRequestBuilder txReqBuilder = new TxRequestBuilder(this.initTxContent); - txReqBuilder.addNodeSignature(nodeSignatures); - - TransactionRequest txRequest = txReqBuilder.buildRequest(); - - TransactionBatchProcessor txProcessor = new TransactionBatchProcessor(FULL_PERMISSION_SECURITY_MANAGER, - ledgerEditor, EMPTY_LEDGER, DEFAULT_OP_HANDLE_REG); - - txProcessor.schedule(txRequest); - - txResultsHandle = txProcessor.prepare(); - return txResultsHandle.getBlock(); - } - - private static class EmptyLedgerQuery implements LedgerQuery{ - - private EmptyLedgerDataset dataset; - - @Override - public HashDigest getHash() { - return null; - } - - @Override - public long getLatestBlockHeight() { - return 0; - } - - @Override - public HashDigest getLatestBlockHash() { - return null; - } - - @Override - public LedgerBlock getLatestBlock() { - return null; - } - - @Override - public HashDigest getBlockHash(long height) { - return null; - } - - @Override - public LedgerBlock getBlock(long height) { - return null; - } - - @Override - public LedgerAdminInfo getAdminInfo() { - return null; - } - - @Override - public LedgerAdminInfo getAdminInfo(LedgerBlock block) { - return null; - } - - @Override - public LedgerAdminSettings getAdminSettings() { - return null; - } - - @Override - public LedgerAdminSettings getAdminSettings(LedgerBlock block) { - return null; - } - - @Override - public LedgerBlock getBlock(HashDigest hash) { - return null; - } - - @Override - public LedgerDataQuery getLedgerData(LedgerBlock block) { - return dataset; - } - - @Override - public TransactionQuery getTransactionSet(LedgerBlock block) { - return null; - } - - @Override - public UserAccountQuery getUserAccountSet(LedgerBlock block) { - return dataset.getUserAccountSet(); - } - - @Override - public DataAccountQuery getDataAccountSet(LedgerBlock block) { - return dataset.getDataAccountSet(); - } - - @Override - public ContractAccountQuery getContractAccountSet(LedgerBlock block) { - return dataset.getContractAccountset(); - } - - @Override - public LedgerBlock retrieveLatestBlock() { - return null; - } - - @Override - public long retrieveLatestBlockHeight() { - return 0; - } - - @Override - public HashDigest retrieveLatestBlockHash() { - return null; - } - - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManage.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManage.java deleted file mode 100644 index 69cafb95..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManage.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.storage.service.KVStorageService; - -/** - * 账本管理器; - * - * @author huanghaiquan - * - */ -public interface LedgerManage extends LedgerService { - - static final String LEDGER_PREFIX = "LDG://"; - - LedgerQuery register(HashDigest ledgerHash, KVStorageService storageService); - - void unregister(HashDigest ledgerHash); - -// /** -// * 创建新账本; -// * -// * @param initSetting -// * 初始化配置; -// * @param initPermissions -// * 参与者的初始化授权列表;与参与者列表一致; -// * @return -// */ -// LedgerEditor newLedger(LedgerInitSetting initSetting, KVStorageService storageService); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManager.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManager.java deleted file mode 100644 index 715c68f3..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManager.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.HashMap; -import java.util.Map; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.codec.Base58Utils; - -/** - * 账本管理器; - * - * @author huanghaiquan - * - */ -public class LedgerManager implements LedgerManage { - - private Map ledgers = new HashMap<>(); - - @Override - public HashDigest[] getLedgerHashs() { - return ledgers.keySet().toArray(new HashDigest[ledgers.size()]); - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.LedgerManager#getLedger(com.jd.blockchain. - * crypto.hash.HashDigest) - */ - @Override - public LedgerRepository getLedger(HashDigest ledgerHash) { - LedgerRepositoryContext ledgerCtx = ledgers.get(ledgerHash); - if (ledgerCtx == null) { - return null; - } - - return ledgerCtx.ledgerRepo; - } - - @Override - public LedgerRepository register(HashDigest ledgerHash, KVStorageService storageService) { - // 加载账本数据库; - VersioningKVStorage ledgerVersioningStorage = storageService.getVersioningKVStorage(); - ExPolicyKVStorage ledgerExPolicyStorage = storageService.getExPolicyKVStorage(); - LedgerRepository ledgerRepo = new LedgerRepositoryImpl(ledgerHash, LEDGER_PREFIX, ledgerExPolicyStorage, - ledgerVersioningStorage); - - // 校验 crypto service provider ; - CryptoSetting cryptoSetting = ledgerRepo.getAdminInfo().getSettings().getCryptoSetting(); - checkCryptoSetting(cryptoSetting, ledgerHash); - - // 创建账本上下文; - LedgerRepositoryContext ledgerCtx = new LedgerRepositoryContext(ledgerRepo, storageService); - ledgers.put(ledgerHash, ledgerCtx); - return ledgerRepo; - } - - /** - * 检查账本的密码参数设置与本地节点的运行时环境是否匹配; - * - * @param cryptoSetting - * @param ledgerHash - */ - private void checkCryptoSetting(CryptoSetting cryptoSetting, HashDigest ledgerHash) { - CryptoProvider[] cryptoProviders = cryptoSetting.getSupportedProviders(); - if (cryptoProviders == null || cryptoProviders.length == 0) { - throw new LedgerException("No supported crypto service providers has been setted in the ledger[" - + ledgerHash.toBase58() + "]!"); - } - for (CryptoProvider cp : cryptoProviders) { - CryptoProvider regCp = Crypto.getProvider(cp.getName()); - checkCryptoProviderConsistency(regCp, cp); - } - } - - /** - * 检查密码服务提供者的信息是否匹配; - * - * @param registeredProvider - * @param settingProvider - */ - private void checkCryptoProviderConsistency(CryptoProvider registeredProvider, CryptoProvider settingProvider) { - if (registeredProvider == null) { - throw new LedgerException("Crypto service provider[" + settingProvider.getName() - + "] has not registered in the runtime environment of current peer!"); - } - - CryptoAlgorithm[] runtimeAlgothms = registeredProvider.getAlgorithms(); - CryptoAlgorithm[] settingAlgothms = settingProvider.getAlgorithms(); - if (runtimeAlgothms.length != settingAlgothms.length) { - throw new LedgerException("Crypto service provider[" + settingProvider.getName() - + "] has not registered in runtime of current peer!"); - } - HashMap runtimeAlgothmMap = new HashMap(); - for (CryptoAlgorithm alg : runtimeAlgothms) { - runtimeAlgothmMap.put(alg.code(), alg); - } - for (CryptoAlgorithm alg : settingAlgothms) { - CryptoAlgorithm regAlg = runtimeAlgothmMap.get(alg.code()); - if (regAlg == null) { - throw new LedgerException( - String.format("Crypto algorithm[%s] is not defined by provider[%s] in runtime of current peer!", - alg.toString(), registeredProvider.getName())); - } - if (!regAlg.name().equals(alg.name())) { - throw new LedgerException(String.format( - "Crypto algorithm[%s] do not match the same code algorithm[%s] defined by provider[%s] in runtime of current peer!", - CryptoAlgorithm.getString(alg), CryptoAlgorithm.getString(regAlg), - registeredProvider.getName())); - } - } - } - - @Override - public void unregister(HashDigest ledgerHash) { - LedgerRepositoryContext ledgerCtx = ledgers.remove(ledgerHash); - if (ledgerCtx != null) { - ledgerCtx.ledgerRepo.close(); - } - } - -// /* -// * (non-Javadoc) -// * -// * @see com.jd.blockchain.ledger.core.LedgerManager#newLedger(com.jd.blockchain. -// * ledger.core.ConsensusConfig, com.jd.blockchain.ledger.core.CryptoConfig) -// */ -// @Override -// public LedgerEditor newLedger(LedgerInitSetting initSetting, KVStorageService storageService) { -// LedgerEditor genesisBlockEditor = LedgerTransactionalEditor.createEditor(initSetting, LEDGER_PREFIX, -// storageService.getExPolicyKVStorage(), storageService.getVersioningKVStorage()); -// return genesisBlockEditor; -// } - - static String getLedgerStoragePrefix(HashDigest ledgerHash) { - String base58LedgerHash = Base58Utils.encode(ledgerHash.toBytes()); - return LEDGER_PREFIX + base58LedgerHash + LedgerConsts.KEY_SEPERATOR; - } - - - private static class LedgerRepositoryContext { - - public final LedgerRepository ledgerRepo; - - @SuppressWarnings("unused") - public final KVStorageService storageService; - - public LedgerRepositoryContext(LedgerRepository ledgerRepo, KVStorageService storageService) { - this.ledgerRepo = ledgerRepo; - this.storageService = storageService; - } - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerMetadata.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerMetadata.java deleted file mode 100644 index 68d51ae2..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerMetadata.java +++ /dev/null @@ -1,36 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.binaryproto.DataContract; -//import com.jd.blockchain.binaryproto.DataField; -//import com.jd.blockchain.binaryproto.PrimitiveType; -//import com.jd.blockchain.consts.DataCodes; -//import com.jd.blockchain.crypto.HashDigest; -// -//@DataContract(code = DataCodes.METADATA) -//public interface LedgerMetadata { -// -// /** -// * 账本的初始化种子; -// * -// * @return -// */ -// @DataField(order = 1, primitiveType = PrimitiveType.BYTES) -// byte[] getSeed(); -// -// /** -// * 共识参与方的默克尔树的根; -// * -// * @return -// */ -// @DataField(order = 2, primitiveType = PrimitiveType.BYTES) -// HashDigest getParticipantsHash(); -// -// /** -// * 账本配置; -// * -// * @return -// */ -// @DataField(order = 3, refContract = true) -// LedgerSetting getSetting(); -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerQuery.java deleted file mode 100644 index 75233ae5..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerQuery.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.LedgerAdminSettings; -import com.jd.blockchain.ledger.LedgerBlock; - -public interface LedgerQuery { - - /** - * 账本哈希,这是账本的唯一标识; - * - * @return - */ - HashDigest getHash(); - - /** - * 最新区块高度; - * - * @return - */ - long getLatestBlockHeight(); - - /** - * 最新区块哈希; - * - * @return - */ - HashDigest getLatestBlockHash(); - - /** - * 最新区块; - * - * @return - */ - LedgerBlock getLatestBlock(); - - /** - * 指定高度的区块哈希; - * - * @param height - * @return - */ - HashDigest getBlockHash(long height); - - /** - * 指定高度的区块; - * - * @param height - * @return - */ - LedgerBlock getBlock(long height); - - LedgerAdminInfo getAdminInfo(); - - LedgerAdminInfo getAdminInfo(LedgerBlock block); - - LedgerAdminSettings getAdminSettings(); - - LedgerAdminSettings getAdminSettings(LedgerBlock block); - - LedgerBlock getBlock(HashDigest hash); - - /** - * 返回指定 - * @param block - * @return - */ - LedgerDataQuery getLedgerData(LedgerBlock block); - - /** - * 返回最新区块对应的账本数据; - * - * @return - */ - default LedgerDataQuery getLedgerData() { - return getLedgerData(getLatestBlock()); - } - - TransactionQuery getTransactionSet(LedgerBlock block); - - UserAccountQuery getUserAccountSet(LedgerBlock block); - - DataAccountQuery getDataAccountSet(LedgerBlock block); - - ContractAccountQuery getContractAccountSet(LedgerBlock block); - - default TransactionQuery getTransactionSet() { - return getTransactionSet(getLatestBlock()); - } - - default UserAccountQuery getUserAccountSet() { - return getUserAccountSet(getLatestBlock()); - } - - default DataAccountQuery getDataAccountSet() { - return getDataAccountSet(getLatestBlock()); - } - - default ContractAccountQuery getContractAccountset() { - return getContractAccountSet(getLatestBlock()); - } - - /** - * 重新检索最新区块,同时更新缓存; - * - * @return - */ - LedgerBlock retrieveLatestBlock(); - - /** - * 重新检索最新区块,同时更新缓存; - * - * @return - */ - long retrieveLatestBlockHeight(); - - /** - * 重新检索最新区块哈希,同时更新缓存; - * - * @return - */ - HashDigest retrieveLatestBlockHash(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepository.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepository.java deleted file mode 100644 index e98ff376..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.io.Closeable; - -public interface LedgerRepository extends Closeable, LedgerQuery { - - - /** - * 创建新区块的编辑器; - * - * @return - */ - LedgerEditor createNextBlock(); - - /** - * 获取新区块的编辑器; - *

- * - * 如果未创建新的区块,或者新区块已经提交或取消,则返回 null; - * - * @return - */ - LedgerEditor getNextBlockEditor(); - - @Override - void close(); -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepositoryImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepositoryImpl.java deleted file mode 100644 index 49e7ebba..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepositoryImpl.java +++ /dev/null @@ -1,622 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.ledger.BlockBody; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.LedgerAdminSettings; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.LedgerSettings; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; - -/** - * 账本的存储结构:
- * - * 1、账本数据以版本化KV存储({@link VersioningKVStorage})为基础;
- * - * 2、以账本hash为 key,保存账本的每一个区块的hash,对应的版本序号恰好一致地表示了区块高度;
- * - * 3、区块数据以区块 hash 加上特定前缀({@link #BLOCK_PREFIX}) 构成 key - * 进行保存,每个区块只有唯一个版本,在存储时会进行版本唯一性校验;
- * - * @author huanghaiquan - * - */ -class LedgerRepositoryImpl implements LedgerRepository { - - private static final Bytes LEDGER_PREFIX = Bytes.fromString("IDX" + LedgerConsts.KEY_SEPERATOR); - - private static final Bytes BLOCK_PREFIX = Bytes.fromString("BLK" + LedgerConsts.KEY_SEPERATOR); - - private static final Bytes USER_SET_PREFIX = Bytes.fromString("USRS" + LedgerConsts.KEY_SEPERATOR); - - private static final Bytes DATA_SET_PREFIX = Bytes.fromString("DATS" + LedgerConsts.KEY_SEPERATOR); - - private static final Bytes CONTRACT_SET_PREFIX = Bytes.fromString("CTRS" + LedgerConsts.KEY_SEPERATOR); - - private static final Bytes TRANSACTION_SET_PREFIX = Bytes.fromString("TXS" + LedgerConsts.KEY_SEPERATOR); - - private static final AccountAccessPolicy DEFAULT_ACCESS_POLICY = new OpeningAccessPolicy(); - - private HashDigest ledgerHash; - - private final String keyPrefix; - - private Bytes ledgerIndexKey; - - private VersioningKVStorage versioningStorage; - - private ExPolicyKVStorage exPolicyStorage; - - private volatile LedgerState latestState; - - private volatile LedgerEditor nextBlockEditor; - - private volatile boolean closed = false; - - public LedgerRepositoryImpl(HashDigest ledgerHash, String keyPrefix, ExPolicyKVStorage exPolicyStorage, - VersioningKVStorage versioningStorage) { - this.keyPrefix = keyPrefix; - - this.ledgerHash = ledgerHash; - this.versioningStorage = versioningStorage; - this.exPolicyStorage = exPolicyStorage; - this.ledgerIndexKey = encodeLedgerIndexKey(ledgerHash); - - if (getLatestBlockHeight() < 0) { - throw new RuntimeException("Ledger doesn't exist!"); - } - - retrieveLatestState(); - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.LedgerRepository#getHash() - */ - @Override - public HashDigest getHash() { - return ledgerHash; - } - - @Override - public HashDigest getLatestBlockHash() { - if (latestState == null) { - return innerGetBlockHash(innerGetLatestBlockHeight()); - } - return latestState.block.getHash(); - } - - @Override - public long getLatestBlockHeight() { - if (latestState == null) { - return innerGetLatestBlockHeight(); - } - return latestState.block.getHeight(); - } - - @Override - public LedgerBlock getLatestBlock() { - return latestState.block; - } - - /** - * 重新检索加载最新的状态; - * - * @return - */ - private LedgerState retrieveLatestState() { - LedgerBlock latestBlock = innerGetBlock(innerGetLatestBlockHeight()); - LedgerDataset ledgerDataset = innerGetLedgerDataset(latestBlock); - TransactionQuery txSet = loadTransactionSet(latestBlock.getTransactionSetHash(), - ledgerDataset.getAdminDataset().getSettings().getCryptoSetting(), keyPrefix, exPolicyStorage, - versioningStorage, true); - this.latestState = new LedgerState(latestBlock, ledgerDataset, txSet); - return latestState; - } - - @Override - public LedgerBlock retrieveLatestBlock() { - return retrieveLatestState().block; - } - - @Override - public HashDigest retrieveLatestBlockHash() { - HashDigest latestBlockHash = innerGetBlockHash(innerGetLatestBlockHeight()); - if (latestState != null && !latestBlockHash.equals(latestState.block.getHash())) { - latestState = null; - } - return latestBlockHash; - } - - @Override - public long retrieveLatestBlockHeight() { - long latestBlockHeight = innerGetLatestBlockHeight(); - if (latestState != null && latestBlockHeight != latestState.block.getHeight()) { - latestState = null; - } - return latestBlockHeight; - } - - private long innerGetLatestBlockHeight() { - return versioningStorage.getVersion(ledgerIndexKey); - } - - @Override - public HashDigest getBlockHash(long height) { - LedgerBlock blk = latestState == null ? null : latestState.block; - if (blk != null && height == blk.getHeight()) { - return blk.getHash(); - } - return innerGetBlockHash(height); - } - - private HashDigest innerGetBlockHash(long height) { - if (height < 0) { - return null; - } - // get block hash by height; - byte[] hashBytes = versioningStorage.get(ledgerIndexKey, height); - if (hashBytes == null || hashBytes.length == 0) { - return null; - } - return new HashDigest(hashBytes); - } - - @Override - public LedgerBlock getBlock(long height) { - LedgerBlock blk = latestState == null ? null : latestState.block; - if (blk != null && height == blk.getHeight()) { - return blk; - } - return innerGetBlock(height); - } - - private LedgerBlock innerGetBlock(long height) { - if (height < 0) { - return null; - } - return innerGetBlock(innerGetBlockHash(height)); - } - - @Override - public LedgerBlock getBlock(HashDigest blockHash) { - LedgerBlock blk = latestState == null ? null : latestState.block; - if (blk != null && blockHash.equals(blk.getHash())) { - return blk; - } - return innerGetBlock(blockHash); - } - - private LedgerBlock innerGetBlock(HashDigest blockHash) { - Bytes key = encodeBlockStorageKey(blockHash); - // Every one block has only one version; - byte[] blockBytes = versioningStorage.get(key, 0); - LedgerBlockData block = new LedgerBlockData(deserialize(blockBytes)); - - if (!blockHash.equals(block.getHash())) { - throw new RuntimeException("Block hash not equals to it's storage key!"); - } - - // verify block hash; - byte[] blockBodyBytes = null; - if (block.getHeight() == 0) { - // 计算创世区块的 hash 时,不包括 ledgerHash 字段; - blockBodyBytes = BinaryProtocol.encode(block, BlockBody.class); - } else { - blockBodyBytes = BinaryProtocol.encode(block, BlockBody.class); - } - HashFunction hashFunc = Crypto.getHashFunction(blockHash.getAlgorithm()); - boolean pass = hashFunc.verify(blockHash, blockBodyBytes); - if (!pass) { - throw new RuntimeException("Block hash verification fail!"); - } - - // verify height; - HashDigest indexedHash = getBlockHash(block.getHeight()); - if (indexedHash == null || !indexedHash.equals(blockHash)) { - throw new RuntimeException( - "Illegal ledger state in storage that ledger height index doesn't match it's block data in height[" - + block.getHeight() + "] and block hash[" + Base58Utils.encode(blockHash.toBytes()) - + "] !"); - } - - return block; - } - - /** - * 获取最新区块的账本参数; - * - * @return - */ - private LedgerSettings getLatestSettings() { - return getAdminInfo().getSettings(); - } - - @Override - public LedgerAdminInfo getAdminInfo() { - return createAdminData(getLatestBlock()); - } - - private LedgerBlock deserialize(byte[] blockBytes) { - return BinaryProtocol.decode(blockBytes); - } - - @Override - public TransactionQuery getTransactionSet(LedgerBlock block) { - long height = getLatestBlockHeight(); - if (height == block.getHeight()) { - // 从缓存中返回最新区块的数据集; - return latestState.getTransactionSet(); - } - LedgerAdminInfo adminAccount = getAdminInfo(block); - // All of existing block is readonly; - return loadTransactionSet(block.getTransactionSetHash(), adminAccount.getSettings().getCryptoSetting(), - keyPrefix, exPolicyStorage, versioningStorage, true); - } - - @Override - public LedgerAdminInfo getAdminInfo(LedgerBlock block) { - return createAdminData(block); - } - - @Override - public LedgerAdminSettings getAdminSettings() { - return getAdminSettings(getLatestBlock()); - } - - @Override - public LedgerAdminSettings getAdminSettings(LedgerBlock block) { - long height = getLatestBlockHeight(); - if (height == block.getHeight()) { - return latestState.getAdminDataset(); - } - - return createAdminDataset(block); - } - - /** - * 生成LedgerAdminInfoData对象 - * 该对象主要用于页面展示 - * - * @param block - * @return - */ - private LedgerAdminInfoData createAdminData(LedgerBlock block) { - return new LedgerAdminInfoData(createAdminDataset(block)); - } - - /** - * 生成LedgerAdminDataset对象 - * - * @param block - * @return - */ - private LedgerAdminDataset createAdminDataset(LedgerBlock block) { - return new LedgerAdminDataset(block.getAdminAccountHash(), keyPrefix, exPolicyStorage, versioningStorage, true); - } - - @Override - public UserAccountQuery getUserAccountSet(LedgerBlock block) { - long height = getLatestBlockHeight(); - if (height == block.getHeight()) { - return latestState.getUserAccountSet(); - } - LedgerAdminSettings adminAccount = getAdminSettings(block); - return createUserAccountSet(block, adminAccount.getSettings().getCryptoSetting()); - } - - private UserAccountSet createUserAccountSet(LedgerBlock block, CryptoSetting cryptoSetting) { - return loadUserAccountSet(block.getUserAccountSetHash(), cryptoSetting, keyPrefix, exPolicyStorage, - versioningStorage, true); - } - - @Override - public DataAccountQuery getDataAccountSet(LedgerBlock block) { - long height = getLatestBlockHeight(); - if (height == block.getHeight()) { - return latestState.getDataAccountSet(); - } - - LedgerAdminSettings adminAccount = getAdminSettings(block); - return createDataAccountSet(block, adminAccount.getSettings().getCryptoSetting()); - } - - private DataAccountSet createDataAccountSet(LedgerBlock block, CryptoSetting setting) { - return loadDataAccountSet(block.getDataAccountSetHash(), setting, keyPrefix, exPolicyStorage, versioningStorage, - true); - } - - @Override - public ContractAccountQuery getContractAccountSet(LedgerBlock block) { - long height = getLatestBlockHeight(); - if (height == block.getHeight()) { - return latestState.getContractAccountSet(); - } - - LedgerAdminSettings adminAccount = getAdminSettings(block); - return createContractAccountSet(block, adminAccount.getSettings().getCryptoSetting()); - } - - private ContractAccountSet createContractAccountSet(LedgerBlock block, CryptoSetting cryptoSetting) { - return loadContractAccountSet(block.getContractAccountSetHash(), cryptoSetting, keyPrefix, exPolicyStorage, - versioningStorage, true); - } - - @Override - public LedgerDataset getLedgerData(LedgerBlock block) { - long height = getLatestBlockHeight(); - if (height == block.getHeight()) { - return latestState.getLedgerDataset(); - } - - // All of existing block is readonly; - return innerGetLedgerDataset(block); - } - - private LedgerDataset innerGetLedgerDataset(LedgerBlock block) { - LedgerAdminDataset adminDataset = createAdminDataset(block); - CryptoSetting cryptoSetting = adminDataset.getSettings().getCryptoSetting(); - - UserAccountSet userAccountSet = createUserAccountSet(block, cryptoSetting); - DataAccountSet dataAccountSet = createDataAccountSet(block, cryptoSetting); - ContractAccountSet contractAccountSet = createContractAccountSet(block, cryptoSetting); - return new LedgerDataset(adminDataset, userAccountSet, dataAccountSet, contractAccountSet, true); - } - - public synchronized void resetNextBlockEditor() { - this.nextBlockEditor = null; - } - - @Override - public synchronized LedgerEditor createNextBlock() { - if (closed) { - throw new RuntimeException("Ledger repository has been closed!"); - } - if (this.nextBlockEditor != null) { - throw new RuntimeException( - "A new block is in process, cann't create another one until it finish by committing or canceling."); - } - LedgerBlock previousBlock = getLatestBlock(); - LedgerTransactionalEditor editor = LedgerTransactionalEditor.createEditor(previousBlock, getLatestSettings(), - keyPrefix, exPolicyStorage, versioningStorage); - NewBlockCommittingMonitor committingMonitor = new NewBlockCommittingMonitor(editor, this); - this.nextBlockEditor = committingMonitor; - return committingMonitor; - } - - @Override - public LedgerEditor getNextBlockEditor() { - return nextBlockEditor; - } - - @Override - public synchronized void close() { - if (closed) { - return; - } - if (this.nextBlockEditor != null) { - throw new RuntimeException("A new block is in process, cann't close the ledger repository!"); - } - closed = true; - } - - static Bytes encodeLedgerIndexKey(HashDigest ledgerHash) { - return LEDGER_PREFIX.concat(ledgerHash); - } - - static Bytes encodeBlockStorageKey(HashDigest blockHash) { - return BLOCK_PREFIX.concat(blockHash); - } - - static LedgerDataset newDataSet(LedgerInitSetting initSetting, String keyPrefix, - ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage) { - LedgerAdminDataset adminAccount = new LedgerAdminDataset(initSetting, keyPrefix, ledgerExStorage, - ledgerVerStorage); - - String usersetKeyPrefix = keyPrefix + USER_SET_PREFIX; - String datasetKeyPrefix = keyPrefix + DATA_SET_PREFIX; - String contractsetKeyPrefix = keyPrefix + CONTRACT_SET_PREFIX; - - UserAccountSet userAccountSet = new UserAccountSet(adminAccount.getSettings().getCryptoSetting(), - usersetKeyPrefix, ledgerExStorage, ledgerVerStorage, DEFAULT_ACCESS_POLICY); - - DataAccountSet dataAccountSet = new DataAccountSet(adminAccount.getSettings().getCryptoSetting(), - datasetKeyPrefix, ledgerExStorage, ledgerVerStorage, DEFAULT_ACCESS_POLICY); - - ContractAccountSet contractAccountSet = new ContractAccountSet(adminAccount.getSettings().getCryptoSetting(), - contractsetKeyPrefix, ledgerExStorage, ledgerVerStorage, DEFAULT_ACCESS_POLICY); - - LedgerDataset newDataSet = new LedgerDataset(adminAccount, userAccountSet, dataAccountSet, - contractAccountSet, false); - - return newDataSet; - } - - static TransactionSet newTransactionSet(LedgerSettings ledgerSetting, String keyPrefix, - ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage) { - - String txsetKeyPrefix = keyPrefix + TRANSACTION_SET_PREFIX; - - TransactionSet transactionSet = new TransactionSet(ledgerSetting.getCryptoSetting(), txsetKeyPrefix, - ledgerExStorage, ledgerVerStorage); - return transactionSet; - } - - static LedgerDataset loadDataSet(LedgerDataSnapshot dataSnapshot, CryptoSetting cryptoSetting, String keyPrefix, - ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, boolean readonly) { - LedgerAdminDataset adminAccount = new LedgerAdminDataset(dataSnapshot.getAdminAccountHash(), keyPrefix, - ledgerExStorage, ledgerVerStorage, readonly); - - UserAccountSet userAccountSet = loadUserAccountSet(dataSnapshot.getUserAccountSetHash(), cryptoSetting, - keyPrefix, ledgerExStorage, ledgerVerStorage, readonly); - - DataAccountSet dataAccountSet = loadDataAccountSet(dataSnapshot.getDataAccountSetHash(), cryptoSetting, - keyPrefix, ledgerExStorage, ledgerVerStorage, readonly); - - ContractAccountSet contractAccountSet = loadContractAccountSet(dataSnapshot.getContractAccountSetHash(), - cryptoSetting, keyPrefix, ledgerExStorage, ledgerVerStorage, readonly); - - LedgerDataset dataset = new LedgerDataset(adminAccount, userAccountSet, dataAccountSet, - contractAccountSet, readonly); - - return dataset; - } - - static UserAccountSet loadUserAccountSet(HashDigest userAccountSetHash, CryptoSetting cryptoSetting, - String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, - boolean readonly) { - - String usersetKeyPrefix = keyPrefix + USER_SET_PREFIX; - return new UserAccountSet(userAccountSetHash, cryptoSetting, usersetKeyPrefix, ledgerExStorage, - ledgerVerStorage, readonly, DEFAULT_ACCESS_POLICY); - } - - static DataAccountSet loadDataAccountSet(HashDigest dataAccountSetHash, CryptoSetting cryptoSetting, - String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, - boolean readonly) { - - String datasetKeyPrefix = keyPrefix + DATA_SET_PREFIX; - return new DataAccountSet(dataAccountSetHash, cryptoSetting, datasetKeyPrefix, ledgerExStorage, - ledgerVerStorage, readonly, DEFAULT_ACCESS_POLICY); - } - - static ContractAccountSet loadContractAccountSet(HashDigest contractAccountSetHash, CryptoSetting cryptoSetting, - String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, - boolean readonly) { - - String contractsetKeyPrefix = keyPrefix + CONTRACT_SET_PREFIX; - return new ContractAccountSet(contractAccountSetHash, cryptoSetting, contractsetKeyPrefix, ledgerExStorage, - ledgerVerStorage, readonly, DEFAULT_ACCESS_POLICY); - } - - static TransactionSet loadTransactionSet(HashDigest txsetHash, CryptoSetting cryptoSetting, String keyPrefix, - ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, boolean readonly) { - - String txsetKeyPrefix = keyPrefix + TRANSACTION_SET_PREFIX; - return new TransactionSet(txsetHash, cryptoSetting, txsetKeyPrefix, ledgerExStorage, ledgerVerStorage, - readonly); - - } - - private static class NewBlockCommittingMonitor implements LedgerEditor { - - private LedgerTransactionalEditor editor; - - private LedgerRepositoryImpl ledgerRepo; - - public NewBlockCommittingMonitor(LedgerTransactionalEditor editor, LedgerRepositoryImpl ledgerRepo) { - this.editor = editor; - this.ledgerRepo = ledgerRepo; - } - - @Override - public HashDigest getLedgerHash() { - return editor.getLedgerHash(); - } - - @Override - public long getBlockHeight() { - return editor.getBlockHeight(); - } - - @Override - public LedgerDataset getLedgerDataset() { - return editor.getLedgerDataset(); - } - - @Override - public TransactionSet getTransactionSet() { - return editor.getTransactionSet(); - } - - @Override - public LedgerTransactionContext newTransaction(TransactionRequest txRequest) { - return editor.newTransaction(txRequest); - } - - @Override - public LedgerBlock prepare() { - return editor.prepare(); - } - - @Override - public void commit() { - try { - editor.commit(); - LedgerBlock latestBlock = editor.getCurrentBlock(); - ledgerRepo.latestState = new LedgerState(latestBlock, editor.getLedgerDataset(), - editor.getTransactionSet()); - } finally { - ledgerRepo.nextBlockEditor = null; - } - } - - @Override - public void cancel() { - try { - editor.cancel(); - } finally { - ledgerRepo.nextBlockEditor = null; - } - } - - } - - /** - * 维护账本某个区块的数据状态的缓存结构; - * - * @author huanghaiquan - * - */ - private static class LedgerState { - - private final LedgerBlock block; - - private final TransactionQuery transactionSet; - - private final LedgerDataset ledgerDataset; - - public LedgerState(LedgerBlock block, LedgerDataset ledgerDataset, TransactionQuery transactionSet) { - this.block = block; - this.ledgerDataset = ledgerDataset; - this.transactionSet = transactionSet; - - } - - public LedgerAdminDataset getAdminDataset() { - return ledgerDataset.getAdminDataset(); - } - - public LedgerDataset getLedgerDataset() { - return ledgerDataset; - } - - public ContractAccountQuery getContractAccountSet() { - return ledgerDataset.getContractAccountset(); - } - - public DataAccountQuery getDataAccountSet() { - return ledgerDataset.getDataAccountSet(); - } - - public UserAccountQuery getUserAccountSet() { - return ledgerDataset.getUserAccountSet(); - } - - public TransactionQuery getTransactionSet() { - return transactionSet; - } - - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManager.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManager.java deleted file mode 100644 index ac819e39..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManager.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Set; - -import com.jd.blockchain.utils.Bytes; - -public interface LedgerSecurityManager { - - String DEFAULT_ROLE = "DEFAULT"; - - /** - * 创建一项与指定的终端用户和节点参与方相关的安全策略; - * - * @param endpoints 终端用户的地址列表; - * @param nodes 节点参与方的地址列表; - * @return 一项安全策略; - */ - SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManagerImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManagerImpl.java deleted file mode 100644 index 56daa556..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManagerImpl.java +++ /dev/null @@ -1,396 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerSecurityException; -import com.jd.blockchain.ledger.ParticipantDataQuery; -import com.jd.blockchain.ledger.ParticipantDoesNotExistException; -import com.jd.blockchain.ledger.RolePrivilegeSettings; -import com.jd.blockchain.ledger.RolePrivileges; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.UserDoesNotExistException; -import com.jd.blockchain.ledger.UserRoles; -import com.jd.blockchain.ledger.UserAuthorizationSettings; -import com.jd.blockchain.utils.Bytes; - -/** - * 账本安全管理器; - * - * @author huanghaiquan - * - */ -public class LedgerSecurityManagerImpl implements LedgerSecurityManager { - - private RolePrivilegeSettings rolePrivilegeSettings; - - private UserAuthorizationSettings userRolesSettings; - - // 用户的权限配置 - private Map userPrivilegesCache = new ConcurrentHashMap<>(); - - private Map userRolesCache = new ConcurrentHashMap<>(); - private Map rolesPrivilegeCache = new ConcurrentHashMap<>(); - - private ParticipantDataQuery participantsQuery; - private UserAccountQuery userAccountsQuery; - - public LedgerSecurityManagerImpl(RolePrivilegeSettings rolePrivilegeSettings, UserAuthorizationSettings userRolesSettings, - ParticipantDataQuery participantsQuery, UserAccountQuery userAccountsQuery) { - this.rolePrivilegeSettings = rolePrivilegeSettings; - this.userRolesSettings = userRolesSettings; - this.participantsQuery = participantsQuery; - this.userAccountsQuery = userAccountsQuery; - } - - @Override - public SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes) { - Map endpointPrivilegeMap = new HashMap<>(); - Map nodePrivilegeMap = new HashMap<>(); - - for (Bytes userAddress : endpoints) { - UserRolesPrivileges userPrivileges = getUserRolesPrivilegs(userAddress); - endpointPrivilegeMap.put(userAddress, userPrivileges); - } - - for (Bytes userAddress : nodes) { - UserRolesPrivileges userPrivileges = getUserRolesPrivilegs(userAddress); - nodePrivilegeMap.put(userAddress, userPrivileges); - } - - return new UserRolesSecurityPolicy(endpointPrivilegeMap, nodePrivilegeMap, participantsQuery, userAccountsQuery); - } - - private UserRolesPrivileges getUserRolesPrivilegs(Bytes userAddress) { - UserRolesPrivileges userPrivileges = userPrivilegesCache.get(userAddress); - if (userPrivileges != null) { - return userPrivileges; - } - - UserRoles userRoles = null; - - List privilegesList = new ArrayList<>(); - - // 加载用户的角色列表; - userRoles = userRolesCache.get(userAddress); - if (userRoles == null) { - userRoles = userRolesSettings.getUserRoles(userAddress); - if (userRoles != null) { - userRolesCache.put(userAddress, userRoles); - } - } - - // 计算用户的综合权限; - if (userRoles != null) { - String[] roles = userRoles.getRoles(); - RolePrivileges privilege = null; - for (String role : roles) { - // 先从缓存读取,如果没有再从原始数据源进行加载; - privilege = rolesPrivilegeCache.get(role); - if (privilege == null) { - privilege = rolePrivilegeSettings.getRolePrivilege(role); - if (privilege == null) { - // 略过不存在的无效角色; - continue; - } - rolesPrivilegeCache.put(role, privilege); - } - privilegesList.add(privilege); - } - } - // 如果用户未被授权任何角色,则采用默认角色的权限; - if (privilegesList.size() == 0) { - RolePrivileges privilege = getDefaultRolePrivilege(); - privilegesList.add(privilege); - } - - if (userRoles == null) { - userPrivileges = new UserRolesPrivileges(userAddress, RolesPolicy.UNION, privilegesList); - } else { - userPrivileges = new UserRolesPrivileges(userAddress, userRoles.getPolicy(), privilegesList); - } - - userPrivilegesCache.put(userAddress, userPrivileges); - return userPrivileges; - } - - private RolePrivileges getDefaultRolePrivilege() { - RolePrivileges privileges = rolesPrivilegeCache.get(DEFAULT_ROLE); - if (privileges == null) { - privileges = rolePrivilegeSettings.getRolePrivilege(DEFAULT_ROLE); - if (privileges == null) { - throw new LedgerSecurityException( - "This ledger is missing the default role-privilege settings for the users who don't have a role!"); - } - } - return privileges; - } - - private class UserRolesSecurityPolicy implements SecurityPolicy { - - /** - * 终端用户的权限表; - */ - private Map endpointPrivilegeMap = new HashMap<>(); - - /** - * 节点参与方的权限表; - */ - private Map nodePrivilegeMap = new HashMap<>(); - - private ParticipantDataQuery participantsQuery; - - private UserAccountQuery userAccountsQuery; - - public UserRolesSecurityPolicy(Map endpointPrivilegeMap, - Map nodePrivilegeMap, ParticipantDataQuery participantsQuery, - UserAccountQuery userAccountsQuery) { - this.endpointPrivilegeMap = endpointPrivilegeMap; - this.nodePrivilegeMap = nodePrivilegeMap; - this.participantsQuery = participantsQuery; - this.userAccountsQuery = userAccountsQuery; - } - - @Override - public boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { - if (p.getLedgerPrivileges().isEnable(permission)) { - return true; - } - } - return false; - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { - if (!p.getLedgerPrivileges().isEnable(permission)) { - return false; - } - } - return true; - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - @Override - public boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { - if (p.getTransactionPrivileges().isEnable(permission)) { - return true; - } - } - return false; - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { - if (!p.getTransactionPrivileges().isEnable(permission)) { - return false; - } - } - return true; - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - @Override - public boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (UserRolesPrivileges p : nodePrivilegeMap.values()) { - if (p.getLedgerPrivileges().isEnable(permission)) { - return true; - } - } - return false; - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (UserRolesPrivileges p : nodePrivilegeMap.values()) { - if (!p.getLedgerPrivileges().isEnable(permission)) { - return false; - } - } - return true; - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - @Override - public boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (UserRolesPrivileges p : nodePrivilegeMap.values()) { - if (p.getTransactionPrivileges().isEnable(permission)) { - return true; - } - } - return false; - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (UserRolesPrivileges p : nodePrivilegeMap.values()) { - if (!p.getTransactionPrivileges().isEnable(permission)) { - return false; - } - } - return true; - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - @Override - public void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - if (!isEndpointEnable(permission, midPolicy)) { - throw new LedgerSecurityException(String.format( - "The security policy [Permission=%s, Policy=%s] for endpoints rejected the current operation!", - permission, midPolicy)); - } - } - - @Override - public void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - if (!isEndpointEnable(permission, midPolicy)) { - throw new LedgerSecurityException(String.format( - "The security policy [Permission=%s, Policy=%s] for endpoints rejected the current operation!", - permission, midPolicy)); - } - } - - @Override - public void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - if (!isNodeEnable(permission, midPolicy)) { - throw new LedgerSecurityException(String.format( - "The security policy [Permission=%s, Policy=%s] for nodes rejected the current operation!", - permission, midPolicy)); - } - } - - @Override - public void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - if (!isNodeEnable(permission, midPolicy)) { - throw new LedgerSecurityException(String.format( - "The security policy [Permission=%s, Policy=%s] for nodes rejected the current operation!", - permission, midPolicy)); - } - } - - @Override - public Set getEndpoints() { - return endpointPrivilegeMap.keySet(); - } - - @Override - public Set getNodes() { - return nodePrivilegeMap.keySet(); - } - - @Override - public boolean isEndpointValid(MultiIDsPolicy midPolicy) { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (Bytes address : getEndpoints()) { - if (userAccountsQuery.contains(address)) { - return true; - } - } - return false; - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (Bytes address : getEndpoints()) { - if (!userAccountsQuery.contains(address)) { - return false; - } - } - return true; - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - @Override - public boolean isNodeValid(MultiIDsPolicy midPolicy) { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (Bytes address : getNodes()) { - if (participantsQuery.contains(address)) { - return true; - } - } - return false; - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (Bytes address : getNodes()) { - if (!participantsQuery.contains(address)) { - return false; - } - } - return true; - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - @Override - public void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (Bytes address : getEndpoints()) { - if (userAccountsQuery.contains(address)) { - return; - } - } - throw new UserDoesNotExistException("All endpoint signers were not registered!"); - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (Bytes address : getEndpoints()) { - if (!userAccountsQuery.contains(address)) { - throw new UserDoesNotExistException("The endpoint signer[" + address + "] was not registered!"); - } - } - return; - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - @Override - public void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { - if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { - // 至少一个; - for (Bytes address : getNodes()) { - if (participantsQuery.contains(address)) { - return; - } - } - throw new ParticipantDoesNotExistException("All node signers were not registered as participant!"); - } else if (MultiIDsPolicy.ALL == midPolicy) { - // 全部; - for (Bytes address : getNodes()) { - if (!participantsQuery.contains(address)) { - throw new ParticipantDoesNotExistException( - "The node signer[" + address + "] was not registered as participant!"); - } - } - } else { - throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); - } - } - - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerService.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerService.java deleted file mode 100644 index b75032d6..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerException; - -/** - * 账本管理器; - * - * @author huanghaiquan - * - */ -public interface LedgerService { - - /** - * 返回已注册的账本哈希; - * @return - */ - HashDigest[] getLedgerHashs(); - - /** - * 获取指定的账本数据库;
- * - * 如果指定的账本不存在,则抛出 {@link LedgerException}; - * - * @param ledgerHash - * @return - */ - LedgerRepository getLedger(HashDigest ledgerHash); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionContext.java deleted file mode 100644 index 5dccc736..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionContext.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.*; - -import java.util.List; - -/** - * 事务上下文; - * - * @author huanghaiquan - * - */ -public interface LedgerTransactionContext { - - /** - * 账本数据集合; - * - * @return - */ - LedgerDataset getDataset(); - - /** - * 事务集合; - * - * @return - */ - TransactionQuery getTransactionSet(); - - /** - * 交易请求; - * - * @return - */ - TransactionRequest getTransactionRequest(); - - /** - * 提交对账本数据的修改,以指定的交易状态提交交易; - * - * @param txResult - * - * @return - */ - LedgerTransaction commit(TransactionState txResult); - - /** - * 提交对账本数据的修改,以指定的交易状态提交交易; - * - * @param txResult - * @param operationResults - * - * @return - */ - LedgerTransaction commit(TransactionState txResult, List operationResults); - - /** - * 抛弃对账本数据的修改,以指定的交易状态提交交易;
- * - * 通常来说,当在开启事务之后,修改账本或者尝试提交交易({@link #commit(TransactionState)})时发生错误,都应该抛弃数据,通过此方法记录一个表示错误状态的交易; - * - * @param txResult - * @return - */ - LedgerTransaction discardAndCommit(TransactionState txResult); - - /** - * 抛弃对账本数据的修改,以指定的交易状态提交交易;
- * - * 通常来说,当在开启事务之后,修改账本或者尝试提交交易({@link #commit(TransactionState, List)})时发生错误,都应该抛弃数据,通过此方法记录一个表示错误状态的交易; - * - * @param txResult - * @return - */ - LedgerTransaction discardAndCommit(TransactionState txResult, List operationResults); - - /** - * 回滚事务,抛弃本次事务的所有数据更新; - */ - void rollback(); -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionData.java deleted file mode 100644 index 516f338f..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionData.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.OperationResult; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionState; - -public class LedgerTransactionData implements LedgerTransaction { - - private TransactionStagedSnapshot txSnapshot; - - private TransactionContent transactionContent; - - private DigitalSignature[] endpointSignatures; - - private DigitalSignature[] nodeSignatures; - - private TransactionState executionState; - - private HashDigest hash; - - private long blockHeight; - - private OperationResult[] operationResults; - - /** - * Declare a private no-arguments constructor for deserializing purpose; - */ - @SuppressWarnings("unused") - private LedgerTransactionData() { - } - - /** - * @param blockHeight 区块链高度; - * @param txReq 交易请求; - * @param execState 执行状态; - * @param txSnapshot 交易级的系统快照; - */ - public LedgerTransactionData(long blockHeight, TransactionRequest txReq, TransactionState execState, - TransactionStagedSnapshot txSnapshot, OperationResult... opResults) { - this.blockHeight = blockHeight; - this.txSnapshot = txSnapshot; - this.transactionContent = txReq.getTransactionContent(); - this.endpointSignatures = txReq.getEndpointSignatures(); - this.nodeSignatures = txReq.getNodeSignatures(); - this.executionState = execState; - this.operationResults = opResults; - } - - @Override - public HashDigest getHash() { - return this.hash; - } - - @Override - public long getBlockHeight() { - return this.blockHeight; - } - - @Override - public TransactionState getExecutionState() { - return executionState; - } - - @Override - public OperationResult[] getOperationResults() { - return operationResults; - } - - @Override - public TransactionContent getTransactionContent() { - return this.transactionContent; - } - - @Override - public DigitalSignature[] getEndpointSignatures() { - return this.endpointSignatures; - } - - @Override - public DigitalSignature[] getNodeSignatures() { - return nodeSignatures; - } - - @Override - public HashDigest getAdminAccountHash() { - return txSnapshot == null ? null : txSnapshot.getAdminAccountHash(); - } - - @Override - public HashDigest getUserAccountSetHash() { - return txSnapshot == null ? null : txSnapshot.getUserAccountSetHash(); - } - - @Override - public HashDigest getDataAccountSetHash() { - return txSnapshot == null ? null : txSnapshot.getDataAccountSetHash(); - } - - @Override - public HashDigest getContractAccountSetHash() { - return txSnapshot == null ? null : txSnapshot.getContractAccountSetHash(); - } - - public void setTxSnapshot(TransactionStagedSnapshot txSnapshot) { - if (txSnapshot == null) { - throw new IllegalArgumentException("Transaction snapshot argument is null!"); - } - this.txSnapshot = txSnapshot; - } - - public void setTransactionContent(TransactionContent content) { - this.transactionContent = content; - } - - public void setEndpointSignatures(DigitalSignature[] participantSignatures) { - this.endpointSignatures = participantSignatures; -// int length = participantSignatures.length; -// this.endpointSignatures = new DigitalSignature[length]; -// for (int i = 0; i < length; i++) { -// this.endpointSignatures[i] = (DigitalSignature) participantSignatures[i]; -// } - } - - public void setNodeSignatures(DigitalSignature[] nodeSignatures) { - this.nodeSignatures = nodeSignatures; -// int length = nodeSignatures.length; -// this.nodeSignatures = new DigitalSignature[length]; -// for (int i = 0; i < length; i++) { -// this.nodeSignatures[i] = (DigitalSignature) nodeSignatures[i]; -// } - } - - public void setExecutionState(TransactionState executionState) { - this.executionState = executionState; - } - - public void setHash(HashDigest hash) { - this.hash = hash; - } - - public void setBlockHeight(long blockHeight) { - this.blockHeight = blockHeight; - } - - public void setAdminAccountHash(HashDigest adminAccountHash) { - if (txSnapshot == null) { - txSnapshot = new TransactionStagedSnapshot(); - } - txSnapshot.setAdminAccountHash(adminAccountHash); - } - - public void setUserAccountSetHash(HashDigest userAccountSetHash) { - if (txSnapshot == null) { - txSnapshot = new TransactionStagedSnapshot(); - } - txSnapshot.setUserAccountSetHash(userAccountSetHash); - } - - public void setDataAccountSetHash(HashDigest dataAccountSetHash) { - if (txSnapshot == null) { - txSnapshot = new TransactionStagedSnapshot(); - } - txSnapshot.setDataAccountSetHash(dataAccountSetHash); - } - - public void setContractAccountSetHash(HashDigest contractAccountSetHash) { - if (txSnapshot == null) { - txSnapshot = new TransactionStagedSnapshot(); - } - txSnapshot.setContractAccountSetHash(contractAccountSetHash); - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionalEditor.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionalEditor.java deleted file mode 100644 index 15954e4f..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionalEditor.java +++ /dev/null @@ -1,634 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.List; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockBody; -import com.jd.blockchain.ledger.BlockRollbackException; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.IllegalTransactionException; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.LedgerSettings; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.OperationResult; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionRollbackException; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.utils.BufferedKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; - -public class LedgerTransactionalEditor implements LedgerEditor { - - private static final boolean PARALLEL_DB_WRITE; - - static { - PARALLEL_DB_WRITE = Boolean.getBoolean("parallel-dbwrite"); - System.out.println("------ [[ parallel-dbwrite=" + PARALLEL_DB_WRITE + " ]] ------"); - } - - /** - * 账本Hash,创世区块的编辑器则返回 null; - */ - private HashDigest ledgerHash; - - private final String ledgerKeyPrefix; - - private CryptoSetting cryptoSetting; - - private LedgerBlockData currentBlock; - -// private Stack stagedSnapshots = new Stack<>(); - - private boolean prepared = false; - - private boolean canceled = false; - - private boolean committed = false; - - private StagedSnapshot startingPoint; - - /** - * 当前区块的存储; - */ - private BufferedKVStorage baseStorage; - - /** - * 上一个交易产生的账本快照; - */ - private TxSnapshot previousTxSnapshot; - - /** - * 当前交易的上下文; - */ - private volatile LedgerTransactionContextImpl currentTxCtx; - - /** - * 最后提交的账本数据集; - */ - private volatile LedgerDataset latestLedgerDataset; - - /** - * 最后提交的交易集合; - */ - private volatile TransactionSet latestTransactionSet; - - /** - * @param ledgerHash - * @param cryptoSetting - * @param currentBlock - * @param startingPoint - * @param ledgerKeyPrefix - * @param bufferedStorage - * @param verifyTx 是否校验交易请求;当外部调用者在调用前已经实施了验证时,将次参数设置为 false 能够提升性能; - */ - private LedgerTransactionalEditor(HashDigest ledgerHash, CryptoSetting cryptoSetting, LedgerBlockData currentBlock, - StagedSnapshot startingPoint, String ledgerKeyPrefix, BufferedKVStorage bufferedStorage) { - this.ledgerHash = ledgerHash; - this.ledgerKeyPrefix = ledgerKeyPrefix; - this.cryptoSetting = cryptoSetting; - this.currentBlock = currentBlock; - this.baseStorage = bufferedStorage; - - this.startingPoint = startingPoint; - -// this.stagedSnapshots.push(startingPoint); - } - - /** - * 创建账本新区块的编辑器; - * - * @param ledgerHash 账本哈希; - * @param ledgerSetting 账本设置; - * @param previousBlock 前置区块; - * @param ledgerKeyPrefix 账本数据前缀; - * @param ledgerExStorage 账本数据存储; - * @param ledgerVerStorage 账本数据版本化存储; - * @param verifyTx 是否校验交易请求;当外部调用者在调用前已经实施了验证时,将次参数设置为 false 能够提升性能; - * @return - */ - public static LedgerTransactionalEditor createEditor(LedgerBlock previousBlock, LedgerSettings ledgerSetting, - String ledgerKeyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage) { - // new block; - HashDigest ledgerHash = previousBlock.getLedgerHash(); - if (ledgerHash == null) { - ledgerHash = previousBlock.getHash(); - } - if (ledgerHash == null) { - throw new IllegalArgumentException("Illegal previous block was specified!"); - } - LedgerBlockData currBlock = new LedgerBlockData(previousBlock.getHeight() + 1, ledgerHash, - previousBlock.getHash()); - - // init storage; - BufferedKVStorage txStagedStorage = new BufferedKVStorage(ledgerExStorage, ledgerVerStorage, PARALLEL_DB_WRITE); - - StagedSnapshot startingPoint = new TxSnapshot(previousBlock, previousBlock.getTransactionSetHash()); - - // instantiate editor; - return new LedgerTransactionalEditor(ledgerHash, ledgerSetting.getCryptoSetting(), currBlock, startingPoint, - ledgerKeyPrefix, txStagedStorage); - } - - /** - * 创建创世区块的编辑器; - * - * @param initSetting - * @param ledgerKeyPrefix - * @param ledgerExStorage - * @param ledgerVerStorage - * @param verifyTx 是否校验交易请求;当外部调用者在调用前已经实施了验证时,将次参数设置为 false 能够提升性能; - * @return - */ - public static LedgerTransactionalEditor createEditor(LedgerInitSetting initSetting, String ledgerKeyPrefix, - ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage) { - LedgerBlockData genesisBlock = new LedgerBlockData(0, null, null); - StagedSnapshot startingPoint = new GenesisSnapshot(initSetting); - // init storage; - BufferedKVStorage txStagedStorage = new BufferedKVStorage(ledgerExStorage, ledgerVerStorage, false); - return new LedgerTransactionalEditor(null, initSetting.getCryptoSetting(), genesisBlock, startingPoint, - ledgerKeyPrefix, txStagedStorage); - } - - private void commitTxSnapshot(TxSnapshot snapshot) { - previousTxSnapshot = snapshot; - latestLedgerDataset = currentTxCtx.getDataset(); - latestLedgerDataset.setReadonly(); - latestTransactionSet = currentTxCtx.getTransactionSet(); - latestTransactionSet.setReadonly(); - currentTxCtx = null; - } - - private void rollbackCurrentTx() { - currentTxCtx = null; - } - - LedgerBlock getCurrentBlock() { - return currentBlock; - } - - @Override - public long getBlockHeight() { - return currentBlock.getHeight(); - } - - @Override - public HashDigest getLedgerHash() { - return ledgerHash; - } - - @Override - public LedgerDataset getLedgerDataset() { - return latestLedgerDataset; - } - - @Override - public TransactionSet getTransactionSet() { - return latestTransactionSet; - } - - /** - * 检查当前账本是否是指定交易请求的账本; - * - * @param txRequest - * @return - */ - private boolean isRequestMatched(TransactionRequest txRequest) { - HashDigest reqLedgerHash = txRequest.getTransactionContent().getLedgerHash(); - if (ledgerHash == reqLedgerHash) { - return true; - } - if (ledgerHash == null || reqLedgerHash == null) { - return false; - } - return ledgerHash.equals(reqLedgerHash); - } - - /** - * 注:此方法不验证交易完整性和签名有效性,仅仅设计为进行交易记录的管理;调用者应在此方法之外进行数据完整性和签名有效性的检查; - */ - @Override - public synchronized LedgerTransactionContext newTransaction(TransactionRequest txRequest) { -// if (SettingContext.txSettings().verifyLedger() && !isRequestMatched(txRequest)) { - if (!isRequestMatched(txRequest)) { - throw new IllegalTransactionException( - "Transaction request is dispatched to a wrong ledger! --[TxHash=" - + txRequest.getTransactionContent().getHash() + "]!", - TransactionState.IGNORED_BY_WRONG_LEDGER); - } - - if (currentTxCtx != null) { - throw new IllegalStateException( - "Unable to open another new transaction before the current transaction is completed! --[TxHash=" - + txRequest.getTransactionContent().getHash() + "]!"); - } - - // 检查状态是否允许创建新的交易请求;; - checkState(); - - // init storage of new transaction; - BufferedKVStorage txBufferedStorage = new BufferedKVStorage(baseStorage, baseStorage, false); - - LedgerDataset txDataset = null; - TransactionSet txset = null; - if (previousTxSnapshot == null) { - // load the starting point of the new transaction; - if (startingPoint instanceof GenesisSnapshot) { - // 准备生成创世区块; - GenesisSnapshot snpht = (GenesisSnapshot) startingPoint; - txDataset = LedgerRepositoryImpl.newDataSet(snpht.initSetting, ledgerKeyPrefix, txBufferedStorage, - txBufferedStorage); - txset = LedgerRepositoryImpl.newTransactionSet(txDataset.getAdminDataset().getSettings(), - ledgerKeyPrefix, txBufferedStorage, txBufferedStorage); - } else if (startingPoint instanceof TxSnapshot) { - // 新的区块; - // TxSnapshot; reload dataset and txset; - TxSnapshot snpht = (TxSnapshot) startingPoint; - // load dataset; - txDataset = LedgerRepositoryImpl.loadDataSet(snpht.dataSnapshot, cryptoSetting, ledgerKeyPrefix, - txBufferedStorage, txBufferedStorage, false); - - // load txset; - txset = LedgerRepositoryImpl.loadTransactionSet(snpht.txsetHash, cryptoSetting, ledgerKeyPrefix, - txBufferedStorage, txBufferedStorage, false); - } else { - // Unreachable; - throw new IllegalStateException("Unreachable code was accidentally executed!"); - } - - } else { - // Reuse previous object to optimize performance; - // load dataset; - txDataset = LedgerRepositoryImpl.loadDataSet(previousTxSnapshot.dataSnapshot, cryptoSetting, - ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); - - // load txset; - txset = LedgerRepositoryImpl.loadTransactionSet(previousTxSnapshot.txsetHash, cryptoSetting, - ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); - } - - currentTxCtx = new LedgerTransactionContextImpl(txRequest, txDataset, txset, txBufferedStorage, this); - - return currentTxCtx; - } - - @Override - public LedgerBlock prepare() { - checkState(); - - if (currentTxCtx != null) { - // 有进行中的交易尚未提交或回滚; - throw new IllegalStateException( - "There is an ongoing transaction that has been not committed or rolled back!"); - } - if (previousTxSnapshot == null) { - // 当前区块没有加入过交易,不允许产生空区块; - throw new IllegalStateException( - "There is no transaction in the current block, and no empty blocks is allowed!"); - } - - // do commit when transaction isolation level is BLOCK; - currentBlock.setAdminAccountHash(previousTxSnapshot.getAdminAccountHash()); - currentBlock.setUserAccountSetHash(previousTxSnapshot.getUserAccountSetHash()); - currentBlock.setDataAccountSetHash(previousTxSnapshot.getDataAccountSetHash()); - currentBlock.setContractAccountSetHash(previousTxSnapshot.getContractAccountSetHash()); - currentBlock.setTransactionSetHash(previousTxSnapshot.getTransactionSetHash()); - - // TODO: 根据所有交易的时间戳的平均值来生成区块的时间戳; -// long timestamp = -// currentBlock.setTimestamp(timestamp); - - // compute block hash; - byte[] blockBodyBytes = BinaryProtocol.encode(currentBlock, BlockBody.class); - HashDigest blockHash = Crypto.getHashFunction(cryptoSetting.getHashAlgorithm()).hash(blockBodyBytes); - currentBlock.setHash(blockHash); - -// if (currentBlock.getLedgerHash() == null) { -// // init GenesisBlock's ledger hash; -// currentBlock.setLedgerHash(blockHash); -// } - - // persist block bytes; - // only one version per block; - byte[] blockBytes = BinaryProtocol.encode(currentBlock, LedgerBlock.class); - Bytes blockStorageKey = LedgerRepositoryImpl.encodeBlockStorageKey(currentBlock.getHash()); - long v = baseStorage.set(blockStorageKey, blockBytes, -1); - if (v < 0) { - throw new IllegalStateException( - "Block already exist! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); - } - - // persist block hash to ledger index; - HashDigest ledgerHash = currentBlock.getLedgerHash(); - if (ledgerHash == null) { - ledgerHash = blockHash; - } - Bytes ledgerIndexKey = LedgerRepositoryImpl.encodeLedgerIndexKey(ledgerHash); - long expectedVersion = currentBlock.getHeight() - 1; - v = baseStorage.set(ledgerIndexKey, currentBlock.getHash().toBytes(), expectedVersion); - if (v < 0) { - throw new IllegalStateException( - String.format("Index of BlockHash already exist! --[BlockHeight=%s][BlockHash=%s]", - currentBlock.getHeight(), currentBlock.getHash())); - } - - prepared = true; - return currentBlock; - } - - @Override - public void commit() { - if (committed) { - throw new IllegalStateException("The current block has been committed!"); - } - if (canceled) { - throw new IllegalStateException("The current block has been canceled!"); - } - if (!prepared) { - // 未就绪; - throw new IllegalStateException("The current block is not ready yet!"); - } - - try { - baseStorage.flush(); - } catch (Exception e) { - throw new BlockRollbackException(e.getMessage(), e); - } - - committed = true; - } - - @Override - public void cancel() { - if (committed) { - throw new IllegalStateException("The current block has been committed!"); - } - if (canceled) { - return; - } - - canceled = true; - - baseStorage.cancel(); - } - - private void checkState() { - if (prepared) { - throw new IllegalStateException("The current block is ready!"); - } - if (committed) { - throw new IllegalStateException("The current block has been committed!"); - } - if (canceled) { - throw new IllegalStateException("The current block has been canceled!"); - } - } - - // --------------------------- inner type -------------------------- - - /** - * 用于暂存交易上下文数据的快照对象; - * - * @author huanghaiquan - * - */ - private static interface StagedSnapshot { - - } - - /** - * 创世区块的快照对象; - * - * @author huanghaiquan - * - */ - private static class GenesisSnapshot implements StagedSnapshot { - - private LedgerInitSetting initSetting; - - public GenesisSnapshot(LedgerInitSetting initSetting) { - this.initSetting = initSetting; - } - } - - /** - * 交易执行完毕后的快照对象; - * - * @author huanghaiquan - * - */ - private static class TxSnapshot implements StagedSnapshot { - - /** - * 账本数据的快照; - */ - private LedgerDataSnapshot dataSnapshot; - - /** - * 交易集合的快照(根哈希); - */ - private HashDigest txsetHash; - - public HashDigest getAdminAccountHash() { - return dataSnapshot.getAdminAccountHash(); - } - - public HashDigest getUserAccountSetHash() { - return dataSnapshot.getUserAccountSetHash(); - } - - public HashDigest getDataAccountSetHash() { - return dataSnapshot.getDataAccountSetHash(); - } - - public HashDigest getContractAccountSetHash() { - return dataSnapshot.getContractAccountSetHash(); - } - - public HashDigest getTransactionSetHash() { - return txsetHash; - } - - public TxSnapshot(LedgerDataSnapshot dataSnapshot, HashDigest txsetHash) { - this.dataSnapshot = dataSnapshot; - this.txsetHash = txsetHash; - } - - } - - /** - * 交易的上下文; - * - * @author huanghaiquan - * - */ - private static class LedgerTransactionContextImpl implements LedgerTransactionContext { - - private LedgerTransactionalEditor blockEditor; - - private TransactionRequest txRequest; - - private LedgerDataset dataset; - - private TransactionSet txset; - - private BufferedKVStorage storage; - - private boolean committed = false; - - private boolean rollbacked = false; - - private LedgerTransaction transaction; - - private HashDigest txRootHash; - - private LedgerTransactionContextImpl(TransactionRequest txRequest, LedgerDataset dataset, - TransactionSet txset, BufferedKVStorage storage, LedgerTransactionalEditor editor) { - this.txRequest = txRequest; - this.dataset = dataset; - this.txset = txset; - this.storage = storage; - this.blockEditor = editor; - } - - @Override - public LedgerDataset getDataset() { - return dataset; - } - - @Override - public TransactionSet getTransactionSet() { - return txset; - } - - @Override - public TransactionRequest getTransactionRequest() { - return txRequest; - } - - @Override - public LedgerTransaction commit(TransactionState txResult) { - return commit(txResult, null); - } - - @Override - public LedgerTransaction commit(TransactionState txResult, List operationResults) { - checkTxState(); - - // capture snapshot - this.dataset.commit(); - TransactionStagedSnapshot txDataSnapshot = takeDataSnapshot(); - - LedgerTransactionData tx; - try { - tx = new LedgerTransactionData(blockEditor.getBlockHeight(), txRequest, txResult, txDataSnapshot, - operationResultArray(operationResults)); - this.txset.add(tx); - this.txset.commit(); - } catch (Exception e) { - throw new TransactionRollbackException(e.getMessage(), e); - } - - try { - this.storage.flush(); - } catch (Exception e) { - throw new BlockRollbackException(e.getMessage(), e); - } - - // put snapshot into stack; - TxSnapshot snapshot = new TxSnapshot(txDataSnapshot, txset.getRootHash()); - blockEditor.commitTxSnapshot(snapshot); - - committed = true; - return tx; - } - - @Override - public LedgerTransaction discardAndCommit(TransactionState txResult) { - return discardAndCommit(txResult, null); - } - - @Override - public LedgerTransaction discardAndCommit(TransactionState txResult, List operationResults) { - checkTxState(); - - // 未处理 - dataset.cancel(); - - TransactionStagedSnapshot txDataSnapshot = takeDataSnapshot(); - - LedgerTransactionData tx; - try { - tx = new LedgerTransactionData(blockEditor.getBlockHeight(), txRequest, txResult, txDataSnapshot, - operationResultArray(operationResults)); - this.txset.add(tx); - this.txset.commit(); - } catch (Exception e) { - throw new TransactionRollbackException(e.getMessage(), e); - } - - try { - this.storage.flush(); - } catch (Exception e) { - throw new BlockRollbackException(e.getMessage(), e); - } - - // put snapshot into stack; - TxSnapshot snapshot = new TxSnapshot(txDataSnapshot, txset.getRootHash()); - blockEditor.commitTxSnapshot(snapshot); - - committed = true; - return tx; - } - - private TransactionStagedSnapshot takeDataSnapshot() { - TransactionStagedSnapshot txDataSnapshot = new TransactionStagedSnapshot(); - txDataSnapshot.setAdminAccountHash(dataset.getAdminDataset().getHash()); - txDataSnapshot.setContractAccountSetHash(dataset.getContractAccountset().getRootHash()); - txDataSnapshot.setDataAccountSetHash(dataset.getDataAccountSet().getRootHash()); - txDataSnapshot.setUserAccountSetHash(dataset.getUserAccountSet().getRootHash()); - return txDataSnapshot; - } - - private OperationResult[] operationResultArray(List operationResults) { - OperationResult[] operationResultArray = null; - if (operationResults != null && !operationResults.isEmpty()) { - operationResultArray = new OperationResult[operationResults.size()]; - operationResults.toArray(operationResultArray); - } - return operationResultArray; - } - - @Override - public void rollback() { - if (this.rollbacked) { - return; - } - if (this.committed) { - throw new IllegalStateException("This transaction had been committed!"); - } - dataset.cancel(); - storage.cancel(); - - blockEditor.rollbackCurrentTx(); - - rollbacked = true; - } - - private void checkTxState() { - if (this.committed) { - throw new IllegalStateException("This transaction had been committed!"); - } - if (this.rollbacked) { - throw new IllegalStateException("This transaction had been rollbacked!"); - } - } - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccount.java deleted file mode 100644 index 38a65e31..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccount.java +++ /dev/null @@ -1,516 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.HashProof; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.MerkleSnapshot; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Dataset; -import com.jd.blockchain.utils.DatasetHelper; -import com.jd.blockchain.utils.DatasetHelper.DataChangedListener; -import com.jd.blockchain.utils.DatasetHelper.TypeMapper; -import com.jd.blockchain.utils.Transactional; - -/** - * 事务性的基础账户; - * - * @author huanghaiquan - * - */ -public class MerkleAccount implements CompositeAccount, HashProvable, MerkleSnapshot, Transactional { - - private static final Bytes HEADER_PREFIX = Bytes.fromString("HD/"); - private static final Bytes DATA_PREFIX = Bytes.fromString("DT/"); - - private static final Bytes KEY_HEADER_ROOT = Bytes.fromString("HEADER"); - - private static final Bytes KEY_DATA_ROOT = Bytes.fromString("DATA"); - - private static final String KEY_PUBKEY = "PUBKEY"; - - private BlockchainIdentity accountID; - - private MerkleDataSet rootDataset; - - private MerkleDataSet headerDataset; - - private MerkleDataSet dataDataset; - - private Dataset typedHeader; - - private Dataset typedData; - -// private long version; - - /** - * Create a new Account with the specified identity(address and pubkey);
- * - * At the same time, a empty merkle dataset is also created for this account, - * which is used for storing data of this account.
- * - * This new account will be writable.
- * - * @param accountID Identity of this new account; - * @param cryptoSetting Settings about crypto operations; - * @param keyPrefix Prefix of all keys in this account's dataset; - * @param exStorage The base storage for existance operation; - * @param verStorage The base storage for versioning operation; - */ - public MerkleAccount(BlockchainIdentity accountID, CryptoSetting cryptoSetting, Bytes keyPrefix, - ExPolicyKVStorage exStorage, VersioningKVStorage verStorage) { - // 初始化数据集; - initializeDatasets(null, cryptoSetting, keyPrefix, exStorage, verStorage, false); - - initPubKey(accountID.getPubKey()); - this.accountID = accountID; - } - - /** - * Create a account instance with the specified address and root hash; load it's - * merkle dataset from the specified root hash. This merkle dateset is used for - * storing data of this account.
- * - * @param address Address of this account; - * @param rootHash Merkle root hash of this account; It can not be null; - * @param cryptoSetting Settings about crypto operations; - * @param keyPrefix Prefix of all keys in this account's dataset; - * @param exStorage The base storage for existance operation; - * @param verStorage The base storage for versioning operation; - * @param readonly Readonly about this account's dataset; - */ - public MerkleAccount(Bytes address, HashDigest rootHash, CryptoSetting cryptoSetting, Bytes keyPrefix, - ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly) { - if (rootHash == null) { - throw new IllegalArgumentException("Specified a null root hash for account[" + address.toBase58() + "]!"); - } - - // 初始化数据集; - initializeDatasets(rootHash, cryptoSetting, keyPrefix, exStorage, verStorage, readonly); - - // 初始化账户的身份; - PubKey pubKey = loadPubKey(); - this.accountID = new AccountID(address, pubKey); - } - - private void initializeDatasets(HashDigest rootHash, CryptoSetting cryptoSetting, Bytes keyPrefix, - ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly) { - // 加载“根数据集” - this.rootDataset = new MerkleDataSet(rootHash, cryptoSetting, keyPrefix, exStorage, verStorage, readonly); - - // 初始化数据修改监听器; - DataChangedListener dataChangedListener = new DataChangedListener() { - @Override - public void onChanged(String key, TypedValue value, long expectedVersion, long newVersion) { - onUpdated(key, value, expectedVersion, newVersion); - } - }; - - TypeMapper valueMapper = new TypeMapper() { - - @Override - public byte[] encode(TypedValue t2) { - return BinaryProtocol.encode(t2, BytesValue.class); - } - - @Override - public TypedValue decode(byte[] t1) { - BytesValue v = BinaryProtocol.decodeAs(t1, BytesValue.class); - return TypedValue.wrap(v); - } - }; - - // 加载“头数据集”; - HashDigest headerRoot = loadHeaderRoot(); - Bytes headerPrefix = keyPrefix.concat(HEADER_PREFIX); - this.headerDataset = new MerkleDataSet(headerRoot, cryptoSetting, headerPrefix, exStorage, verStorage, - readonly); - this.typedHeader = DatasetHelper.listen(DatasetHelper.map(headerDataset, valueMapper), dataChangedListener); - - // 加载“主数据集” - HashDigest dataRoot = loadDataRoot(); - Bytes dataPrefix = keyPrefix.concat(DATA_PREFIX); - this.dataDataset = new MerkleDataSet(dataRoot, cryptoSetting, dataPrefix, exStorage, verStorage, readonly); - this.typedData = DatasetHelper.listen(DatasetHelper.map(dataDataset, valueMapper), dataChangedListener); - } - - private HashDigest loadHeaderRoot() { - byte[] hashBytes = rootDataset.getValue(KEY_HEADER_ROOT); - if (hashBytes == null) { - return null; - } - return new HashDigest(hashBytes); - } - - private HashDigest loadDataRoot() { - byte[] hashBytes = rootDataset.getValue(KEY_DATA_ROOT); - if (hashBytes == null) { - return null; - } - return new HashDigest(hashBytes); - } - - private long getHeaderRootVersion() { - return rootDataset.getVersion(KEY_HEADER_ROOT); - } - - private long getDataRootVersion() { - return rootDataset.getVersion(KEY_DATA_ROOT); - } - - public Bytes getAddress() { - return accountID.getAddress(); - } - - public PubKey getPubKey() { - return accountID.getPubKey(); - } - - @Override - public BlockchainIdentity getID() { - return accountID; - } - - public Dataset getHeaders() { - return typedHeader; - } - - @Override - public Dataset getDataset() { - return typedData; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.AccountDataSet#getRootHash() - */ - @Override - public HashDigest getRootHash() { - return rootDataset.getRootHash(); - } - - @Override - public HashProof getProof(Bytes key) { - MerkleProof dataProof = dataDataset.getProof(key); - if (dataProof == null) { - return null; - } - MerkleProof rootProof = rootDataset.getProof(KEY_DATA_ROOT); - if (rootProof == null) { - return null; - } - HashDigestList proof = new HashDigestList(rootProof); - proof.concat(dataProof); - return proof; - } - - /** - * 是否只读; - * - * @return - */ - public boolean isReadonly() { - return dataDataset.isReadonly() || headerDataset.isReadonly(); - } - - /** - * 初始化账户的公钥; - * - * @param pubKey - */ - private void initPubKey(PubKey pubKey) { - long v = typedHeader.setValue(KEY_PUBKEY, TypedValue.fromPubKey(pubKey), -1); - if (v < 0) { - throw new LedgerException("PubKey storage conflict!"); - } - } - - /** - * 加载公钥; - * - * @return - */ - private PubKey loadPubKey() { - TypedValue value = typedHeader.getValue(KEY_PUBKEY); - if (value == null) { - return null; - } - return value.pubKeyValue(); - } - - /** - * 当写入新值时触发此方法; - * - * @param key - * @param value - * @param newVersion - */ - protected void onUpdated(String key, TypedValue value, long expectedVersion, long newVersion) { - } - - /** - * 当账户数据提交后触发此方法;
- * - * 此方法默认会返回新的账户版本号,等于当前版本号加 1 ; - * - * @param previousRootHash 提交前的根哈希;如果是新账户的首次提交,则为 null; - * @param newRootHash 新的根哈希; - */ - protected void onCommited(HashDigest previousRootHash, HashDigest newRootHash) { - } - - @Override - public boolean isUpdated() { - return headerDataset.isUpdated() || dataDataset.isUpdated() || rootDataset.isUpdated(); - } - - @Override - public void commit() { - if (headerDataset.isUpdated()) { - headerDataset.commit(); - long version = getHeaderRootVersion(); - rootDataset.setValue(KEY_HEADER_ROOT, headerDataset.getRootHash().toBytes(), version); - } - if (dataDataset.isUpdated()) { - long version = getDataRootVersion(); - dataDataset.commit(); - rootDataset.setValue(KEY_DATA_ROOT, dataDataset.getRootHash().toBytes(), version); - } - - if (rootDataset.isUpdated()) { - HashDigest previousRootHash = rootDataset.getRootHash(); - rootDataset.commit(); - onCommited(previousRootHash, rootDataset.getRootHash()); - } - } - - @Override - public void cancel() { - headerDataset.cancel(); - dataDataset.cancel(); - rootDataset.cancel(); - } - - // ---------------------- - - private class AccountID implements BlockchainIdentity { - - private Bytes address; - - private PubKey pubKey; - - public AccountID(Bytes address, PubKey pubKey) { - this.address = address; - this.pubKey = pubKey; - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - } - -// private static class MerkleDatasetAdapter implements Dataset { -// -// private static DataChangedListener NULL_LISTENER = new DataChangedListener() { -// @Override -// public void onChanged(Bytes key, BytesValue value, long newVersion) { -// } -// }; -// -// private DataChangedListener changedListener; -// -// private MerkleDataSet dataset; -// -// public MerkleDataSet getDataset() { -// return dataset; -// } -// -// @SuppressWarnings("unused") -// public MerkleDatasetAdapter(MerkleDataSet dataset) { -// this(dataset, NULL_LISTENER); -// } -// -// public MerkleDatasetAdapter(MerkleDataSet dataset, DataChangedListener listener) { -// this.dataset = dataset; -// this.changedListener = listener == null ? NULL_LISTENER : listener; -// } -// -// @Override -// public DataEntry getDataEntry(String key) { -// return new VersioningKVEntryWraper(dataset.getDataEntry(Bytes.fromString(key))); -// } -// -// @Override -// public DataEntry getDataEntry(String key, long version) { -// return new VersioningKVEntryWraper(dataset.getDataEntry(Bytes.fromString(key), version)); -// } -// -// /** -// * Create or update the value associated the specified key if the version -// * checking is passed.
-// * -// * The value of the key will be updated only if it's latest version equals the -// * specified version argument.
-// * If the key doesn't exist, the version checking will be ignored, and key will -// * be created with a new sequence number as id.
-// * It also could specify the version argument to -1 to ignore the version -// * checking. -// *

-// * If updating is performed, the version of the key increase by 1.
-// * If creating is performed, the version of the key initialize by 0.
-// * -// * @param key The key of data; -// * @param value The value of data; -// * @param version The expected version of the key. -// * @return The new version of the key.
-// * If the key is new created success, then return 0;
-// * If the key is updated success, then return the new version;
-// * If this operation fail by version checking or other reason, then -// * return -1; -// */ -// @Override -// public long setValue(Bytes key, BytesValue value, long version) { -// byte[] bytesValue = BinaryProtocol.encode(value, BytesValue.class); -// long v = dataset.setValue(key, bytesValue, version); -// if (v > -1) { -// changedListener.onChanged(key, value, v); -// } -// return v; -// } -// -// /** -// * Return the latest version entry associated the specified key; If the key -// * doesn't exist, then return -1; -// * -// * @param key -// * @return -// */ -// @Override -// public long getVersion(Bytes key) { -// return dataset.getVersion(key); -// } -// -// /** -// * return the latest version's value; -// * -// * @param key -// * @return return null if not exist; -// */ -// @Override -// public BytesValue getValue(Bytes key) { -// byte[] bytesValue = dataset.getValue(key); -// if (bytesValue == null) { -// return null; -// } -// return BinaryProtocol.decodeAs(bytesValue, BytesValue.class); -// } -// -// /** -// * Return the specified version's value; -// * -// * @param key -// * @param version -// * @return return null if not exist; -// */ -// @Override -// public BytesValue getValue(Bytes key, long version) { -// byte[] bytesValue = dataset.getValue(key, version); -// if (bytesValue == null) { -// return null; -// } -// return BinaryProtocol.decodeAs(bytesValue, BytesValue.class); -// } -// -// @Override -// public long getDataCount() { -// return dataset.getDataCount(); -// } -// -// @Override -// public long setValue(String key, BytesValue value, long version) { -// byte[] bytesValue = BinaryProtocol.encode(value, BytesValue.class); -// return dataset.setValue(key, bytesValue, version); -// } -// -// @Override -// public BytesValue getValue(String key, long version) { -// byte[] bytesValue = dataset.getValue(key, version); -// if (bytesValue == null) { -// return null; -// } -// return BinaryProtocol.decodeAs(bytesValue, BytesValue.class); -// } -// -// @Override -// public BytesValue getValue(String key) { -// byte[] bytesValue = dataset.getValue(key); -// if (bytesValue == null) { -// return null; -// } -// return BinaryProtocol.decodeAs(bytesValue, BytesValue.class); -// } -// -// @Override -// public long getVersion(String key) { -// return dataset.getVersion(key); -// } -// -// @Override -// public DataEntry getDataEntry(String key) { -// return new VersioningKVEntryWraper(dataset.getDataEntry(key)); -// } -// -// @Override -// public DataEntry getDataEntry(String key, long version) { -// return new VersioningKVEntryWraper(dataset.getDataEntry(key, version)); -// } -// } - -// private static interface DataChangedListener { -// -// void onChanged(Bytes key, BytesValue value, long newVersion); -// -// } - -// private static class VersioningKVEntryWraper implements DataEntry { -// -// private DataEntry kv; -// -// public VersioningKVEntryWraper(DataEntry kv) { -// this.kv = kv; -// } -// -// @Override -// public String getKey() { -// return kv.getKey().toUTF8String(); -// } -// -// @Override -// public long getVersion() { -// return kv.getVersion(); -// } -// -// @Override -// public BytesValue getValue() { -// return BinaryProtocol.decodeAs(kv.getValue(), BytesValue.class); -// } -// -// } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccountHeader.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccountHeader.java deleted file mode 100644 index 94faeb6a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccountHeader.java +++ /dev/null @@ -1,12 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.binaryproto.DataField; -//import com.jd.blockchain.ledger.BlockchainIdentity; -//import com.jd.blockchain.ledger.MerkleSnapshot; -// -//public interface MerkleAccountHeader extends MerkleSnapshot { -// -// @DataField(order = 1, refContract = true) -// BlockchainIdentity getID(); -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataCluster.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataCluster.java deleted file mode 100644 index 41339c58..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataCluster.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Map; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.MerkleSnapshot; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Transactional; - -public class MerkleDataCluster implements Transactional, MerkleSnapshot { - - private boolean readonly; - - private MerkleDataSet rootDS; - - private Map partitions; - - /** - * Create an empty readable {@link MerkleDataCluster} instance; - */ - public MerkleDataCluster(CryptoSetting setting, Bytes keyPrefix, ExPolicyKVStorage exPolicyStorage, - VersioningKVStorage versioningStorage) { - this(null, setting, keyPrefix, exPolicyStorage, versioningStorage, false); - } - - /** - * Create an {@link MerkleDataCluster} instance; - * - * @param rootHash root hash of this {@link MerkleDataCluster} instance; - * @param readonly whether read only; - */ - public MerkleDataCluster(HashDigest rootHash, CryptoSetting setting, Bytes keyPrefix, - ExPolicyKVStorage exPolicyStorage, VersioningKVStorage versioningStorage, boolean readonly) { - this.rootDS = new MerkleDataSet(rootHash, setting, keyPrefix, exPolicyStorage, versioningStorage, readonly); - } - - @Override - public HashDigest getRootHash() { - return rootDS.getRootHash(); - } - - @Override - public boolean isUpdated() { - return rootDS.isUpdated(); - } - -// public VersioningMap getPartition(Bytes name) { -// return getPartition(name, false); -// } -// -// public VersioningMap getPartition(Bytes name, boolean create) { -// -// } -// -// public VersioningMap createPartition(Bytes name) { -// -// } - - @Override - public void commit() { - // TODO Auto-generated method stub - - } - - @Override - public void cancel() { - // TODO Auto-generated method stub - - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataEntry.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataEntry.java deleted file mode 100644 index 15de35b5..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataEntry.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.DataEntry; - -public interface MerkleDataEntry { - - DataEntry getData(); - - MerkleProof getProof(); -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder.java deleted file mode 100644 index 1b4cb0f7..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.core.MerkleTree.DataNode; -import com.jd.blockchain.utils.Bytes; - -public interface MerkleDataNodeEncoder { - - byte getFormatVersion(); - - DataNode create(short hashAlgorithm, long sn, Bytes key, long version, byte[] hashedData); - - DataNode resolve(byte[] bytes); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder_V0.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder_V0.java deleted file mode 100644 index aa47aa6f..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder_V0.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.ledger.core.MerkleTree.DataNode; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.NumberMask; - -/** - * The first version of the DataNode binary sequence encoder, which's version - * number is 0. - * - *

- * This version of DataNode binary sequence is composed of sn(8 bytes), - * key(variable size), version(8 bytes) and node hash(32 bytes for SHA256); - * - *

- * In this version, the node hash is computed from bytes sequence composing of - * sn, key, version and original value of the key; - * - *

- * For the purpose of upgrading the version of DataNode binary format, we use - * the first byte of the binary sequence as the tag to identify the version of - * DataNode binary format, and reduce the maximum value of the valid range of SN - * to 2^56.
- * Other versions of the implementation also follow the above rules, the version - * of the data node binary format is marked from 0, incremented by 1. - * - * @author huanghaiquan - * - */ -class MerkleDataNodeEncoder_V0 implements MerkleDataNodeEncoder { - - @Override - public byte getFormatVersion() { - return 0; - } - - @Override - public DataNode resolve(byte[] bytes) { - if (bytes[0] != getFormatVersion()) { - throw new IllegalArgumentException("Unsupported version of data node bytes sequence[" + bytes[0] + "]! "); - } - - // resolve SN; - byte[] snBytes = new byte[8]; - snBytes[0] = 0x0; - System.arraycopy(bytes, 1, snBytes, 1, 7); - long sn = BytesUtils.toLong(snBytes); - - // skip bytes of SN; - int offset = 8; - - // byte[] keyBytes = BytesEncoding.read(NumberMask.SHORT, in); - // String key = BytesUtils.toString(keyBytes); - int keySize = NumberMask.SHORT.resolveMaskedNumber(bytes, offset); - offset += NumberMask.SHORT.getMaskLength(keySize); - byte[] keyBytes = new byte[keySize]; - System.arraycopy(bytes, offset, keyBytes, 0, keySize); - offset += keySize; - // String key = BytesUtils.toString(keyBytes); - Bytes key = new Bytes(keyBytes); - - // long version = BytesUtils.readLong(in); - long version = BytesUtils.toLong(bytes, offset); - offset += 8; - - // byte[] dataHashBytes = BytesEncoding.read(NumberMask.SHORT, in); - int hashSize = NumberMask.TINY.resolveMaskedNumber(bytes, offset); - offset += NumberMask.TINY.getMaskLength(hashSize); - byte[] nodeHashBytes = new byte[hashSize]; - System.arraycopy(bytes, offset, nodeHashBytes, 0, hashSize); - offset += hashSize; - HashDigest nodeHash = new HashDigest(nodeHashBytes); - return new DataNode(nodeHash, sn, key, version, null, bytes); - } - - @Deprecated - @Override - public DataNode create(short hashAlgorithm, long sn, Bytes key, long version, byte[] value) { - // Header is composed of sn, key and version; - // So the size of header is: 8 + "mask of key size" + "key bytes" + 8; - int keySize = key.size(); - int maskSize = NumberMask.SHORT.getMaskLength(keySize); - - int headerSize = 8 + maskSize + keySize + 8; - byte[] headerBytes = new byte[headerSize]; - - int offset = 0; - // write sn; - offset += BytesUtils.toBytes(sn, headerBytes, 0); - - // write the size of key bytes; - NumberMask.SHORT.writeMask(keySize, headerBytes, offset); - offset += maskSize; - - // write the key bytes; - offset += key.copyTo(headerBytes, offset, keySize); - - // version; - offset += BytesUtils.toBytes(version, headerBytes, offset); - - // compute node hash from the combination of header and data value; - byte[] dataBytes = BytesUtils.concat(headerBytes, value); - - HashFunction hashFunc = Crypto.getHashFunction(hashAlgorithm); - HashDigest dataNodeHash = hashFunc.hash(dataBytes); - - // build bytes of data node, which is composed of sn, key, version and node - // hash; - int hashMaskSize = NumberMask.TINY.getMaskLength(dataNodeHash.size()); - int dataNodeSize = headerSize + hashMaskSize + dataNodeHash.size(); - byte[] nodeBytes = new byte[dataNodeSize]; - - offset = 0; - System.arraycopy(headerBytes, 0, nodeBytes, offset, headerSize); - offset += headerSize; - NumberMask.TINY.writeMask(dataNodeHash.size(), nodeBytes, offset); - offset += hashMaskSize; - System.arraycopy(dataNodeHash.toBytes(), 0, nodeBytes, offset, dataNodeHash.size()); - - // No data hash has been computed and record in this old version of - // implementation; - return new DataNode(dataNodeHash, sn, key, version, null, nodeBytes); - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder_V1.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder_V1.java deleted file mode 100644 index 929e7e40..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoder_V1.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.ledger.core.MerkleTree.DataNode; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.NumberMask; - -/** - * The second version of the DataNode binary sequence encoder, which's version - * number is 1. - * - *

- * This version of DataNode binary sequence is composed of sn(8 bytes), - * key(variable size), version(8 bytes), hash of original value the key, and - * node hash; - * - *

- * In this version, the node hash is computed from bytes sequence composing of - * sn, key, version , hash of original value of the key; - * - *

- * For the purpose of upgrading the version of DataNode binary format, we use - * the first byte of the binary sequence as the tag to identify the version of - * DataNode binary format, and reduce the maximum value of the valid range of SN - * to 2^56.
- * Other versions of the implementation also follow the above rules, the version - * of the data node binary format is marked from 0, incremented by 1. - * - * @author huanghaiquan - * - */ -class MerkleDataNodeEncoder_V1 implements MerkleDataNodeEncoder { - - @Override - public byte getFormatVersion() { - return 1; - } - - /** - * Parse DataNode from it's bytes sequence; - *

- * the bytes sequence is: sn + key + version + data_hash; - * - * @param bytes - * @return - */ - @Override - public DataNode resolve(byte[] bytes) { - if (bytes[0] != getFormatVersion()) { - throw new IllegalArgumentException("Unsupported version of data node bytes sequence[" + bytes[0] + "]! "); - } - - // resolve SN; - byte[] snBytes = new byte[8]; - snBytes[0] = 0x0; - System.arraycopy(bytes, 1, snBytes, 1, 7); - long sn = BytesUtils.toLong(snBytes); - - // skip bytes of SN; - int offset = 8; - - // resolve key of data; - // First, resolve the number mask of the key size; - // Second, read the key bytes; - int keySize = NumberMask.SHORT.resolveMaskedNumber(bytes, offset); - offset += NumberMask.SHORT.getMaskLength(keySize); - byte[] keyBytes = new byte[keySize]; - System.arraycopy(bytes, offset, keyBytes, 0, keySize); - offset += keySize; - Bytes key = new Bytes(keyBytes); - - // Resolve version of key; - long version = BytesUtils.toLong(bytes, offset); - offset += 8; - - // resovle data hash; - int dataHashSize = NumberMask.TINY.resolveMaskedNumber(bytes, offset); - offset += NumberMask.TINY.getMaskLength(dataHashSize); - byte[] dataHashBytes = new byte[dataHashSize]; - System.arraycopy(bytes, offset, dataHashBytes, 0, dataHashSize); - offset += dataHashSize; - HashDigest dataHash = new HashDigest(dataHashBytes); - - // resovle node hash; - int nodeHashSize = NumberMask.TINY.resolveMaskedNumber(bytes, offset); - offset += NumberMask.TINY.getMaskLength(nodeHashSize); - byte[] nodeHashBytes = new byte[nodeHashSize]; - System.arraycopy(bytes, offset, nodeHashBytes, 0, nodeHashSize); - offset += nodeHashSize; - HashDigest nodeHash = new HashDigest(nodeHashBytes); - - return new DataNode(nodeHash, sn, key, version, dataHash, bytes); - } - - public DataNode newDataNode(short hashAlgorithm, long sn, Bytes key, long version, HashDigest dataHash) { - HashFunction hashFunc = Crypto.getHashFunction(hashAlgorithm); - return create(hashFunc, sn, key, version, dataHash); - } - - @Override - public DataNode create(short hashAlgorithm, long sn, Bytes key, long version, byte[] data) { - HashFunction hashFunc = Crypto.getHashFunction(hashAlgorithm); - HashDigest dataHash = hashFunc.hash(data); - - return create(hashFunc, sn, key, version, dataHash); - } - - /** - * Data node's bytes sequence is composited by header( reference: - * {@link #buildKeyHeaderBytes(long, Bytes, long)} ) and data hash; - * - *

- * In general, the bytes sequence is: sn + key + version + data_hash + - * node_hash; - * - * @param hashFunc - * @param sn - * @param key - * @param version - * @param dataHash - * @return - */ - private DataNode create(HashFunction hashFunc, long sn, Bytes key, long version, HashDigest dataHash) { - byte[] headerBytes = buildKeyHeaderBytes(sn, key, version); - int headerSize = headerBytes.length; - - // 单独对头部和数据进行哈希,以便在提供 Merkle 证明时能够不必传递原始数据即可进行哈希验证; - HashDigest headerHash = hashFunc.hash(headerBytes); - byte[] dataHashBytes = BytesUtils.concat(headerHash.getRawDigest(), dataHash.getRawDigest()); - - HashDigest dataNodeHash = hashFunc.hash(dataHashBytes); - - int dataHashSize = dataHash.size(); - int nodeHashSize = dataNodeHash.size(); - int dataHashMaskSize = NumberMask.TINY.getMaskLength(dataHashSize); - int nodeHashMaskSize = NumberMask.TINY.getMaskLength(nodeHashSize); - int nodeSize = headerSize + dataHashMaskSize + dataHashSize + nodeHashMaskSize + nodeHashSize; - byte[] nodeBytes = new byte[nodeSize]; - - // write header; - int offset = 0; - System.arraycopy(headerBytes, 0, nodeBytes, offset, headerSize); - offset += headerSize; - - // write data hash; - NumberMask.TINY.writeMask(dataHashSize, nodeBytes, offset); - offset += dataHashMaskSize; - System.arraycopy(dataHash.toBytes(), 0, nodeBytes, offset, dataHashSize); - offset += dataHashSize; - - // write node hash; - NumberMask.TINY.writeMask(nodeHashSize, nodeBytes, offset); - offset += nodeHashMaskSize; - System.arraycopy(dataNodeHash.toBytes(), 0, nodeBytes, offset, nodeHashSize); - - // set format version; - nodeBytes[0] = getFormatVersion(); - - return new DataNode(dataNodeHash, sn, key, version, dataHash, nodeBytes); - } - - /** - * Header is composited by sn + key + version; Bytes sequence: sn_size(8) + - * number_mask_of_key_size + key_bytes + version_size(8); - * - * @param sn - * @param key - * @param version - * @return - */ - private static byte[] buildKeyHeaderBytes(long sn, Bytes key, long version) { - int keySize = key.size(); - int maskSize = NumberMask.SHORT.getMaskLength(keySize); - - // Size Of header = sn + key + version; - // sn_size(8) + mask_size + key_size + version_size(8); - int headerSize = 8 + maskSize + keySize + 8; - byte[] headerBytes = new byte[headerSize]; - - // write bytes of sn; - int offset = 0; - offset += BytesUtils.toBytes(sn, headerBytes, 0); - - // write bytes of key mask; - NumberMask.SHORT.writeMask(keySize, headerBytes, offset); - offset += maskSize; - - // write bytes of key; - offset += key.copyTo(headerBytes, offset, keySize); - - // write bytes of version; - offset += BytesUtils.toBytes(version, headerBytes, offset); - - return headerBytes; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProofException.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProofException.java deleted file mode 100644 index 1dd50173..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProofException.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.ledger.core; - -/** - * 默克尔证明异常; - *

- * 表示 {@link MerkleTree} 在处理数据时数据无法通过校验,潜在的原因可能是数据已被修改或篡改; - * - * @author huanghaiquan - * - */ -public class MerkleProofException extends RuntimeException { - - private static final long serialVersionUID = 4110511167046780109L; - - public MerkleProofException(String message) { - super(message); - } - - public MerkleProofException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProvable.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProvable.java deleted file mode 100644 index b41e6856..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProvable.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.MerkleSnapshot; -import com.jd.blockchain.utils.Bytes; - -public interface MerkleProvable extends MerkleSnapshot { - - /** - * Get the merkle proof of the latest version of specified key;
- * - * The proof doesn't represent the latest changes until do - * committing({@link #commit()}). - * - * @param key - * @return Return the {@link MerkleProof} instance, or null if the key doesn't - * exist. - */ - MerkleProof getProof(Bytes key); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleSequenceSNGenerator.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleSequenceSNGenerator.java deleted file mode 100644 index e61a3f71..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleSequenceSNGenerator.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.concurrent.atomic.AtomicLong; - -import com.jd.blockchain.utils.Bytes; - -public class MerkleSequenceSNGenerator implements SNGenerator { - - private AtomicLong sn; - - public MerkleSequenceSNGenerator(MerkleTree merkleTree) { - this.sn = new AtomicLong(merkleTree.getMaxSn() + 1); - } - - @Override - public long generate(Bytes key) { - return sn.getAndIncrement(); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTree.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTree.java deleted file mode 100644 index b34cf9fe..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTree.java +++ /dev/null @@ -1,1536 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinTask; -import java.util.concurrent.RecursiveTask; -import java.util.concurrent.atomic.AtomicLong; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.MerkleDataNode; -import com.jd.blockchain.ledger.MerkleNode; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Transactional; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesSerializable; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.NumberMask; - -/** - * 默克尔树; - *

- * 树的level是按照倒置的方式计算,而不是以根节点的距离衡量,即叶子节点的 level 是 0;
- * 所有的数据的哈希索引都以叶子节点进行记录;
- * 每一个数据节点都以标记一个序列号(Sequence Number, 缩写为 SN),并按照序列号的大小统一地在 level 0 - * 上排列,并填充从根节点到数据节点的所有路径节点;
- * 随着数据节点的增加,整棵树以倒置方式向上增长(根节点在上,叶子节点在下),此设计带来显著特性是已有节点的信息都可以不必修改; - * - *

- * 注:此实现不是线程安全的;
- * 但由于对单个账本中的写入过程被设计为同步写入,因而非线程安全的设计并不会影响在此场景下的使用,而且由于省去了线程间同步操作,反而提升了性能; - * - * @author huanghaiquan - * - */ -public class MerkleTree implements Transactional { - - public static final int TREE_DEGREE = 16; - - public static final int MAX_LEVEL = 14; - - // 正好是 2 的 56 次方(7字节),将 SN 8个字节中的首个字节预留作为 DataNode 的编码格式版本标记; - public static final long MAX_DATACOUNT = power(TREE_DEGREE, MAX_LEVEL); - - public static final long MAX_SN = MAX_DATACOUNT - 1; - - public static final String NODE_PREFIX = "MKT://"; - - public static final String PATH_SEPERATOR = "/"; - - public static final boolean PARALLEL; - - static { - // get property from System; - PARALLEL = Boolean.getBoolean("parallel-merkle"); - System.out.println("------ [[ parallel-merkle=" + PARALLEL + " ]] -----"); - } - - private final Bytes keyPrefix; - - private CryptoSetting setting; - - private ExPolicyKVStorage kvStorage; - - private boolean readonly; - - private SortedMap updatedDataNodes = Collections.synchronizedSortedMap(new TreeMap<>()); - - private PathNode root; - - /** - * Merkle树的根哈希; - * - * @return - */ - public HashDigest getRootHash() { - return root.getNodeHash(); - } - - /** - * 当前 Merkle 数据记录的数据节点的总数; - * - * @return - */ - public long getDataCount() { - return root.getDataCount(); - } - - /** - * 节点的层级; - *

- * 叶子节点(即数据节点)的层级为 0;每一级父节点的层级加 1 ; - * - * @return - */ - public int getLevel() { - return root.getLevel(); - } - - /** - * 构建空的树; - * - * @param kvStorage - */ - public MerkleTree(CryptoSetting setting, String keyPrefix, ExPolicyKVStorage kvStorage) { - this(null, setting, Bytes.fromString(keyPrefix), kvStorage, false); - } - - /** - * 构建空的树; - * - * @param kvStorage - */ - public MerkleTree(CryptoSetting setting, Bytes keyPrefix, ExPolicyKVStorage kvStorage) { - this(null, setting, keyPrefix, kvStorage, false); - } - - // /** - // * 创建一颗可写的 Merkle 树; - // * - // * @param rootHash - // * 节点的根Hash; 如果指定为 null,则实际上创建一个空的 Merkle Tree; - // * @param verifyOnLoad - // * 从外部存储加载节点时是否校验节点的哈希; - // * @param kvStorage - // * 保存 Merkle 节点的存储服务; - // */ - // public MerkleTree(HashDigest rootHash, CryptoSetting setting, - // ExistentialKVStorage kvStorage) { - // this(rootHash, setting, kvStorage, false); - // } - - /** - * 创建 Merkle 树; - * - * @param rootHash 节点的根Hash; 如果指定为 null,则实际上创建一个空的 Merkle Tree; - * @param verifyOnLoad 从外部存储加载节点时是否校验节点的哈希; - * @param kvStorage 保存 Merkle 节点的存储服务; - * @param readonly 是否只读; - */ - public MerkleTree(HashDigest rootHash, CryptoSetting setting, String keyPrefix, ExPolicyKVStorage kvStorage, - boolean readonly) { - this(rootHash, setting, Bytes.fromString(keyPrefix), kvStorage, readonly); - } - - /** - * 创建 Merkle 树; - * - * @param rootHash 节点的根Hash; 如果指定为 null,则实际上创建一个空的 Merkle Tree; - * @param verifyOnLoad 从外部存储加载节点时是否校验节点的哈希; - * @param kvStorage 保存 Merkle 节点的存储服务; - * @param readonly 是否只读; - */ - public MerkleTree(HashDigest rootHash, CryptoSetting setting, Bytes keyPrefix, ExPolicyKVStorage kvStorage, - boolean readonly) { - this.setting = setting; - this.keyPrefix = keyPrefix; - this.kvStorage = kvStorage; - this.readonly = readonly; - if (rootHash == null) { - root = new PathNode(setting.getHashAlgorithm(), 0, (byte) 1, 0); - } else { - PathNode rootNode = loadPathNode(rootHash, setting.getAutoVerifyHash()); - if (rootNode == null) { - throw new IllegalStateException( - "The root path node[" + Base58Utils.encode(rootHash.toBytes()) + "] not exist!"); - } - if (rootNode.getStartingSN() != 0) { - String hashStr = Base58Utils.encode(rootNode.getNodeHash().toBytes()); - throw new MerkleProofException(String.format( - "The starting sn of the specified merkle root node is not zero! --[RootNodeHash=%s]", - hashStr)); - } - this.root = rootNode; - } - } - - /** - * 返回数据的默克尔证明; - * - *

- * 如果不存在,则返回 null; - *

- * 如果 sn 超出范围,则引发 {@link IndexOutOfBoundsException} ; - * - * @param sn 数据的序列号; - * @return 默克尔证明的实例; - */ - public MerkleProof getProof(long sn) { - MerkleNode[] nodePath = new MerkleNode[root.level + 1]; - MerkleDataNode dataNode = seekPath(sn, nodePath); - if (dataNode == null) { - return null; - } - for (int i = 0; i < nodePath.length; i++) { - if (i < nodePath.length - 1) { - // PathNode will be changed on updating data; - // So record the path info with the immutable ProofNodeEntry instead; - PathNode n = (PathNode) nodePath[i]; - ProofNodeEntry p = new ProofNodeEntry(); - p.nodeHash = n.getNodeHash(); - p.level = n.getLevel(); - p.dataCount = n.getDataCount(); - p.startingSN = n.getStartingSN(); - nodePath[i] = p; - } - } - return new MerkleProofImpl(sn, nodePath); - } - - /** - * 以指定序号建立对指定键值的索引; - *

- * - *

- * 此方法不会立即更新整棵默克尔树,直到方法 {@link #commit()} 被调用; - * - *

- * 注:默克尔树只保存指定数据的哈希以及关联的键,而不会保存数据原文,因此调用者需要自己处理对数据的存储;
- * 此外,哈希计算是把键和数据内容拼接一起进行计算的; - * - * @param sn 与此数据唯一相关的序列号;sn 必须大于等于 0 ; - * @param key 与此数据唯一相关的键; - * @param version - * @param hashedData 要参与哈希计算的数据内容;注:此参数值并不会被默克尔树保存; - * @return - */ - public MerkleDataNode setData(long sn, String key, long version, byte[] hashedData) { - return setData(sn, Bytes.fromString(key), version, hashedData); - } - - /** - * 以指定序号建立对指定键值的索引; - *

- * - *

- * 此方法不会立即更新整棵默克尔树,直到方法 {@link #commit()} 被调用; - * - *

- * 注:默克尔树只保存指定数据的哈希以及关联的键,而不会保存数据原文,因此调用者需要自己处理对数据的存储;
- * 此外,哈希计算是把键和数据内容拼接一起进行计算的; - * - * @param sn 与此数据唯一相关的序列号;sn 必须大于等于 0 ; - * @param key 与此数据唯一相关的键; - * @param version - * @param hashedData 要参与哈希计算的数据内容;注:此参数值并不会被默克尔树保存; - * @return - */ - public MerkleDataNode setData(long sn, Bytes key, long version, byte[] hashedData) { - if (readonly) { - throw new IllegalStateException("This merkle tree is readonly!"); - } - if (sn < 0) { - throw new IllegalArgumentException("The sn is negative!"); - } - if (sn > MAX_SN) { - throw new IllegalArgumentException("The sn is great than MAX[" + MAX_SN + "]!"); - } - DataNode dataNode = MerkleTreeEncoder.LATEST_DATANODE_ENCODER.create(setting.getHashAlgorithm(), sn, key, - version, hashedData); - updatedDataNodes.put(sn, dataNode); - return dataNode; - } - - public MerkleDataNode getData(long sn) { - DataNode dataNode = updatedDataNodes.get(sn); - if (dataNode != null) { - return dataNode; - } - return seekPath(sn, null); - } - - /** - * Return the max sequence number in all data nodes;
- * - * Return -1 if no data node existed; - * - * @return - */ - public long getMaxSn() { - DataNode maxDataNode = getMaxDataNode(); - if (maxDataNode == null) { - return -1; - } - return maxDataNode.sn; - } - - private DataNode getMaxDataNode() { - MerkleNode node = root; - PathNode pathNode; - int idx = -1; - while (node.getLevel() > 0) { - pathNode = (PathNode) node; - // find the last child, because all children are ascension sorted by sn; - for (idx = pathNode.childrenHashes.length - 1; idx > -1; idx--) { - if (pathNode.childrenHashes[idx] != null) { - break; - } - } - if (idx == -1) { - // no child; - return null; - } - // if child node have been loaded, then load it; - if (pathNode.children[idx] == null) { - if (pathNode.getLevel() > 1) { - // load path node; - PathNode child = loadPathNode(pathNode.childrenHashes[idx], setting.getAutoVerifyHash()); - pathNode.attachChildNode(child, idx); - } else { - DataNode child = loadDataNode(pathNode.childrenHashes[idx], setting.getAutoVerifyHash()); - pathNode.attachChildNode(child, idx); - } - } - node = pathNode.children[idx]; - } - return (DataNode) node; - } - - @Override - public boolean isUpdated() { - return updatedDataNodes.size() > 0; - } - - /** - * 回滚上一次提交以来的变更; - */ - @Override - public void cancel() { - updatedDataNodes.clear(); - } - - /** - * 根据新修改重新计算哈希,并将产生变更的节点保存到存储服务;
- * - * 注:调用者在执行批量更改时,不应该在每一次更改之后立即调用此方法,而是完成批量操作之后,仅调用此一次 commit 操作,这样可以更改的中间重复地对 - * hash 节点进行计算,达到性能优化的目的; - */ - @Override - public void commit() { - if (!isUpdated()) { - return; - } - long sn; - PathNode leafPathNode = null; - // 按照升序处理; - Set updatedLeafNodes = new HashSet<>(); - for (Entry entry : updatedDataNodes.entrySet()) { - sn = entry.getKey().longValue(); - if (leafPathNode == null || sn >= leafPathNode.startingSN + leafPathNode.interval) { - leafPathNode = extendPaths(sn); - } - leafPathNode.setData(sn, entry.getValue()); - updatedLeafNodes.add(leafPathNode); - } - - // 遍历涉及更改的所有路径节点,重新计算根节点哈希; - if (PARALLEL) { - concurrentRehash(updatedLeafNodes); - } else { - rehash(updatedLeafNodes); - } - - // List updatedNodes = Collections.synchronizedList(new - // LinkedList<>()); - // rehash(root, updatedNodes); - // - // // 把更改的节点写入到存储服务; - // for (AbstractMerkleNode merkleNode : updatedNodes) { - // String key = encodeNodeKey(merkleNode.getNodeHash()); - // boolean nx = kvStorage.set(key, merkleNode.toBytes(), ExPolicy.NOT_EXISTING); - // if (!nx) { - // throw new LedgerException("Merkle node already exist!"); - // } - // } - - // 清空缓存; - updatedDataNodes.clear(); - } - - private void saveNode(AbstractMerkleNode merkleNode) { - Bytes key = encodeNodeKey(merkleNode.getNodeHash()); - boolean nx = kvStorage.set(key, merkleNode.toBytes(), ExPolicy.NOT_EXISTING); - if (!nx) { - throw new LedgerException("Merkle node already exist!"); - } - } - - private void rehash(Set updatedPathNodes) { - - Set updatedParentNodes = new HashSet<>(); - - for (PathNode pathNode : updatedPathNodes) { - AbstractMerkleNode[] children = pathNode.children; - HashDigest[] childrenHashes = pathNode.childrenHashes; - boolean updated = false; - for (int i = 0; i < children.length; i++) { - if (children[i] == null) { - continue; - } - HashDigest origChildHash = childrenHashes[i]; - HashDigest newChildHash = children[i].getNodeHash(); - if (origChildHash == null) { - childrenHashes[i] = newChildHash; - updated = true; - if (pathNode.level == 1) { - // 在叶子节点上发现新增加了数据节点; - pathNode.increaseDataCount(1); - // 同时保存新增的数据节点; - saveNode(children[i]); - } - } else if (!origChildHash.equals(newChildHash)) { - childrenHashes[i] = newChildHash; - updated = true; - if (pathNode.level == 1) { - // 同时保存更新的数据节点; - saveNode(children[i]); - } - } - } - - if (updated) { - // 计算节点哈希: - pathNode.rehash(); - - saveNode(pathNode); - - if (pathNode.parent != null) { - updatedParentNodes.add((PathNode) pathNode.parent); - } - } - } - - if (updatedParentNodes.size() > 0) { - rehash(updatedParentNodes); - } - } - - private void concurrentRehash(Set updatedPathNodes) { - - // Set updatedParentNodes = new HashSet<>(); - // List tasks = new ArrayList<>(); - // for (PathNode pathNode : updatedPathNodes) { - // RehashTask task = new RehashTask(pathNode, kvStorage); - // ForkJoinPool.commonPool().execute(task); - // tasks.add(task); - // } - PathNode[] nodes = updatedPathNodes.toArray(new PathNode[updatedPathNodes.size()]); - RehashTask task = new RehashTask(nodes, this, kvStorage); - List updatedNodes = ForkJoinPool.commonPool().invoke(task); - Set updatedParentNodes = new HashSet<>(); - for (PathNode pathNode : updatedNodes) { - if (pathNode.parent != null) { - updatedParentNodes.add((PathNode) pathNode.parent); - } - } - if (updatedParentNodes.size() > 0) { - rehash(updatedParentNodes); - } - } - - /** - * @author huanghaiquan - * - */ - private static class RehashTask extends RecursiveTask> { - - private static final long serialVersionUID = -9165021733321713070L; - - private MerkleTree tree; - - private PathNode[] pathNodes; - - private ExPolicyKVStorage kvStorage; - - private static int TASK_THRESHOLD = 100; - - public RehashTask(PathNode[] pathNodes, MerkleTree tree, ExPolicyKVStorage kvStorage) { - this.tree = tree; - this.pathNodes = pathNodes; - this.kvStorage = kvStorage; - } - - @Override - protected List compute() { - int count = pathNodes.length; - if (count > TASK_THRESHOLD) { - PathNode[] nodes1 = new PathNode[count / 2]; - PathNode[] nodes2 = new PathNode[count - nodes1.length]; - System.arraycopy(pathNodes, 0, nodes1, 0, nodes1.length); - System.arraycopy(pathNodes, nodes1.length, nodes2, 0, nodes2.length); - RehashTask task1 = new RehashTask(nodes1, tree, kvStorage); - RehashTask task2 = new RehashTask(nodes2, tree, kvStorage); - ForkJoinTask.invokeAll(task1, task2); - List updatedNodes = task1.join(); - updatedNodes.addAll(task2.join()); - return updatedNodes; - } else { - List updatedNodes = new ArrayList<>(); - for (PathNode pathNode : pathNodes) { - if (rehash(pathNode)) { - updatedNodes.add(pathNode); - } - } - return updatedNodes; - } - } - - private boolean rehash(PathNode pathNode) { - AbstractMerkleNode[] children = pathNode.children; - HashDigest[] childrenHashes = pathNode.childrenHashes; - boolean updated = false; - for (int i = 0; i < children.length; i++) { - if (children[i] == null) { - continue; - } - HashDigest origChildHash = childrenHashes[i]; - HashDigest newChildHash = children[i].getNodeHash(); - if (origChildHash == null) { - childrenHashes[i] = newChildHash; - updated = true; - if (pathNode.level == 1) { - // 在叶子节点上发现新增加了数据节点; - // newDataCount++; - pathNode.increaseDataCount(1); - // 同时保存新增的数据节点; - tree.saveNode(children[i]); - } - } else if (!origChildHash.equals(newChildHash)) { - childrenHashes[i] = newChildHash; - updated = true; - if (pathNode.level == 1) { - // 同时保存更新的数据节点; - tree.saveNode(children[i]); - } - } - } - - if (updated) { - // 计算节点哈希: - pathNode.rehash(); - tree.saveNode(pathNode); - - // if (pathNode.parent != null) { - // return (PathNode) pathNode.parent; - // } - return true; - } - - return false; - } - - // private void saveNode(AbstractMerkleNode merkleNode) { - // String key = encodeNodeKey(merkleNode.getNodeHash()); - // boolean nx = kvStorage.set(key, merkleNode.toBytes(), ExPolicy.NOT_EXISTING); - // if (!nx) { - // throw new LedgerException("Merkle node already exist!"); - // } - // } - - } - - /** - * 重新计算所有子节点以及自身的哈希,并返回新加入的数据节点的数量; - * - * @param pathNode 需要重新计算 hash 的路径节点; - * @param updatedNodes 用于记录已更新节点的列表; - * @return - */ - @SuppressWarnings("unused") - private int rehash(PathNode pathNode, List updatedNodes) { - // int newDataCount = 0; - boolean updated = false; - - // 先检查并更新子节点的 hash; - AbstractMerkleNode[] children = pathNode.children; - HashDigest[] childrenHashes = pathNode.childrenHashes; - - if (pathNode.level == 1) { - // 检查作为叶子的数据节点的哈希是否更新; - // 注:因为数据节点加入时已经进行过计算了它本身的哈希,在此不需重新计算; - for (int i = 0; i < children.length; i++) { - if (children[i] == null) { - continue; - } - HashDigest origChildHash = childrenHashes[i]; - HashDigest newChildHash = children[i].getNodeHash(); - if (origChildHash == null) { - // newDataCount++; - pathNode.increaseDataCount(1); - childrenHashes[i] = newChildHash; - updated = true; - updatedNodes.add(children[i]); - } else if (!origChildHash.equals(newChildHash)) { - childrenHashes[i] = newChildHash; - updated = true; - updatedNodes.add(children[i]); - } - } - } else { - for (int i = 0; i < children.length; i++) { - if (children[i] == null) { - continue; - } - - // 递归重新计算子路径的哈希; - // 更新数据节点数量; - // newDataCount += rehash((PathNode) children[i], updatedNodes); - rehash((PathNode) children[i], updatedNodes); - - HashDigest origChildHash = childrenHashes[i]; - HashDigest newChildHash = children[i].getNodeHash(); - if (origChildHash == null || !origChildHash.equals(newChildHash)) { - childrenHashes[i] = newChildHash; - updated = true; - } - } - } - - // 如果子节点发生了更改,则重新计算当前节点的 hash; - // 注:当加入了新的数据节点,即 newDataCount > 0 时,必然地 updated > 0 - if (updated) { - // 更新数据节点的计数器; - // pathNode.dataCount += newDataCount; - - // 计算节点哈希: - pathNode.rehash(); - - updatedNodes.add(pathNode); - } - - // return newDataCount; - return 0; - } - - /** - * 加载或创建能够到达指定序号的数据节点的完整路径节点,并返回路径最末端的路径节点; - * - * @param sn - * @return - */ - private PathNode extendPaths(long sn) { - if (root.getLevel() < 0) { - throw new IllegalStateException("The level of root is negative!"); - } - if (root.getLevel() > 15) { - // 超过15会导致接下来的幂运算溢出; - throw new IllegalStateException("The level of root is out of range, and it will lead to a overflow!"); - } - if (root.startingSN != 0) { - // 根节点的起始序号应该为 0 ; - throw new IllegalStateException("The start sn of root is not zero!"); - } - - // 如果指定的序号超出当前根节点的范围,需要向上扩展根节点; - // 逻辑最大序号(logicMaxSN)满足:logicMaxSN=rootNode.startSN + rootNode.interval; - // 由于rootNode.startSN==0,所以简化为:logicMaxSN=rootNode.interval; - long logicMaxSN = -1; - PathNode rootNode = root; - while ((logicMaxSN = rootNode.interval) <= sn) { - if (rootNode.getLevel() == 15) { - throw new IllegalStateException( - "The specified starting sn exceed the upper limit[" + logicMaxSN + "]!"); - } - PathNode newRoot = new PathNode(setting.getHashAlgorithm(), rootNode.startingSN, - (byte) (rootNode.getLevel() + 1), rootNode.getDataCount()); - newRoot.attachChildNode(rootNode, 0); - rootNode = newRoot; - } - this.root = rootNode; - - // 加载或创建从根节点到目标序号 - PathNode leafPathNode = rootNode; - while (leafPathNode.level > 1) { - int index = leafPathNode.index(sn); - if (leafPathNode.children[index] == null) { - if (leafPathNode.childrenHashes[index] == null) { - // 创建新节点; - leafPathNode.newEmptyChild(setting.getHashAlgorithm(), index); - } else { - // 加载节点; - PathNode node = loadPathNode(leafPathNode.childrenHashes[index], setting.getAutoVerifyHash()); - if (node == null) { - throw new IllegalStateException("The merkle path node[" - + leafPathNode.childrenHashes[index].toBase58() + "] not exist!"); - } - leafPathNode.attachChildNode(node, index); - } - } - leafPathNode = (PathNode) leafPathNode.children[index]; - } - - return leafPathNode; - } - - /** - * 查找指定序号的数据节点,并记录该数据节点的完整路径; - * - *
- * 路径由节点数组表示,首个元素是根节点,最后一个元素是数据节点; - *

- * - * 如果 sn 超出范围,则引发 {@link IndexOutOfBoundsException} ; - * - * @param sn 数据节点的序列号; - * @param path 用于记录节点路径的列表,长度必须大于等于当前默克尔树的总的层级(即 path.length 大于等于 root.level + - * 1);
- * 如果参数为 null,则不记录; - * @return 序列号对应的数据节点;
- * 如果不存在,则返回 null,注意,此时指定的路径参数 path 依然写入了查找过程的路径; - */ - private MerkleDataNode seekPath(long sn, MerkleNode[] path) { - /* - * 如果指定的序号超出当前根节点的范围,需要向上扩展根节点; - * - * 逻辑最大序号(logicMaxSN)满足:logicMaxSN=rootNode.startSN + rootNode.interval; - * 由于rootNode.startSN==0,所以简化为:logicMaxSN=rootNode.interval; - */ - long logicMaxSN = root.interval; - if (sn < 0 || sn >= logicMaxSN) { - throw new IndexOutOfBoundsException("The specified sn is out of range!"); - } - - if (path != null && path.length < (root.level + 1)) { - throw new IllegalArgumentException("The path length is too short to contain all path nodes!"); - } - // 加载或创建从根节点到目标序号 - // List path = new ArrayList<>(); - // MerkleNode[] path = new MerkleNode[root.level + 1]; - // path.add(leafPathNode); - PathNode leafPathNode = root; - if (path != null) { - path[path.length - leafPathNode.level - 1] = leafPathNode; - } - - while (leafPathNode.level > 1) { - int index = leafPathNode.index(sn); - if (leafPathNode.children[index] == null) { - if (leafPathNode.childrenHashes[index] == null) { - // 节点不存在; - return null; - } else { - // 加载节点; - PathNode node = loadPathNode(leafPathNode.childrenHashes[index], setting.getAutoVerifyHash()); - if (node == null) { - return null; - } - leafPathNode.attachChildNode(node, index); - } - } - leafPathNode = (PathNode) leafPathNode.children[index]; - if (path != null) { - path[path.length - leafPathNode.level - 1] = leafPathNode; - } - } - - // 数据节点; - int index = leafPathNode.index(sn); - if (leafPathNode.children[index] == null) { - if (leafPathNode.childrenHashes[index] == null) { - // 节点不存在; - return null; - } else { - // 加载节点; - DataNode dataNode = loadDataNode(leafPathNode.childrenHashes[index], setting.getAutoVerifyHash()); - if (dataNode == null) { - return null; - } - leafPathNode.setData(sn, dataNode); - } - } - if (path != null) { - path[path.length - leafPathNode.children[index].getLevel() - 1] = leafPathNode.children[index]; - } - return (MerkleDataNode) leafPathNode.children[index]; - } - - private Bytes encodeNodeKey(HashDigest hashBytes) { - // return keyPrefix + hashBytes.toBase58(); - return new Bytes(keyPrefix, hashBytes.toBytes()); - } - - /** - * Load {@link AbstractMerkleNode} from storage service; - * - *

- * - * @param hashDigest - * @param verify - * @return return instance of {@link PathNode}, or null if not exist; - */ - private PathNode loadPathNode(HashDigest hashDigest, boolean verify) { - Bytes key = encodeNodeKey(hashDigest); - byte[] bytes = kvStorage.get(key); - if (bytes == null || bytes.length == 0) { - return null; - } - PathNode pathNode = PathNode.parse(bytes, verify); - if (verify && !hashDigest.equals(pathNode.getNodeHash())) { - String keyStr = hashDigest.toBase58(); - String actualHashStr = pathNode.getNodeHash().toBase58(); - throw new MerkleProofException(String.format( - "The actually hash of PathNode is not equal with it's key! -- [Key=%s][ActualHash=%s]", keyStr, - actualHashStr)); - } - return pathNode; - } - - private DataNode loadDataNode(HashDigest hashBytes, boolean verify) { - Bytes key = encodeNodeKey(hashBytes); - byte[] bytes = kvStorage.get(key); - if (bytes == null || bytes.length == 0) { - return null; - } - - DataNode dataNode = MerkleTreeEncoder.resolve(bytes); - if (verify && !hashBytes.equals(dataNode.nodeHash)) { - String keyStr = hashBytes.toBase58(); - String actualHashStr = dataNode.nodeHash.toBase58(); - throw new MerkleProofException(String.format( - "The actually hash of DataNode is not equal with it's key! -- [Key=%s][ActualHash=%s]", keyStr, - actualHashStr)); - } - return dataNode; - } - - /** - * 计算 value 的 x 次方; - *

- * 注:此方法不处理溢出;调用者需要自行规避; - * - * @param value - * @param x 大于等于 0 的整数; - * @return - */ - private static long power(long value, int x) { - if (x == 0) { - return 1; - } - long r = value; - for (int i = 1; i < x; i++) { - r *= value; - } - return r; - } - - // ================================================= - - /** - * 数据证明; - * - *

- * 数据证明是由从 Merkle Tree 的根节点出发到目标数据节点的经过的全部节点构成的一条路径; - *

- * - * @author huanghaiquan - * - */ - private static class MerkleProofImpl implements MerkleProof { - - /** - * 从根节点到数据节点的路径;
- * 路径的首个元素是根节点,最后一个原始是数据节点; - */ - private MerkleNode[] path; - - private long sn; - - private MerkleProofImpl(long sn, MerkleNode[] path) { - this.sn = sn; - this.path = path; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.MerkleProof#getSN() - */ - @Override - public long getSN() { - return sn; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.MerkleProof#getLevel() - */ - @Override - public int getLevels() { - return path[0].getLevel(); - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.MerkleProof#getHash(int) - */ - @Override - public HashDigest getHash(int level) { - return path[path.length - 1 - level].getNodeHash(); - } - - @Override - public MerkleNode getNode(int level) { - return path[path.length - 1 - level]; - } - - // @Override - // public long getStartingSN(int level) { - // return path[path.length - 1 - level].startingSN; - // } - // - // @Override - // public long getDataCount(int level) { - // return path[path.length - 1 - level].dataCount; - // } - - @Override - public String toString() { - StringBuilder strPath = new StringBuilder(NODE_PREFIX); - for (int i = 0; i < path.length; i++) { - if (i > 0) { - strPath.append(PATH_SEPERATOR); - } - strPath.append(path[i].getNodeHash().toBase58()); - } - return strPath.toString(); - } - - @Override - public int hashCode() { - return Arrays.hashCode(path); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj instanceof MerkleProofImpl) { - MerkleProofImpl proof1 = (MerkleProofImpl) obj; - if (path.length != proof1.path.length) { - return false; - } - for (int i = 0; i < path.length; i++) { - if (!path[i].equals(proof1.path[i])) { - return false; - } - } - return true; - } - return false; - } - - } - - private static class ProofNodeEntry implements MerkleNode { - - private int level; - - @SuppressWarnings("unused") - private long dataCount; - - @SuppressWarnings("unused") - private long startingSN; - - private HashDigest nodeHash; - - @Override - public HashDigest getNodeHash() { - return nodeHash; - } - - @Override - public int getLevel() { - return level; - } - - @Override - public int hashCode() { - return nodeHash.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj instanceof ProofNodeEntry) { - ProofNodeEntry node1 = (ProofNodeEntry) obj; - return this.nodeHash.equals(node1.nodeHash); - } - return false; - } - } - - /** - * Abstract node of merkle tree; - * - * @author huanghaiquan - * - */ - private static abstract class AbstractMerkleNode implements BytesSerializable, MerkleNode { - - protected HashDigest nodeHash; - - protected AbstractMerkleNode parent; - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleNode#getNodeHash() - */ - @Override - public HashDigest getNodeHash() { - return nodeHash; - } - - /** - * 直接或间接从属在该节点下的数据节点的起始序号; - * - * @return - */ - protected abstract long getStartingSN(); - - /** - * 直接或间接从属在该节点下的数据节点的数量; - * - * @return - */ - protected abstract long getDataCount(); - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleNode#getLevel() - */ - @Override - public abstract int getLevel(); - - } - - /** - * 路径节点; - * - * @author huanghaiquan - * - */ - private static class PathNode extends AbstractMerkleNode { - - /** - * 当前节点采用的 hash 算法; - */ - private short hashAlgorithm; - - /** - * 节点的起始序列号; - */ - public final long startingSN; - - /** - * 节点在 MerkleTree 中的层级; - */ - public final int level; - - /** - * 当前节点的序列号区间大小; - */ - public final long interval; - - /** - * 当前节点的直接子节点的序列号区间大小; - */ - public final long subinterval; - - /** - * nodeHash = Hash(startSn + childCount + childNodeHashes); - */ - // private HashDigest nodeHash; - - public HashDigest[] childrenHashes; - - public AbstractMerkleNode[] children; - - // private long dataCount; - private AtomicLong dataCount; - - /** - * 增加数据节点计数器;
- * 操作将级联更新到根节点; - * - * @param newCount - */ - public void increaseDataCount(int newCount) { - dataCount.addAndGet(newCount); - if (parent != null) { - ((PathNode) parent).increaseDataCount(newCount); - } - } - - /** - * 创建一个路径节点; - * - * @param hashAlgorithm 生成节点采用的哈希算法; - * @param startingSN 路径节点表示的子树的起始序列号; - * @param level 路径节点的层级深度;路径节点的深度从 1 开始往上递增(数据节点作为树的深度为 0); - * @param dataCount 路径节点表示的子树所包含的数据节点的数量; - */ - private PathNode(CryptoAlgorithm hashAlgorithm, long startingSN, int level, long dataCount) { - this(hashAlgorithm, startingSN, level, dataCount, new HashDigest[TREE_DEGREE], null); - } - - private PathNode(short hashAlgorithm, long startingSN, int level, long dataCount) { - this(hashAlgorithm, startingSN, level, dataCount, new HashDigest[TREE_DEGREE], null); - } - - private PathNode(long startingSN, int level, long dataCount, HashDigest[] childrenHashes, HashDigest nodeHash) { - this(nodeHash.getAlgorithm(), startingSN, level, dataCount, childrenHashes, nodeHash); - } - - private PathNode(CryptoAlgorithm defaultHashAlgorithm, long startingSN, int level, long dataCount, - HashDigest[] childrenHashes, HashDigest nodeHash) { - this(defaultHashAlgorithm.code(), startingSN, level, dataCount, childrenHashes, nodeHash); - } - - private PathNode(short hashAlgorithm, long startingSN, int level, long dataCount, HashDigest[] childrenHashes, - HashDigest nodeHash) { - if (startingSN < 0) { - throw new IllegalArgumentException("The specified starting sn of PathNode is negative!"); - } - if (level < 1) { - throw new IllegalArgumentException("The specified level of PathNode is less than 1!"); - } - if (dataCount < 0) { - throw new IllegalArgumentException("The specified data count of PathNode is negative!"); - } - this.hashAlgorithm = hashAlgorithm; - this.startingSN = startingSN; - this.level = level; - - this.interval = computeInterval(); - this.subinterval = computeSubinterval(); - - if (dataCount > this.interval) { - throw new IllegalArgumentException("The specified data count of PathNode exceed the upper limit!"); - } - this.dataCount = new AtomicLong(dataCount); - - this.children = new AbstractMerkleNode[TREE_DEGREE]; - - this.childrenHashes = childrenHashes; - this.nodeHash = nodeHash; - } - - public void attachChildNode(PathNode node, int index) { - if (node.level != this.level - 1) { - throw new IllegalArgumentException("The level of the attaching child node is illegal!"); - } - long expectedStartingSN = startingSN + subinterval * index; - if (expectedStartingSN != node.startingSN) { - throw new IllegalArgumentException("The starting sn of the attaching child node is illegal!"); - } - children[index] = node; - node.parent = this; - } - - public void attachChildNode(DataNode dataNode, int index) { - if (level != 1) { - throw new IllegalStateException("Cann't set data by the PathNode witch's isn't the leaf path!"); - } - children[index] = dataNode; - dataNode.parent = this; - } - - private void setData(long sn, DataNode dataNode) { - assert sn >= startingSN - && sn < startingSN + interval : "The specified sn of the DataNode exceed the upper limit!"; - - int index = (int) (sn - startingSN); - attachChildNode(dataNode, index); - } - - /** - * 计算当前节点的序列号区间大小; - * - * @return - */ - private long computeInterval() { - return power(TREE_DEGREE, level); - } - - /** - * 计算当前节点的直接子节点的序列号区间大小; - * - * @return - */ - private long computeSubinterval() { - return power(TREE_DEGREE, level - 1); - } - - /** - * 定位指定序号在此路径的子节点列表中的下标索引; - * - * @param sn - * @return - */ - private int index(long sn) { - long s = subinterval; - long offset = sn - startingSN; - return (int) ((offset - offset % s) / s); - } - - @SuppressWarnings("unused") - private PathNode newEmptyChild(CryptoAlgorithm hashAlgorithm, int index) { - return newEmptyChild(hashAlgorithm.code(), index); - } - - private PathNode newEmptyChild(short hashAlgorithm, int index) { - long newStartingSN = startingSN + subinterval * index; - PathNode child = new PathNode(hashAlgorithm, newStartingSN, (byte) (level - 1), 0); - attachChildNode(child, index); - return child; - } - - public long getStartingSN() { - return startingSN; - } - - @Override - public long getDataCount() { - return dataCount.get(); - } - - @Override - public int getLevel() { - return level; - } - - /** - * 序列化当前节点的属性;包括节点哈希、数据节点计数器、子节点哈希列表; - */ - @Override - public byte[] toBytes() { - int bodySize = getBodySize(); - int hashSize = nodeHash.size(); - int totalSize = bodySize + NumberMask.TINY.MAX_HEADER_LENGTH + hashSize; - byte[] totalBytes = new byte[totalSize]; - int offset = generateBodyBytes(totalBytes); - - offset += NumberMask.TINY.writeMask(hashSize, totalBytes, offset); - System.arraycopy(nodeHash.toBytes(), 0, totalBytes, offset, hashSize); - offset += hashSize; - return totalBytes; - } - - private int getBodySize() { - int totalSize = 8 + 4 + 8;// startingSN + level + dataCount; - HashDigest h; - for (int i = 0; i < TREE_DEGREE; i++) { - h = childrenHashes[i]; - totalSize += NumberMask.TINY.getMaskLength(h == null ? 0 : h.size()); - if (h != null) { - totalSize += h.size(); - } - } - return totalSize; - } - - private int generateBodyBytes(byte[] bodyBytes) { - int offset = 0; - offset += BytesUtils.toBytes(startingSN, bodyBytes, offset); - - offset += BytesUtils.toBytes(level, bodyBytes, offset); - - offset += BytesUtils.toBytes(getDataCount(), bodyBytes, offset); - - HashDigest h; - for (int i = 0; i < TREE_DEGREE; i++) { - h = childrenHashes[i]; - if (h == null) { - // 只写入一个字节的长度头部,值为 0; - bodyBytes[offset] = 0; - offset++; - } else { - int len = h.size(); - offset += NumberMask.TINY.writeMask(len, bodyBytes, offset); - System.arraycopy(h.toBytes(), 0, bodyBytes, offset, len); - offset += len; - } - } - - return offset; - } - - /** - * 从指定的字节数组反序列化节点; - * - * @param bytes 字节数组;合法的输入应等同于 {@link #toBytes()} 方法的输出; - * @param checkHash 是否重新计算并校验节点的哈希; - * @return - */ - private static PathNode parse(byte[] bytes, boolean checkHash) { - int offset = 0; - - long startingSN = BytesUtils.toLong(bytes, offset); - offset += 8; - - int level = BytesUtils.toInt(bytes, offset); - offset += 4; - - long dataCount = BytesUtils.toLong(bytes, offset); - offset += 8; - - HashDigest[] childrenHashes = new HashDigest[TREE_DEGREE]; - byte[] h; - for (int i = 0; i < TREE_DEGREE; i++) { - int hashSize = NumberMask.TINY.resolveMaskedNumber(bytes, offset); - offset += NumberMask.TINY.getMaskLength(hashSize); - - if (hashSize == 0) { - continue; - } - h = new byte[hashSize]; - System.arraycopy(bytes, offset, h, 0, hashSize); - offset += hashSize; - childrenHashes[i] = new HashDigest(h); - } - - int hashSize = NumberMask.TINY.resolveMaskedNumber(bytes, offset); - offset += NumberMask.TINY.getMaskLength(hashSize); - - byte[] nodeHashBytes = new byte[hashSize]; - System.arraycopy(bytes, offset, nodeHashBytes, 0, hashSize); - offset += hashSize; - - HashDigest nodeHash = new HashDigest(nodeHashBytes); - - PathNode node = new PathNode(startingSN, level, dataCount, childrenHashes, nodeHash); - if (checkHash) { - HashDigest actualHash = node.computeBodyHash(); - if (!node.nodeHash.equals(actualHash)) { - String origHashStr = node.nodeHash.toBase58(); - String actualHashStr = actualHash.toBase58(); - throw new MerkleProofException(String.format( - "The actually hash of PathNode is not equal with it's original hash! -- [OrigHash=%s][ActualHash=%s]", - origHashStr, actualHashStr)); - } - } - - return node; - } - - /** - * 重新计算并更新当前节点的哈希; - */ - public void rehash() { - this.nodeHash = computeBodyHash(); - } - - /** - * 计算节点的 hash,但不会更新 {@link #getNodeHash()} 属性; - *

- * - * 节点哈希: - * nodeHash = Hash(toBytes(startingSN) + toBytes(level) + toBytes(dataCount) + h1 + h2 + ... + h16); - * - * - * @param pathNode - * @return - */ - private HashDigest computeBodyHash() { - int totalSize = getBodySize(); - byte[] bodyBytes = new byte[totalSize]; - generateBodyBytes(bodyBytes); - HashFunction hashFunc = Crypto.getHashFunction(hashAlgorithm); - return hashFunc.hash(bodyBytes); - } - - } - - /** - * 数据节点; - * - * @author huanghaiquan - * - */ - static class DataNode extends AbstractMerkleNode implements MerkleDataNode { - - private long sn; - - private Bytes key; - - private long version; - - private byte[] nodeBytes; - - private HashDigest valueHash; - - DataNode(HashDigest nodeHash, long sn, Bytes key, long version, HashDigest valueHash, byte[] nodeBytes) { - this.sn = sn; - this.key = key; - this.version = version; - this.nodeHash = nodeHash; - this.valueHash = valueHash; - this.nodeBytes = nodeBytes; - } - - @Override - protected long getStartingSN() { - return sn; - } - - @Override - protected long getDataCount() { - return 1; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getLevel() - */ - @Override - public int getLevel() { - return 0; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getSN() - */ - @Override - public long getSN() { - return sn; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getKey() - */ - @Override - public Bytes getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getVersion() - */ - @Override - public long getVersion() { - return version; - } - - @Override - public HashDigest getValueHash() { - return valueHash; - } - - @Override - public byte[] toBytes() { - // ByteArrayOutputStream out = new ByteArrayOutputStream(); - // - // BytesUtils.writeLong(sn, out); - // - // byte[] keyBytes = BytesUtils.toBytes(key); - // BytesEncoding.write(keyBytes, NumberMask.SHORT, out); - // - // BytesUtils.writeLong(version, out); - - // int hashSize = nodeHash.size(); - // - // int totalSize = dataNodeBytes.length + NumberMask.TINY.MAX_HEADER_LENGTH + - // hashSize; - // byte[] totalBytes = new byte[totalSize]; - // - // int offset = 0; - // System.arraycopy(dataNodeBytes, 0, totalBytes, offset, dataNodeBytes.length); - // offset += dataNodeBytes.length; - - // BytesEncoding.write(nodeHash.toBytes(), NumberMask.SHORT, out); - // NumberMask.TINY.writeMask(hashSize, totalBytes, offset); - // offset += NumberMask.TINY.MAX_HEADER_LENGTH; - // - // System.arraycopy(nodeHash.toBytes(), 0, totalBytes, offset, hashSize); - - return nodeBytes; - } - - @Override - public int hashCode() { - return nodeHash.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj instanceof DataNode) { - DataNode node1 = (DataNode) obj; - return this.nodeHash.equals(node1.nodeHash); - } - return false; - } - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTreeEncoder.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTreeEncoder.java deleted file mode 100644 index a02ba65a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTreeEncoder.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import com.jd.blockchain.ledger.core.MerkleTree.DataNode; - -class MerkleTreeEncoder { - - static final MerkleDataNodeEncoder LATEST_DATANODE_ENCODER = new MerkleDataNodeEncoder_V1(); - - static final MerkleDataNodeEncoder V0_DATANODE_ENCODER = new MerkleDataNodeEncoder_V0(); - - static final List DATANODE_ENCODERS = Collections - .unmodifiableList(Arrays.asList(LATEST_DATANODE_ENCODER, V0_DATANODE_ENCODER)); - - /** - * @param bytes - * @return - */ - static DataNode resolve(byte[] bytes) { - for (MerkleDataNodeEncoder encoder : MerkleTreeEncoder.DATANODE_ENCODERS) { - if (encoder.getFormatVersion() == bytes[0]) { - return encoder.resolve(bytes); - } - } - - throw new IllegalStateException("Unsupported version of DataNode bytes sequence[" + bytes[0] + "]!"); - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MultiIDsPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MultiIDsPolicy.java deleted file mode 100644 index 20f1caab..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MultiIDsPolicy.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger.core; - -/** - * 多重身份的校验策略; - * - * @author huanghaiquan - * - */ -public enum MultiIDsPolicy { - - /** - * 至少有一个都能通过; - */ - AT_LEAST_ONE, - - /** - * 每一个都能通过; - */ - ALL - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OpeningAccessPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OpeningAccessPolicy.java deleted file mode 100644 index 8efd1d10..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OpeningAccessPolicy.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.utils.Bytes; - -/** - * 开放的访问策略;
- * - * 不做任何访问限制; - * - * @author huanghaiquan - * - */ -public class OpeningAccessPolicy implements AccountAccessPolicy { - - @Override - public boolean checkDataWriting(BlockchainIdentity account) { - return true; - } - - @Override - public boolean checkRegistering(Bytes address, PubKey pubKey) { - return true; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandle.java deleted file mode 100644 index ac3dbbec..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandle.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.Operation; - -public interface OperationHandle { - - /** - * 是否支持指定类型的操作; - * - * @param operationType - * @return - */ - Class getOperationType(); - - /** - * 同步解析和执行操作; - * - * - * @param op 操作实例; - * @param newBlockDataset 需要修改的新区块的数据集; - * @param requestContext 交易请求上下文; - * @param previousBlockDataset 新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集;注:此数据集是只读的; - * - * @param handleContext 操作上下文;` - * @param ledgerService - * @return - */ - BytesValue process(Operation op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, - LedgerQuery ledger, OperationHandleContext handleContext); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleContext.java deleted file mode 100644 index 1d837f15..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleContext.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.Operation; - -/** - * 在交易处理过程中,提供对多种交易操作处理器互相调用的机制; - * - * @author huanghaiquan - * - */ -public interface OperationHandleContext { - - void handle(Operation operation); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleRegisteration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleRegisteration.java deleted file mode 100644 index 1b783eb0..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleRegisteration.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.Operation; - -public interface OperationHandleRegisteration { - - OperationHandle getHandle(Class operationType); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataset.java deleted file mode 100644 index bd629b8a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataset.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.ParticipantDataQuery; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Transactional; - -public class ParticipantDataset implements Transactional, MerkleProvable, ParticipantDataQuery { - - static { - DataContractRegistry.register(ParticipantNode.class); - } - - private MerkleDataSet dataset; - - public ParticipantDataset(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, - VersioningKVStorage verStorage) { - dataset = new MerkleDataSet(cryptoSetting, prefix, exPolicyStorage, verStorage); - } - - public ParticipantDataset(HashDigest merkleRootHash, CryptoSetting cryptoSetting, String prefix, - ExPolicyKVStorage exPolicyStorage, VersioningKVStorage verStorage, boolean readonly) { - dataset = new MerkleDataSet(merkleRootHash, cryptoSetting, Bytes.fromString(prefix), exPolicyStorage, verStorage, readonly); - } - - @Override - public HashDigest getRootHash() { - return dataset.getRootHash(); - } - - @Override - public MerkleProof getProof(Bytes key) { - return dataset.getProof(key); - } - - @Override - public boolean isUpdated() { - return dataset.isUpdated(); - } - - @Override - public void commit() { - dataset.commit(); - } - - @Override - public void cancel() { - dataset.cancel(); - } - - @Override - public long getParticipantCount() { - return dataset.getDataCount(); - } - - /** - * 加入新的共识参与方;
- * 如果指定的共识参与方已经存在,则引发 {@link LedgerException} 异常; - * - * @param participant - */ - public void addConsensusParticipant(ParticipantNode participant) { - Bytes key = encodeKey(participant.getAddress()); - byte[] participantBytes = BinaryProtocol.encode(participant, ParticipantNode.class); - long nv = dataset.setValue(key, participantBytes, -1); - if (nv < 0) { - throw new LedgerException("Participant already exist! --[id=" + key + "]"); - } - } - - /** - * 更新共识参与方的状态信息;
- * - * @param participant - */ - public void updateConsensusParticipant(ParticipantNode participant) { - Bytes key = encodeKey(participant.getAddress()); - byte[] participantBytes = BinaryProtocol.encode(participant, ParticipantNode.class); - long version = dataset.getVersion(key); - if (version < 0) { - throw new LedgerException("Participant not exist, update failed!"); - } - - long nv = dataset.setValue(key, participantBytes, version); - if (nv < 0) { - throw new LedgerException("Participant update failed!"); - } - } - - private Bytes encodeKey(Bytes address) { - return address; - } - - @Override - public boolean contains(Bytes address) { - Bytes key = encodeKey(address); - long latestVersion = dataset.getVersion(key); - return latestVersion > -1; - } - - /** - * 返回指定地址的参与方凭证; - * - *
- * 如果不存在,则返回 null; - * - * @param address - * @return - */ - @Override - public ParticipantNode getParticipant(Bytes address) { - Bytes key = encodeKey(address); - byte[] bytes = dataset.getValue(key); - if (bytes == null) { - return null; - } - return BinaryProtocol.decode(bytes); - } - - @Override - public ParticipantNode[] getParticipants() { - byte[][] bytes = dataset.getLatestValues(0, (int) dataset.getDataCount()); - ParticipantNode[] pns = new ParticipantNode[bytes.length]; - - for (int i = 0; i < pns.length; i++) { - pns[i] = BinaryProtocol.decode(bytes[i]); - } - return pns; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PermissionService.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PermissionService.java deleted file mode 100644 index 78be086b..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PermissionService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public interface PermissionService { - - boolean checkLedgerPermission(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrefixAppender.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrefixAppender.java deleted file mode 100644 index a6a68a35..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrefixAppender.java +++ /dev/null @@ -1,119 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.storage.service.ExPolicyKVStorage; -//import com.jd.blockchain.storage.service.VersioningKVEntry; -//import com.jd.blockchain.storage.service.VersioningKVStorage; -// -//public class PrefixAppender { -// -// private PrefixAppender() { -// } -// -// /** -// * Wrapper the specified {@link VersioningKVStorage} and auto prefix it's key -// * with the specified String; -// * -// * @param prefix -// * @param storage -// * @return -// */ -// public static VersioningKVStorage prefix(String prefix, VersioningKVStorage storage) { -// return new VersioningKVStoragePrefixAppender(prefix, storage); -// } -// -//// public static SimpleKVStorage prefix(String prefix, SimpleKVStorage storage) { -//// return new SimpleKVStoragePrefixAppender(prefix, storage); -//// } -// -// public static ExPolicyKVStorage prefix(String prefix, ExPolicyKVStorage storage) { -// return new ExistancePolicyKVStoragePrefixAppender(prefix, storage); -// } -// -// private static String encodePrefixKey(String prefix, String key) { -// return prefix.concat(key); -// } -// -//// private static class SimpleKVStoragePrefixAppender implements SimpleKVStorage { -//// -//// private SimpleKVStorage storage; -//// -//// private String prefix; -//// -//// private SimpleKVStoragePrefixAppender(String prefix, SimpleKVStorage dataStorage) { -//// this.prefix = prefix; -//// this.storage = dataStorage; -//// } -//// -//// @Override -//// public byte[] get(String key) { -//// return storage.get(encodePrefixKey(prefix, key)); -//// } -//// -//// @Override -//// public boolean set(String key, byte[] value) { -//// return storage.set(encodePrefixKey(prefix, key), value); -//// } -//// } -// -// private static class ExistancePolicyKVStoragePrefixAppender implements ExPolicyKVStorage { -// -// private ExPolicyKVStorage storage; -// -// private String prefix; -// -// private ExistancePolicyKVStoragePrefixAppender(String prefix, ExPolicyKVStorage dataStorage) { -// this.prefix = prefix; -// this.storage = dataStorage; -// } -// -// @Override -// public byte[] get(String key) { -// return storage.get(encodePrefixKey(prefix, key)); -// } -// -// @Override -// public boolean exist(String key) { -// return storage.exist(key); -// } -// -// @Override -// public boolean set(String key, byte[] value, ExPolicy ex) { -// return storage.set(encodePrefixKey(prefix, key), value, ex); -// } -// } -// -// private static class VersioningKVStoragePrefixAppender implements VersioningKVStorage { -// -// private VersioningKVStorage storage; -// -// private String prefix; -// -// private VersioningKVStoragePrefixAppender(String prefix, VersioningKVStorage dataStorage) { -// this.prefix = prefix; -// this.storage = dataStorage; -// } -// -// -// @Override -// public long getVersion(String key) { -// return storage.getVersion(encodePrefixKey(prefix, key)); -// } -// -// @Override -// public VersioningKVEntry getEntry(String key, long version) { -// return storage.getEntry(encodePrefixKey(prefix, key), version); -// } -// -// @Override -// public byte[] get(String key, long version) { -// return storage.get(encodePrefixKey(prefix, key), version); -// } -// -// @Override -// public long set(String key, byte[] value, long version) { -// return storage.set(encodePrefixKey(prefix, key), value, version); -// } -// -// } -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrivilegeModelSetting.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrivilegeModelSetting.java deleted file mode 100644 index 1687c989..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrivilegeModelSetting.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public interface PrivilegeModelSetting { - - long getLatestVersion(); - - PermissionService getPrivilege(long version); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/RolePrivilegeDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/RolePrivilegeDataset.java deleted file mode 100644 index 220b519c..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/RolePrivilegeDataset.java +++ /dev/null @@ -1,294 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerPrivilege; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.PrivilegeSet; -import com.jd.blockchain.ledger.Privileges; -import com.jd.blockchain.ledger.RolePrivilegeSettings; -import com.jd.blockchain.ledger.RolePrivileges; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.TransactionPrivilege; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Transactional; -import com.jd.blockchain.utils.DataEntry; - -public class RolePrivilegeDataset implements Transactional, MerkleProvable, RolePrivilegeSettings { - - private MerkleDataSet dataset; - - public RolePrivilegeDataset(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, - VersioningKVStorage verStorage) { - dataset = new MerkleDataSet(cryptoSetting, prefix, exPolicyStorage, verStorage); - } - - public RolePrivilegeDataset(HashDigest merkleRootHash, CryptoSetting cryptoSetting, String prefix, - ExPolicyKVStorage exPolicyStorage, VersioningKVStorage verStorage, boolean readonly) { - dataset = new MerkleDataSet(merkleRootHash, cryptoSetting, Bytes.fromString(prefix), exPolicyStorage, - verStorage, readonly); - } - - @Override - public HashDigest getRootHash() { - return dataset.getRootHash(); - } - - @Override - public MerkleProof getProof(Bytes key) { - return dataset.getProof(key); - } - - @Override - public boolean isUpdated() { - return dataset.isUpdated(); - } - - @Override - public void commit() { - dataset.commit(); - } - - @Override - public void cancel() { - dataset.cancel(); - } - - @Override - public long getRoleCount() { - return dataset.getDataCount(); - } - - @Override - public long addRolePrivilege(String roleName, Privileges privileges) { - return addRolePrivilege(roleName, privileges.getLedgerPrivilege(), privileges.getTransactionPrivilege()); - } - - @Override - public long addRolePrivilege(String roleName, LedgerPrivilege ledgerPrivilege, TransactionPrivilege txPrivilege) { - RolePrivileges roleAuth = new RolePrivileges(roleName, -1, ledgerPrivilege, txPrivilege); - long nv = setRolePrivilege(roleAuth); - if (nv < 0) { - throw new LedgerException("Role[" + roleName + "] already exist!"); - } - return nv; - } - - @Override - public long addRolePrivilege(String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] txPermissions) { - LedgerPrivilege ledgerPrivilege = new LedgerPrivilege(); - for (LedgerPermission lp : ledgerPermissions) { - ledgerPrivilege.enable(lp); - } - TransactionPrivilege txPrivilege = new TransactionPrivilege(); - for (TransactionPermission tp : txPermissions) { - txPrivilege.enable(tp); - } - return addRolePrivilege(roleName, ledgerPrivilege, txPrivilege); - } - - /** - * 设置角色权限;
- * 如果版本校验不匹配,则返回 -1; - * - * @param roleAuth - * @return - */ - private long setRolePrivilege(RolePrivileges roleAuth) { - if (roleAuth.getRoleName().length() > MAX_ROLE_NAME_LENGTH) { - throw new LedgerException("Too long role name!"); - } - Bytes key = encodeKey(roleAuth.getRoleName()); - byte[] privilegeBytes = BinaryProtocol.encode(roleAuth, PrivilegeSet.class); - return dataset.setValue(key, privilegeBytes, roleAuth.getVersion()); - } - - /** - * 更新角色权限;
- * 如果指定的角色不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; - * - * @param participant - */ - @Override - public void updateRolePrivilege(RolePrivileges roleAuth) { - long nv = setRolePrivilege(roleAuth); - if (nv < 0) { - throw new LedgerException("Update to RoleAuthorization[" + roleAuth.getRoleName() - + "] failed due to wrong version[" + roleAuth.getVersion() + "] !"); - } - } - - /** - * 授权角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - @Override - public long enablePermissions(String roleName, LedgerPermission... permissions) { - RolePrivileges roleAuth = getRolePrivilege(roleName); - if (roleAuth == null) { - return -1; - } - roleAuth.getLedgerPrivilege().enable(permissions); - return setRolePrivilege(roleAuth); - } - - /** - * 授权角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - @Override - public long enablePermissions(String roleName, TransactionPermission... permissions) { - RolePrivileges roleAuth = getRolePrivilege(roleName); - if (roleAuth == null) { - return -1; - } - roleAuth.getTransactionPrivilege().enable(permissions); - return setRolePrivilege(roleAuth); - } - - /** - * 禁止角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - @Override - public long disablePermissions(String roleName, LedgerPermission... permissions) { - RolePrivileges roleAuth = getRolePrivilege(roleName); - if (roleAuth == null) { - return -1; - } - roleAuth.getLedgerPrivilege().disable(permissions); - return setRolePrivilege(roleAuth); - } - - /** - * 禁止角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - @Override - public long disablePermissions(String roleName, TransactionPermission... permissions) { - RolePrivileges roleAuth = getRolePrivilege(roleName); - if (roleAuth == null) { - return -1; - } - roleAuth.getTransactionPrivilege().disable(permissions); - return setRolePrivilege(roleAuth); - } - - /** - * 授权角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName - * @param ledgerPermissions - * @param txPermissions - * @return - */ - @Override - public long enablePermissions(String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] txPermissions) { - RolePrivileges roleAuth = getRolePrivilege(roleName); - if (roleAuth == null) { - return -1; - } - roleAuth.getLedgerPrivilege().enable(ledgerPermissions); - roleAuth.getTransactionPrivilege().enable(txPermissions); - return setRolePrivilege(roleAuth); - } - - /** - * 禁用角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName - * @param ledgerPermissions - * @param txPermissions - * @return - */ - @Override - public long disablePermissions(String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] txPermissions) { - RolePrivileges roleAuth = getRolePrivilege(roleName); - if (roleAuth == null) { - return -1; - } - roleAuth.getLedgerPrivilege().disable(ledgerPermissions); - roleAuth.getTransactionPrivilege().disable(txPermissions); - return setRolePrivilege(roleAuth); - } - - private Bytes encodeKey(String address) { - // return id + ""; - return Bytes.fromString(address); - } - - /** - * 查询角色权限; - * - *
- * 如果不存在,则返回 null; - * - * @param address - * @return - */ - @Override - public RolePrivileges getRolePrivilege(String roleName) { - // 只返回最新版本; - Bytes key = encodeKey(roleName); - DataEntry kv = dataset.getDataEntry(key); - if (kv == null) { - return null; - } - PrivilegeSet privilege = BinaryProtocol.decode(kv.getValue()); - return new RolePrivileges(roleName, kv.getVersion(), privilege); - } - - @Override - public RolePrivileges[] getRolePrivileges(int index, int count) { - DataEntry[] kvEntries = dataset.getLatestDataEntries(index, count); - RolePrivileges[] pns = new RolePrivileges[kvEntries.length]; - PrivilegeSet privilege; - for (int i = 0; i < pns.length; i++) { - privilege = BinaryProtocol.decode(kvEntries[i].getValue()); - pns[i] = new RolePrivileges(kvEntries[i].getKey().toUTF8String(), kvEntries[i].getVersion(), privilege); - } - return pns; - } - - @Override - public RolePrivileges[] getRolePrivileges() { - return getRolePrivileges(0, (int) getRoleCount()); - } - - @Override - public boolean isReadonly() { - return dataset.isReadonly(); - } - - @Override - public boolean contains(String roleName) { - Bytes key = encodeKey(roleName); - return dataset.getVersion(key) > -1; - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SNGenerator.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SNGenerator.java deleted file mode 100644 index 50ae5c10..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SNGenerator.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.utils.Bytes; - -/** - * 序列号生成器; - * - * @author huanghaiquan - * - */ -public interface SNGenerator { - - long generate(Bytes key); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityContext.java deleted file mode 100644 index 2fde0054..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityContext.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public class SecurityContext { - - private static ThreadLocal policyHolder = new ThreadLocal(); - - public static void setContextUsersPolicy(SecurityPolicy policy) { - policyHolder.set(policy); - } - - public static SecurityPolicy removeContextUsersPolicy() { - SecurityPolicy p = policyHolder.get(); - policyHolder.remove(); - return p; - } - - public static SecurityPolicy getContextUsersPolicy() { - return policyHolder.get(); - } - - /** - * 把上下文安全策略切换为指定的策略,并执行参数指定的 {@link Runnable} 操作,当操作完成后恢复原来的上下文策略; - * - * @param contextUsersPolicy - * @param runnable - */ - public static void switchContextUsersPolicy(SecurityPolicy contextUsersPolicy, Runnable runnable) { - - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityPolicy.java deleted file mode 100644 index 17d487dd..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityPolicy.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Set; - -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerSecurityException; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.utils.Bytes; - -/** - * 针对特定交易请求的账本安全策略; - * - * @author huanghaiquan - * - */ -public interface SecurityPolicy { - - /** - * 签署交易的终端用户的地址列表;(来自{@link TransactionRequest#getEndpointSignatures()}) - * - * @return - */ - Set getEndpoints(); - - /** - * 签署交易的节点参与方的地址列表(来自{@link TransactionRequest#getNodeSignatures()}) - * - * @return - */ - Set getNodes(); - - /** - * 终端身份是否合法; - * - * @param midPolicy - * @return - */ - boolean isEndpointValid(MultiIDsPolicy midPolicy); - - /** - * 节点身份是否合法; - * - * @param midPolicy - * @return - */ - boolean isNodeValid(MultiIDsPolicy midPolicy); - - /** - * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
- * - * @param permission 要检查的权限; - * @param midPolicy 针对多个签名用户的权限策略; - * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; - */ - boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy); - - /** - * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
- * - * @param permission 要检查的权限; - * @param midPolicy 针对多个签名用户的权限策略; - * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; - */ - boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy); - - /** - * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
- * - * @param permission 要检查的权限; - * @param midPolicy 针对多个签名用户的权限策略; - * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; - */ - boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy); - - /** - * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
- * - * @param permission 要检查的权限; - * @param midPolicy 针对多个签名用户的权限策略; - * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; - */ - boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy); - - /** - * 检查终端身份的合法性; - * - * @param midPolicy - * @throws LedgerSecurityException - */ - void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException; - - /** - * 检查节点身份的合法性; - * - * @param midPolicy - * @throws LedgerSecurityException - */ - void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException; - - /** - * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
- * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; - * - * @param permission 要检查的权限; - * @param midPolicy 针对多个签名用户的权限策略; - * @throws LedgerSecurityException - */ - void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException; - - /** - * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
- * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; - * - * @param permission - * @param midPolicy - * @throws LedgerSecurityException - */ - void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException; - - /** - * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
- * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; - * - * @param permission - * @param midPolicy - * @throws LedgerSecurityException - */ - void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException; - - /** - * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
- * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; - * - * @param permission - * @param midPolicy - * @throws LedgerSecurityException - */ - void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException; - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SettingContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SettingContext.java deleted file mode 100644 index f464db7f..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SettingContext.java +++ /dev/null @@ -1,51 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//public class SettingContext { -// -// private static final TxSettingContext txSettings = new TxSettingContext(); -// -// private static final QueryingSettingContext queryingSettings = new QueryingSettingContext(); -// -// public static TxSettingContext txSettings() { -// return txSettings; -// } -// -// public static QueryingSettingContext queryingSettings() { -// return queryingSettings; -// } -// -// /** -// * 与交易处理相关的设置; -// * @author huanghaiquan -// * -// */ -// public static class TxSettingContext { -// -// public boolean verifyLedger() { -// return true; -// } -// -// public boolean verifySignature() { -// return true; -// } -// -// } -// -// /** -// * 与账本查询相关的设置; -// * @author huanghaiquan -// * -// */ -// public static class QueryingSettingContext { -// -// /** -// * 查询区块等具有 hash 标识符的对象时是否重新校验哈希; -// * @return -// */ -// public boolean verifyHash() { -// return false; -// } -// -// } -// -//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SmartContract.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SmartContract.java deleted file mode 100644 index 80fa27ba..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SmartContract.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.DataContract; - -@DataContract(code=0x01) -public interface SmartContract { - - String getName(); - - String getDescription(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionEngineImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionEngineImpl.java deleted file mode 100644 index e684ff4d..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionEngineImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.beans.factory.annotation.Autowired; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.service.TransactionBatchProcess; -import com.jd.blockchain.service.TransactionEngine; - -public class TransactionEngineImpl implements TransactionEngine { - - @Autowired - private LedgerService ledgerService; - - @Autowired - private OperationHandleRegisteration opHdlRegs; - - private Map batchs = new ConcurrentHashMap<>(); - - public TransactionEngineImpl() { - } - - public TransactionEngineImpl(LedgerService ledgerService, OperationHandleRegisteration opHdlRegs) { - this.ledgerService = ledgerService; - this.opHdlRegs = opHdlRegs; - } - - @Override - public synchronized TransactionBatchProcess createNextBatch(HashDigest ledgerHash) { - TransactionBatchProcessor batch = batchs.get(ledgerHash); - if (batch != null) { - throw new IllegalStateException( - "The transaction batch process of ledger already exist! Cann't create another one!"); - } - - LedgerRepository ledgerRepo = ledgerService.getLedger(ledgerHash); - - batch = new InnerTransactionBatchProcessor(ledgerRepo, - opHdlRegs); - batchs.put(ledgerHash, batch); - return batch; - } - - @Override - public TransactionBatchProcess getBatch(HashDigest ledgerHash) { - return batchs.get(ledgerHash); - } - - public void freeBatch(HashDigest ledgerHash) { - finishBatch(ledgerHash); - } - - public void resetNewBlockEditor(HashDigest ledgerHash) { - - LedgerRepository ledgerRepo = ledgerService.getLedger(ledgerHash); - ((LedgerRepositoryImpl)ledgerRepo).resetNextBlockEditor(); - } - - private void finishBatch(HashDigest ledgerHash) { - batchs.remove(ledgerHash); - } - - private class InnerTransactionBatchProcessor extends TransactionBatchProcessor { - -// private HashDigest ledgerHash; - - /** - * 创建交易批处理器; - * - * @param ledgerRepo 账本; - * @param handlesRegisteration 操作处理对象注册表; - * - */ - public InnerTransactionBatchProcessor(LedgerRepository ledgerRepo, - OperationHandleRegisteration handlesRegisteration) { - super(ledgerRepo, handlesRegisteration); -// ledgerHash = ledgerRepo.getHash(); - } - - @Override - protected void onCommitted() { - super.onCommitted(); - finishBatch(getLedgerHash()); - } - - @Override - protected void onCanceled() { - super.onCanceled(); - finishBatch(getLedgerHash()); - } - - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionQuery.java deleted file mode 100644 index 887782d4..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionQuery.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.TransactionState; - -public interface TransactionQuery extends MerkleProvable { - - LedgerTransaction[] getTxs(int fromIndex, int count); - - byte[][] getValuesByIndex(int fromIndex, int count); - - long getTotalCount(); - - /** - * @param txContentHash - * Base58 编码的交易内容的哈希; - * @return - */ - LedgerTransaction get(HashDigest txContentHash); - - TransactionState getState(HashDigest txContentHash); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtension.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtension.java deleted file mode 100644 index ec6b1122..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtension.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Collection; -import java.util.Set; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainIdentityData; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.utils.Bytes; - -/** - * 交易请求上下文; - * - * @author huanghaiquan - * - */ -public interface TransactionRequestExtension extends TransactionRequest { - -// /** -// * 交易请求; -// * -// * @return -// */ -// TransactionRequest getRequest(); - - /** - * 签名发起请求的终端用户的地址列表; - * - * @return - */ - Set getEndpointAddresses(); - - /** - * 签名发起请求的终端用户列表; - * - * @return - */ - Collection getEndpoints(); - - /** - * 签名发起请求的节点的地址列表; - * - * @return - */ - Set getNodeAddresses(); - - /** - * 签名发起请求的节点列表; - * - * @return - */ - Collection getNodes(); - - /** - * 请求的终端发起人列表中是否包含指定地址的终端用户; - * - * @param address - * @return - */ - boolean containsEndpoint(Bytes address); - - /** - * 请求的经手节点列表中是否包含指定地址的节点; - * - * @param address - * @return - */ - boolean containsNode(Bytes address); - - /** - * 获取交易请求中指定地址的终端的签名; - * - * @param address - * @return - */ - DigitalSignature getEndpointSignature(Bytes address); - - /** - * 获取交易请求中指定地址的节点的签名; - * - * @param address - * @return - */ - DigitalSignature getNodeSignature(Bytes address); - - public static class Credential { - - private final BlockchainIdentity identity; - - private final DigitalSignature signature; - - Credential(DigitalSignature signature) { - this.identity = new BlockchainIdentityData(signature.getPubKey()); - this.signature = signature; - } - - public Bytes getAddress() { - return identity.getAddress(); - } - - public PubKey getPubKey() { - return identity.getPubKey(); - } - - public BlockchainIdentity getIdentity() { - return identity; - } - - public DigitalSignature getSignature() { - return signature; - } - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtensionImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtensionImpl.java deleted file mode 100644 index 1d93fbbe..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtensionImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.utils.Bytes; - -/** - * 交易请求的扩展信息; - * - * @author huanghaiquan - * - */ -public class TransactionRequestExtensionImpl implements TransactionRequestExtension { - - private TransactionRequest request; - - private Map endpointSignatures = new HashMap<>(); - - private Map nodeSignatures = new HashMap<>(); - - public TransactionRequestExtensionImpl(TransactionRequest request) { - this.request = request; - resolveSigners(); - } - - private void resolveSigners() { - if (request.getEndpointSignatures() != null) { - for (DigitalSignature signature : request.getEndpointSignatures()) { - Credential cred = new Credential(signature); - endpointSignatures.put(cred.getIdentity().getAddress(), cred); - } - } - if (request.getEndpointSignatures() != null) { - for (DigitalSignature signature : request.getNodeSignatures()) { - Credential cred = new Credential(signature); - nodeSignatures.put(cred.getIdentity().getAddress(), cred); - } - } - } - - @Override - public Set getEndpointAddresses() { - return endpointSignatures.keySet(); - } - - @Override - public Set getNodeAddresses() { - return nodeSignatures.keySet(); - } - - @Override - public Collection getEndpoints() { - return endpointSignatures.values(); - } - - @Override - public Collection getNodes() { - return nodeSignatures.values(); - } - - @Override - public boolean containsEndpoint(Bytes address) { - return endpointSignatures.containsKey(address); - } - - @Override - public boolean containsNode(Bytes address) { - return nodeSignatures.containsKey(address); - } - - @Override - public DigitalSignature getEndpointSignature(Bytes address) { - return endpointSignatures.get(address).getSignature(); - } - - @Override - public DigitalSignature getNodeSignature(Bytes address) { - return nodeSignatures.get(address).getSignature(); - } - - @Override - public HashDigest getHash() { - return request.getHash(); - } - - @Override - public DigitalSignature[] getNodeSignatures() { - return request.getNodeSignatures(); - } - - @Override - public DigitalSignature[] getEndpointSignatures() { - return request.getEndpointSignatures(); - } - - @Override - public TransactionContent getTransactionContent() { - return request.getTransactionContent(); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionSet.java deleted file mode 100644 index fe336005..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionSet.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Transactional; - -public class TransactionSet implements Transactional, TransactionQuery { - - static { - DataContractRegistry.register(LedgerTransaction.class); - } - - private static final String TX_STATE_PREFIX = "STA" + LedgerConsts.KEY_SEPERATOR; - - private final Bytes txStatePrefix; - - private MerkleDataSet txSet; - - @Override - public LedgerTransaction[] getTxs(int fromIndex, int count) { - if (count > LedgerConsts.MAX_LIST_COUNT) { - throw new IllegalArgumentException("Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!"); - } - byte[][] results = getValuesByIndex(fromIndex, count); - LedgerTransaction[] ledgerTransactions = new LedgerTransaction[results.length]; - - for (int i = 0; i < results.length; i++) { - ledgerTransactions[i] = deserialize(results[i]); - } - return ledgerTransactions; - } - - @Override - public byte[][] getValuesByIndex(int fromIndex, int count) { - byte[][] values = new byte[count][]; - for (int i = 0; i < count; i++) { - values[i] = txSet.getValuesAtIndex(fromIndex * 2); - fromIndex++; - } - return values; - } - - @Override - public HashDigest getRootHash() { - return txSet.getRootHash(); - } - - @Override - public MerkleProof getProof(Bytes key) { - return txSet.getProof(key); - } - - @Override - public long getTotalCount() { - // 每写入一个交易,同时写入交易内容Hash与交易结果的索引,因此交易记录数为集合总记录数除以 2; - return txSet.getDataCount() / 2; - } - - /** - * Create a new TransactionSet which can be added transaction; - * - * @param setting - * @param merkleTreeStorage - * @param dataStorage - */ - public TransactionSet(CryptoSetting setting, String keyPrefix, ExPolicyKVStorage merkleTreeStorage, - VersioningKVStorage dataStorage) { - this.txStatePrefix = Bytes.fromString(keyPrefix + TX_STATE_PREFIX); - this.txSet = new MerkleDataSet(setting, keyPrefix, merkleTreeStorage, dataStorage); - } - - /** - * Create TransactionSet which is readonly to the history transactions; - * - * @param setting - * @param merkleTreeStorage - * @param dataStorage - */ - public TransactionSet(HashDigest txRootHash, CryptoSetting setting, String keyPrefix, - ExPolicyKVStorage merkleTreeStorage, VersioningKVStorage dataStorage, boolean readonly) { - this.txStatePrefix = Bytes.fromString(keyPrefix + TX_STATE_PREFIX); - this.txSet = new MerkleDataSet(txRootHash, setting, Bytes.fromString(keyPrefix), merkleTreeStorage, dataStorage, - readonly); - } - - /** - * @param txRequest - * @param result - */ - public void add(LedgerTransaction tx) { - // TODO: 优化对交易内存存储的优化,应对大数据量单交易,共享操作的“写集”与实际写入账户的KV版本; - // 序列化交易内容; - byte[] txBytes = serialize(tx); - // 以交易内容的 hash 为 key; - // String key = tx.getTransactionContent().getHash().toBase58(); - Bytes key = new Bytes(tx.getTransactionContent().getHash().toBytes()); - // 交易只有唯一的版本; - long v = txSet.setValue(key, txBytes, -1); - if (v < 0) { - throw new LedgerException("Transaction is persisted repeatly! --[" + key + "]"); - } - // 以交易内容的hash值为key,单独记录交易结果的索引,以便快速查询交易结果; - Bytes resultKey = encodeTxStateKey(key); - v = txSet.setValue(resultKey, new byte[] { tx.getExecutionState().CODE }, -1); - if (v < 0) { - throw new LedgerException("Transaction result is persisted repeatly! --[" + key + "]"); - } - } - - /** - * @param txContentHash Base58 编码的交易内容的哈希; - * @return - */ - @Override - public LedgerTransaction get(HashDigest txContentHash) { - // transaction has only one version; - Bytes key = new Bytes(txContentHash.toBytes()); - // byte[] txBytes = txSet.getValue(txContentHash.toBase58(), 0); - byte[] txBytes = txSet.getValue(key, 0); - if (txBytes == null) { - return null; - } - LedgerTransaction tx = deserialize(txBytes); - return tx; - } - - @Override - public TransactionState getState(HashDigest txContentHash) { - Bytes resultKey = encodeTxStateKey(txContentHash); - // transaction has only one version; - byte[] bytes = txSet.getValue(resultKey, 0); - if (bytes == null || bytes.length == 0) { - return null; - } - return TransactionState.valueOf(bytes[0]); - } - - private Bytes encodeTxStateKey(Bytes txContentHash) { - return new Bytes(txStatePrefix, txContentHash); - } - - private LedgerTransaction deserialize(byte[] txBytes) { - return BinaryProtocol.decode(txBytes); - } - - private byte[] serialize(LedgerTransaction txRequest) { - return BinaryProtocol.encode(txRequest, LedgerTransaction.class); - } - - public boolean isReadonly() { - return txSet.isReadonly(); - } - - void setReadonly() { - txSet.setReadonly(); - } - - @Override - public boolean isUpdated() { - return txSet.isUpdated(); - } - - @Override - public void commit() { - txSet.commit(); - } - - @Override - public void cancel() { - txSet.cancel(); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionStagedSnapshot.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionStagedSnapshot.java deleted file mode 100644 index cee5487f..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionStagedSnapshot.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerDataSnapshot; - -public class TransactionStagedSnapshot implements LedgerDataSnapshot { - - private HashDigest adminAccountHash; - private HashDigest userAccountSetHash; - private HashDigest dataAccountSetHash; - private HashDigest contractAccountSetHash; - - @Override - public HashDigest getAdminAccountHash() { - return adminAccountHash; - } - - @Override - public HashDigest getUserAccountSetHash() { - return userAccountSetHash; - } - - @Override - public HashDigest getDataAccountSetHash() { - return dataAccountSetHash; - } - - @Override - public HashDigest getContractAccountSetHash() { - return contractAccountSetHash; - } - - public void setAdminAccountHash(HashDigest adminAccountHash) { - this.adminAccountHash = adminAccountHash; - } - - public void setUserAccountSetHash(HashDigest userAccountSetHash) { - this.userAccountSetHash = userAccountSetHash; - } - - public void setDataAccountSetHash(HashDigest dataAccountSetHash) { - this.dataAccountSetHash = dataAccountSetHash; - } - - public void setContractAccountSetHash(HashDigest contractAccountSetHash) { - this.contractAccountSetHash = contractAccountSetHash; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountQuery.java deleted file mode 100644 index 44e85b03..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountQuery.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public interface UserAccountQuery extends AccountQuery { - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRoleDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRoleDataset.java deleted file mode 100644 index 8aa45ebc..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRoleDataset.java +++ /dev/null @@ -1,196 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Collection; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.AuthorizationException; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.RoleSet; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.UserRoles; -import com.jd.blockchain.ledger.UserAuthorizationSettings; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Transactional; -import com.jd.blockchain.utils.DataEntry; - -/** - * User-Role authorization data set; - * - * @author huanghaiquan - * - */ -public class UserRoleDataset implements Transactional, MerkleProvable, UserAuthorizationSettings { - - private MerkleDataSet dataset; - - public UserRoleDataset(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, - VersioningKVStorage verStorage) { - dataset = new MerkleDataSet(cryptoSetting, prefix, exPolicyStorage, verStorage); - } - - public UserRoleDataset(HashDigest merkleRootHash, CryptoSetting cryptoSetting, String prefix, - ExPolicyKVStorage exPolicyStorage, VersioningKVStorage verStorage, boolean readonly) { - dataset = new MerkleDataSet(merkleRootHash, cryptoSetting, Bytes.fromString(prefix), exPolicyStorage, verStorage, readonly); - } - - @Override - public HashDigest getRootHash() { - return dataset.getRootHash(); - } - - @Override - public MerkleProof getProof(Bytes key) { - return dataset.getProof(key); - } - - @Override - public boolean isUpdated() { - return dataset.isUpdated(); - } - - @Override - public void commit() { - dataset.commit(); - } - - @Override - public void cancel() { - dataset.cancel(); - } - - @Override - public long getUserCount() { - return dataset.getDataCount(); - } - - /** - * 加入新的用户角色授权;
- * - * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; - * - * @param userAddress - * @param rolesPolicy - * @param roles - */ - @Override - public void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, String... roles) { - UserRoles roleAuth = new UserRoles(userAddress, -1, rolesPolicy); - roleAuth.addRoles(roles); - long nv = setUserRolesAuthorization(roleAuth); - if (nv < 0) { - throw new AuthorizationException("Roles authorization of User[" + userAddress + "] already exists!"); - } - } - - /** - * 加入新的用户角色授权;
- * - * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; - * - * @param userAddress - * @param rolesPolicy - * @param roles - */ - @Override - public void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, Collection roles) { - UserRoles roleAuth = new UserRoles(userAddress, -1, rolesPolicy); - roleAuth.addRoles(roles); - long nv = setUserRolesAuthorization(roleAuth); - if (nv < 0) { - throw new AuthorizationException("Roles authorization of User[" + userAddress + "] already exists!"); - } - } - - /** - * 设置用户角色授权;
- * 如果版本校验不匹配,则返回 -1; - * - * @param userRoles - * @return - */ - private long setUserRolesAuthorization(UserRoles userRoles) { - if (userRoles.getRoleCount() > MAX_ROLES_PER_USER) { - throw new AuthorizationException("The number of roles exceeds the maximum range!"); - } - byte[] rolesetBytes = BinaryProtocol.encode(userRoles, RoleSet.class); - return dataset.setValue(userRoles.getUserAddress(), rolesetBytes, userRoles.getVersion()); - } - - /** - * 更新用户角色授权;
- * 如果指定用户的授权不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; - * - * @param userRoles - */ - @Override - public void updateUserRoles(UserRoles userRoles) { - long nv = setUserRolesAuthorization(userRoles); - if (nv < 0) { - throw new AuthorizationException("Update to roles of user[" + userRoles.getUserAddress() - + "] failed due to wrong version[" + userRoles.getVersion() + "] !"); - } - } - - /** - * 设置用户的角色;
- * 如果用户的角色授权不存在,则创建新的授权; - * - * @param userAddress 用户; - * @param policy 角色策略; - * @param roles 角色列表; - * @return - */ - @Override - public long setRoles(Bytes userAddress, RolesPolicy policy, String... roles) { - UserRoles userRoles = getUserRoles(userAddress); - if (userRoles == null) { - userRoles = new UserRoles(userAddress, -1, policy); - } - userRoles.setPolicy(policy); - userRoles.setRoles(roles); - return setUserRolesAuthorization(userRoles); - } - - /** - * 查询角色授权; - * - *
- * 如果不存在,则返回 null; - * - * @param address - * @return - */ - @Override - public UserRoles getUserRoles(Bytes userAddress) { - // 只返回最新版本; - DataEntry kv = dataset.getDataEntry(userAddress); - if (kv == null) { - return null; - } - RoleSet roleSet = BinaryProtocol.decode(kv.getValue()); - return new UserRoles(userAddress, kv.getVersion(), roleSet); - } - - @Override - public UserRoles[] getUserRoles() { - DataEntry[] kvEntries = dataset.getLatestDataEntries(0, (int) dataset.getDataCount()); - UserRoles[] pns = new UserRoles[kvEntries.length]; - RoleSet roleset; - for (int i = 0; i < pns.length; i++) { - roleset = BinaryProtocol.decode(kvEntries[i].getValue()); - pns[i] = new UserRoles(kvEntries[i].getKey(), kvEntries[i].getVersion(), roleset); - } - return pns; - } - - @Override - public boolean isReadonly() { - return dataset.isReadonly(); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRolesPrivileges.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRolesPrivileges.java deleted file mode 100644 index dee7fb48..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRolesPrivileges.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Collection; - -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerPrivilege; -import com.jd.blockchain.ledger.PrivilegeBitset; -import com.jd.blockchain.ledger.RolePrivileges; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.TransactionPrivilege; -import com.jd.blockchain.utils.Bytes; - -/** - * {@link UserRolesPrivileges} 表示多角色用户的综合权限; - * - * @author huanghaiquan - * - */ -class UserRolesPrivileges { - - private Bytes userAddress; - - private LedgerPrivilege ledgerPrivileges; - - private TransactionPrivilege transactionPrivileges; - - public UserRolesPrivileges(Bytes userAddress, RolesPolicy policy, Collection privilegesList) { - this.userAddress = userAddress; - LedgerPrivilege[] ledgerPrivileges = privilegesList.stream().map(p -> p.getLedgerPrivilege()) - .toArray(LedgerPrivilege[]::new); - TransactionPrivilege[] transactionPrivileges = privilegesList.stream().map(p -> p.getTransactionPrivilege()) - .toArray(TransactionPrivilege[]::new); - - this.ledgerPrivileges = ledgerPrivileges[0].clone(); - this.transactionPrivileges = transactionPrivileges[0].clone(); - - if (policy == RolesPolicy.UNION) { - this.ledgerPrivileges.union(ledgerPrivileges, 1, ledgerPrivileges.length - 1); - this.transactionPrivileges.union(transactionPrivileges, 1, transactionPrivileges.length - 1); - - } else if (policy == RolesPolicy.INTERSECT) { - this.ledgerPrivileges.intersect(ledgerPrivileges, 1, ledgerPrivileges.length - 1); - this.transactionPrivileges.intersect(transactionPrivileges, 1, transactionPrivileges.length - 1); - } else { - throw new IllegalStateException("Unsupported roles policy[" + policy.toString() + "]!"); - } - - } - - public Bytes getUserAddress() { - return userAddress; - } - - public PrivilegeBitset getLedgerPrivileges() { - return ledgerPrivileges; - } - - public PrivilegeBitset getTransactionPrivileges() { - return transactionPrivileges; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbstractLedgerOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbstractLedgerOperationHandle.java deleted file mode 100644 index 2b259d4a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbstractLedgerOperationHandle.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; - -/** - * 执行直接账本操作的处理类; - * - * @author huanghaiquan - * - * @param - */ -public abstract class AbstractLedgerOperationHandle implements OperationHandle { - - static { - DataContractRegistry.register(BytesValue.class); - } - - private final Class SUPPORTED_OPERATION_TYPE; - - public AbstractLedgerOperationHandle(Class supportedOperationType) { - this.SUPPORTED_OPERATION_TYPE = supportedOperationType; - } - -// @Override -// public final boolean support(Class operationType) { -// return SUPPORTED_OPERATION_TYPE.isAssignableFrom(operationType); -// } - - @Override - public Class getOperationType() { - return SUPPORTED_OPERATION_TYPE; - } - - @Override - public final BytesValue process(Operation op, LedgerDataset newBlockDataset, - TransactionRequestExtension requestContext, LedgerQuery ledger, OperationHandleContext handleContext) { - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(TransactionPermission.DIRECT_OPERATION, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - @SuppressWarnings("unchecked") - T concretedOp = (T) op; - doProcess(concretedOp, newBlockDataset, requestContext, ledger, handleContext); - - // 账本操作没有返回值; - return null; - } - - protected abstract void doProcess(T op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, - LedgerQuery ledger, OperationHandleContext handleContext); -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbtractContractEventSendOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbtractContractEventSendOperationHandle.java deleted file mode 100644 index 5cd6dcfb..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbtractContractEventSendOperationHandle.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import org.springframework.stereotype.Service; - -import com.jd.blockchain.contract.LocalContractEventContext; -import com.jd.blockchain.contract.engine.ContractCode; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.ContractEventSendOperation; -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.core.ContractAccount; -import com.jd.blockchain.ledger.core.ContractAccountQuery; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.LedgerQueryService; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; - -@Service -public abstract class AbtractContractEventSendOperationHandle implements OperationHandle { - - @Override - public Class getOperationType() { - return ContractEventSendOperation.class; - } - - @Override - public BytesValue process(Operation op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, - LedgerQuery ledger, OperationHandleContext opHandleContext) { - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(TransactionPermission.CONTRACT_OPERATION, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - ContractEventSendOperation contractOP = (ContractEventSendOperation) op; - - return doProcess(requestContext, contractOP, newBlockDataset, ledger, opHandleContext); - } - - private BytesValue doProcess(TransactionRequestExtension request, ContractEventSendOperation contractOP, - LedgerDataset newBlockDataset, LedgerQuery ledger, OperationHandleContext opHandleContext) { - // 先从账本校验合约的有效性; - // 注意:必须在前一个区块的数据集中进行校验,因为那是经过共识的数据;从当前新区块链数据集校验则会带来攻击风险:未经共识的合约得到执行; - ContractAccountQuery contractSet = ledger.getContractAccountset(); - if (!contractSet.contains(contractOP.getContractAddress())) { - throw new LedgerException(String.format("Contract was not registered! --[ContractAddress=%s]", - contractOP.getContractAddress())); - } - - // 创建合约的账本上下文实例; - LedgerQueryService queryService = new LedgerQueryService(ledger); - ContractLedgerContext ledgerContext = new ContractLedgerContext(queryService, opHandleContext); - - // 先检查合约引擎是否已经加载合约;如果未加载,再从账本中读取合约代码并装载到引擎中执行; - ContractAccount contract = contractSet.getAccount(contractOP.getContractAddress()); - if (contract == null) { - throw new LedgerException(String.format("Contract was not registered! --[ContractAddress=%s]", - contractOP.getContractAddress())); - } - - // 创建合约上下文; - LocalContractEventContext localContractEventContext = new LocalContractEventContext( - request.getTransactionContent().getLedgerHash(), contractOP.getEvent()); - localContractEventContext.setArgs(contractOP.getArgs()).setTransactionRequest(request) - .setLedgerContext(ledgerContext); - - // 装载合约; - ContractCode contractCode = loadContractCode(contract); - - // 处理合约事件; - return contractCode.processEvent(localContractEventContext); - } - - protected abstract ContractCode loadContractCode(ContractAccount contract); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractCodeDeployOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractCodeDeployOperationHandle.java deleted file mode 100644 index b4e1cac3..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractCodeDeployOperationHandle.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.contract.ContractJarUtils; -import com.jd.blockchain.ledger.ContractCodeDeployOperation; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.core.*; - -public class ContractCodeDeployOperationHandle extends AbstractLedgerOperationHandle { - - public ContractCodeDeployOperationHandle() { - super(ContractCodeDeployOperation.class); - } - - @Override - protected void doProcess(ContractCodeDeployOperation op, LedgerDataset newBlockDataset, - TransactionRequestExtension requestContext, LedgerQuery ledger, - OperationHandleContext handleContext) { - - - // TODO: 请求者应该提供合约账户的公钥签名,以确保注册人对注册的地址和公钥具有合法的使用权; - - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.UPGRADE_CONTRACT, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - ContractCodeDeployOperation contractOP = op; - - // 校验合约内容 - byte[] chainCode = contractOP.getChainCode(); - - // 校验合约代码,不通过会抛出异常 - ContractJarUtils.verify(chainCode); - - newBlockDataset.getContractAccountset().deploy(contractOP.getContractID().getAddress(), - contractOP.getContractID().getPubKey(), contractOP.getAddressSignature(), contractOP.getChainCode()); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractLedgerContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractLedgerContext.java deleted file mode 100644 index fe3f9826..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractLedgerContext.java +++ /dev/null @@ -1,390 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import java.util.ArrayList; -import java.util.List; - -import com.jd.blockchain.contract.LedgerContext; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.ContractInfo; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.DataAccountRegisterOperation; -import com.jd.blockchain.ledger.TypedKVEntry; -import com.jd.blockchain.ledger.KVInfoVO; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInfo; -import com.jd.blockchain.ledger.LedgerMetadata; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.UserInfo; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.DataAccountKVSetOperationBuilder; -import com.jd.blockchain.transaction.DataAccountRegisterOperationBuilder; -import com.jd.blockchain.transaction.DataAccountRegisterOperationBuilderImpl; -import com.jd.blockchain.transaction.KVData; -import com.jd.blockchain.transaction.UserRegisterOperationBuilder; -import com.jd.blockchain.transaction.UserRegisterOperationBuilderImpl; -import com.jd.blockchain.utils.Bytes; - -public class ContractLedgerContext implements LedgerContext { - - private BlockchainQueryService innerQueryService; - - private OperationHandleContext opHandleContext; - - private List generatedOpList = new ArrayList<>(); - - public ContractLedgerContext(BlockchainQueryService innerQueryService, OperationHandleContext opHandleContext) { - this.innerQueryService = innerQueryService; - this.opHandleContext = opHandleContext; - } - - @Override - public HashDigest[] getLedgerHashs() { - return innerQueryService.getLedgerHashs(); - } - - @Override - public LedgerInfo getLedger(HashDigest ledgerHash) { - return innerQueryService.getLedger(ledgerHash); - } - - @Override - public LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash) { - return innerQueryService.getLedgerAdminInfo(ledgerHash); - } - - @Override - public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { - return innerQueryService.getConsensusParticipants(ledgerHash); - } - - @Override - public LedgerMetadata getLedgerMetadata(HashDigest ledgerHash) { - return innerQueryService.getLedgerMetadata(ledgerHash); - } - - @Override - public LedgerBlock getBlock(HashDigest ledgerHash, long height) { - return innerQueryService.getBlock(ledgerHash, height); - } - - @Override - public LedgerBlock getBlock(HashDigest ledgerHash, HashDigest blockHash) { - return innerQueryService.getBlock(ledgerHash, blockHash); - } - - @Override - public long getTransactionCount(HashDigest ledgerHash, long height) { - return innerQueryService.getTransactionCount(ledgerHash, height); - } - - @Override - public long getTransactionCount(HashDigest ledgerHash, HashDigest blockHash) { - return innerQueryService.getTransactionCount(ledgerHash, blockHash); - } - - @Override - public long getTransactionTotalCount(HashDigest ledgerHash) { - return innerQueryService.getTransactionTotalCount(ledgerHash); - } - - @Override - public long getDataAccountCount(HashDigest ledgerHash, long height) { - return innerQueryService.getDataAccountCount(ledgerHash, height); - } - - @Override - public long getDataAccountCount(HashDigest ledgerHash, HashDigest blockHash) { - return innerQueryService.getDataAccountCount(ledgerHash, blockHash); - } - - @Override - public long getDataAccountTotalCount(HashDigest ledgerHash) { - return innerQueryService.getDataAccountTotalCount(ledgerHash); - } - - @Override - public long getUserCount(HashDigest ledgerHash, long height) { - return innerQueryService.getUserCount(ledgerHash, height); - } - - @Override - public long getUserCount(HashDigest ledgerHash, HashDigest blockHash) { - return innerQueryService.getUserCount(ledgerHash, blockHash); - } - - @Override - public long getUserTotalCount(HashDigest ledgerHash) { - return innerQueryService.getUserTotalCount(ledgerHash); - } - - @Override - public long getContractCount(HashDigest ledgerHash, long height) { - return innerQueryService.getContractCount(ledgerHash, height); - } - - @Override - public long getContractCount(HashDigest ledgerHash, HashDigest blockHash) { - return innerQueryService.getContractCount(ledgerHash, blockHash); - } - - @Override - public long getContractTotalCount(HashDigest ledgerHash) { - return innerQueryService.getContractTotalCount(ledgerHash); - } - - @Override - public LedgerTransaction[] getTransactions(HashDigest ledgerHash, long height, int fromIndex, int count) { - return innerQueryService.getTransactions(ledgerHash, height, fromIndex, count); - } - - @Override - public LedgerTransaction[] getTransactions(HashDigest ledgerHash, HashDigest blockHash, int fromIndex, int count) { - return innerQueryService.getTransactions(ledgerHash, blockHash, fromIndex, count); - } - - @Override - public LedgerTransaction getTransactionByContentHash(HashDigest ledgerHash, HashDigest contentHash) { - return innerQueryService.getTransactionByContentHash(ledgerHash, contentHash); - } - - @Override - public TransactionState getTransactionStateByContentHash(HashDigest ledgerHash, HashDigest contentHash) { - return innerQueryService.getTransactionStateByContentHash(ledgerHash, contentHash); - } - - @Override - public UserInfo getUser(HashDigest ledgerHash, String address) { - return innerQueryService.getUser(ledgerHash, address); - } - - @Override - public BlockchainIdentity getDataAccount(HashDigest ledgerHash, String address) { - return innerQueryService.getDataAccount(ledgerHash, address); - } - - @Override - public TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, String... keys) { - return innerQueryService.getDataEntries(ledgerHash, address, keys); - } - - @Override - public TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, KVInfoVO kvInfoVO) { - return innerQueryService.getDataEntries(ledgerHash, address, kvInfoVO); - } - - @Override - public TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, int fromIndex, int count) { - return innerQueryService.getDataEntries(ledgerHash, address, fromIndex, count); - } - - @Override - public long getDataEntriesTotalCount(HashDigest ledgerHash, String address) { - return innerQueryService.getDataEntriesTotalCount(ledgerHash, address); - } - - @Override - public ContractInfo getContract(HashDigest ledgerHash, String address) { - return innerQueryService.getContract(ledgerHash, address); - } - - // ---------------------------user()---------------------------- - - @Override - public BlockchainIdentity[] getUsers(HashDigest ledgerHash, int fromIndex, int count) { - return innerQueryService.getUsers(ledgerHash, fromIndex, count); - } - - @Override - public BlockchainIdentity[] getDataAccounts(HashDigest ledgerHash, int fromIndex, int count) { - return innerQueryService.getDataAccounts(ledgerHash, fromIndex, count); - } - - @Override - public BlockchainIdentity[] getContractAccounts(HashDigest ledgerHash, int fromIndex, int count) { - return innerQueryService.getContractAccounts(ledgerHash, fromIndex, count); - } - - @Override - public UserRegisterOperationBuilder users() { - return new UserRegisterOperationBuilder1(); - } - - @Override - public DataAccountRegisterOperationBuilder dataAccounts() { - return new DataAccountRegisterOperationBuilder1(); - } - - @Override - public DataAccountKVSetOperationBuilder dataAccount(String accountAddress) { - return new DataAccountKVSetOperationExecBuilder(Bytes.fromBase58(accountAddress)); - } - - @Override - public DataAccountKVSetOperationBuilder dataAccount(Bytes accountAddress) { - return new DataAccountKVSetOperationExecBuilder(accountAddress); - } - - // ========end============= - - private class DataAccountRegisterOperationBuilder1 implements DataAccountRegisterOperationBuilder { - @Override - public DataAccountRegisterOperation register(BlockchainIdentity accountID) { - final DataAccountRegisterOperationBuilderImpl DATA_ACC_REG_OP_BUILDER = new DataAccountRegisterOperationBuilderImpl(); - DataAccountRegisterOperation op = DATA_ACC_REG_OP_BUILDER.register(accountID); - generatedOpList.add(op); - opHandleContext.handle(op); - return op; - } - } - - private class UserRegisterOperationBuilder1 implements UserRegisterOperationBuilder { - private final UserRegisterOperationBuilderImpl USER_REG_OP_BUILDER = new UserRegisterOperationBuilderImpl(); - - @Override - public UserRegisterOperation register(BlockchainIdentity userID) { - UserRegisterOperation op = USER_REG_OP_BUILDER.register(userID); - generatedOpList.add(op); - opHandleContext.handle(op); - return op; - } - } - - // -------------------------------- - - private class DataAccountKVSetOperationExecBuilder implements DataAccountKVSetOperationBuilder { - - private Bytes accountAddress; - - private SingleKVSetOpTemplate op; - - public DataAccountKVSetOperationExecBuilder(Bytes accountAddress) { - this.accountAddress = accountAddress; - } - - @Override - public DataAccountKVSetOperation getOperation() { - return op; - } - -// @Override -// public DataAccountKVSetOperationBuilder set(String key, byte[] value, long expVersion) { -// BytesValue bytesValue = BytesValueEntry.fromBytes(value); -// this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); -// handle(op); -// return this; -// } - - @Override - public DataAccountKVSetOperationBuilder setText(String key, String value, long expVersion) { - BytesValue bytesValue = TypedValue.fromText(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - - @Override - public DataAccountKVSetOperationBuilder setBytes(String key, Bytes value, long expVersion) { - BytesValue bytesValue = TypedValue.fromBytes(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - - @Override - public DataAccountKVSetOperationBuilder setInt64(String key, long value, long expVersion) { - BytesValue bytesValue = TypedValue.fromInt64(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - -// @Deprecated -// @Override -// public DataAccountKVSetOperationBuilder set(String key, String value, long expVersion) { -// BytesValue bytesValue = BytesValueEntry.fromText(value); -// this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); -// handle(op); -// return this; -// } - - @Override - public DataAccountKVSetOperationBuilder setJSON(String key, String value, long expVersion) { - BytesValue bytesValue = TypedValue.fromJSON(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - - @Override - public DataAccountKVSetOperationBuilder setXML(String key, String value, long expVersion) { - BytesValue bytesValue = TypedValue.fromXML(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - - @Override - public DataAccountKVSetOperationBuilder setBytes(String key, byte[] value, long expVersion) { - BytesValue bytesValue = TypedValue.fromBytes(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - - @Override - public DataAccountKVSetOperationBuilder setImage(String key, byte[] value, long expVersion) { - BytesValue bytesValue = TypedValue.fromImage(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - - @Override - public DataAccountKVSetOperationBuilder setTimestamp(String key, long value, long expVersion) { - BytesValue bytesValue = TypedValue.fromTimestamp(value); - this.op = new SingleKVSetOpTemplate(key, bytesValue, expVersion); - handle(op); - return this; - } - - private void handle(Operation op) { - generatedOpList.add(op); - opHandleContext.handle(op); - } - - /** - * 单个KV写入操作; - * - * @author huanghaiquan - * - */ - private class SingleKVSetOpTemplate implements DataAccountKVSetOperation { - - private KVWriteEntry[] writeset = new KVWriteEntry[1]; - - private SingleKVSetOpTemplate(String key, BytesValue value, long expVersion) { - writeset[0] = new KVData(key, value, expVersion); - } - - @Override - public Bytes getAccountAddress() { - return accountAddress; - } - - @Override - public KVWriteEntry[] getWriteSet() { - return writeset; - } - - } - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountKVSetOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountKVSetOperationHandle.java deleted file mode 100644 index dfab3f1c..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountKVSetOperationHandle.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.ledger.DataAccountDoesNotExistException; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.DataAccountKVSetOperation.KVWriteEntry; -import com.jd.blockchain.ledger.DataVersionConflictException; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; -import com.jd.blockchain.utils.Bytes; - -public class DataAccountKVSetOperationHandle extends AbstractLedgerOperationHandle { - - public DataAccountKVSetOperationHandle() { - super(DataAccountKVSetOperation.class); - } - - @Override - protected void doProcess(DataAccountKVSetOperation kvWriteOp, LedgerDataset newBlockDataset, - TransactionRequestExtension requestContext, LedgerQuery ledger, - OperationHandleContext handleContext) { - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.WRITE_DATA_ACCOUNT, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - DataAccount account = newBlockDataset.getDataAccountSet().getAccount(kvWriteOp.getAccountAddress()); - if (account == null) { - throw new DataAccountDoesNotExistException("DataAccount doesn't exist!"); - } - KVWriteEntry[] writeSet = kvWriteOp.getWriteSet(); - long v = -1L; - for (KVWriteEntry kvw : writeSet) { - v = account.getDataset().setValue(kvw.getKey(), TypedValue.wrap(kvw.getValue()), kvw.getExpectedVersion()); - if (v < 0) { - throw new DataVersionConflictException(); - } - } - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountRegisterOperationHandle.java deleted file mode 100644 index ab852255..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountRegisterOperationHandle.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.DataAccountRegisterOperation; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; - -public class DataAccountRegisterOperationHandle extends AbstractLedgerOperationHandle { - - public DataAccountRegisterOperationHandle() { - super(DataAccountRegisterOperation.class); - } - - @Override - protected void doProcess(DataAccountRegisterOperation op, LedgerDataset newBlockDataset, - TransactionRequestExtension requestContext, LedgerQuery ledger, OperationHandleContext handleContext) { - // TODO: 请求者应该提供数据账户的公钥签名,以更好地确保注册人对该地址和公钥具有合法使用权; - - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.REGISTER_DATA_ACCOUNT, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - DataAccountRegisterOperation dataAccountRegOp = (DataAccountRegisterOperation) op; - BlockchainIdentity bid = dataAccountRegOp.getAccountID(); - newBlockDataset.getDataAccountSet().register(bid.getAddress(), bid.getPubKey(), null); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/JVMContractEventSendOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/JVMContractEventSendOperationHandle.java deleted file mode 100644 index b153320e..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/JVMContractEventSendOperationHandle.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import static com.jd.blockchain.utils.BaseConstant.CONTRACT_SERVICE_PROVIDER; - -import com.jd.blockchain.contract.engine.ContractCode; -import com.jd.blockchain.contract.engine.ContractEngine; -import com.jd.blockchain.contract.engine.ContractServiceProviders; -import com.jd.blockchain.ledger.core.ContractAccount; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -public class JVMContractEventSendOperationHandle extends AbtractContractEventSendOperationHandle { - - private static final ContractEngine JVM_ENGINE; - - private static final Lock JVM_LOAD_LOCK = new ReentrantLock(); - - static { - JVM_ENGINE = ContractServiceProviders.getProvider(CONTRACT_SERVICE_PROVIDER).getEngine(); - } - - @Override - protected ContractCode loadContractCode(ContractAccount contract) { - ContractCode contractCode = JVM_ENGINE.getContract(contract.getAddress(), contract.getChaincodeVersion()); - if (contractCode == null) { - JVM_LOAD_LOCK.lock(); - try { - // Double Check - contractCode = JVM_ENGINE.getContract(contract.getAddress(), contract.getChaincodeVersion()); - if (contractCode == null) { - // 装载合约; - contractCode = JVM_ENGINE.setupContract(contract.getAddress(), contract.getChaincodeVersion(), - contract.getChainCode()); - } - } finally { - JVM_LOAD_LOCK.unlock(); - } - } - return contractCode; - } -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/LedgerInitOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/LedgerInitOperationHandle.java deleted file mode 100644 index ff22f777..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/LedgerInitOperationHandle.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; - -public class LedgerInitOperationHandle implements OperationHandle { - - @Override - public Class getOperationType() { - return LedgerInitOperation.class; - } - - @Override - public BytesValue process(Operation op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, - LedgerQuery ledger,OperationHandleContext handleContext) { - // 对初始化操作不需要做任何处理; - return null; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantRegisterOperationHandle.java deleted file mode 100644 index e02c2220..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantRegisterOperationHandle.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantInfoData; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.ledger.ParticipantRegisterOperation; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.LedgerAdminDataset; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; -import com.jd.blockchain.transaction.UserRegisterOpTemplate; -import com.jd.blockchain.utils.Bytes; - - -public class ParticipantRegisterOperationHandle extends AbstractLedgerOperationHandle { - public ParticipantRegisterOperationHandle() { - super(ParticipantRegisterOperation.class); - } - - @Override - protected void doProcess(ParticipantRegisterOperation op, LedgerDataset newBlockDataset, - TransactionRequestExtension requestContext, LedgerQuery previousBlockDataset, - OperationHandleContext handleContext) { - - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.REGISTER_PARTICIPANT, MultiIDsPolicy.AT_LEAST_ONE); - - ParticipantRegisterOperation participantRegOp = (ParticipantRegisterOperation) op; - - LedgerAdminDataset adminAccountDataSet = newBlockDataset.getAdminDataset(); - - ParticipantInfo participantInfo = new ParticipantInfoData(participantRegOp.getParticipantName(), participantRegOp.getParticipantRegisterIdentity().getPubKey(), participantRegOp.getNetworkAddress()); - - ParticipantNode participantNode = new PartNode((int)(adminAccountDataSet.getParticipantCount()), participantInfo.getName(), participantInfo.getPubKey(), ParticipantNodeState.REGISTERED); - - //add new participant as consensus node - adminAccountDataSet.addParticipant(participantNode); - - // Build UserRegisterOperation, reg participant as user - UserRegisterOperation userRegOp = new UserRegisterOpTemplate(participantRegOp.getParticipantRegisterIdentity()); - handleContext.handle(userRegOp); - } - - private static class PartNode implements ParticipantNode { - - private int id; - - private Bytes address; - - private String name; - - private PubKey pubKey; - - private ParticipantNodeState participantNodeState; - - public PartNode(int id, String name, PubKey pubKey, ParticipantNodeState participantNodeState) { - this.id = id; - this.name = name; - this.pubKey = pubKey; - this.address = AddressEncoding.generateAddress(pubKey); - this.participantNodeState = participantNodeState; - } - - @Override - public int getId() { - return id; - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public String getName() { - return name; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - @Override - public ParticipantNodeState getParticipantNodeState() { - return participantNodeState; - } - } - - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantStateUpdateOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantStateUpdateOperationHandle.java deleted file mode 100644 index 094a2e1a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantStateUpdateOperationHandle.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerSettings; -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantInfoData; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.ledger.ParticipantStateUpdateOperation; -import com.jd.blockchain.ledger.core.LedgerAdminDataset; -import com.jd.blockchain.ledger.core.LedgerConfiguration; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; -import com.jd.blockchain.utils.Bytes; - - -public class ParticipantStateUpdateOperationHandle extends AbstractLedgerOperationHandle { - public ParticipantStateUpdateOperationHandle() { - super(ParticipantStateUpdateOperation.class); - } - - @Override - protected void doProcess(ParticipantStateUpdateOperation op, LedgerDataset newBlockDataset, - TransactionRequestExtension requestContext, LedgerQuery previousBlockDataset, - OperationHandleContext handleContext) { - - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.REGISTER_PARTICIPANT, MultiIDsPolicy.AT_LEAST_ONE); - - ParticipantStateUpdateOperation stateUpdateOperation = (ParticipantStateUpdateOperation) op; - - LedgerAdminDataset adminAccountDataSet = newBlockDataset.getAdminDataset(); - - ConsensusProvider provider = ConsensusProviders.getProvider(adminAccountDataSet.getSettings().getConsensusProvider()); - - ParticipantNode[] participants = adminAccountDataSet.getParticipants(); - - ParticipantNode participantNode = null; - - for(int i = 0; i < participants.length; i++) { - if (stateUpdateOperation.getStateUpdateIdentity().getPubKey().equals(participants[i].getPubKey())) { - participantNode = new PartNode(participants[i].getId(), participants[i].getName(), participants[i].getPubKey(), ParticipantNodeState.ACTIVED); - break; - } - } - - //update consensus setting - ParticipantInfo participantInfo = new ParticipantInfoData(participantNode.getName(), participantNode.getPubKey(), stateUpdateOperation.getNetworkAddress()); - - Bytes newConsensusSettings = provider.getSettingsFactory().getConsensusSettingsBuilder().updateSettings(adminAccountDataSet.getSettings().getConsensusSetting(), participantInfo); - - LedgerSettings ledgerSetting = new LedgerConfiguration(adminAccountDataSet.getSettings().getConsensusProvider(), - newConsensusSettings, adminAccountDataSet.getPreviousSetting().getCryptoSetting()); - - adminAccountDataSet.setLedgerSetting(ledgerSetting); - - adminAccountDataSet.updateParticipant(participantNode); - - } - - private static class PartNode implements ParticipantNode { - - private int id; - - private Bytes address; - - private String name; - - private PubKey pubKey; - - private ParticipantNodeState participantNodeState; - - public PartNode(int id, String name, PubKey pubKey, ParticipantNodeState participantNodeState) { - this.id = id; - this.name = name; - this.pubKey = pubKey; - this.address = AddressEncoding.generateAddress(pubKey); - this.participantNodeState = participantNodeState; - } - - @Override - public int getId() { - return id; - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public String getName() { - return name; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - @Override - public ParticipantNodeState getParticipantNodeState() { - return participantNodeState; - } - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/RolesConfigureOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/RolesConfigureOperationHandle.java deleted file mode 100644 index 1d3c472c..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/RolesConfigureOperationHandle.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.RolePrivilegeSettings; -import com.jd.blockchain.ledger.RolePrivileges; -import com.jd.blockchain.ledger.RolesConfigureOperation; -import com.jd.blockchain.ledger.RolesConfigureOperation.RolePrivilegeEntry; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; - -public class RolesConfigureOperationHandle extends AbstractLedgerOperationHandle { - - public RolesConfigureOperationHandle() { - super(RolesConfigureOperation.class); - } - - @Override - protected void doProcess(RolesConfigureOperation operation, LedgerDataset newBlockDataset, - TransactionRequestExtension request, LedgerQuery ledger, OperationHandleContext handleContext) { - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.CONFIGURE_ROLES, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - RolePrivilegeEntry[] rpcfgs = operation.getRoles(); - RolePrivilegeSettings rpSettings = newBlockDataset.getAdminDataset().getRolePrivileges(); - if (rpcfgs != null) { - for (RolePrivilegeEntry rpcfg : rpcfgs) { - RolePrivileges rp = rpSettings.getRolePrivilege(rpcfg.getRoleName()); - if (rp == null) { - rpSettings.addRolePrivilege(rpcfg.getRoleName(), rpcfg.getEnableLedgerPermissions(), - rpcfg.getEnableTransactionPermissions()); - } else { - rp.enable(rpcfg.getEnableLedgerPermissions()); - rp.enable(rpcfg.getEnableTransactionPermissions()); - - rp.disable(rpcfg.getDisableLedgerPermissions()); - rp.disable(rpcfg.getDisableTransactionPermissions()); - } - } - } - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserAuthorizeOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserAuthorizeOperationHandle.java deleted file mode 100644 index 295cb0fb..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserAuthorizeOperationHandle.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import java.util.ArrayList; -import java.util.List; - -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.RolePrivilegeSettings; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.UserAuthorizeOperation; -import com.jd.blockchain.ledger.UserAuthorizeOperation.UserRolesEntry; -import com.jd.blockchain.ledger.UserRoles; -import com.jd.blockchain.ledger.UserAuthorizationSettings; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; -import com.jd.blockchain.utils.Bytes; - -public class UserAuthorizeOperationHandle extends AbstractLedgerOperationHandle { - - public UserAuthorizeOperationHandle() { - super(UserAuthorizeOperation.class); - } - - @Override - protected void doProcess(UserAuthorizeOperation operation, LedgerDataset newBlockDataset, - TransactionRequestExtension request, LedgerQuery ledger, - OperationHandleContext handleContext) { - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.CONFIGURE_ROLES, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - - UserRolesEntry[] urcfgs = operation.getUserRolesAuthorizations(); - UserAuthorizationSettings urSettings = newBlockDataset.getAdminDataset().getAuthorizations(); - RolePrivilegeSettings rolesSettings = newBlockDataset.getAdminDataset().getRolePrivileges(); - if (urcfgs != null) { - for (UserRolesEntry urcfg : urcfgs) { - // - String[] authRoles = urcfg.getAuthorizedRoles(); - List validRoles = new ArrayList(); - if (authRoles != null) { - for (String r : authRoles) { - if (rolesSettings.contains(r)) { - validRoles.add(r); - } - } - } - for (Bytes address : urcfg.getUserAddresses()) { - UserRoles ur = urSettings.getUserRoles(address); - if (ur == null) { - // 这是新的授权; - RolesPolicy policy = urcfg.getPolicy(); - if (policy == null) { - policy = RolesPolicy.UNION; - } - urSettings.addUserRoles(address, policy, validRoles); - } else { - // 更改之前的授权; - ur.addRoles(validRoles); - ur.removeRoles(urcfg.getUnauthorizedRoles()); - - // 如果请求中设置了策略,才进行更新; - RolesPolicy policy = urcfg.getPolicy(); - if (policy != null) { - ur.setPolicy(policy); - } - } - } - } - } - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserRegisterOperationHandle.java deleted file mode 100644 index a5573019..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserRegisterOperationHandle.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jd.blockchain.ledger.core.handles; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.SecurityContext; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; -import com.jd.blockchain.utils.Bytes; - -public class UserRegisterOperationHandle extends AbstractLedgerOperationHandle { - - public UserRegisterOperationHandle() { - super(UserRegisterOperation.class); - } - - @Override - protected void doProcess(UserRegisterOperation op, LedgerDataset newBlockDataset, - TransactionRequestExtension requestContext, LedgerQuery ledger, OperationHandleContext handleContext) { - // 权限校验; - SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); - securityPolicy.checkEndpointPermission(LedgerPermission.REGISTER_USER, MultiIDsPolicy.AT_LEAST_ONE); - - // 操作账本; - UserRegisterOperation userRegOp = (UserRegisterOperation) op; - BlockchainIdentity bid = userRegOp.getUserID(); - - Bytes userAddress = bid.getAddress(); - - newBlockDataset.getUserAccountSet().register(userAddress, bid.getPubKey()); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockDeserializer.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockDeserializer.java deleted file mode 100644 index 65d2dd81..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockDeserializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.ledger.core.serialize; - -import com.alibaba.fastjson.parser.DefaultJSONParser; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.utils.codec.Base58Utils; - -import java.lang.reflect.Type; - -public class LedgerBlockDeserializer implements ObjectDeserializer{ - - @SuppressWarnings("unchecked") - @Override - public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { - if (type instanceof Class && HashDigest.class.isAssignableFrom((Class) type)) { - String base58Str = parser.parseObject(String.class); - byte[] hashBytes = Base58Utils.decode(base58Str); - return (T) new HashDigest(hashBytes); - } - return (T) parser.parse(fieldName); - } - - @Override - public int getFastMatchToken() { - return JSONToken.LBRACE; - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockSerializer.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockSerializer.java deleted file mode 100644 index 09cedf9d..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockSerializer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.ledger.core.serialize; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.serializer.JSONSerializer; -import com.alibaba.fastjson.serializer.ObjectSerializer; -import com.alibaba.fastjson.serializer.SerializeWriter; -import com.jd.blockchain.ledger.LedgerBlock; - -public class LedgerBlockSerializer implements ObjectSerializer { - - @Override - public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) { - SerializeWriter out = serializer.out; - if (object == null) { - out.writeNull(); - return; - } - if (object instanceof LedgerBlock) { - LedgerBlock ledgerBlock = (LedgerBlock) object; -// out.writeString(hash.toBase58()); - } - } -} diff --git a/source/ledger/ledger-core/src/test/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoderTest.java b/source/ledger/ledger-core/src/test/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoderTest.java deleted file mode 100644 index d8757e0e..00000000 --- a/source/ledger/ledger-core/src/test/java/com/jd/blockchain/ledger/core/MerkleDataNodeEncoderTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.util.Random; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.ledger.core.MerkleTree.DataNode; -import com.jd.blockchain.utils.Bytes; - -public class MerkleDataNodeEncoderTest { - - @Test - public void testEnocoderV0() { - - - Random rand = new Random(); - - byte[] data = new byte[512]; - byte[] keyBytes = new byte[256]; - - rand.nextBytes(data); - rand.nextBytes(keyBytes); - Bytes key = new Bytes(keyBytes); - - long sn = 1024; - long version = 1; - doTestV0(sn, version, key, data); - - sn = 0; - version = 1000; - doTestV0(sn, version, key, data); - - sn = (1 << 56) -1; - version = 1000; - doTestV0(sn, version, key, data); - } - - private void doTestV0(long sn, long version, Bytes key, byte[] data) { - MerkleDataNodeEncoder encoderV0 = new MerkleDataNodeEncoder_V0(); - DataNode nodeV0 = encoderV0.create(ClassicAlgorithm.SHA256.code(), sn, key, version, data); - - assertNull(nodeV0.getValueHash()); - - assertEquals(sn, nodeV0.getSN()); - assertEquals(version, nodeV0.getVersion()); - assertEquals(key, nodeV0.getKey()); - - byte[] nodeBytes = nodeV0.toBytes(); - - DataNode nodeV0_reversed = encoderV0.resolve(nodeBytes); - assertNull(nodeV0_reversed.getValueHash()); - - assertEquals(nodeV0.getNodeHash(), nodeV0_reversed.getNodeHash()); - assertEquals(encoderV0.getFormatVersion(), nodeBytes[0]); - - assertEquals(sn, nodeV0_reversed.getSN()); - assertEquals(version, nodeV0_reversed.getVersion()); - assertEquals(key, nodeV0_reversed.getKey()); - } - - @Test - public void testEnocoderV1() { - Random rand = new Random(); - - byte[] data = new byte[512]; - byte[] keyBytes = new byte[256]; - - rand.nextBytes(data); - rand.nextBytes(keyBytes); - Bytes key = new Bytes(keyBytes); - - long sn = 1024; - long version = 1; - doTestV1(sn, version, key, data); - - sn = 0; - version = 10088; - doTestV1(sn, version, key, data); - - sn = (1 << 56) -1; - version = 1000; - doTestV1(sn, version, key, data); - } - - private void doTestV1(long sn, long version, Bytes key, byte[] data) { - HashFunction hashFunc = Crypto.getHashFunction(ClassicAlgorithm.SHA256); - HashDigest dataHash = hashFunc.hash(data); - - MerkleDataNodeEncoder encoderV1 = new MerkleDataNodeEncoder_V1(); - DataNode node = encoderV1.create(ClassicAlgorithm.SHA256.code(), sn, key, version, data); - - assertEquals(dataHash, node.getValueHash()); - - assertEquals(sn, node.getSN()); - assertEquals(version, node.getVersion()); - assertEquals(key, node.getKey()); - - byte[] nodeBytes = node.toBytes(); - - DataNode node_reversed = encoderV1.resolve(nodeBytes); - - assertEquals(dataHash, node_reversed.getValueHash()); - assertEquals(node.getNodeHash(), node_reversed.getNodeHash()); - assertEquals(encoderV1.getFormatVersion(), nodeBytes[0]); - - assertEquals(sn, node_reversed.getSN()); - assertEquals(version, node_reversed.getVersion()); - assertEquals(key, node_reversed.getKey()); - } - - @Test - public void testCompatibility() { - Random rand = new Random(); - - byte[] data = new byte[512]; - byte[] keyBytes = new byte[256]; - - rand.nextBytes(data); - rand.nextBytes(keyBytes); - - Bytes key = new Bytes(keyBytes); - - long sn = 1024; - long version = 1; - - - PreviousDataNode pdataNode = PreviousDataNode.newDataNode(ClassicAlgorithm.SHA256.code(), sn, key, version, - data); - - MerkleDataNodeEncoder encoderV0 = new MerkleDataNodeEncoder_V0(); - DataNode dataNode = encoderV0.create(ClassicAlgorithm.SHA256.code(), sn, key, version, data); - - assertEquals(pdataNode.getNodeHash(), dataNode.getNodeHash()); - assertEquals(pdataNode.getSN(), dataNode.getSN()); - assertEquals(pdataNode.getVersion(), dataNode.getVersion()); - assertEquals(pdataNode.getKey(), dataNode.getKey()); - - DataNode dataNode_reversed = encoderV0.resolve(pdataNode.toBytes()); - - assertNull(dataNode_reversed.getValueHash()); - assertEquals(pdataNode.getNodeHash(), dataNode_reversed.getNodeHash()); - assertEquals(pdataNode.getSN(), dataNode_reversed.getSN()); - assertEquals(pdataNode.getVersion(), dataNode_reversed.getVersion()); - assertEquals(pdataNode.getKey(), dataNode_reversed.getKey()); - } -} diff --git a/source/ledger/ledger-core/src/test/java/com/jd/blockchain/ledger/core/PreviousDataNode.java b/source/ledger/ledger-core/src/test/java/com/jd/blockchain/ledger/core/PreviousDataNode.java deleted file mode 100644 index 49f0039c..00000000 --- a/source/ledger/ledger-core/src/test/java/com/jd/blockchain/ledger/core/PreviousDataNode.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.NumberMask; - - - -/** - * A copy of previous version of com.jd.blockchain.ledger.core.MerkleTree.DataNode; - * - * @author huanghaiquan - * - */ -public class PreviousDataNode { - - private HashDigest nodeHash; - - private long sn; - - private Bytes key; - - private long version; - - private byte[] dataNodeBytes; - - private PreviousDataNode(long sn, Bytes key, long version, HashDigest dataHash, byte[] dataBytes) { - this.sn = sn; - this.key = key; - this.version = version; - this.nodeHash = dataHash; - this.dataNodeBytes = dataBytes; - } - - static PreviousDataNode newDataNode(CryptoAlgorithm hashAlgorithm, long sn, Bytes key, long version, - byte[] hashedData) { - return newDataNode(hashAlgorithm.code(), sn, key, version, hashedData); - } - - static PreviousDataNode newDataNode(short hashAlgorithm, long sn, Bytes key, long version, byte[] hashedData) { - // byte[] keyStrBytes = BytesUtils.toBytes(key); - // int maskSize = NumberMask.SHORT.getMaskLength(keyStrBytes.length); - int keySize = key.size(); - int maskSize = NumberMask.SHORT.getMaskLength(keySize); - - // int bodySize = 8 + maskSize + keyStrBytes.length + 8;// sn + key + version; - int bodySize = 8 + maskSize + keySize + 8;// sn + key + version; - byte[] bodyBytes = new byte[bodySize]; - - int offset = 0; - offset += BytesUtils.toBytes(sn, bodyBytes, 0); - - // NumberMask.SHORT.writeMask(keyStrBytes.length, bodyBytes, offset); - NumberMask.SHORT.writeMask(keySize, bodyBytes, offset); - offset += maskSize; - - // System.arraycopy(keyStrBytes, 0, bodyBytes, offset, keyStrBytes.length); - // System.arraycopy(keyStrBytes, 0, bodyBytes, offset, keyStrBytes.length); - // offset += keyStrBytes.length; - offset += key.copyTo(bodyBytes, offset, keySize); - - // TODO: version; - offset += BytesUtils.toBytes(version, bodyBytes, offset); - - byte[] dataBytes = BytesUtils.concat(bodyBytes, hashedData); - - HashFunction hashFunc = Crypto.getHashFunction(hashAlgorithm); - HashDigest dataHash = hashFunc.hash(dataBytes); - - int hashMaskSize = NumberMask.TINY.getMaskLength(dataHash.size()); - int dataNodeSize = bodySize + hashMaskSize + dataHash.size(); - byte[] dataNodeBytes = new byte[dataNodeSize]; - - offset = 0; - System.arraycopy(bodyBytes, 0, dataNodeBytes, offset, bodySize); - offset += bodySize; - NumberMask.TINY.writeMask(dataHash.size(), dataNodeBytes, offset); - offset += hashMaskSize; - System.arraycopy(dataHash.toBytes(), 0, dataNodeBytes, offset, dataHash.size()); - - return new PreviousDataNode(sn, key, version, dataHash, dataNodeBytes); - } - - public HashDigest getNodeHash() { - return nodeHash; - } - - protected long getStartingSN() { - return sn; - } - - protected long getDataCount() { - return 1; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getLevel() - */ - public int getLevel() { - return 0; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getSN() - */ - public long getSN() { - return sn; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getKey() - */ - public Bytes getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.MerkleDataNode#getVersion() - */ - public long getVersion() { - return version; - } - - public byte[] toBytes() { - return dataNodeBytes; - } - - static PreviousDataNode parse(byte[] bytes) { - // InputStream in = new ByteArrayInputStream(bytes); - - int offset = 0; - long sn = BytesUtils.toLong(bytes, offset); - offset += 8; - - // byte[] keyBytes = BytesEncoding.read(NumberMask.SHORT, in); - // String key = BytesUtils.toString(keyBytes); - int keySize = NumberMask.SHORT.resolveMaskedNumber(bytes, offset); - offset += NumberMask.SHORT.getMaskLength(keySize); - byte[] keyBytes = new byte[keySize]; - System.arraycopy(bytes, offset, keyBytes, 0, keySize); - offset += keySize; - // String key = BytesUtils.toString(keyBytes); - Bytes key = new Bytes(keyBytes); - - // long version = BytesUtils.readLong(in); - long version = BytesUtils.toLong(bytes, offset); - offset += 8; - - // byte[] dataHashBytes = BytesEncoding.read(NumberMask.SHORT, in); - int hashSize = NumberMask.TINY.resolveMaskedNumber(bytes, offset); - offset += NumberMask.TINY.getMaskLength(hashSize); - byte[] dataHashBytes = new byte[hashSize]; - System.arraycopy(bytes, offset, dataHashBytes, 0, hashSize); - offset += hashSize; - HashDigest dataHash = new HashDigest(dataHashBytes); - return new PreviousDataNode(sn, key, version, dataHash, bytes); - } - - @Override - public int hashCode() { - return nodeHash.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj instanceof PreviousDataNode) { - PreviousDataNode node1 = (PreviousDataNode) obj; - return this.nodeHash.equals(node1.nodeHash); - } - return false; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingHandle.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingHandle.java deleted file mode 100644 index 2a2be01d..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingHandle.java +++ /dev/null @@ -1,50 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.contract.ContractType; -import com.jd.blockchain.contract.engine.ContractCode; -import com.jd.blockchain.contract.jvm.AbstractContractCode; -import com.jd.blockchain.contract.jvm.ContractDefinition; -import com.jd.blockchain.ledger.core.ContractAccount; -import com.jd.blockchain.ledger.core.handles.AbtractContractEventSendOperationHandle; -import com.jd.blockchain.utils.Bytes; - -public class ContractInvokingHandle extends AbtractContractEventSendOperationHandle { - - private Map contractInstances = new ConcurrentHashMap(); - - @Override - protected ContractCode loadContractCode(ContractAccount contract) { - return contractInstances.get(contract.getAddress()); - } - - public ContractCode setup(Bytes address, Class contractIntf, T instance) { - ContractCodeInstance contract = new ContractCodeInstance(address, 0, contractIntf, instance); - contractInstances.put(address, contract); - return contract; - } - - private static class ContractCodeInstance extends AbstractContractCode { - - private T instance; - - public ContractCodeInstance(Bytes address, long version, Class delaredInterface, T instance) { - super(address, version, resolveContractDefinition(delaredInterface, instance.getClass())); - this.instance = instance; - } - - private static ContractDefinition resolveContractDefinition(Class declaredIntf, Class implementedClass) { - ContractType contractType = ContractType.resolve(declaredIntf); - return new ContractDefinition(contractType, implementedClass); - } - - @Override - protected T getContractInstance() { - return instance; - } - - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingTest.java deleted file mode 100644 index 49d14071..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingTest.java +++ /dev/null @@ -1,199 +0,0 @@ -//package test.com.jd.blockchain.ledger; -// -//import com.jd.blockchain.binaryproto.BinaryProtocol; -//import com.jd.blockchain.binaryproto.DataContractRegistry; -//import com.jd.blockchain.crypto.HashDigest; -//import com.jd.blockchain.ledger.*; -//import com.jd.blockchain.ledger.core.*; -//import com.jd.blockchain.service.TransactionBatchResultHandle; -//import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -//import com.jd.blockchain.transaction.TxBuilder; -//import com.jd.blockchain.utils.Bytes; -//import com.jd.blockchain.utils.io.BytesUtils; -//import org.apache.commons.io.IOUtils; -//import org.junit.Test; -//import org.mockito.Mockito; -//import test.com.jd.blockchain.ledger.core.TestContract; -// -//import java.io.ByteArrayOutputStream; -//import java.io.InputStream; -//import java.util.Random; -// -//import static org.junit.Assert.*; -//import static org.mockito.Matchers.anyLong; -//import static org.mockito.Matchers.anyString; -//import static org.mockito.Mockito.*; -// -//public class ContractInvokingTest { -// static { -// DataContractRegistry.register(TransactionContent.class); -// DataContractRegistry.register(TransactionContentBody.class); -// DataContractRegistry.register(TransactionRequest.class); -// DataContractRegistry.register(NodeRequest.class); -// DataContractRegistry.register(EndpointRequest.class); -// DataContractRegistry.register(TransactionResponse.class); -// DataContractRegistry.register(UserRegisterOperation.class); -// } -// -// private static final String LEDGER_KEY_PREFIX = "LDG://"; -// -// private BlockchainKeypair parti0 = BlockchainKeyGenerator.getInstance().generate(); -// private BlockchainKeypair parti1 = BlockchainKeyGenerator.getInstance().generate(); -// private BlockchainKeypair parti2 = BlockchainKeyGenerator.getInstance().generate(); -// private BlockchainKeypair parti3 = BlockchainKeyGenerator.getInstance().generate(); -// -// // 采用基于内存的 Storage; -// private MemoryKVStorage storage = new MemoryKVStorage(); -// -// // 用于测试的发布合约文件 -// private static final String CONTRACT_JAR = "contract-JDChain-Contract.jar"; -// -// @Test -// public void test() { -// // 初始化账本到指定的存储库; -// HashDigest ledgerHash = initLedger(storage, parti0, parti1, parti2, parti3); -// -// // 重新加载账本; -// LedgerManager ledgerManager = new LedgerManager(); -// LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, storage); -// -// // 创建合约处理器; -// ContractInvokingHandle contractInvokingHandle = new ContractInvokingHandle(); -// -// // 创建和加载合约实例; -// BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate(); -// Bytes contractAddress = contractKey.getAddress(); -// TestContract contractInstance = Mockito.mock(TestContract.class); -// contractInvokingHandle.setup(contractAddress, TestContract.class, contractInstance); -// -// // 注册合约处理器; -// DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); -// opReg.insertAsTopPriority(contractInvokingHandle); -// -// // 发布指定地址合约 -// deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey); -// -// -// // 创建新区块的交易处理器; -// LedgerBlock preBlock = ledgerRepo.getLatestBlock(); -// LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(preBlock); -// -// // 加载合约 -// LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); -// TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, -// opReg, ledgerManager); -// -// // 构建基于接口调用合约的交易请求,用于测试合约调用; -// TxBuilder txBuilder = new TxBuilder(ledgerHash); -// TestContract contractProxy = txBuilder.contract(contractAddress, TestContract.class); -// -// String asset = "AK"; -// long issueAmount = new Random().nextLong(); -// when(contractInstance.issue(anyString(), anyLong())).thenReturn(issueAmount); -// contractProxy.issue(asset, issueAmount); -// -// TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); -// txReqBuilder.signAsEndpoint(parti0); -// txReqBuilder.signAsNode(parti0); -// TransactionRequest txReq = txReqBuilder.buildRequest(); -// -// TransactionResponse resp = txbatchProcessor.schedule(txReq); -// verify(contractInstance, times(1)).issue(asset, issueAmount); -// OperationResult[] opResults = resp.getOperationResults(); -// assertEquals(1, opResults.length); -// assertEquals(0, opResults[0].getIndex()); -// -// byte[] expectedRetnBytes = BinaryProtocol.encode(BytesData.fromInt64(issueAmount), BytesValue.class); -// byte[] reallyRetnBytes = BinaryProtocol.encode(opResults[0].getResult(), BytesValue.class); -// assertArrayEquals(expectedRetnBytes, reallyRetnBytes); -// -// // 提交区块; -// TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare(); -// txResultHandle.commit(); -// -// LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); -// assertEquals(preBlock.getHeight() + 1, latestBlock.getHeight()); -// assertEquals(resp.getBlockHeight(), latestBlock.getHeight()); -// assertEquals(resp.getBlockHash(), latestBlock.getHash()); -// -// // 再验证一次结果; -// assertEquals(1, opResults.length); -// assertEquals(0, opResults[0].getIndex()); -// -// reallyRetnBytes = BinaryProtocol.encode(opResults[0].getResult(), BytesValue.class); -// assertArrayEquals(expectedRetnBytes, reallyRetnBytes); -// -// } -// -// private void deploy(LedgerRepository ledgerRepo, LedgerManager ledgerManager, -// DefaultOperationHandleRegisteration opReg, HashDigest ledgerHash, -// BlockchainKeypair contractKey) { -// // 创建新区块的交易处理器; -// LedgerBlock preBlock = ledgerRepo.getLatestBlock(); -// LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(preBlock); -// -// // 加载合约 -// LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); -// TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, -// opReg, ledgerManager); -// -// // 构建基于接口调用合约的交易请求,用于测试合约调用; -// TxBuilder txBuilder = new TxBuilder(ledgerHash); -// txBuilder.contracts().deploy(contractKey.getIdentity(), chainCode()); -// TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); -// txReqBuilder.signAsEndpoint(parti0); -// txReqBuilder.signAsNode(parti0); -// TransactionRequest txReq = txReqBuilder.buildRequest(); -// -// TransactionResponse resp = txbatchProcessor.schedule(txReq); -// OperationResult[] opResults = resp.getOperationResults(); -// assertNull(opResults); -// -// // 提交区块; -// TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare(); -// txResultHandle.commit(); -// } -// -// private HashDigest initLedger(MemoryKVStorage storage, BlockchainKeypair... partiKeys) { -// // 创建初始化配置; -// LedgerInitSetting initSetting = LedgerTestUtils.createLedgerInitSetting(partiKeys); -// -// // 创建账本; -// LedgerEditor ldgEdt = LedgerTransactionalEditor.createEditor(initSetting, LEDGER_KEY_PREFIX, storage, storage); -// -// TransactionRequest genesisTxReq = LedgerTestUtils.createTxRequest_UserReg(null); -// LedgerTransactionContext genisisTxCtx = ldgEdt.newTransaction(genesisTxReq); -// LedgerDataSet ldgDS = genisisTxCtx.getDataSet(); -// -// for (int i = 0; i < partiKeys.length; i++) { -// UserAccount userAccount = ldgDS.getUserAccountSet().register(partiKeys[i].getAddress(), -// partiKeys[i].getPubKey()); -// userAccount.setProperty("Name", "参与方-" + i, -1); -// userAccount.setProperty("Share", "" + (10 + i), -1); -// } -// -// LedgerTransaction tx = genisisTxCtx.commit(TransactionState.SUCCESS); -// -// assertEquals(genesisTxReq.getTransactionContent().getHash(), tx.getTransactionContent().getHash()); -// assertEquals(0, tx.getBlockHeight()); -// -// LedgerBlock block = ldgEdt.prepare(); -// -// assertEquals(0, block.getHeight()); -// assertNotNull(block.getHash()); -// assertNull(block.getPreviousHash()); -// -// assertEquals(block.getHash(), block.getLedgerHash()); -// -// // 提交数据,写入存储; -// ldgEdt.commit(); -// -// HashDigest ledgerHash = block.getHash(); -// return ledgerHash; -// } -// -// private byte[] chainCode() { -// -// return BytesUtils.copyToBytes(this.getClass().getResourceAsStream("/" + CONTRACT_JAR)); -// } -//} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/KeyValueEntry.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/KeyValueEntry.java deleted file mode 100644 index c4b40d59..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/KeyValueEntry.java +++ /dev/null @@ -1,19 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; - -@DataContract(code = 0x4010) -public interface KeyValueEntry { - - @DataField(order = 1, primitiveType = PrimitiveType.TEXT) - String getKey(); - - @DataField(order = 2, primitiveType = PrimitiveType.TEXT) - String getValue(); - - @DataField(order = 3, primitiveType = PrimitiveType.INT64) - long getVersion(); - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/KeyValueObject.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/KeyValueObject.java deleted file mode 100644 index 24215ea7..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/KeyValueObject.java +++ /dev/null @@ -1,47 +0,0 @@ -package test.com.jd.blockchain.ledger; - -public class KeyValueObject implements KeyValueEntry { - - private String key; - - private String value; - - private long version; - - public KeyValueObject() { - } - - public KeyValueObject(String key, String value, long version) { - this.key = key; - this.value = value; - this.version = version; - } - - @Override - public String getKey() { - return key; - } - - @Override - public String getValue() { - return value; - } - - @Override - public long getVersion() { - return version; - } - - public void setKey(String key) { - this.key = key; - } - - public void setValue(String value) { - this.value = value; - } - - public void setVersion(long version) { - this.version = version; - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TxTestContract.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TxTestContract.java deleted file mode 100644 index 80ee477f..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TxTestContract.java +++ /dev/null @@ -1,15 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEvent; - -@Contract -public interface TxTestContract { - - @ContractEvent(name = "testReadable") - boolean testReadable(); - - @ContractEvent(name = "testRollbackWhileVersionConfliction") - void testRollbackWhileVersionConfliction(String address, String key, String value, long version); - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TxTestContractImpl.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TxTestContractImpl.java deleted file mode 100644 index a0bf65be..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TxTestContractImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.contract.ContractEventContext; -import com.jd.blockchain.contract.ContractLifecycleAware; -import com.jd.blockchain.contract.EventProcessingAware; -import com.jd.blockchain.ledger.TypedKVEntry; -import com.jd.blockchain.utils.Bytes; - -public class TxTestContractImpl implements TxTestContract, ContractLifecycleAware, EventProcessingAware { - - private ContractEventContext eventContext; - - private Bytes dataAddress; - - public static String KEY = "k1"; - - @Override - public boolean testReadable() { - TypedKVEntry v1 = eventContext.getLedger().getDataEntries(eventContext.getCurrentLedgerHash(), - dataAddress.toBase58(), KEY)[0]; - String text1 = (String) v1.getValue(); - System.out.printf("k1=%s, version=%s \r\n", text1, v1.getVersion()); - - text1 = null == text1 ? "v" : text1; - String newValue = text1 + "-" + (v1.getVersion() + 1); - System.out.printf("new value = %s\r\n", newValue); - eventContext.getLedger().dataAccount(dataAddress).setText(KEY, newValue, v1.getVersion()); - - TypedKVEntry v2 = eventContext.getLedger().getDataEntries(eventContext.getCurrentLedgerHash(), - dataAddress.toBase58(), KEY)[0]; - System.out.printf("---- read new value ----\r\nk1=%s, version=%s \r\n", v2.getValue(), v2.getVersion()); - - String text2 = (String) v2.getValue(); - return text1.equals(text2); - } - - @Override - public void testRollbackWhileVersionConfliction(String address, String key, String value, long version) { - eventContext.getLedger().dataAccount(address).setText(key, value, version); - } - - - @Override - public void postConstruct() { - // TODO Auto-generated method stub - - } - - @Override - public void beforeDestroy() { - // TODO Auto-generated method stub - - } - - @Override - public void beforeEvent(ContractEventContext eventContext) { - this.eventContext = eventContext; - } - - @Override - public void postEvent(ContractEventContext eventContext, Exception error) { - this.eventContext = null; - } - - public Bytes getDataAddress() { - return dataAddress; - } - - public void setDataAddress(Bytes dataAddress) { - this.dataAddress = dataAddress; - } - - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/AccountSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/AccountSetTest.java deleted file mode 100644 index 99bd2076..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/AccountSetTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.core.CompositeAccount; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.MerkleAccountSet; -import com.jd.blockchain.ledger.core.OpeningAccessPolicy; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.utils.Bytes; - -public class AccountSetTest { - - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - - @Test - public void test() { - OpeningAccessPolicy accessPolicy = new OpeningAccessPolicy(); - - MemoryKVStorage storage = new MemoryKVStorage(); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig cryptoConf = new CryptoConfig(); - cryptoConf.setSupportedProviders(supportedProviders); - cryptoConf.setAutoVerifyHash(true); - cryptoConf.setHashAlgorithm(ClassicAlgorithm.SHA256); - - String keyPrefix = ""; - MerkleAccountSet accset = new MerkleAccountSet(cryptoConf, Bytes.fromString(keyPrefix), storage, storage, accessPolicy); - - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - accset.register(userKey.getAddress(), userKey.getPubKey()); - - //尚未提交之前,可以检索到账户的存在,但版本仍然标记为 -1; - CompositeAccount userAcc = accset.getAccount(userKey.getAddress()); - assertNotNull(userAcc); - assertTrue(accset.contains(userKey.getAddress())); - - accset.commit(); - HashDigest rootHash = accset.getRootHash(); - assertNotNull(rootHash); - - MerkleAccountSet reloadAccSet = new MerkleAccountSet(rootHash, cryptoConf, Bytes.fromString(keyPrefix), storage, storage, true, accessPolicy); - CompositeAccount reloadUserAcc = reloadAccSet.getAccount(userKey.getAddress()); - assertNotNull(reloadUserAcc); - assertTrue(reloadAccSet.contains(userKey.getAddress())); - - assertEquals(userAcc.getID().getAddress(), reloadUserAcc.getID().getAddress()); - assertEquals(userAcc.getID().getPubKey(), reloadUserAcc.getID().getPubKey()); - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BaseAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BaseAccountTest.java deleted file mode 100644 index 9d55b19e..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BaseAccountTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.MerkleAccount; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.utils.Bytes; - -/** - * - * @author huanghaiquan - * - */ -public class BaseAccountTest { - - public static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - @Test - public void basicTest() { - String keyPrefix = ""; - MemoryKVStorage testStorage = new MemoryKVStorage(); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConf = new CryptoConfig(); - cryptoConf.setSupportedProviders(supportedProviders); - cryptoConf.setAutoVerifyHash(true); - cryptoConf.setHashAlgorithm(ClassicAlgorithm.SHA256); - -// OpeningAccessPolicy accPlc = new OpeningAccessPolicy(); - - BlockchainKeypair bck = BlockchainKeyGenerator.getInstance().generate(); - - // 新建账户; - MerkleAccount baseAccount = new MerkleAccount(bck.getIdentity(), cryptoConf, Bytes.fromString(keyPrefix), - testStorage, testStorage); - assertTrue(baseAccount.isUpdated());//初始化新账户时,先写入PubKey; - assertFalse(baseAccount.isReadonly()); - - // 在空白状态下写入数据; - long v = baseAccount.getDataset().setValue("A", TypedValue.fromText("VALUE_A"), 0); - // 预期失败; - assertEquals(-1, v); - - v = baseAccount.getDataset().setValue("A", TypedValue.fromText("VALUE_A"), 1); - // 预期失败; - assertEquals(-1, v); - - v = baseAccount.getDataset().setValue("A", TypedValue.fromText("VALUE_A"), -1); - // 预期成功; - assertEquals(0, v); - - v = baseAccount.getDataset().setValue("A", TypedValue.fromText("VALUE_A-1"), -1); - // 已经存在版本,指定版本号-1,预期导致失败; - assertEquals(-1, v); - - baseAccount.commit(); - v = 0; - for (int i = 0; i < 10; i++) { - long s = baseAccount.getDataset().setValue("A", TypedValue.fromText("VALUE_A_" + i), v); - baseAccount.commit(); - // 预期成功; - assertEquals(v + 1, s); - v++; - } - - v = baseAccount.getDataset().setValue("A", TypedValue.fromText("VALUE_A_" + v), v + 1); - // 预期成功; - assertEquals(-1, v); - - System.out.println("============== commit =============="); - baseAccount.commit(); - - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BlockFullRollBackTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BlockFullRollBackTest.java deleted file mode 100644 index 6c8009f9..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BlockFullRollBackTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.*; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import org.junit.Test; -import org.mockito.Mockito; - -import static org.junit.Assert.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Mockito.doCallRealMethod; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; - -public class BlockFullRollBackTest { - - static { - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - } - - private static final String LEDGER_KEY_PREFIX = "LDG://"; - - private HashDigest ledgerHash = null; - - private BlockchainKeypair parti0 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti1 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti2 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti3 = BlockchainKeyGenerator.getInstance().generate(); - - private BlockchainKeypair[] participants = { parti0, parti1, parti2, parti3 }; - - - @Test - public void testBlockFullkRollBack() { - - final MemoryKVStorage STORAGE = new MemoryKVStorage(); - - final MemoryKVStorage STORAGE_Mock = Mockito.spy(STORAGE); - - // 初始化账本到指定的存储库; - ledgerHash = initLedger(STORAGE_Mock, parti0, parti1, parti2, parti3); - - System.out.println("---------- Ledger init OK !!! ----------"); - - // 加载账本; - LedgerManager ledgerManager = new LedgerManager(); - - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE_Mock); - - // 构造存储错误,并产生区块回滚 - doThrow(BlockRollbackException.class).when(STORAGE_Mock).set(any(), any(), anyLong()); - - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - - OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - LedgerSecurityManager securityManager = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, - ledgerRepo, opReg); - - // 注册新用户; - BlockchainKeypair userKeypair = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest = LedgerTestUtils.createTxRequest_UserReg(userKeypair, ledgerHash, - parti0, parti0); - TransactionResponse txResp = txbatchProcessor.schedule(transactionRequest); - - LedgerBlock newBlock = newBlockEditor.prepare(); - try { - newBlockEditor.commit(); - } catch (BlockRollbackException e) { - newBlockEditor.cancel(); - } - - // 验证正确性; - ledgerManager = new LedgerManager(); - ledgerRepo = ledgerManager.register(ledgerHash, STORAGE_Mock); - LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); - assertEquals(ledgerRepo.getBlockHash(0), latestBlock.getHash()); - assertEquals(0, latestBlock.getHeight()); - - LedgerDataQuery ledgerDS = ledgerRepo.getLedgerData(latestBlock); - boolean existUser = ledgerDS.getUserAccountSet().contains(userKeypair.getAddress()); - - assertFalse(existUser); - - doCallRealMethod().when(STORAGE_Mock).set(any(), any(), anyLong()); - - //区块正常提交 - // 生成新区块; - LedgerEditor newBlockEditor1 = ledgerRepo.createNextBlock(); - - OperationHandleRegisteration opReg1 = new DefaultOperationHandleRegisteration(); - LedgerSecurityManager securityManager1 = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor1 = new TransactionBatchProcessor(securityManager1, newBlockEditor1, - ledgerRepo, opReg1); - - // 注册新用户; - BlockchainKeypair userKeypair1 = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest1 = LedgerTestUtils.createTxRequest_UserReg(userKeypair1, ledgerHash, - parti0, parti0); - TransactionResponse txResp1 = txbatchProcessor1.schedule(transactionRequest1); - - LedgerBlock newBlock1 = newBlockEditor1.prepare(); - - try { - newBlockEditor1.commit(); - } catch (BlockRollbackException e) { - newBlockEditor1.cancel(); - } - - ledgerManager = new LedgerManager(); - ledgerRepo = ledgerManager.register(ledgerHash, STORAGE_Mock); - LedgerBlock latestBlock1 = ledgerRepo.getLatestBlock(); - assertEquals(newBlock1.getHash(), latestBlock1.getHash()); - assertEquals(1, latestBlock1.getHeight()); - - LedgerDataQuery ledgerDS1 = ledgerRepo.getLedgerData(latestBlock1); - boolean existUser1 = ledgerDS1.getUserAccountSet().contains(userKeypair1.getAddress()); - - assertTrue(existUser1); - - } - - private static LedgerSecurityManager getSecurityManager() { - LedgerSecurityManager securityManager = Mockito.mock(LedgerSecurityManager.class); - - SecurityPolicy securityPolicy = Mockito.mock(SecurityPolicy.class); - when(securityPolicy.isEndpointEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isEndpointEnable(any(TransactionPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(TransactionPermission.class), any())).thenReturn(true); - - when(securityManager.createSecurityPolicy(any(), any())).thenReturn(securityPolicy); - - return securityManager; - } - - private HashDigest initLedger(MemoryKVStorage storage, BlockchainKeypair... partiKeys) { - // 创建初始化配置; - LedgerInitSetting initSetting = LedgerTestUtils.createLedgerInitSetting(partiKeys); - - // 创建账本; - LedgerEditor ldgEdt = LedgerTransactionalEditor.createEditor(initSetting, LEDGER_KEY_PREFIX, storage, storage); - - TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(partiKeys); - LedgerTransactionContext genisisTxCtx = ldgEdt.newTransaction(genesisTxReq); - LedgerDataset ldgDS = genisisTxCtx.getDataset(); - - for (int i = 0; i < partiKeys.length; i++) { - UserAccount userAccount = ldgDS.getUserAccountSet().register(partiKeys[i].getAddress(), - partiKeys[i].getPubKey()); - userAccount.setProperty("Name", "参与方-" + i, -1); - userAccount.setProperty("Share", "" + (10 + i), -1); - } - - LedgerTransaction tx = genisisTxCtx.commit(TransactionState.SUCCESS); - - assertEquals(genesisTxReq.getTransactionContent().getHash(), tx.getTransactionContent().getHash()); - assertEquals(0, tx.getBlockHeight()); - - LedgerBlock block = ldgEdt.prepare(); - - assertEquals(0, block.getHeight()); - assertNotNull(block.getHash()); - assertNull(block.getPreviousHash()); - - // 创世区块的账本哈希为 null; - assertNull(block.getLedgerHash()); - assertNotNull(block.getHash()); - - // 提交数据,写入存储; - ldgEdt.commit(); - - HashDigest ledgerHash = block.getHash(); - return ledgerHash; - } -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingHandle.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingHandle.java deleted file mode 100644 index 2bd98895..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingHandle.java +++ /dev/null @@ -1,28 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.contract.engine.ContractCode; -import com.jd.blockchain.contract.jvm.InstantiatedContractCode; -import com.jd.blockchain.ledger.core.ContractAccount; -import com.jd.blockchain.ledger.core.handles.AbtractContractEventSendOperationHandle; -import com.jd.blockchain.utils.Bytes; - -public class ContractInvokingHandle extends AbtractContractEventSendOperationHandle { - - private Map contractInstances = new ConcurrentHashMap(); - - @Override - protected ContractCode loadContractCode(ContractAccount contract) { - return contractInstances.get(contract.getAddress()); - } - - public ContractCode setup(Bytes address, Class contractIntf, T instance) { - InstantiatedContractCode contract = new InstantiatedContractCode(address, 0, contractIntf, instance); - contractInstances.put(address, contract); - return contract; - } - - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingTest.java deleted file mode 100644 index de1d224f..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingTest.java +++ /dev/null @@ -1,508 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static com.jd.blockchain.transaction.ContractReturnValue.decode; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.InputStream; -import java.util.Random; - -import org.junit.Test; -import org.mockito.Mockito; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataAccountRegisterOperation; -import com.jd.blockchain.ledger.EndpointRequest; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.NodeRequest; -import com.jd.blockchain.ledger.OperationResult; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.ParticipantRegisterOperation; -import com.jd.blockchain.ledger.ParticipantStateUpdateOperation; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionContentBody; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionRequestBuilder; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.LedgerDataQuery; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerSecurityManager; -import com.jd.blockchain.ledger.core.LedgerService; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.ledger.core.LedgerTransactionalEditor; -import com.jd.blockchain.ledger.core.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionBatchProcessor; -import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.service.TransactionBatchResultHandle; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.transaction.BooleanValueHolder; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.DataEntry; -import com.jd.blockchain.utils.io.BytesUtils; - -import test.com.jd.blockchain.ledger.TxTestContract; -import test.com.jd.blockchain.ledger.TxTestContractImpl; - -public class ContractInvokingTest { - static { - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(ParticipantNode.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - } - - private static final String LEDGER_KEY_PREFIX = "LDG://"; - - private BlockchainKeypair parti0 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti1 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti2 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti3 = BlockchainKeyGenerator.getInstance().generate(); - - // 采用基于内存的 Storage; - private MemoryKVStorage storage = new MemoryKVStorage(); - - private static final String CONTRACT_JAR = "contract-JDChain-Contract.jar"; - - @Test - public void testNormal() { - // 初始化账本到指定的存储库; - HashDigest ledgerHash = initLedger(storage, parti0, parti1, parti2, parti3); - - // 重新加载账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, storage); - - // 创建合约处理器; - ContractInvokingHandle contractInvokingHandle = new ContractInvokingHandle(); - - // 创建和加载合约实例; - BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate(); - Bytes contractAddress = contractKey.getAddress(); - - TestContract contractInstance = Mockito.mock(TestContract.class); - final String asset = "AK"; - final long issueAmount = new Random().nextLong(); - when(contractInstance.issue(anyString(), anyLong())).thenReturn(issueAmount); - - // 装载合约; - contractInvokingHandle.setup(contractAddress, TestContract.class, contractInstance); - - // 注册合约处理器; - DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - opReg.registerHandle(contractInvokingHandle); - - // 发布指定地址合约 - deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey); - // 创建新区块的交易处理器; - LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(preBlock); - - // 加载合约 - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - LedgerSecurityManager securityManager = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, - ledgerRepo, opReg); - - // 构建基于接口调用合约的交易请求,用于测试合约调用; - TxBuilder txBuilder = new TxBuilder(ledgerHash); - TestContract contractProxy = txBuilder.contract(contractAddress, TestContract.class); - - // 构造调用合约的交易; - contractProxy.issue(asset, issueAmount); - - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - txReqBuilder.signAsEndpoint(parti0); - txReqBuilder.signAsNode(parti0); - TransactionRequest txReq = txReqBuilder.buildRequest(); - - TransactionResponse resp = txbatchProcessor.schedule(txReq); - verify(contractInstance, times(1)).issue(asset, issueAmount); - OperationResult[] opResults = resp.getOperationResults(); - assertEquals(1, opResults.length); - assertEquals(0, opResults[0].getIndex()); - - byte[] expectedRetnBytes = BinaryProtocol.encode(TypedValue.fromInt64(issueAmount), BytesValue.class); - byte[] reallyRetnBytes = BinaryProtocol.encode(opResults[0].getResult(), BytesValue.class); - assertArrayEquals(expectedRetnBytes, reallyRetnBytes); - - // 提交区块; - TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare(); - txResultHandle.commit(); - - LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); - assertEquals(preBlock.getHeight() + 1, latestBlock.getHeight()); - assertEquals(resp.getBlockHeight(), latestBlock.getHeight()); - assertEquals(resp.getBlockHash(), latestBlock.getHash()); - - // 再验证一次结果; - assertEquals(1, opResults.length); - assertEquals(0, opResults[0].getIndex()); - - reallyRetnBytes = BinaryProtocol.encode(opResults[0].getResult(), BytesValue.class); - assertArrayEquals(expectedRetnBytes, reallyRetnBytes); - - } - -// @Test - public void testReadNewWritting() { - // 初始化账本到指定的存储库; - HashDigest ledgerHash = initLedger(storage, parti0, parti1, parti2, parti3); - - // 重新加载账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, storage); - - // 创建合约处理器; - ContractInvokingHandle contractInvokingHandle = new ContractInvokingHandle(); - - // 创建和加载合约实例; - BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate(); - Bytes contractAddress = contractKey.getAddress(); - TxTestContractImpl contractInstance = new TxTestContractImpl(); - contractInvokingHandle.setup(contractAddress, TxTestContract.class, contractInstance); - - // 注册合约处理器; - DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - opReg.registerHandle(contractInvokingHandle); - - // 发布指定地址合约 - deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey); - - // 创建新区块的交易处理器; - LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(preBlock); - - // 加载合约 - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(getSecurityManager(), newBlockEditor, - ledgerRepo, opReg); - - String key = TxTestContractImpl.KEY; - String value = "VAL"; - - TxBuilder txBuilder = new TxBuilder(ledgerHash); - BlockchainKeypair kpDataAccount = BlockchainKeyGenerator.getInstance().generate(); - contractInstance.setDataAddress(kpDataAccount.getAddress()); - - txBuilder.dataAccounts().register(kpDataAccount.getIdentity()); - TransactionRequestBuilder txReqBuilder1 = txBuilder.prepareRequest(); - txReqBuilder1.signAsEndpoint(parti0); - txReqBuilder1.signAsNode(parti0); - TransactionRequest txReq1 = txReqBuilder1.buildRequest(); - - // 构建基于接口调用合约的交易请求,用于测试合约调用; - txBuilder = new TxBuilder(ledgerHash); - TxTestContract contractProxy = txBuilder.contract(contractAddress, TxTestContract.class); - BooleanValueHolder readableHolder = decode(contractProxy.testReadable()); - - TransactionRequestBuilder txReqBuilder2 = txBuilder.prepareRequest(); - txReqBuilder2.signAsEndpoint(parti0); - txReqBuilder2.signAsNode(parti0); - TransactionRequest txReq2 = txReqBuilder2.buildRequest(); - - TransactionResponse resp1 = txbatchProcessor.schedule(txReq1); - TransactionResponse resp2 = txbatchProcessor.schedule(txReq2); - - // 提交区块; - TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare(); - txResultHandle.commit(); - - BytesValue latestValue = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getValue(key, - -1); - System.out.printf("latest value=[%s] %s \r\n", latestValue.getType(), latestValue.getBytes().toUTF8String()); - - boolean readable = readableHolder.get(); - assertTrue(readable); - - LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); - assertEquals(preBlock.getHeight() + 1, latestBlock.getHeight()); - assertEquals(resp1.getBlockHeight(), latestBlock.getHeight()); - assertEquals(resp1.getBlockHash(), latestBlock.getHash()); - } - - /** - * 验证在合约方法中写入数据账户时,如果版本校验失败是否会引发异常而导致回滚;
- * 期待正确的表现是引发异常而回滚当前交易; - */ - @Test - public void testRollbackWhileVersionConfliction() { - // 初始化账本到指定的存储库; - HashDigest ledgerHash = initLedger(storage, parti0, parti1, parti2, parti3); - - // 重新加载账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, storage); - - // 创建合约处理器; - ContractInvokingHandle contractInvokingHandle = new ContractInvokingHandle(); - - // 创建和加载合约实例; - BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate(); - Bytes contractAddress = contractKey.getAddress(); - TxTestContractImpl contractInstance = new TxTestContractImpl(); - contractInvokingHandle.setup(contractAddress, TxTestContract.class, contractInstance); - - // 注册合约处理器; - DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - opReg.registerHandle(contractInvokingHandle); - - // 发布指定地址合约 - deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey); - - // 注册数据账户; - BlockchainKeypair kpDataAccount = BlockchainKeyGenerator.getInstance().generate(); - contractInstance.setDataAddress(kpDataAccount.getAddress()); - registerDataAccount(ledgerRepo, ledgerManager, opReg, ledgerHash, kpDataAccount); - - // 调用合约 - // 构建基于接口调用合约的交易请求,用于测试合约调用; - buildBlock(ledgerRepo, ledgerManager, opReg, new TxDefinitor() { - @Override - public void buildTx(TxBuilder txBuilder) { - TxTestContract contractProxy = txBuilder.contract(contractAddress, TxTestContract.class); - contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K1", "V1-0", - -1); - contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K2", "V2-0", - -1); - } - }); - // 预期数据都能够正常写入; - DataEntry kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", - 0); - DataEntry kv2 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K2", - 0); - assertEquals(0, kv1.getVersion()); - assertEquals(0, kv2.getVersion()); - assertEquals("V1-0", kv1.getValue().stringValue()); - assertEquals("V2-0", kv2.getValue().stringValue()); - - // 构建基于接口调用合约的交易请求,用于测试合约调用; - buildBlock(ledgerRepo, ledgerManager, opReg, new TxDefinitor() { - @Override - public void buildTx(TxBuilder txBuilder) { - TxTestContract contractProxy = txBuilder.contract(contractAddress, TxTestContract.class); - contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K1", "V1-1", - 0); - contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K2", "V2-1", - 0); - } - }); - // 预期数据都能够正常写入; - kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", 1); - kv2 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K2", 1); - assertEquals(1, kv1.getVersion()); - assertEquals(1, kv2.getVersion()); - assertEquals("V1-1", kv1.getValue().stringValue()); - assertEquals("V2-1", kv2.getValue().stringValue()); - - // 构建基于接口调用合约的交易请求,用于测试合约调用; - buildBlock(ledgerRepo, ledgerManager, opReg, new TxDefinitor() { - @Override - public void buildTx(TxBuilder txBuilder) { - TxTestContract contractProxy = txBuilder.contract(contractAddress, TxTestContract.class); - contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K1", "V1-2", - 1); - contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K2", "V2-2", - 0);//预期会回滚; - } - }); - // 预期数据回滚,账本没有发生变更; - kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", 1); - assertEquals(1, kv1.getVersion()); - assertEquals("V1-1", kv1.getValue().stringValue()); - kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", 2); - assertNull(kv1); - kv2 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K2", 1); - assertEquals(1, kv2.getVersion()); - - } - - private LedgerBlock buildBlock(LedgerRepository ledgerRepo, LedgerService ledgerService, - OperationHandleRegisteration opReg, TxDefinitor txDefinitor) { - LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(preBlock); - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(getSecurityManager(), newBlockEditor, - ledgerRepo, opReg); - - TxBuilder txBuilder = new TxBuilder(ledgerRepo.getHash()); - txDefinitor.buildTx(txBuilder); - - TransactionRequest txReq = buildAndSignRequest(txBuilder, parti0, parti0); - TransactionResponse resp = txbatchProcessor.schedule(txReq); - - // 提交区块; - TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare(); - txResultHandle.commit(); - - LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); - assertNotNull(resp.getBlockHash()); - assertEquals(preBlock.getHeight() + 1, resp.getBlockHeight()); - return latestBlock; - } - - private TransactionRequest buildAndSignRequest(TxBuilder txBuilder, BlockchainKeypair endpointKey, - BlockchainKeypair nodeKey) { - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - txReqBuilder.signAsEndpoint(endpointKey); - txReqBuilder.signAsNode(nodeKey); - TransactionRequest txReq = txReqBuilder.buildRequest(); - return txReq; - } - - private void registerDataAccount(LedgerRepository ledgerRepo, LedgerManager ledgerManager, - DefaultOperationHandleRegisteration opReg, HashDigest ledgerHash, BlockchainKeypair kpDataAccount) { - LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(preBlock); - - // 加载合约 - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(getSecurityManager(), newBlockEditor, - ledgerRepo, opReg); - - // 注册数据账户; - TxBuilder txBuilder = new TxBuilder(ledgerHash); - - txBuilder.dataAccounts().register(kpDataAccount.getIdentity()); - TransactionRequestBuilder txReqBuilder1 = txBuilder.prepareRequest(); - txReqBuilder1.signAsEndpoint(parti0); - txReqBuilder1.signAsNode(parti0); - TransactionRequest txReq = txReqBuilder1.buildRequest(); - - TransactionResponse resp = txbatchProcessor.schedule(txReq); - - TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare(); - txResultHandle.commit(); - - assertNotNull(resp.getBlockHash()); - assertEquals(TransactionState.SUCCESS, resp.getExecutionState()); - assertEquals(preBlock.getHeight() + 1, resp.getBlockHeight()); - } - - private void deploy(LedgerRepository ledgerRepo, LedgerManager ledgerManager, - DefaultOperationHandleRegisteration opReg, HashDigest ledgerHash, BlockchainKeypair contractKey) { - // 创建新区块的交易处理器; - LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(preBlock); - - // 加载合约 - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - LedgerSecurityManager securityManager = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, - ledgerRepo, opReg); - - // 构建基于接口调用合约的交易请求,用于测试合约调用; - TxBuilder txBuilder = new TxBuilder(ledgerHash); - txBuilder.contracts().deploy(contractKey.getIdentity(), chainCode()); - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - txReqBuilder.signAsEndpoint(parti0); - txReqBuilder.signAsNode(parti0); - TransactionRequest txReq = txReqBuilder.buildRequest(); - - TransactionResponse resp = txbatchProcessor.schedule(txReq); - OperationResult[] opResults = resp.getOperationResults(); - assertNull(opResults); - - // 提交区块; - TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare(); - txResultHandle.commit(); - } - - private HashDigest initLedger(MemoryKVStorage storage, BlockchainKeypair... partiKeys) { - // 创建初始化配置; - LedgerInitSetting initSetting = LedgerTestUtils.createLedgerInitSetting(partiKeys); - - // 创建账本; - LedgerEditor ldgEdt = LedgerTransactionalEditor.createEditor(initSetting, LEDGER_KEY_PREFIX, storage, storage); - - TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(partiKeys); - LedgerTransactionContext genisisTxCtx = ldgEdt.newTransaction(genesisTxReq); - LedgerDataset ldgDS = genisisTxCtx.getDataset(); - - for (int i = 0; i < partiKeys.length; i++) { - UserAccount userAccount = ldgDS.getUserAccountSet().register(partiKeys[i].getAddress(), - partiKeys[i].getPubKey()); - userAccount.setProperty("Name", "参与方-" + i, -1); - userAccount.setProperty("Share", "" + (10 + i), -1); - } - - LedgerTransaction tx = genisisTxCtx.commit(TransactionState.SUCCESS); - - assertEquals(genesisTxReq.getTransactionContent().getHash(), tx.getTransactionContent().getHash()); - assertEquals(0, tx.getBlockHeight()); - - LedgerBlock block = ldgEdt.prepare(); - - assertEquals(0, block.getHeight()); - assertNotNull(block.getHash()); - assertNull(block.getLedgerHash()); - assertNull(block.getPreviousHash()); - - // 提交数据,写入存储; - ldgEdt.commit(); - - HashDigest ledgerHash = block.getHash(); - return ledgerHash; - } - - private byte[] chainCode() { - - InputStream in = this.getClass().getResourceAsStream("/" + CONTRACT_JAR); - - return BytesUtils.copyToBytes(in); - } - - private static LedgerSecurityManager getSecurityManager() { - LedgerSecurityManager securityManager = Mockito.mock(LedgerSecurityManager.class); - - SecurityPolicy securityPolicy = Mockito.mock(SecurityPolicy.class); - when(securityPolicy.isEndpointEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isEndpointEnable(any(TransactionPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(TransactionPermission.class), any())).thenReturn(true); - - when(securityManager.createSecurityPolicy(any(), any())).thenReturn(securityPolicy); - - return securityManager; - } - - public static interface TxDefinitor { - - void buildTx(TxBuilder txBuilder); - - } -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAccountTest.java deleted file mode 100644 index 53e9eb4d..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAccountTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import java.util.Random; - -import org.junit.Before; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.UserInfo; - -/** - * Created by zhangshuang3 on 2018/9/3. - */ -public class LedgerAccountTest { - byte[] seed = null; - byte[] settingValue = null; - byte[] rawDigestBytes = null; - - @Before - public void initCfg() throws Exception { - Random rand = new Random(); - seed = new byte[8]; - settingValue = new byte[8]; - rawDigestBytes = new byte[8]; - rand.nextBytes(seed); - rand.nextBytes(settingValue); - rand.nextBytes(rawDigestBytes); - DataContractRegistry.register(BlockchainIdentity.class); - DataContractRegistry.register(UserInfo.class); - } - -// @Test -// public void testSerialize_AccountHeader() { -// String address = "xxxxxxxxxxxx"; -// PubKey pubKey = new PubKey(SMAlgorithm.SM2, rawDigestBytes); -// HashDigest hashDigest = new HashDigest(ClassicAlgorithm.SHA256, rawDigestBytes); -// MerkleAccountSet.AccountHeaderData accountHeaderData = new MerkleAccountSet.AccountHeaderData(Bytes.fromString(address), -// pubKey, hashDigest); -// -// // encode and decode -// byte[] encodeBytes = BinaryProtocol.encode(accountHeaderData, AccountHeader.class); -// AccountHeader deAccountHeaderData = BinaryProtocol.decode(encodeBytes); -// -// // verify start -// assertEquals(accountHeaderData.getAddress(), deAccountHeaderData.getAddress()); -// assertEquals(accountHeaderData.getPubKey(), deAccountHeaderData.getPubKey()); -// assertEquals(accountHeaderData.getRootHash(), deAccountHeaderData.getRootHash()); - -// } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAdminDatasetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAdminDatasetTest.java deleted file mode 100644 index e7fd2c27..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAdminDatasetTest.java +++ /dev/null @@ -1,308 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Random; - -import org.junit.Test; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.LedgerAdminSettings; -import com.jd.blockchain.ledger.LedgerMetadata_V2; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerSettings; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.ledger.RolePrivilegeSettings; -import com.jd.blockchain.ledger.RolePrivileges; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.UserRoles; -import com.jd.blockchain.ledger.UserAuthorizationSettings; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerAdminDataset; -import com.jd.blockchain.ledger.core.LedgerConfiguration; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class LedgerAdminDatasetTest { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private Random rand = new Random(); - - @Test - public void testSerialization() { - String keyPrefix = ""; - LedgerInitData initSetting = new LedgerInitData(); - ConsensusParticipantData[] parties = new ConsensusParticipantData[5]; - BlockchainKeypair[] bckeys = new BlockchainKeypair[parties.length]; - for (int i = 0; i < parties.length; i++) { - bckeys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ConsensusParticipantData(); - parties[i].setId(i); - parties[i].setAddress(AddressEncoding.generateAddress(bckeys[i].getPubKey())); - parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i)); - parties[i].setName("Participant[" + i + "]"); - parties[i].setPubKey(bckeys[i].getPubKey()); - parties[i].setParticipantState(ParticipantNodeState.ACTIVED); - } - ConsensusParticipantData[] parties1 = Arrays.copyOf(parties, 4); - initSetting.setConsensusParticipants(parties1); - - byte[] csSysSettingBytes = new byte[64]; - rand.nextBytes(csSysSettingBytes); - initSetting.setConsensusSettings(new Bytes(csSysSettingBytes)); - initSetting.setConsensusProvider("consensus-provider"); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig cryptoSetting = new CryptoConfig(); - cryptoSetting.setSupportedProviders(supportedProviders); - cryptoSetting.setAutoVerifyHash(true); - cryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - initSetting.setCryptoSetting(cryptoSetting); - - byte[] ledgerSeed = new byte[16]; - rand.nextBytes(ledgerSeed); - initSetting.setLedgerSeed(ledgerSeed); - - MemoryKVStorage testStorage = new MemoryKVStorage(); - - // Create intance with init setting; - LedgerAdminDataset ledgerAdminDataset = new LedgerAdminDataset(initSetting, keyPrefix, testStorage, - testStorage); - - ledgerAdminDataset.getRolePrivileges().addRolePrivilege("DEFAULT", - new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.REGISTER_USER, - LedgerPermission.APPROVE_TX }, - new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, - TransactionPermission.CONTRACT_OPERATION }); - - ledgerAdminDataset.getAuthorizations().addUserRoles(parties[0].getAddress(), RolesPolicy.UNION, "DEFAULT"); - - // New created instance is updated until being committed; - assertTrue(ledgerAdminDataset.isUpdated()); - // Hash of account is null until being committed; - assertNull(ledgerAdminDataset.getHash()); - - LedgerMetadata_V2 meta = ledgerAdminDataset.getMetadata(); - assertNull(meta.getParticipantsHash()); - - // Commit, and check the storage keys; - ledgerAdminDataset.commit(); - - // New created instance isn't updated after being committed; - assertFalse(ledgerAdminDataset.isUpdated()); - // Hash of account isn't null after being committed; - assertNotNull(ledgerAdminDataset.getHash()); - - meta = ledgerAdminDataset.getMetadata(); - assertNotNull(meta.getParticipantsHash()); - assertNotNull(meta.getSettingsHash()); - assertNotNull(meta.getRolePrivilegesHash()); - assertNotNull(meta.getUserRolesHash()); - - assertNotNull(ledgerAdminDataset.getRolePrivileges().getRolePrivilege("DEFAULT")); - - // ---------------------- - // Reload account from storage with readonly mode, and check the integrity of - // data; - HashDigest adminAccHash = ledgerAdminDataset.getHash(); - LedgerAdminDataset reloadAdminAccount1 = new LedgerAdminDataset(adminAccHash, keyPrefix, testStorage, - testStorage, true); - - LedgerMetadata_V2 meta2 = reloadAdminAccount1.getMetadata(); - assertNotNull(meta2.getParticipantsHash()); - assertNotNull(meta2.getSettingsHash()); - assertNotNull(meta2.getRolePrivilegesHash()); - assertNotNull(meta2.getUserRolesHash()); - - // verify realod settings of admin account; - verifyRealoadingSettings(reloadAdminAccount1, adminAccHash, ledgerAdminDataset.getMetadata(), - ledgerAdminDataset.getSettings()); - // verify the consensus participant list; - verifyRealoadingParities(reloadAdminAccount1, parties1); - // It will throw exeception because of this account is readonly; - verifyReadonlyState(reloadAdminAccount1); - - verifyRealoadingRoleAuthorizations(reloadAdminAccount1, ledgerAdminDataset.getRolePrivileges(), - ledgerAdminDataset.getAuthorizations()); - - // -------------- - // 重新加载,并进行修改; - LedgerAdminDataset reloadAdminAccount2 = new LedgerAdminDataset(adminAccHash, keyPrefix, testStorage, testStorage, false); - LedgerConfiguration newSetting = new LedgerConfiguration(reloadAdminAccount2.getPreviousSetting()); - byte[] newCsSettingBytes = new byte[64]; - rand.nextBytes(newCsSettingBytes); - newSetting.setConsensusSetting(new Bytes(newCsSettingBytes)); - newSetting.getCryptoSetting().setAutoVerifyHash(false); - reloadAdminAccount2.setLedgerSetting(newSetting); - - reloadAdminAccount2.addParticipant(parties[4]); - - reloadAdminAccount2.getRolePrivileges().addRolePrivilege("ADMIN", - new LedgerPermission[] { LedgerPermission.APPROVE_TX }, - new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION }); - - reloadAdminAccount2.getRolePrivileges().disablePermissions("DEFAULT", TransactionPermission.CONTRACT_OPERATION); - - reloadAdminAccount2.getAuthorizations().addUserRoles(parties[1].getAddress(), RolesPolicy.UNION, "DEFAULT", "ADMIN"); - - reloadAdminAccount2.commit(); - - LedgerSettings newlyLedgerSettings = reloadAdminAccount2.getSettings(); - - // record the new account hash; - HashDigest newAccHash = reloadAdminAccount2.getHash(); - LedgerMetadata_V2 newMeta = reloadAdminAccount2.getMetadata(); - - // load the last version of account and verify again; - LedgerAdminDataset previousAdminAccount = new LedgerAdminDataset(adminAccHash, keyPrefix, testStorage, - testStorage, true); - verifyRealoadingSettings(previousAdminAccount, adminAccHash, ledgerAdminDataset.getMetadata(), - ledgerAdminDataset.getSettings()); - verifyRealoadingParities(previousAdminAccount, parties1); - verifyReadonlyState(previousAdminAccount); - - // load the hash of new committing; - LedgerAdminDataset newlyAdminAccount = new LedgerAdminDataset(newAccHash, keyPrefix, testStorage, testStorage, - true); - verifyRealoadingSettings(newlyAdminAccount, newAccHash, newMeta, newlyLedgerSettings); - verifyRealoadingParities(newlyAdminAccount, parties); - verifyReadonlyState(newlyAdminAccount); - -// System.out.println("========= [LedgerAdminAccount Test] Show generated storage keys... ======="); -// testStorage.printStoragedKeys(); - } - - private void verifyRealoadingSettings(LedgerAdminDataset actualAccount, HashDigest expAccRootHash, - LedgerMetadata_V2 expMeta, LedgerSettings expLedgerSettings) { - // 验证基本信息; - assertFalse(actualAccount.isUpdated()); - assertTrue(actualAccount.isReadonly()); - - assertEquals(expAccRootHash, actualAccount.getHash()); - - // verify metadata; - LedgerMetadata_V2 actualMeta = actualAccount.getMetadata(); - assertArrayEquals(expMeta.getSeed(), actualMeta.getSeed()); - assertEquals(expMeta.getParticipantsHash(), actualMeta.getParticipantsHash()); - assertNotNull(actualMeta.getSettingsHash()); - assertEquals(expMeta.getSettingsHash(), actualMeta.getSettingsHash()); - assertNotNull(actualMeta.getRolePrivilegesHash()); - assertEquals(expMeta.getRolePrivilegesHash(), actualMeta.getRolePrivilegesHash()); - assertNotNull(actualMeta.getUserRolesHash()); - assertEquals(expMeta.getUserRolesHash(), actualMeta.getUserRolesHash()); - - LedgerSettings actualLedgerSettings = actualAccount.getSettings(); - - assertEquals(expLedgerSettings.getConsensusSetting(), actualLedgerSettings.getConsensusSetting()); - assertEquals(expLedgerSettings.getConsensusProvider(), actualLedgerSettings.getConsensusProvider()); - - assertEquals(expLedgerSettings.getCryptoSetting().getAutoVerifyHash(), - actualLedgerSettings.getCryptoSetting().getAutoVerifyHash()); - assertEquals(expLedgerSettings.getCryptoSetting().getHashAlgorithm(), - actualLedgerSettings.getCryptoSetting().getHashAlgorithm()); - } - - private void verifyRealoadingRoleAuthorizations(LedgerAdminSettings actualAccount, - RolePrivilegeSettings expRolePrivilegeSettings, UserAuthorizationSettings expUserRoleSettings) { - // 验证基本信息; - RolePrivilegeSettings actualRolePrivileges = actualAccount.getRolePrivileges(); - RolePrivileges[] expRPs = expRolePrivilegeSettings.getRolePrivileges(); - - assertEquals(expRPs.length, actualRolePrivileges.getRoleCount()); - - for (RolePrivileges expRP : expRPs) { - RolePrivileges actualRP = actualRolePrivileges.getRolePrivilege(expRP.getRoleName()); - assertNotNull(actualRP); - assertArrayEquals(expRP.getLedgerPrivilege().toBytes(), actualRP.getLedgerPrivilege().toBytes()); - assertArrayEquals(expRP.getTransactionPrivilege().toBytes(), actualRP.getTransactionPrivilege().toBytes()); - } - - UserAuthorizationSettings actualUserRoleSettings = actualAccount.getAuthorizations(); - UserRoles[] expUserRoles = expUserRoleSettings.getUserRoles(); - assertEquals(expUserRoles.length, actualUserRoleSettings.getUserCount()); - - for (UserRoles expUR : expUserRoles) { - UserRoles actualUR = actualAccount.getAuthorizations().getUserRoles(expUR.getUserAddress()); - assertNotNull(actualUR); - assertEquals(expUR.getPolicy(), actualUR.getPolicy()); - String[] expRoles = expUR.getRoles(); - Arrays.sort(expRoles); - String[] actualRoles = actualUR.getRoles(); - Arrays.sort(actualRoles); - assertArrayEquals(expRoles, actualRoles); - } - } - - private void verifyRealoadingParities(LedgerAdminInfo actualAccount, ParticipantNode[] expParties) { - assertEquals(expParties.length, actualAccount.getParticipantCount()); - ParticipantNode[] actualPaticipants = actualAccount.getParticipants(); - assertEquals(expParties.length, actualPaticipants.length); - for (int i = 0; i < actualPaticipants.length; i++) { - ParticipantNode rlParti = actualPaticipants[i]; - assertEquals(expParties[i].getAddress(), rlParti.getAddress()); - assertEquals(expParties[i].getName(), rlParti.getName()); - // assertEquals(expParties[i].getConsensusAddress(), - // rlParti.getConsensusAddress()); - assertEquals(expParties[i].getPubKey(), rlParti.getPubKey()); - } - } - - /** - * 验证指定账户是否只读; - * - * @param readonlyAccount - */ - private void verifyReadonlyState(LedgerAdminDataset readonlyAccount) { - ConsensusParticipantData newParti = new ConsensusParticipantData(); - newParti.setId((int) readonlyAccount.getParticipantCount()); - newParti.setHostAddress( - new NetworkAddress("192.168.10." + (10 + newParti.getId()), 10010 + 10 * newParti.getId())); - newParti.setName("Participant[" + newParti.getAddress() + "]"); - - BlockchainKeypair newKey = BlockchainKeyGenerator.getInstance().generate(); - newParti.setPubKey(newKey.getPubKey()); - - Throwable ex = null; - try { - readonlyAccount.addParticipant(newParti); - } catch (Exception e) { - ex = e; - } - assertNotNull(ex); - - ex = null; - try { - LedgerConfiguration newLedgerSetting = new LedgerConfiguration(readonlyAccount.getSettings()); - readonlyAccount.setLedgerSetting(newLedgerSetting); - } catch (Exception e) { - ex = e; - } - assertNotNull(ex); - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerBlockImplTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerBlockImplTest.java deleted file mode 100644 index 9479cc2b..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerBlockImplTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.LedgerBlockImplTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午10:45 - * Description: - */ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.core.LedgerBlockData; -import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class LedgerBlockImplTest { - - private LedgerBlockData data; - - @Before - public void initLedgerBlockImpl() { - DataContractRegistry.register(LedgerBlock.class); - DataContractRegistry.register(LedgerDataSnapshot.class); - long height = 9999L; - HashDigest ledgerHash = new HashDigest(ClassicAlgorithm.SHA256, "zhangsan".getBytes()); - HashDigest previousHash = new HashDigest(ClassicAlgorithm.SHA256, "lisi".getBytes()); - data = new LedgerBlockData(height, ledgerHash, previousHash); - data.setHash(new HashDigest(ClassicAlgorithm.SHA256, "wangwu".getBytes())); - data.setTransactionSetHash(new HashDigest(ClassicAlgorithm.SHA256, "zhaoliu".getBytes())); - - // 设置LedgerDataSnapshot相关属性 - data.setAdminAccountHash(new HashDigest(ClassicAlgorithm.SHA256, "jd1".getBytes())); - data.setDataAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "jd2".getBytes())); - data.setUserAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "jd3".getBytes())); - data.setContractAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "jd4".getBytes())); - - } - - @Test - public void testSerialize_LedgerBlock() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, LedgerBlock.class); - LedgerBlock resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getHash(), data.getHash()); - assertEquals(resolvedData.getHeight(), data.getHeight()); - assertEquals(resolvedData.getLedgerHash(), data.getLedgerHash()); - assertEquals(resolvedData.getPreviousHash(), data.getPreviousHash()); - assertEquals(resolvedData.getTransactionSetHash(), data.getTransactionSetHash()); - assertEquals(resolvedData.getAdminAccountHash(), data.getAdminAccountHash()); - assertEquals(resolvedData.getContractAccountSetHash(), data.getContractAccountSetHash()); - assertEquals(resolvedData.getDataAccountSetHash(), data.getDataAccountSetHash()); - assertEquals(resolvedData.getUserAccountSetHash(), data.getUserAccountSetHash()); - System.out.println("------Assert OK ------"); - } - - // notice: LedgerBlock interface has more field info than LedgerDataSnapshot - // interface, so cannot deserialize LedgerBlock - // with LedgerDataSnapshot encode - // @Test - // public void testSerialize_LedgerDataSnapshot() throws Exception { - // byte[] serialBytes = BinaryEncodingUtils.encode(data, - // LedgerDataSnapshot.class); - // LedgerDataSnapshot resolvedData = BinaryEncodingUtils.decode(serialBytes, - // null, - // LedgerBlockData.class); - // System.out.println("------Assert start ------"); - // assertEquals(resolvedData.getAdminAccountHash(), data.getAdminAccountHash()); - // assertEquals(resolvedData.getAdminAccountHash(), data.getAdminAccountHash()); - // assertEquals(resolvedData.getContractAccountSetHash(), - // data.getContractAccountSetHash()); - // assertEquals(resolvedData.getDataAccountSetHash(), - // data.getDataAccountSetHash()); - // assertEquals(resolvedData.getUserAccountSetHash(), - // data.getUserAccountSetHash()); - // System.out.println("------Assert OK ------"); - // } - - @Test - public void testSerialize_LedgerDataSnapshot() throws Exception { - TransactionStagedSnapshot transactionStagedSnapshot = new TransactionStagedSnapshot(); - - HashDigest admin = new HashDigest(ClassicAlgorithm.SHA256, "alice".getBytes()); - HashDigest contract = new HashDigest(ClassicAlgorithm.SHA256, "bob".getBytes()); - HashDigest data = new HashDigest(ClassicAlgorithm.SHA256, "jerry".getBytes()); - HashDigest user = new HashDigest(ClassicAlgorithm.SHA256, "tom".getBytes()); - - transactionStagedSnapshot.setAdminAccountHash(admin); - transactionStagedSnapshot.setContractAccountSetHash(contract); - transactionStagedSnapshot.setDataAccountSetHash(data); - transactionStagedSnapshot.setUserAccountSetHash(user); - - byte[] serialBytes = BinaryProtocol.encode(transactionStagedSnapshot, LedgerDataSnapshot.class); - LedgerDataSnapshot resolvedData = BinaryProtocol.decode(serialBytes); - - // verify start - assertEquals(resolvedData.getAdminAccountHash(), transactionStagedSnapshot.getAdminAccountHash()); - assertEquals(resolvedData.getContractAccountSetHash(), transactionStagedSnapshot.getContractAccountSetHash()); - assertEquals(resolvedData.getDataAccountSetHash(), transactionStagedSnapshot.getDataAccountSetHash()); - assertEquals(resolvedData.getUserAccountSetHash(), transactionStagedSnapshot.getUserAccountSetHash()); - // verify succeed - - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerEditorTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerEditorTest.java deleted file mode 100644 index 78f04762..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerEditorTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.ledger.core.LedgerTransactionalEditor; -import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; - -public class LedgerEditorTest { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - static { - DataContractRegistry.register(com.jd.blockchain.ledger.TransactionContent.class); - DataContractRegistry.register(com.jd.blockchain.ledger.UserRegisterOperation.class); - DataContractRegistry.register(com.jd.blockchain.ledger.BlockBody.class); - } - - private static final String LEDGER_KEY_PREFIX = "LDG://"; - private SignatureFunction signatureFunction; - - private BlockchainKeypair parti0 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti1 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti2 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti3 = BlockchainKeyGenerator.getInstance().generate(); - - private BlockchainKeypair[] participants = { parti0, parti1, parti2, parti3 }; - - /** - * 初始化一个; - */ - @Before - public void beforeTest() { - signatureFunction = Crypto.getSignatureFunction("ED25519"); - } - - /** - * @return - */ - private LedgerEditor createLedgerInitEditor() { - // 存储; - MemoryKVStorage storage = new MemoryKVStorage(); - - // 创建初始化配置; - LedgerInitSetting initSetting = LedgerTestUtils.createLedgerInitSetting(); - - // 创建账本; - return LedgerTransactionalEditor.createEditor(initSetting, LEDGER_KEY_PREFIX, storage, storage); - } - - private LedgerTransactionContext createGenisisTx(LedgerEditor ldgEdt, BlockchainKeypair[] partis) { - TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(partis); - - LedgerTransactionContext txCtx = ldgEdt.newTransaction(genesisTxReq); - - return txCtx; - } - - @SuppressWarnings("unused") - @Test - public void testWriteDataAccoutKvOp() { - LedgerEditor ldgEdt = createLedgerInitEditor(); - LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants); - LedgerDataset ldgDS = genisisTxCtx.getDataset(); - - AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair(); - BlockchainKeypair dataKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey()); - - DataAccount dataAccount = ldgDS.getDataAccountSet().register(dataKP.getAddress(), dataKP.getPubKey(), null); - - dataAccount.getDataset().setValue("A", TypedValue.fromText("abc"), -1); - - LedgerTransaction tx = genisisTxCtx.commit(TransactionState.SUCCESS); - LedgerBlock block = ldgEdt.prepare(); - // 提交数据,写入存储; - ldgEdt.commit(); - - // 预期这是第1个区块; - assertNotNull(block); - assertNotNull(block.getHash()); - assertEquals(0, block.getHeight()); - - // 验证数据读写的一致性; - BytesValue bytes = dataAccount.getDataset().getValue("A"); - assertEquals(DataType.TEXT, bytes.getType()); - String textValue = bytes.getBytes().toUTF8String(); - assertEquals("abc", textValue); - } - - /** - * 测试创建账本; - */ - @Test - public void testGennesisBlockCreation() { - LedgerEditor ldgEdt = createLedgerInitEditor(); - LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants); - LedgerDataset ldgDS = genisisTxCtx.getDataset(); - - AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair(); - BlockchainKeypair userKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey()); - UserAccount userAccount = ldgDS.getUserAccountSet().register(userKP.getAddress(), userKP.getPubKey()); - userAccount.setProperty("Name", "孙悟空", -1); - userAccount.setProperty("Age", "10000", -1); - - LedgerTransaction tx = genisisTxCtx.commit(TransactionState.SUCCESS); - - TransactionRequest genesisTxReq = genisisTxCtx.getTransactionRequest(); - assertEquals(genesisTxReq.getTransactionContent().getHash(), tx.getTransactionContent().getHash()); - assertEquals(0, tx.getBlockHeight()); - - LedgerBlock block = ldgEdt.prepare(); - - assertEquals(0, block.getHeight()); - assertNotNull(block.getHash()); - assertNull(block.getLedgerHash()); - assertNull(block.getPreviousHash()); - - // 提交数据,写入存储; - ldgEdt.commit(); - - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitOperationTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitOperationTest.java deleted file mode 100644 index e916cc66..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitOperationTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Random; - -import com.jd.blockchain.ledger.*; -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.ParticipantCertData; -import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitOpTemplate; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class LedgerInitOperationTest { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - byte[] seed = null; - byte[] csSysSettingBytes = null; - LedgerInitData ledgerInitSettingData = new LedgerInitData(); - - @Before - public void initCfg() { - - DataContractRegistry.register(LedgerInitSetting.class); - DataContractRegistry.register(LedgerInitOperation.class); - - Random rand = new Random(); - - seed = new byte[8]; - rand.nextBytes(seed); - csSysSettingBytes = new byte[64]; - rand.nextBytes(csSysSettingBytes); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - - ledgerInitSettingData.setConsensusSettings(new Bytes(csSysSettingBytes)); - ledgerInitSettingData.setConsensusProvider("cons-provider"); - - ledgerInitSettingData.setLedgerSeed(seed); - - ledgerInitSettingData.setCryptoSetting(cryptoConfig); - } - - @Test - public void test_LedgerInitOperation_ConsensusParticipantData() { - ConsensusParticipantData[] parties = new ConsensusParticipantData[4]; - BlockchainKeypair[] keys = new BlockchainKeypair[parties.length]; - for (int i = 0; i < parties.length; i++) { - keys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ConsensusParticipantData(); - // parties[i].setId(i); - parties[i].setAddress(AddressEncoding.generateAddress(keys[i].getPubKey())); - parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i)); - parties[i].setName("Participant[" + i + "]"); - parties[i].setPubKey(keys[i].getPubKey()); - parties[i].setParticipantState(ParticipantNodeState.ACTIVED); - } - ConsensusParticipantData[] parties1 = Arrays.copyOf(parties, 4); - - ledgerInitSettingData.setConsensusParticipants(parties1); - - LedgerInitOpTemplate template = new LedgerInitOpTemplate(ledgerInitSettingData); - - byte[] encode = BinaryProtocol.encode(template, LedgerInitOperation.class); - LedgerInitOperation decode = BinaryProtocol.decode(encode); - - for (int i = 0; i < template.getInitSetting().getConsensusParticipants().length; i++) { - assertEquals(template.getInitSetting().getConsensusParticipants()[i].getAddress(), - decode.getInitSetting().getConsensusParticipants()[i].getAddress()); - assertEquals(template.getInitSetting().getConsensusParticipants()[i].getName(), - decode.getInitSetting().getConsensusParticipants()[i].getName()); - assertEquals(template.getInitSetting().getConsensusParticipants()[i].getPubKey(), - decode.getInitSetting().getConsensusParticipants()[i].getPubKey()); - - } - assertArrayEquals(template.getInitSetting().getLedgerSeed(), decode.getInitSetting().getLedgerSeed()); - assertArrayEquals(template.getInitSetting().getConsensusSettings().toBytes(), - decode.getInitSetting().getConsensusSettings().toBytes()); - assertEquals(template.getInitSetting().getCryptoSetting().getHashAlgorithm(), - decode.getInitSetting().getCryptoSetting().getHashAlgorithm()); - assertEquals(template.getInitSetting().getCryptoSetting().getAutoVerifyHash(), - decode.getInitSetting().getCryptoSetting().getAutoVerifyHash()); - assertEquals(template.getInitSetting().getConsensusProvider(), decode.getInitSetting().getConsensusProvider()); - - } - - @Test - public void test_LedgerInitOperation_ParticipantCertData() { - ParticipantCertData[] parties = new ParticipantCertData[4]; - BlockchainKeypair[] keys = new BlockchainKeypair[parties.length]; - - for (int i = 0; i < parties.length; i++) { - keys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ParticipantCertData(AddressEncoding.generateAddress(keys[i].getPubKey()), - "Participant[" + i + "]", keys[i].getPubKey(), ParticipantNodeState.ACTIVED); - } - - ParticipantCertData[] parties1 = Arrays.copyOf(parties, 4); - - ledgerInitSettingData.setConsensusParticipants(parties1); - - LedgerInitOpTemplate template = new LedgerInitOpTemplate(ledgerInitSettingData); - - byte[] encode = BinaryProtocol.encode(template, LedgerInitOperation.class); - LedgerInitOperation decode = BinaryProtocol.decode(encode); - - for (int i = 0; i < template.getInitSetting().getConsensusParticipants().length; i++) { - assertEquals(template.getInitSetting().getConsensusParticipants()[i].getAddress(), - decode.getInitSetting().getConsensusParticipants()[i].getAddress()); - assertEquals(template.getInitSetting().getConsensusParticipants()[i].getName(), - decode.getInitSetting().getConsensusParticipants()[i].getName()); - assertEquals(template.getInitSetting().getConsensusParticipants()[i].getPubKey(), - decode.getInitSetting().getConsensusParticipants()[i].getPubKey()); - - } - assertArrayEquals(template.getInitSetting().getLedgerSeed(), decode.getInitSetting().getLedgerSeed()); - assertArrayEquals(template.getInitSetting().getConsensusSettings().toBytes(), - decode.getInitSetting().getConsensusSettings().toBytes()); - assertEquals(template.getInitSetting().getCryptoSetting().getHashAlgorithm(), - decode.getInitSetting().getCryptoSetting().getHashAlgorithm()); - assertEquals(template.getInitSetting().getCryptoSetting().getAutoVerifyHash(), - decode.getInitSetting().getCryptoSetting().getAutoVerifyHash()); - assertEquals(template.getInitSetting().getConsensusProvider(), decode.getInitSetting().getConsensusProvider()); - } -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitSettingSerializeTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitSettingSerializeTest.java deleted file mode 100644 index 3884186e..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitSettingSerializeTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Random; - -import com.jd.blockchain.ledger.ParticipantNodeState; -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.ParticipantCertData; -import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitOpTemplate; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class LedgerInitSettingSerializeTest { - byte[] seed = null; - byte[] csSysSettingBytes = null; - LedgerInitData ledgerInitSettingData = new LedgerInitData(); - LedgerInitOpTemplate template = new LedgerInitOpTemplate(); - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - @Before - public void initCfg() { - - DataContractRegistry.register(LedgerInitSetting.class); - Random rand = new Random(); - - seed = new byte[8]; - rand.nextBytes(seed); - csSysSettingBytes = new byte[64]; - rand.nextBytes(csSysSettingBytes); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - - ledgerInitSettingData.setConsensusSettings(new Bytes(csSysSettingBytes)); - ledgerInitSettingData.setConsensusProvider("cons-provider"); - - ledgerInitSettingData.setLedgerSeed(seed); - - ledgerInitSettingData.setCryptoSetting(cryptoConfig); - - } - - @Test - public void test_ledgerinitsetting_ConsensusParticipantData() { - - ConsensusParticipantData[] parties = new ConsensusParticipantData[4]; - BlockchainKeypair[] keys = new BlockchainKeypair[parties.length]; - for (int i = 0; i < parties.length; i++) { - keys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ConsensusParticipantData(); - // parties[i].setId(i); - parties[i].setAddress(AddressEncoding.generateAddress(keys[i].getPubKey())); - parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i)); - parties[i].setName("Participant[" + i + "]"); - parties[i].setPubKey(keys[i].getPubKey()); - parties[i].setParticipantState(ParticipantNodeState.ACTIVED); - } - ConsensusParticipantData[] parties1 = Arrays.copyOf(parties, 4); - - ledgerInitSettingData.setConsensusParticipants(parties1); - - byte[] encode = BinaryProtocol.encode(ledgerInitSettingData, LedgerInitSetting.class); - - LedgerInitSetting decode = BinaryProtocol.decode(encode); - - for (int i = 0; i < ledgerInitSettingData.getConsensusParticipants().length; i++) { - assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getAddress(), - decode.getConsensusParticipants()[i].getAddress()); - assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getName(), - decode.getConsensusParticipants()[i].getName()); - assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getPubKey(), - decode.getConsensusParticipants()[i].getPubKey()); - - } - assertArrayEquals(ledgerInitSettingData.getLedgerSeed(), decode.getLedgerSeed()); - assertArrayEquals(ledgerInitSettingData.getConsensusSettings().toBytes(), - decode.getConsensusSettings().toBytes()); - assertEquals(ledgerInitSettingData.getCryptoSetting().getHashAlgorithm(), - decode.getCryptoSetting().getHashAlgorithm()); - assertEquals(ledgerInitSettingData.getCryptoSetting().getAutoVerifyHash(), - decode.getCryptoSetting().getAutoVerifyHash()); - assertEquals(ledgerInitSettingData.getConsensusProvider(), decode.getConsensusProvider()); - - } - - // @Test - // public void test_ledgerinitsetting_ConsensusParticipantConfig() { - // } - - @Test - public void test_ledgerinitsetting_ParticipantCertData() { - - ParticipantCertData[] parties = new ParticipantCertData[4]; - BlockchainKeypair[] keys = new BlockchainKeypair[parties.length]; - - for (int i = 0; i < parties.length; i++) { - keys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ParticipantCertData(AddressEncoding.generateAddress(keys[i].getPubKey()), - "Participant[" + i + "]", keys[i].getPubKey(), ParticipantNodeState.ACTIVED); - } - - ParticipantCertData[] parties1 = Arrays.copyOf(parties, 4); - - ledgerInitSettingData.setConsensusParticipants(parties1); - - byte[] encode = BinaryProtocol.encode(ledgerInitSettingData, LedgerInitSetting.class); - - LedgerInitSetting decode = BinaryProtocol.decode(encode); - - for (int i = 0; i < ledgerInitSettingData.getConsensusParticipants().length; i++) { - assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getAddress(), - decode.getConsensusParticipants()[i].getAddress()); - assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getName(), - decode.getConsensusParticipants()[i].getName()); - assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getPubKey(), - decode.getConsensusParticipants()[i].getPubKey()); - - } - assertArrayEquals(ledgerInitSettingData.getLedgerSeed(), decode.getLedgerSeed()); - assertArrayEquals(ledgerInitSettingData.getConsensusSettings().toBytes(), - decode.getConsensusSettings().toBytes()); - assertEquals(ledgerInitSettingData.getCryptoSetting().getHashAlgorithm(), - decode.getCryptoSetting().getHashAlgorithm()); - assertEquals(ledgerInitSettingData.getCryptoSetting().getAutoVerifyHash(), - decode.getCryptoSetting().getAutoVerifyHash()); - assertEquals(ledgerInitSettingData.getConsensusProvider(), decode.getConsensusProvider()); - } -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerManagerTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerManagerTest.java deleted file mode 100644 index 225bd16d..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerManagerTest.java +++ /dev/null @@ -1,243 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.stream.Stream; - -import com.jd.blockchain.ledger.*; -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.core.ContractAccountQuery; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.DataAccountQuery; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerInitializer; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.UserAccountQuery; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class LedgerManagerTest { - - static { - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(ParticipantNode.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - DataContractRegistry.register(BlockBody.class); - DataContractRegistry.register(CryptoProvider.class); - } - - public static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private BlockchainKeypair parti0 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti1 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti2 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti3 = BlockchainKeyGenerator.getInstance().generate(); - - private BlockchainKeypair[] participants = { parti0, parti1, parti2, parti3 }; - - private SignatureFunction signatureFunction; - - @Before - public void intialize() { - signatureFunction = Crypto.getSignatureFunction("ED25519"); - } - - @Test - public void testLedgerInit() { - // 创建账本初始化配置; - LedgerInitSetting initSetting = createLedgerInitSetting(); - - // 采用基于内存的 Storage; - MemoryKVStorage storage = new MemoryKVStorage(); - - // 新建账本; - LedgerEditor ldgEdt = LedgerInitializer.createLedgerEditor(initSetting, storage); - - // 创建一个模拟的创世交易; - TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(participants); - - // 记录交易,注册用户; - LedgerTransactionContext txCtx = ldgEdt.newTransaction(genesisTxReq); - LedgerDataset ldgDS = txCtx.getDataset(); - BlockchainKeypair userKP = BlockchainKeyGenerator.getInstance().generate(); - - UserAccount userAccount = ldgDS.getUserAccountSet().register(userKP.getAddress(), userKP.getPubKey()); - userAccount.setProperty("Name", "孙悟空", -1); - userAccount.setProperty("Age", "10000", -1); - - System.out.println("UserAddress=" + userAccount.getAddress()); - - // 提交交易结果; - LedgerTransaction tx = txCtx.commit(TransactionState.SUCCESS); - - assertEquals(genesisTxReq.getTransactionContent().getHash(), tx.getTransactionContent().getHash()); - assertEquals(0, tx.getBlockHeight()); - - // 生成区块; - LedgerBlock genesisBlock = ldgEdt.prepare(); - HashDigest ledgerHash = genesisBlock.getHash(); - - assertEquals(0, genesisBlock.getHeight()); - assertNotNull(genesisBlock.getHash()); - assertNull(genesisBlock.getPreviousHash()); - // 创世区块的账本hash 为null;创世区块本身的哈希就代表了账本的哈希; - assertNull(genesisBlock.getLedgerHash()); - - // 提交数据,写入存储; - ldgEdt.commit(); - - assertNull(genesisBlock.getLedgerHash()); - assertNotNull(genesisBlock.getHash()); - - // 重新加载并校验结果; - LedgerManager reloadLedgerManager = new LedgerManager(); - LedgerRepository reloadLedgerRepo = reloadLedgerManager.register(ledgerHash, storage); - - HashDigest genesisHash = reloadLedgerRepo.getBlockHash(0); - assertEquals(ledgerHash, genesisHash); - - LedgerBlock latestBlock = reloadLedgerRepo.getLatestBlock(); - assertEquals(0, latestBlock.getHeight()); - assertEquals(ledgerHash, latestBlock.getHash()); - // 创世区块的账本hash 为null;创世区块本身的哈希就代表了账本的哈希; - assertNull(latestBlock.getLedgerHash()); - - LedgerEditor editor1 = reloadLedgerRepo.createNextBlock(); - - TxBuilder txBuilder = new TxBuilder(ledgerHash); - BlockchainKeypair dataKey = BlockchainKeyGenerator.getInstance().generate(); - txBuilder.dataAccounts().register(dataKey.getIdentity()); - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - DigitalSignature dgtsign = txReqBuilder.signAsEndpoint(userKP); - TransactionRequest txRequest = txReqBuilder.buildRequest(); - - LedgerTransactionContext txCtx1 = editor1.newTransaction(txRequest); - txCtx1.getDataset().getDataAccountSet().register(dataKey.getAddress(), dataKey.getPubKey(), null); - txCtx1.commit(TransactionState.SUCCESS); - - LedgerBlock block1 = editor1.prepare(); - editor1.commit(); - assertEquals(1, block1.getHeight()); - assertNotNull(block1.getHash()); - assertEquals(genesisHash, block1.getPreviousHash()); - assertEquals(ledgerHash, block1.getLedgerHash()); - - latestBlock = reloadLedgerRepo.getLatestBlock(); - assertEquals(1, latestBlock.getHeight()); - assertEquals(block1.getHash(), latestBlock.getHash()); - - showStorageKeys(storage); - - reloadLedgerManager = new LedgerManager(); - reloadLedgerRepo = reloadLedgerManager.register(ledgerHash, storage); - latestBlock = reloadLedgerRepo.getLatestBlock(); - assertEquals(1, latestBlock.getHeight()); - assertEquals(block1.getHash(), latestBlock.getHash()); - - DataAccountQuery dataAccountSet = reloadLedgerRepo.getDataAccountSet(latestBlock); - UserAccountQuery userAccountSet = reloadLedgerRepo.getUserAccountSet(latestBlock); - ContractAccountQuery contractAccountSet = reloadLedgerRepo.getContractAccountSet(latestBlock); - - } - - private void showStorageKeys(MemoryKVStorage storage) { - // 输出写入的 kv; - System.out.println("------------------- Storage Keys -------------------"); - Object[] keys = Stream.of(storage.getStorageKeySet().toArray(new Bytes[0])).map(p -> p.toString()) - .sorted((o1, o2) -> o1.compareTo(o2)).toArray(); - int i = 0; - for (Object k : keys) { - i++; - System.out.println(i + ":" + k.toString()); - } - } - - private LedgerInitSetting createLedgerInitSetting() { - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig defCryptoSetting = new CryptoConfig(); - - defCryptoSetting.setSupportedProviders(supportedProviders); - - defCryptoSetting.setAutoVerifyHash(true); - defCryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - - LedgerInitData initSetting = new LedgerInitData(); - - initSetting.setLedgerSeed(BytesUtils.toBytes("A Test Ledger seed!", "UTF-8")); - initSetting.setCryptoSetting(defCryptoSetting); - ConsensusParticipantData[] parties = new ConsensusParticipantData[4]; - parties[0] = new ConsensusParticipantData(); - parties[0].setId(0); - parties[0].setName("John"); - AsymmetricKeypair kp0 = signatureFunction.generateKeypair(); - parties[0].setPubKey(kp0.getPubKey()); - parties[0].setAddress(AddressEncoding.generateAddress(kp0.getPubKey())); - parties[0].setHostAddress(new NetworkAddress("127.0.0.1", 9000)); - parties[0].setParticipantState(ParticipantNodeState.ACTIVED); - - parties[1] = new ConsensusParticipantData(); - parties[1].setId(1); - parties[1].setName("Mary"); - AsymmetricKeypair kp1 = signatureFunction.generateKeypair(); - parties[1].setPubKey(kp1.getPubKey()); - parties[1].setAddress(AddressEncoding.generateAddress(kp1.getPubKey())); - parties[1].setHostAddress(new NetworkAddress("127.0.0.1", 9010)); - parties[1].setParticipantState(ParticipantNodeState.ACTIVED); - - parties[2] = new ConsensusParticipantData(); - parties[2].setId(2); - parties[2].setName("Jerry"); - AsymmetricKeypair kp2 = signatureFunction.generateKeypair(); - parties[2].setPubKey(kp2.getPubKey()); - parties[2].setAddress(AddressEncoding.generateAddress(kp2.getPubKey())); - parties[2].setHostAddress(new NetworkAddress("127.0.0.1", 9020)); - parties[2].setParticipantState(ParticipantNodeState.ACTIVED); - - parties[3] = new ConsensusParticipantData(); - parties[3].setId(3); - parties[3].setName("Tom"); - AsymmetricKeypair kp3 = signatureFunction.generateKeypair(); - parties[3].setPubKey(kp3.getPubKey()); - parties[3].setAddress(AddressEncoding.generateAddress(kp3.getPubKey())); - parties[3].setHostAddress(new NetworkAddress("127.0.0.1", 9030)); - parties[3].setParticipantState(ParticipantNodeState.ACTIVED); - - initSetting.setConsensusParticipants(parties); - - return initSetting; - } - - // -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerMetaDataTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerMetaDataTest.java deleted file mode 100644 index 51254613..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerMetaDataTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Random; - -import com.jd.blockchain.ledger.*; -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerAdminDataset; -import com.jd.blockchain.ledger.core.LedgerConfiguration; -import com.jd.blockchain.ledger.core.ParticipantCertData; -import com.jd.blockchain.utils.Bytes; - -/** - * Created by zhangshuang3 on 2018/8/31. - */ -public class LedgerMetaDataTest { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - byte[] seed = null; - String consensusProvider = "test-provider"; - byte[] consensusSettingBytes = null; - byte[] rawDigestBytes = null; - - @Before - public void initCfg() throws Exception { - Random rand = new Random(); - seed = new byte[8]; - consensusSettingBytes = new byte[8]; - rawDigestBytes = new byte[8]; - rand.nextBytes(seed); - rand.nextBytes(consensusSettingBytes); - rand.nextBytes(rawDigestBytes); - DataContractRegistry.register(LedgerMetadata.class); - DataContractRegistry.register(ParticipantNode.class); - } - - @Test - public void testSerialize_LedgerMetadata() { - // LedgerCodes.METADATA - - // prepare work - // ConsensusConfig consensusConfig = new ConsensusConfig(); - // consensusConfig.setValue(settingValue);ClassicCryptoService.ED25519_ALGORITHM - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - -// LedgerConfiguration ledgerConfiguration = new LedgerConfiguration(consensusProvider, -// new Bytes(consensusSettingBytes), cryptoConfig); - HashDigest settingsHash = Crypto.getHashFunction("SHA256").hash(consensusSettingBytes); - - LedgerAdminDataset.LedgerMetadataInfo ledgerMetadata = new LedgerAdminDataset.LedgerMetadataInfo(); - - ledgerMetadata.setSeed(seed); - ledgerMetadata.setSettingsHash(settingsHash); - - HashDigest hashDigest = new HashDigest(ClassicAlgorithm.SHA256, rawDigestBytes); - ledgerMetadata.setParticipantsHash(hashDigest); - - // encode and decode - byte[] encodeBytes = BinaryProtocol.encode(ledgerMetadata, LedgerMetadata.class); - LedgerMetadata deLedgerMetaData = BinaryProtocol.decode(encodeBytes); - - // verify start - assertArrayEquals(ledgerMetadata.getSeed(), deLedgerMetaData.getSeed()); - assertEquals(ledgerMetadata.getParticipantsHash(), deLedgerMetaData.getParticipantsHash()); - assertEquals(ledgerMetadata.getSettingsHash(), deLedgerMetaData.getSettingsHash()); - - return; - } - - @Test - public void testSerialize_LedgerSetting() { - // LedgerCodes.METADATA_LEDGER_SETTING - Random rand = new Random(); - byte[] csSettingsBytes = new byte[8]; - rand.nextBytes(csSettingsBytes); - String consensusProvider = "testprovider"; - - // ConsensusConfig consensusConfig = new ConsensusConfig(); - // consensusConfig.setValue(settingValue); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - - LedgerConfiguration ledgerConfiguration = new LedgerConfiguration(consensusProvider, new Bytes(csSettingsBytes), - cryptoConfig); - byte[] encodeBytes = BinaryProtocol.encode(ledgerConfiguration, LedgerSettings.class); - LedgerSettings deLedgerConfiguration = BinaryProtocol.decode(encodeBytes); - // verify start - assertTrue(ledgerConfiguration.getConsensusSetting().equals(deLedgerConfiguration.getConsensusSetting())); - assertEquals(ledgerConfiguration.getCryptoSetting().getAutoVerifyHash(), - deLedgerConfiguration.getCryptoSetting().getAutoVerifyHash()); - assertEquals(ledgerConfiguration.getCryptoSetting().getHashAlgorithm(), - deLedgerConfiguration.getCryptoSetting().getHashAlgorithm()); - - return; - } - - // @Test - // public void testSerialize_ConsensusSetting() { - // //LedgerCodes.METADATA_LEDGER_SETTING_CONSENSUS - // Random rand = new Random(); - // byte[] settingValue = new byte[8]; - // rand.nextBytes(settingValue); - // - // ConsensusConfig consensusConfig = new ConsensusConfig(); - // consensusConfig.setValue(settingValue); - // byte[] encodeBytes = BinaryEncodingUtils.encode(consensusConfig, - // ConsensusSetting.class); - // ConsensusSetting deConsensusConfig = BinaryEncodingUtils.decode(encodeBytes); - // - // //verify start - // assertArrayEquals(consensusConfig.getValue(), deConsensusConfig.getValue()); - // - // return; - // } - - @Test - public void testSerialize_CryptoSetting() { - // LedgerCodes.METADATA_LEDGER_SETTING_CRYPTO - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - byte[] encodeBytes = BinaryProtocol.encode(cryptoConfig, CryptoSetting.class); - CryptoSetting deCryptoConfig = BinaryProtocol.decode(encodeBytes); - - // verify start - assertEquals(cryptoConfig.getHashAlgorithm(), deCryptoConfig.getHashAlgorithm()); - assertEquals(cryptoConfig.getAutoVerifyHash(), deCryptoConfig.getAutoVerifyHash()); - return; - } - - @Test - public void testSerialize_ParticipantCert() { - // LedgerCodes.METADATA_PARTICIPANT_CERT - // prepare work - int id = 1; - // String address = "xxxxxxxxxxxxxx"; - PubKey pubKey = new PubKey(ClassicAlgorithm.ED25519, rawDigestBytes); - // ParticipantInfo info = new ParticipantCertData.ParticipantInfoData(1, "yyy"); - // SignatureDigest signature = new SignatureDigest(CryptoAlgorithm.SM2, - // rawDigestBytes); - String name = "John"; - // NetworkAddress consensusAddress = new NetworkAddress("192.168.1.1", 9001, - // false); - Bytes address = AddressEncoding.generateAddress(pubKey); - ParticipantCertData participantCertData = new ParticipantCertData(address, name, pubKey, ParticipantNodeState.ACTIVED); - - // encode and decode - byte[] encodeBytes = BinaryProtocol.encode(participantCertData, ParticipantNode.class); - ParticipantNode deParticipantInfoData = BinaryProtocol.decode(encodeBytes); - - // verify start - assertEquals(participantCertData.getAddress(), deParticipantInfoData.getAddress()); - assertEquals(participantCertData.getPubKey(), deParticipantInfoData.getPubKey()); - assertEquals(participantCertData.getName(), deParticipantInfoData.getName()); - // assertEquals(participantCertData.getConsensusAddress().getHost(), - // deParticipantInfoData.getConsensusAddress().getHost()); - // assertEquals(participantCertData.getConsensusAddress().getPort(), - // deParticipantInfoData.getConsensusAddress().getPort()); - // assertEquals(participantCertData.getConsensusAddress().isSecure(), - // deParticipantInfoData.getConsensusAddress().isSecure()); - - return; - } - - // @Test - // public void testSerialize_ParticipantInfo() { - // String name = "yyyy"; - // - // ParticipantCertData.ParticipantInfoData participantInfoData = new - // ParticipantCertData.ParticipantInfoData(1, name); - // byte[] encodeBytes = BinaryEncodingUtils.encode(participantInfoData, - // ParticipantInfo.class); - // ParticipantCertData.ParticipantInfoData deParticipantInfoData = - // BinaryEncodingUtils.decode(encodeBytes, null, - // ParticipantCertData.ParticipantInfoData.class); - // - // //verify start - // assertEquals(participantInfoData.getId(), deParticipantInfoData.getId()); - // assertEquals(participantInfoData.getName(), deParticipantInfoData.getName()); - // - // return; - // } -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerSecurityManagerTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerSecurityManagerTest.java deleted file mode 100644 index 7c82d21b..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerSecurityManagerTest.java +++ /dev/null @@ -1,181 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.mockito.Mockito; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.ParticipantDataQuery; -import com.jd.blockchain.ledger.Privileges; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerSecurityManager; -import com.jd.blockchain.ledger.core.LedgerSecurityManagerImpl; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.RolePrivilegeDataset; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.UserAccountQuery; -import com.jd.blockchain.ledger.core.UserRoleDataset; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.utils.Bytes; - -public class LedgerSecurityManagerTest { - - private static final String[] SUPPORTED_PROVIDER_NAMES = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private static final CryptoAlgorithm HASH_ALGORITHM = Crypto.getAlgorithm("SHA256"); - - private static final CryptoProvider[] SUPPORTED_PROVIDERS = new CryptoProvider[SUPPORTED_PROVIDER_NAMES.length]; - - private static final CryptoSetting CRYPTO_SETTINGS; - - static { - for (int i = 0; i < SUPPORTED_PROVIDER_NAMES.length; i++) { - SUPPORTED_PROVIDERS[i] = Crypto.getProvider(SUPPORTED_PROVIDER_NAMES[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setSupportedProviders(SUPPORTED_PROVIDERS); - cryptoConfig.setHashAlgorithm(HASH_ALGORITHM); - - CRYPTO_SETTINGS = cryptoConfig; - } - - private RolePrivilegeDataset createRolePrivilegeDataset(MemoryKVStorage testStorage) { - String prefix = "role-privilege/"; - RolePrivilegeDataset rolePrivilegeDataset = new RolePrivilegeDataset(CRYPTO_SETTINGS, prefix, testStorage, - testStorage); - - return rolePrivilegeDataset; - } - - private UserRoleDataset createUserRoleDataset(MemoryKVStorage testStorage) { - String prefix = "user-roles/"; - UserRoleDataset userRolesDataset = new UserRoleDataset(CRYPTO_SETTINGS, prefix, testStorage, testStorage); - - return userRolesDataset; - } - - @Test - public void testGetSecurityPolicy() { - MemoryKVStorage testStorage = new MemoryKVStorage(); - - // 定义不同角色用户的 keypair; - final BlockchainKeypair kpManager = BlockchainKeyGenerator.getInstance().generate(); - final BlockchainKeypair kpEmployee = BlockchainKeyGenerator.getInstance().generate(); - final BlockchainKeypair kpDevoice = BlockchainKeyGenerator.getInstance().generate(); - final BlockchainKeypair kpPlatform = BlockchainKeyGenerator.getInstance().generate(); - - // 定义角色和权限; - final String ROLE_ADMIN = "ID_ADMIN"; - final String ROLE_OPERATOR = "OPERATOR"; - final String ROLE_DATA_COLLECTOR = "DATA_COLLECTOR"; - final String ROLE_PLATFORM = "PLATFORM"; - - // 定义管理员角色的权限:【账本权限只允许:注册用户、注册数据账户】【交易权限只允许:调用账本直接操作】 - final Privileges PRIVILEGES_ADMIN = Privileges.configure() - .enable(LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT) - .enable(TransactionPermission.DIRECT_OPERATION); - - // 定义操作员角色的权限:【账本权限只允许:写入数据账户】【交易权限只允许:调用合约】 - final Privileges PRIVILEGES_OPERATOR = Privileges.configure().enable(LedgerPermission.WRITE_DATA_ACCOUNT) - .enable(TransactionPermission.CONTRACT_OPERATION); - - // 定义数据收集器角色的权限:【账本权限只允许:写入数据账户】【交易权限只允许:调用账本直接操作】 - final Privileges PRIVILEGES_DATA_COLLECTOR = Privileges.configure().enable(LedgerPermission.WRITE_DATA_ACCOUNT) - .enable(TransactionPermission.DIRECT_OPERATION); - - // 定义平台角色的权限:【账本权限只允许:签署合约】 (只允许作为节点签署交易,不允许作为终端发起交易指令) - final Privileges PRIVILEGES_PLATFORM = Privileges.configure().enable(LedgerPermission.APPROVE_TX); - - RolePrivilegeDataset rolePrivilegeDataset = createRolePrivilegeDataset(testStorage); - long v = rolePrivilegeDataset.addRolePrivilege(ROLE_ADMIN, PRIVILEGES_ADMIN); - assertTrue(v > -1); - v = rolePrivilegeDataset.addRolePrivilege(ROLE_OPERATOR, PRIVILEGES_OPERATOR); - assertTrue(v > -1); - v = rolePrivilegeDataset.addRolePrivilege(ROLE_DATA_COLLECTOR, PRIVILEGES_DATA_COLLECTOR); - assertTrue(v > -1); - v = rolePrivilegeDataset.addRolePrivilege(ROLE_PLATFORM, PRIVILEGES_PLATFORM); - assertTrue(v > -1); - rolePrivilegeDataset.commit(); - - // 为用户分配角色; - String[] managerRoles = new String[] { ROLE_ADMIN, ROLE_OPERATOR }; - String[] employeeRoles = new String[] { ROLE_OPERATOR }; - String[] devoiceRoles = new String[] { ROLE_DATA_COLLECTOR }; - String[] platformRoles = new String[] { ROLE_PLATFORM }; - UserRoleDataset userRolesDataset = createUserRoleDataset(testStorage); - userRolesDataset.addUserRoles(kpManager.getAddress(), RolesPolicy.UNION, managerRoles); - userRolesDataset.addUserRoles(kpEmployee.getAddress(), RolesPolicy.UNION, employeeRoles); - userRolesDataset.addUserRoles(kpDevoice.getAddress(), RolesPolicy.UNION, devoiceRoles); - userRolesDataset.addUserRoles(kpPlatform.getAddress(), RolesPolicy.UNION, platformRoles); - userRolesDataset.commit(); - - ParticipantDataQuery partisQuery = Mockito.mock(ParticipantDataQuery.class); - UserAccountQuery usersQuery = Mockito.mock(UserAccountQuery.class); - - // 创建安全管理器; - LedgerSecurityManager securityManager = new LedgerSecurityManagerImpl(rolePrivilegeDataset, userRolesDataset, - partisQuery, usersQuery); - - // 定义终端用户列表;终端用户一起共同具有 ADMIN、OPERATOR 角色; - final Map endpoints = new HashMap<>(); - endpoints.put(kpManager.getAddress(), kpManager); - endpoints.put(kpEmployee.getAddress(), kpEmployee); - - // 定义节点参与方列表; - final Map nodes = new HashMap<>(); - nodes.put(kpPlatform.getAddress(), kpPlatform); - - // 创建一项与指定的终端用户和节点参与方相关的安全策略; - SecurityPolicy policy = securityManager.createSecurityPolicy(endpoints.keySet(), nodes.keySet()); - - // 校验安全策略的正确性; - LedgerPermission[] ledgerPermissions = LedgerPermission.values(); - for (LedgerPermission p : ledgerPermissions) { - // 终端节点有 ADMIN 和 OPERATOR 两种角色的合并权限; - if (p == LedgerPermission.REGISTER_USER || p == LedgerPermission.REGISTER_DATA_ACCOUNT - || p == LedgerPermission.WRITE_DATA_ACCOUNT) { - assertTrue(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); - } else { - assertFalse(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); - } - - if (p == LedgerPermission.APPROVE_TX) { - // 共识参与方只有 PLATFORM 角色的权限:核准交易; - assertTrue(policy.isNodeEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); - } else { - assertFalse(policy.isNodeEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); - } - } - - TransactionPermission[] transactionPermissions = TransactionPermission.values(); - for (TransactionPermission p : transactionPermissions) { - // 终端节点有 ADMIN 和 OPERATOR 两种角色的合并权限; - if (p == TransactionPermission.DIRECT_OPERATION || p == TransactionPermission.CONTRACT_OPERATION) { - assertTrue(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); - } else { - assertFalse(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); - } - - assertFalse(policy.isNodeEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); - } - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTestUtils.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTestUtils.java deleted file mode 100644 index a9c8a683..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTestUtils.java +++ /dev/null @@ -1,236 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import java.util.Random; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; -import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.transaction.TransactionService; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class LedgerTestUtils { - - public static final SignatureFunction ED25519_SIGN_FUNC = Crypto.getSignatureFunction("ED25519"); - - public static final CryptoAlgorithm ED25519 = ED25519_SIGN_FUNC.getAlgorithm(); - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private static Random rand = new Random(); - -// public static TransactionRequest createTxRequest_UserReg(HashDigest ledgerHash) { -// BlockchainKeypair key = BlockchainKeyGenerator.getInstance().generate(ED25519); -// return createTxRequest_UserReg(ledgerHash, key); -// } - - public static LedgerInitSetting createLedgerInitSetting() { - BlockchainKeypair[] partiKeys = new BlockchainKeypair[2]; - partiKeys[0] = BlockchainKeyGenerator.getInstance().generate(); - partiKeys[1] = BlockchainKeyGenerator.getInstance().generate(); - return createLedgerInitSetting(partiKeys); - } - - public static CryptoProvider[] getContextProviders() { - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - return supportedProviders; - } - - public static LedgerInitSetting createLedgerInitSetting(BlockchainKeypair[] partiKeys) { - CryptoProvider[] supportedProviders =getContextProviders(); - - CryptoConfig defCryptoSetting = new CryptoConfig(); - defCryptoSetting.setSupportedProviders(supportedProviders); - defCryptoSetting.setAutoVerifyHash(true); - defCryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - - LedgerInitData initSetting = new LedgerInitData(); - - initSetting.setLedgerSeed(BytesUtils.toBytes("A Test Ledger seed!", "UTF-8")); - initSetting.setCryptoSetting(defCryptoSetting); - ConsensusParticipantData[] parties = new ConsensusParticipantData[partiKeys.length]; - for (int i = 0; i < parties.length; i++) { - parties[i] = new ConsensusParticipantData(); - parties[i].setId(0); - parties[i].setName("Parti-" + i); - parties[i].setPubKey(partiKeys[i].getPubKey()); - parties[i].setAddress(AddressEncoding.generateAddress(partiKeys[i].getPubKey())); - parties[i].setHostAddress(new NetworkAddress("192.168.1." + (10 + i), 9000)); - parties[i].setParticipantState(ParticipantNodeState.ACTIVED); - - } - - initSetting.setConsensusParticipants(parties); - - return initSetting; - } - -// public static TransactionRequest createTxRequest_UserReg(BlockchainKeypair userKeypair, HashDigest ledgerHash, BlockchainKeypair... partiKeys) { -// return createTxRequest_UserReg(userKeypair, ledgerHash, null, null); -// } - - public static TransactionRequest createLedgerInitTxRequest(BlockchainKeypair... participants) { - TxBuilder txBuilder = new TxBuilder(null); - - for (BlockchainKeypair parti : participants) { - txBuilder.users().register(parti.getIdentity()); - } - - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - for (BlockchainKeypair parti : participants) { - txReqBuilder.signAsNode(parti); - } - - return txReqBuilder.buildRequest(); - } - -// public static TransactionRequest createTxRequest_UserReg(HashDigest ledgerHash, BlockchainKeypair nodeKeypair, -// BlockchainKeypair... signers) { -// return createTxRequest_UserReg(BlockchainKeyGenerator.getInstance().generate(), ledgerHash, nodeKeypair, -// signers); -// } - - public static TransactionRequest createTxRequest_UserReg(BlockchainKeypair userKeypair, HashDigest ledgerHash, - BlockchainKeypair nodeKeypair, BlockchainKeypair... signers) { - TxBuilder txBuilder = new TxBuilder(ledgerHash); - - txBuilder.users().register(userKeypair.getIdentity()); - - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - if (signers != null) { - for (BlockchainKeypair signer : signers) { - txReqBuilder.signAsEndpoint(signer); - } - } - if (nodeKeypair != null) { - txReqBuilder.signAsNode(nodeKeypair); - } - - return txReqBuilder.buildRequest(); - } - - public static TransactionRequest createTxRequest_DataAccountReg(BlockchainKeypair dataAccountID, - HashDigest ledgerHash, BlockchainKeypair nodeKeypair, BlockchainKeypair... signers) { - TxBuilder txBuilder = new TxBuilder(ledgerHash); - - txBuilder.dataAccounts().register(dataAccountID.getIdentity()); - - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - if (signers != null) { - for (BlockchainKeypair signer : signers) { - txReqBuilder.signAsEndpoint(signer); - } - } - if (nodeKeypair != null) { - txReqBuilder.signAsNode(nodeKeypair); - } - - return txReqBuilder.buildRequest(); - } - - public static TransactionRequest createTxRequest_DataAccountWrite(Bytes dataAccountAddress, String key, - String value, long version, HashDigest ledgerHash, BlockchainKeypair nodeKeypair, - BlockchainKeypair... signers) { - TxBuilder txBuilder = new TxBuilder(ledgerHash); - - txBuilder.dataAccount(dataAccountAddress).setText(key, value, version); - - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - if (signers != null) { - for (BlockchainKeypair signer : signers) { - txReqBuilder.signAsEndpoint(signer); - } - } - if (nodeKeypair != null) { - txReqBuilder.signAsNode(nodeKeypair); - } - - return txReqBuilder.buildRequest(); - } - - /** - * @param userKeypair 要注册的用户key; - * @param ledgerHash 账本哈希; - * @param nodeKeypair 节点key; - * @param signers 签名者列表; - * @return - */ - public static TransactionRequest createTxRequest_MultiOPs_WithNotExistedDataAccount(BlockchainKeypair userKeypair, - HashDigest ledgerHash, BlockchainKeypair nodeKeypair, BlockchainKeypair... signers) { - TxBuilder txBuilder = new TxBuilder(ledgerHash); - - txBuilder.users().register(userKeypair.getIdentity()); - - // 故意构建一个错误的 - BlockchainKeypair testKey = BlockchainKeyGenerator.getInstance().generate(); - txBuilder.dataAccount(testKey.getAddress()).setBytes("AA", "Value".getBytes(), 1); - - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - txReqBuilder.signAsEndpoint(nodeKeypair); - if (nodeKeypair != null) { - txReqBuilder.signAsNode(nodeKeypair); - } - - return txReqBuilder.buildRequest(); - } - - public static TransactionStagedSnapshot generateRandomSnapshot() { - TransactionStagedSnapshot txDataSnapshot = new TransactionStagedSnapshot(); - txDataSnapshot.setAdminAccountHash(generateRandomHash()); - txDataSnapshot.setContractAccountSetHash(generateRandomHash()); - txDataSnapshot.setDataAccountSetHash(generateRandomHash()); - txDataSnapshot.setUserAccountSetHash(generateRandomHash()); - return txDataSnapshot; - } - - public static HashDigest generateRandomHash() { - byte[] data = new byte[64]; - rand.nextBytes(data); - return Crypto.getHashFunction("SHA256").hash(data); - } - - public static CryptoSetting createDefaultCryptoSetting() { - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoSetting = new CryptoConfig(); - cryptoSetting.setSupportedProviders(supportedProviders); - cryptoSetting.setAutoVerifyHash(true); - cryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - return cryptoSetting; - } - - private static class TxHandle implements TransactionService { - - private TransactionRequest txRequest; - - @Override - public TransactionResponse process(TransactionRequest txRequest) { - this.txRequest = txRequest; - return null; - } - - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTransactionDataTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTransactionDataTest.java deleted file mode 100644 index f676ea87..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTransactionDataTest.java +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.LedgerTransactionImplTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午9:48 - * Description: - */ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; - -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.EndpointRequest; -import com.jd.blockchain.ledger.HashObject; -import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.NodeRequest; -import com.jd.blockchain.ledger.Transaction; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.core.LedgerTransactionData; -import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; -import com.jd.blockchain.transaction.BlockchainOperationFactory; -import com.jd.blockchain.transaction.DigitalSignatureBlob; -import com.jd.blockchain.transaction.TxContentBlob; -import com.jd.blockchain.transaction.TxRequestMessage; -import com.jd.blockchain.utils.io.ByteArray; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class LedgerTransactionDataTest { - - private LedgerTransactionData data; - - @Before - public void initLedgerTransactionImpl() throws Exception { - DataContractRegistry.register(LedgerTransaction.class); - DataContractRegistry.register(Transaction.class); - DataContractRegistry.register(LedgerDataSnapshot.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(HashObject.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - - TransactionRequest txRequestMessage = initTxRequestMessage(); - - long blockHeight = 9986L; - data = new LedgerTransactionData(blockHeight, txRequestMessage, TransactionState.SUCCESS, - initTransactionStagedSnapshot(), null); - - HashDigest hash = new HashDigest(ClassicAlgorithm.SHA256, "zhangsan".getBytes()); - HashDigest adminAccountHash = new HashDigest(ClassicAlgorithm.SHA256, "lisi".getBytes()); - HashDigest userAccountSetHash = new HashDigest(ClassicAlgorithm.SHA256, "wangwu".getBytes()); - HashDigest dataAccountSetHash = new HashDigest(ClassicAlgorithm.SHA256, "zhaoliu".getBytes()); - HashDigest contractAccountSetHash = new HashDigest(ClassicAlgorithm.SHA256, "sunqi".getBytes()); - - data.setHash(hash); - // data.setBlockHeight(blockHeight); - data.setAdminAccountHash(adminAccountHash); - data.setUserAccountSetHash(userAccountSetHash); - data.setDataAccountSetHash(dataAccountSetHash); - data.setContractAccountSetHash(contractAccountSetHash); - } - - @Test - public void testSerialize_LedgerTransaction() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, LedgerTransaction.class); - LedgerTransaction resolvedData = BinaryProtocol.decode(serialBytes); - - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getAdminAccountHash(), data.getAdminAccountHash()); - assertEquals(resolvedData.getContractAccountSetHash(), data.getContractAccountSetHash()); - assertEquals(resolvedData.getDataAccountSetHash(), data.getDataAccountSetHash()); - assertEquals(resolvedData.getUserAccountSetHash(), data.getUserAccountSetHash()); - assertEquals(resolvedData.getExecutionState(), data.getExecutionState()); - assertEquals(resolvedData.getHash(), data.getHash()); - assertEquals(resolvedData.getBlockHeight(), data.getBlockHeight()); - - // EndpointSignatures 验证 - DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures(); - DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures(); - for (int i = 0; i < dataEndpointSignatures.length; i++) { - assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey()); - assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest()); - } - - // NodeSignatures 验证 - DigitalSignature[] dataNodeSignatures = data.getNodeSignatures(); - DigitalSignature[] resolvedNodeSignatures = resolvedData.getNodeSignatures(); - for (int i = 0; i < dataNodeSignatures.length; i++) { - assertEquals(dataNodeSignatures[i].getPubKey(), resolvedNodeSignatures[i].getPubKey()); - assertEquals(dataNodeSignatures[i].getDigest(), resolvedNodeSignatures[i].getDigest()); - } - - assertEqual(data.getTransactionContent(), resolvedData.getTransactionContent()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_Transaction() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, Transaction.class); - Transaction resolvedData = BinaryProtocol.decode(serialBytes); - - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getExecutionState(), data.getExecutionState()); - assertEquals(resolvedData.getHash(), data.getHash()); - assertEquals(resolvedData.getBlockHeight(), data.getBlockHeight()); - - // EndpointSignatures 验证 - DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures(); - DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures(); - for (int i = 0; i < dataEndpointSignatures.length; i++) { - assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey()); - assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest()); - } - - // NodeSignatures 验证 - DigitalSignature[] dataNodeSignatures = data.getNodeSignatures(); - DigitalSignature[] resolvedNodeSignatures = resolvedData.getNodeSignatures(); - for (int i = 0; i < dataNodeSignatures.length; i++) { - assertEquals(dataNodeSignatures[i].getPubKey(), resolvedNodeSignatures[i].getPubKey()); - assertEquals(dataNodeSignatures[i].getDigest(), resolvedNodeSignatures[i].getDigest()); - } - - assertEqual(data.getTransactionContent(), resolvedData.getTransactionContent()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_LedgerDataSnapshot() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, LedgerDataSnapshot.class); - LedgerDataSnapshot resolvedData = BinaryProtocol.decode(serialBytes); - - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getAdminAccountHash(), data.getAdminAccountHash()); - assertEquals(resolvedData.getContractAccountSetHash(), data.getContractAccountSetHash()); - assertEquals(resolvedData.getDataAccountSetHash(), data.getDataAccountSetHash()); - assertEquals(resolvedData.getUserAccountSetHash(), data.getUserAccountSetHash()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_NodeRequest() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, NodeRequest.class); - NodeRequest resolvedData = BinaryProtocol.decode(serialBytes); - - System.out.println("------Assert start ------"); - // EndpointSignatures 验证 - DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures(); - DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures(); - for (int i = 0; i < dataEndpointSignatures.length; i++) { - assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey()); - assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest()); - } - - // NodeSignatures 验证 - DigitalSignature[] dataNodeSignatures = data.getNodeSignatures(); - DigitalSignature[] resolvedNodeSignatures = resolvedData.getNodeSignatures(); - for (int i = 0; i < dataNodeSignatures.length; i++) { - assertEquals(dataNodeSignatures[i].getPubKey(), resolvedNodeSignatures[i].getPubKey()); - assertEquals(dataNodeSignatures[i].getDigest(), resolvedNodeSignatures[i].getDigest()); - } - - assertEqual(data.getTransactionContent(), resolvedData.getTransactionContent()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_EndpointRequest() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, EndpointRequest.class); - EndpointRequest resolvedData = BinaryProtocol.decode(serialBytes); - - System.out.println("------Assert start ------"); - // EndpointSignatures 验证 - DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures(); - DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures(); - for (int i = 0; i < dataEndpointSignatures.length; i++) { - assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey()); - assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest()); - } - assertEqual(data.getTransactionContent(), resolvedData.getTransactionContent()); - System.out.println("------Assert OK ------"); - } - - private void assertEqual(TransactionContent dataTxContent, TransactionContent resolvedTxContent) { - assertEquals(dataTxContent.getHash(), resolvedTxContent.getHash()); - assertEquals(dataTxContent.getLedgerHash(), resolvedTxContent.getLedgerHash()); - // assertEquals(dataTxContent.getSequenceNumber(), - // resolvedTxContent.getSequenceNumber()); - // assertEquals(dataTxContent.getSubjectAccount(), - // resolvedTxContent.getSubjectAccount()); - } - - private TransactionStagedSnapshot initTransactionStagedSnapshot() { - TransactionStagedSnapshot transactionStagedSnapshot = new TransactionStagedSnapshot(); - transactionStagedSnapshot.setAdminAccountHash(new HashDigest(ClassicAlgorithm.SHA256, "zhangsan".getBytes())); - transactionStagedSnapshot.setContractAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "lisi".getBytes())); - transactionStagedSnapshot.setDataAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "wangwu".getBytes())); - transactionStagedSnapshot.setUserAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "zhaoliu".getBytes())); - return transactionStagedSnapshot; - } - - private TxRequestMessage initTxRequestMessage() throws Exception { - TxRequestMessage txRequestMessage = new TxRequestMessage(initTransactionContent()); - - SignatureDigest digest1 = new SignatureDigest(ClassicAlgorithm.ED25519, "zhangsan".getBytes()); - SignatureDigest digest2 = new SignatureDigest(ClassicAlgorithm.ED25519, "lisi".getBytes()); - DigitalSignatureBlob endPoint1 = new DigitalSignatureBlob( - new PubKey(ClassicAlgorithm.ED25519, "jd1.com".getBytes()), digest1); - DigitalSignatureBlob endPoint2 = new DigitalSignatureBlob( - new PubKey(ClassicAlgorithm.ED25519, "jd2.com".getBytes()), digest2); - txRequestMessage.addEndpointSignatures(endPoint1); - txRequestMessage.addEndpointSignatures(endPoint2); - - SignatureDigest digest3 = new SignatureDigest(ClassicAlgorithm.ED25519, "wangwu".getBytes()); - SignatureDigest digest4 = new SignatureDigest(ClassicAlgorithm.ED25519, "zhaoliu".getBytes()); - DigitalSignatureBlob node1 = new DigitalSignatureBlob( - new PubKey(ClassicAlgorithm.ED25519, "jd3.com".getBytes()), digest3); - DigitalSignatureBlob node2 = new DigitalSignatureBlob( - new PubKey(ClassicAlgorithm.ED25519, "jd4.com".getBytes()), digest4); - txRequestMessage.addNodeSignatures(node1); - txRequestMessage.addNodeSignatures(node2); - - return txRequestMessage; - } - - private TransactionContent initTransactionContent() throws Exception { - TxContentBlob contentBlob = null; - BlockchainKeypair id = BlockchainKeyGenerator.getInstance().generate(ClassicAlgorithm.ED25519); - HashDigest ledgerHash = Crypto.getHashFunction("SHA256") - .hash(UUID.randomUUID().toString().getBytes("UTF-8")); - BlockchainOperationFactory opFactory = new BlockchainOperationFactory(); - contentBlob = new TxContentBlob(ledgerHash); - contentBlob.setHash(new HashDigest(ClassicAlgorithm.SHA256, "jd.com".getBytes())); - // contentBlob.setSubjectAccount(id.getAddress()); - // contentBlob.setSequenceNumber(1); - DataAccountKVSetOperation kvsetOP = opFactory.dataAccount(id.getAddress()) - .setText("Name", "AAA", -1).getOperation(); - contentBlob.addOperation(kvsetOP); - return contentBlob; - } -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleAccountSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleAccountSetTest.java deleted file mode 100644 index f3bb67da..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleAccountSetTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.core.CompositeAccount; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.MerkleAccountSet; -import com.jd.blockchain.ledger.core.OpeningAccessPolicy; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.utils.Bytes; - -public class MerkleAccountSetTest { - - @Test - public void testRegister() { - final OpeningAccessPolicy POLICY = new OpeningAccessPolicy(); - - final MemoryKVStorage STORAGE = new MemoryKVStorage(); - - Bytes KEY_PREFIX = Bytes.fromString("/ACCOUNT"); - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(LedgerTestUtils.getContextProviders()); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); - - MerkleAccountSet accountset = new MerkleAccountSet(cryptoConfig, KEY_PREFIX, STORAGE, STORAGE, POLICY); - - BlockchainKeypair key1 = BlockchainKeyGenerator.getInstance().generate(); - accountset.register(key1.getIdentity()); - - accountset.commit(); - - CompositeAccount acc1 = accountset.getAccount(key1.getAddress()); - assertNotNull(acc1); - assertEquals(0, accountset.getVersion(key1.getAddress())); - - acc1.getDataset().setValue("K1", TypedValue.fromText("V0"), -1); - - TypedValue v1 = acc1.getDataset().getValue("K1"); - assertNotNull(v1); - assertEquals(0, acc1.getDataset().getVersion("K1")); - - accountset.commit(); - - v1 = acc1.getDataset().getValue("K1"); - assertNotNull(v1); - assertEquals(0, acc1.getDataset().getVersion("K1")); - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleDataSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleDataSetTest.java deleted file mode 100644 index a8ab595b..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleDataSetTest.java +++ /dev/null @@ -1,450 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.MerkleDataSet; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.DataEntry; -import com.jd.blockchain.utils.Dataset; -import com.jd.blockchain.utils.DatasetHelper; -import com.jd.blockchain.utils.io.BytesUtils; - -public class MerkleDataSetTest { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - /** - * 测试存储的增长; - */ - @Test - public void testKeyIndex() { - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - String keyPrefix = ""; - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - cryptoConfig.setAutoVerifyHash(true); - - MemoryKVStorage storage = new MemoryKVStorage(); - - MerkleDataSet mds = new MerkleDataSet(cryptoConfig, keyPrefix, storage, storage); - mds.setValue(Bytes.fromString("A"), "A".getBytes(), -1); - mds.setValue(Bytes.fromString("B"), "B".getBytes(), -1); - mds.setValue(Bytes.fromString("C"), "C".getBytes(), -1); - - mds.commit(); - - //校验 Key 的正确性; - assertEquals("A", mds.getKeyAtIndex(0)); - assertEquals("B", mds.getKeyAtIndex(1)); - assertEquals("C", mds.getKeyAtIndex(2)); - } - - /** - * 测试存储的增长; - */ - @Test - public void testStorageIncreasement() { - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - String keyPrefix = ""; - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - cryptoConfig.setAutoVerifyHash(true); - - MemoryKVStorage storage = new MemoryKVStorage(); - - MerkleDataSet mds = new MerkleDataSet(cryptoConfig, keyPrefix, storage, storage); - Dataset ds = DatasetHelper.map(mds); - ds.setValue("A", "A".getBytes(), -1); - ds.setValue("B", "B".getBytes(), -1); - ds.setValue("C", "C".getBytes(), -1); - - mds.commit(); - - byte[] va = ds.getValue("A"); - assertNotNull(va); - assertEquals("A", new String(va)); - - byte[] vc = ds.getValue("C"); - DataEntry ventry = ds.getDataEntry("C"); - assertNotNull(vc); - assertNotNull(ventry); - assertEquals("C", new String(vc)); - assertEquals("C", ventry.getKey()); - - HashDigest root1 = mds.getRootHash(); - - - // 1个KV项的存储KEY的数量= 1 + 1(保存SN) + Merkle节点数量; - // 所以:3 项; - // so the expected item count in storage is 10; - int expStorageCount = 10; - assertEquals(expStorageCount, storage.getStorageCount()); - - ds.setValue("B", "B".getBytes(), 0); - ds.setValue("C", "C".getBytes(), 0); - mds.commit(); - HashDigest root2 = mds.getRootHash(); - assertNotEquals(root1, root2); - - // Version changed only;仅仅增加 merkle 节点,此时 Merkle 树只有 1 层路径节点,因此只更新2个数据节点和 1 - // 个路径节点;(注:版本值是在同一个 key 下按序列保存的); - expStorageCount = expStorageCount + 3; - assertEquals(expStorageCount, storage.getStorageCount()); - - ds.setValue("D", "DValue".getBytes(), -1); - mds.commit(); - HashDigest root3 = mds.getRootHash(); - assertNotEquals(root2, root3); - assertNotEquals(root1, root3); - - // New key added, include 1 versioning kv, 1 sn key, 2 merkle nodes; - // String[] keys = StringUtils.toStringArray(storage.keySet()); - Bytes[] keys = storage.keySet().toArray(new Bytes[0]); - expStorageCount = expStorageCount + 1 + 1 + 2; - assertEquals(expStorageCount, storage.getStorageCount()); - - // Check rollback function: Add some keys, and then rollback; - long v = ds.setValue("E", "E-values".getBytes(), -1); - assertEquals(v, 0); - String expEValue = new String(ds.getValue("E")); - assertEquals(expEValue, "E-values"); - - v = ds.setValue("F", "F-values".getBytes(), -1); - assertEquals(v, 0); - String expFValue = new String(ds.getValue("F")); - assertEquals(expFValue, "F-values"); - - v = ds.setValue("E", "E-values-1".getBytes(), 0); - assertEquals(v, 1); - expEValue = new String(ds.getValue("E")); - assertEquals(expEValue, "E-values-1"); - - mds.cancel(); - - byte[] bv = ds.getValue("E"); - assertNull(bv); - bv = ds.getValue("F"); - assertNull(bv); - - v = ds.getVersion("E"); - assertEquals(-1, v); - v = ds.getVersion("F"); - assertEquals(-1, v); - - // Expect that states has been recover; - keys = storage.keySet().toArray(new Bytes[0]); - assertEquals(expStorageCount, storage.getStorageCount()); - - // ------ - System.out.println("\r\n------------- storage keys --------------"); - Set storageKeys = storage.getStorageKeySet(); - int i = 0; - for (Bytes k : storageKeys) { - System.out.println(String.format("keys[%s]=%s", i, k)); - i++; - } - } - - @Test - public void testDataReload() { - String keyPrefix = ""; - Random rand = new Random(); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - cryptoConfig.setAutoVerifyHash(true); - - MemoryKVStorage storage = new MemoryKVStorage(); - - MerkleDataSet mds = new MerkleDataSet(cryptoConfig, keyPrefix, storage, storage); - Dataset ds = DatasetHelper.map(mds); - - // 初始的时候没有任何数据,总是返回 null; - DataEntry verKVEntry = ds.getDataEntry("NULL_KEY"); - byte[] vbytes = ds.getValue("NULL_KEY"); - assertNull(verKVEntry); - assertNull(vbytes); - - Map dataVersions = new HashMap<>(); - Map dataValues = new HashMap<>(); - - Map> history = new LinkedHashMap<>(); - - HashDigest rootHash; - - // generate base data sample; - int count = 1024;// + rand.nextInt(1024); - String key; - byte[] data = new byte[64]; - long v; - MerkleProof proof; - for (int i = 0; i < count; i++) { - key = "data" + i; - rand.nextBytes(data); - v = ds.setValue(key, data, -1); - dataVersions.put(key, v); - dataValues.put(key + "_" + v, data); - assertEquals(v, 0); - } - mds.commit(); - - // Take snapshot; - { - rootHash = mds.getRootHash(); - Map snapshot = new HashMap<>(); - for (int i = 0; i < count; i++) { - key = "data" + i; - - proof = mds.getProof(key); - assertNotNull(proof); - assertEquals(rootHash, proof.getRootHash()); - - KeySnapshot ks = new KeySnapshot(); - ks.proof = proof; - ks.maxVersion = ds.getVersion(key); - - snapshot.put(key, ks); - } - history.put(rootHash, snapshot); - } - - // verify; - { - MerkleDataSet mdsReload = new MerkleDataSet(rootHash, cryptoConfig, keyPrefix, storage, storage, true); - // verify every keys; - Map snapshot = history.get(rootHash); - MerkleProof expProof; - for (int i = 0; i < count; i++) { - key = "data" + i; - proof = mdsReload.getProof(key); - assertNotNull(proof); - assertEquals(rootHash, proof.getRootHash()); - expProof = snapshot.get(key).proof; - assertEquals(expProof.toString(), proof.toString()); - } - } - - // generate multi-version data sample; - long expVer; - long maxVer = 0; - long minIdx = count; - long maxIdx = 0; - for (int t = 0; t < 100; t++) { - int bound = rand.nextInt(500) + 1; - for (int i = rand.nextInt(count); i < count; i = i + rand.nextInt(bound) + 1) { - key = "data" + i; - rand.nextBytes(data); - expVer = dataVersions.get(key); - v = ds.setValue(key, data, expVer); - - assertEquals(v, expVer + 1); - - dataVersions.put(key, v); - - dataValues.put(key + "_" + v, data); - - maxVer = v > maxVer ? v : maxVer; - minIdx = i < minIdx ? i : minIdx; - maxIdx = i > maxIdx ? i : maxIdx; - } - mds.commit(); - - assertNotEquals(rootHash, mds.getRootHash()); - - // Take snapshot; - { - rootHash = mds.getRootHash(); - Map snapshot = new HashMap<>(); - for (int i = 0; i < count; i++) { - key = "data" + i; - - proof = mds.getProof(key); - assertNotNull(proof); - assertEquals(rootHash, proof.getRootHash()); - - KeySnapshot ks = new KeySnapshot(); - ks.proof = proof; - ks.maxVersion = ds.getVersion(key); - snapshot.put(key, ks); - } - history.put(rootHash, snapshot); - } - } - - System.out.println( - String.format("total count=%s; from %s to %s, max version=%s;", count, minIdx, maxIdx, maxVer)); - - { - for (HashDigest hisRootHash : history.keySet()) { - Map snapshot = history.get(hisRootHash); - - MerkleDataSet mdsReload = new MerkleDataSet(hisRootHash, cryptoConfig, keyPrefix, storage, storage, - true); - Dataset dsReload = DatasetHelper.map(mdsReload); - assertEquals(hisRootHash, mdsReload.getRootHash()); - - // verify every keys; - for (int i = 0; i < count; i++) { - key = "data" + i; - // 最新版本一致; - long expLatestVersion = snapshot.get(key).maxVersion; - long actualLatestVersion = dsReload.getVersion(key); - assertEquals(expLatestVersion, actualLatestVersion); - - // 数据证明一致; - proof = mdsReload.getProof(key); - assertNotNull(proof); - - MerkleProof expProof = snapshot.get(key).proof; - assertEquals(expProof, proof); - - maxVer = dataVersions.get(key); - assertTrue(actualLatestVersion > -1); - assertTrue(actualLatestVersion <= maxVer); - for (long j = 0; j < actualLatestVersion; j++) { - String keyver = key + "_" + j; - byte[] expValue = dataValues.get(keyver); - byte[] actualValue = dsReload.getValue(key, j); - assertTrue(BytesUtils.equals(expValue, actualValue)); - } - } - } - } - } - - @Test - public void testInsertSameData() { - String keyPrefix = ""; - Random rand = new Random(); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - cryptoConfig.setAutoVerifyHash(true); - - MemoryKVStorage storage = new MemoryKVStorage(); - - MerkleDataSet mds = new MerkleDataSet(cryptoConfig, keyPrefix, storage, storage); - Dataset ds = DatasetHelper.map(mds); - - // 初始的时候没有任何数据,总是返回 null; - DataEntry verKVEntry = ds.getDataEntry("NULL_KEY"); - byte[] vbytes = ds.getValue("NULL_KEY"); - assertNull(verKVEntry); - assertNull(vbytes); - - Map dataVersions = new HashMap<>(); - // Map dataValues = new HashMap<>(); - - Map> history = new LinkedHashMap<>(); - - HashDigest rootHash; - - // generate base data sample; - int count = 1024;// + rand.nextInt(1024); - String key; - byte[] data = new byte[64]; - rand.nextBytes(data); - long v; - MerkleProof proof; - for (int i = 0; i < count; i++) { - key = "data" + i; - v = ds.setValue(key, data, -1); - dataVersions.put(key, v); - // dataValues.put(key + "_" + v, data); - assertEquals(v, 0); - } - mds.commit(); - - // Take snapshot; - { - rootHash = mds.getRootHash(); - Map snapshot = new HashMap<>(); - for (int i = 0; i < count; i++) { - key = "data" + i; - - proof = mds.getProof(key); - assertNotNull(proof); - assertEquals(rootHash, proof.getRootHash()); - - KeySnapshot ks = new KeySnapshot(); - ks.proof = proof; - ks.maxVersion = ds.getVersion(key); - - snapshot.put(key, ks); - } - history.put(rootHash, snapshot); - } - - // verify; - { - MerkleDataSet mdsReload = new MerkleDataSet(rootHash, cryptoConfig, keyPrefix, storage, storage, true); - Dataset dsReload = DatasetHelper.map(mdsReload); - // verify every keys; - Map snapshot = history.get(rootHash); - MerkleProof expProof; - for (int i = 0; i < count; i++) { - key = "data" + i; - proof = mdsReload.getProof(key); - assertNotNull(proof); - assertEquals(rootHash, proof.getRootHash()); - expProof = snapshot.get(key).proof; - assertEquals(expProof.toString(), proof.toString()); - - byte[] value = dsReload.getValue(key); - assertTrue(BytesUtils.equals(data, value)); - } - } - } - - private static class KeySnapshot { - private MerkleProof proof; - private long maxVersion; - - } -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleTreeTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleTreeTest.java deleted file mode 100644 index ee3a7509..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleTreeTest.java +++ /dev/null @@ -1,815 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Random; -import java.util.TreeMap; - -import org.junit.Test; -import org.mockito.Mockito; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.MerkleDataNode; -import com.jd.blockchain.ledger.MerkleNode; -import com.jd.blockchain.ledger.MerkleProof; -import com.jd.blockchain.ledger.core.MerkleTree; -import com.jd.blockchain.storage.service.utils.ExistancePolicyKVStorageMap; -import com.jd.blockchain.utils.Bytes; - -public class MerkleTreeTest { - - private static String keyPrefix = ""; - - @Test - public void testWriteAndRead() { - - Random rand = new Random(); - - CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(ClassicAlgorithm.SHA256.code()); - when(setting.getAutoVerifyHash()).thenReturn(true); - - // 测试从空的树开始,顺序增加数据节点; - ExistancePolicyKVStorageMap kvs1 = new ExistancePolicyKVStorageMap(); - MerkleTree mkt = new MerkleTree(setting, Bytes.fromString(keyPrefix), kvs1); - - // 初始化,按照顺序的序列号加入10条记录; - int count = 18; - byte[] dataBuf = new byte[16]; - MerkleDataNode[] dataNodes = new MerkleDataNode[count]; - for (int i = 0; i < count; i++) { - rand.nextBytes(dataBuf); - long sn = i; - dataNodes[i] = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - assertEquals(sn, dataNodes[i].getSN()); - } - mkt.commit(); - - HashDigest rootHash = mkt.getRootHash(); - assertNotNull(rootHash); - long maxSN = mkt.getMaxSn(); - long dataCount = mkt.getDataCount(); - assertEquals(count, dataCount); - assertEquals(dataCount - 1, maxSN);// 仅仅在采用顺序加入的情况下成立; - - // reload; - mkt = new MerkleTree(rootHash, setting, keyPrefix, kvs1, false); - // 校验是否与之前的一致; - maxSN = mkt.getMaxSn(); - dataCount = mkt.getDataCount(); - assertEquals(count, dataCount); - assertEquals(dataCount - 1, maxSN);// 仅仅在采用顺序加入的情况下成立; - - // 取每一个数据节点 - for (int i = 0; i <= maxSN; i++) { - MerkleDataNode dataNode = mkt.getData(i); - assertEquals(i, dataNode.getSN()); - assertEquals(dataNodes[i].getNodeHash(), dataNode.getNodeHash()); - assertEquals(dataNodes[i].getKey(), dataNode.getKey()); - assertEquals(dataNodes[i].getLevel(), dataNode.getLevel()); - assertEquals(dataNodes[i].getVersion(), dataNode.getVersion()); - } - } - - /** - * 测试以单次提交的方式顺序地插入数据; - */ - @Test - public void testSequenceInsert_OneCommit() { - CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(ClassicAlgorithm.SHA256.code()); - when(setting.getAutoVerifyHash()).thenReturn(true); - - // 测试从空的树开始,顺序增加数据节点; - ExistancePolicyKVStorageMap kvs1 = new ExistancePolicyKVStorageMap(); - - // 创建空的的树; - MerkleTree mkt = new MerkleTree(setting, keyPrefix, kvs1); - - // 查询空树的最大序列号,将返回 -1; - long maxSN = mkt.getMaxSn(); - assertEquals(-1, maxSN); - - long sn = 0; - // 加入 4097 条数据记录,预期构成以一颗 4 层 16 叉树; - int count = 4097; - byte[] dataBuf = new byte[16]; - Random rand = new Random(); - for (int i = 0; i < count; i++) { - rand.nextBytes(dataBuf); - mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - sn++; - } - mkt.commit(); - - // 检查节点数; - assertEquals(count, mkt.getDataCount()); - - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - assertEquals(sn - 1, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 4 层16叉树,由 3 层满16叉树扩展 1 新分支(4个路径节点)而形成; - long expectedNodes = getMaxPathNodeCount(3) + 4 + 4097; - assertEquals(expectedNodes, kvs1.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - MerkleProof proof = null; - for (int i = 0; i <= maxSN; i++) { - proof = mkt.getProof(i); - assertNotNull(proof); - } - } - - /** - * 测试以多次提交的方式顺序地插入数据; - */ - @Test - public void testSequenceInsert_MultiCommit() { - CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(ClassicAlgorithm.SHA256.code()); - when(setting.getAutoVerifyHash()).thenReturn(true); - - // 测试从空的树开始,顺序增加数据节点; - ExistancePolicyKVStorageMap kvs1 = new ExistancePolicyKVStorageMap(); - MerkleTree mkt = new MerkleTree(setting, keyPrefix, kvs1); - - long sn = 0; - // 初始化,加入10条记录,预期目前的树只有一层; - int count = 10; - byte[] dataBuf = new byte[16]; - Random rand = new Random(); - for (int i = 0; i < count; i++) { - rand.nextBytes(dataBuf); - mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - sn++; - } - mkt.commit(); - - assertEquals(count, mkt.getDataCount()); - // 检查最大序列号的正确性; - long maxSN = mkt.getMaxSn(); - assertEquals(sn - 1, maxSN); - - assertEquals(1, mkt.getLevel()); - - // 路径节点 + 数据节点;1 层只有一个路径节点; - long expectedNodes = 1 + count; - assertEquals(11, expectedNodes); - - assertEquals(expectedNodes, kvs1.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - MerkleProof proof = null; - for (int i = 0; i <= maxSN; i++) { - proof = mkt.getProof(i); - assertNotNull(proof); - } - - // -------------------------- - // 再加入 6 条记录;总共 16 条,预期目前的树也只有一层; - for (int i = 0; i < 6; i++) { - rand.nextBytes(dataBuf); - mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - sn++; - } - mkt.commit(); - - count = 16; - assertEquals(count, mkt.getDataCount()); - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - assertEquals(sn - 1, maxSN); - - // 预期只有 1 层; - assertEquals(1, mkt.getLevel()); - - // 路径节点 + 数据节点;1 层只有一个路径节点;新增了1个路径节点,以及新增 6 个数据节点; - // 注:上一次未填充满的路径节点由于哈希变化而重新生成,因此多出 1 条; - expectedNodes = expectedNodes + 1 + 6; - assertEquals(expectedNodes, kvs1.getCount()); - - // -------------------------- - // 再加入 10 条记录;总共 26 条数据,预期目前的树有2层[17-32]; - for (int i = 0; i < 10; i++) { - rand.nextBytes(dataBuf); - mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - sn++; - } - mkt.commit(); - - count = 26; - assertEquals(count, mkt.getDataCount()); - // 预期扩展到 2 层; - assertEquals(2, mkt.getLevel()); - - // 路径节点 + 数据节点;扩展到 2 层, 新增加了2个路径节点(包括:新的根节点和其中1个子节点),以及10个新增的数据节点; - expectedNodes = expectedNodes + 2 + 10; - assertEquals(expectedNodes, kvs1.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - for (int i = 0; i <= maxSN; i++) { - proof = mkt.getProof(i); - assertNotNull(proof); - } - - // ---------------------------------------------------------------- - // 再加入 230 条记录,总共 256 条数据记录,预期构成以一颗满的 2 层 16 叉树; - for (int i = 0; i < 230; i++) { - rand.nextBytes(dataBuf); - mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - sn++; - } - mkt.commit(); - - count = 256; - assertEquals(count, mkt.getDataCount()); - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - assertEquals(sn - 1, maxSN); - - // 预期仍然维持 2 层; - assertEquals(2, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 由于原来的两个未满的路径节点重新计算 hash 而新增加了2个路径节点,新增14个 Level(1) 的路径节点,加上230个新增数据记录; - expectedNodes = expectedNodes + 2 + 14 + 230; - assertEquals(expectedNodes, kvs1.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - for (int i = 0; i <= maxSN; i++) { - proof = mkt.getProof(i); - assertNotNull(proof); - } - - // ---------------------------------------------------------------- - // 再加入 3840 条记录,总共 4096 条数据记录,预期构成以一颗满的 3 层 16 叉树; - for (int i = 0; i < 3840; i++) { - rand.nextBytes(dataBuf); - mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - sn++; - } - mkt.commit(); - - count = 4096; - assertEquals(count, mkt.getDataCount()); - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - assertEquals(sn - 1, maxSN); - - // 预期扩展到 3 层; - assertEquals(3, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 3 层的满16叉树,新增256的路径节点,加上3840个新增数据记录; - expectedNodes = expectedNodes + 256 + 3840; - assertEquals(expectedNodes, kvs1.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - for (int i = 0; i <= maxSN; i++) { - proof = mkt.getProof(i); - assertNotNull(proof); - } - - // ---------------------------------------------------------------- - // 再加入 1 条记录,总共 4097 条数据记录,预期构成以一颗 4 层 16 叉树; - for (int i = 0; i < 1; i++) { - rand.nextBytes(dataBuf); - mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - sn++; - } - mkt.commit(); - - count = 4097; - assertEquals(count, mkt.getDataCount()); - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - assertEquals(sn - 1, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 4 层16叉树,新增4个路径节点,加上1个新增数据记录; - expectedNodes = expectedNodes + 4 + 1; - assertEquals(expectedNodes, kvs1.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - for (int i = 0; i <= maxSN; i++) { - proof = mkt.getProof(i); - assertNotNull(proof); - } - } - - /** - * 测试以多次提交的方式随机地插入数据; - */ - @Test - public void testRandomInsert_MultiCommit() { - CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(ClassicAlgorithm.SHA256.code()); - when(setting.getAutoVerifyHash()).thenReturn(true); - - // 保存所有写入的数据节点的 SN-Hash 映射表; - TreeMap dataNodes = new TreeMap<>(); - MerkleNode nd; - - // 测试从空的树开始,顺序增加数据节点; - ExistancePolicyKVStorageMap kvs1 = new ExistancePolicyKVStorageMap(); - MerkleTree mkt = new MerkleTree(setting, keyPrefix, kvs1); - - // 加入 30 条数据记录,分两批各15条分别从序号两端加入,预期构成以一颗 4 层 16 叉树; - int count = 4097; - byte[] dataBuf = new byte[16]; - Random rand = new Random(); - long sn = 0; - for (int i = 0; i < 15; i++) { - rand.nextBytes(dataBuf); - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - dataNodes.put(sn, nd.getNodeHash()); - sn++; - } - sn = count - 1; - - for (int i = 0; i < 15; i++) { - rand.nextBytes(dataBuf); - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - dataNodes.put(sn, nd.getNodeHash()); - sn--; - } - mkt.commit(); - - assertEquals(30, mkt.getDataCount()); - // 检查最大序列号的正确性; - long maxSN = mkt.getMaxSn(); - assertEquals(count - 1, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 4 层16叉树,共9个路径节点,加30个数据节点; - long expectedNodes = 9 + 30; - assertEquals(expectedNodes, kvs1.getCount()); - - // --------------------------------- - // 在 15 - 4081 之间随机插入; - int randomInterval = 4082 - 15; - List snPool = new LinkedList<>(); - for (int i = 0; i < randomInterval; i++) { - snPool.add(15L + i); - } - for (int i = 0; i < randomInterval; i++) { - int selected = rand.nextInt(snPool.size()); - sn = snPool.remove(selected).longValue(); - rand.nextBytes(dataBuf); - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - dataNodes.put(sn, nd.getNodeHash()); - } - mkt.commit(); - - assertEquals(4097, mkt.getDataCount()); - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - assertEquals(count - 1, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 4 层16叉树,之前的路径节点全部被重新计算哈希, 等同于在3层满16叉树之上加入1条记录,共273路径节点,加上 sn 为 4096 - // 的数据对于 4个路径节点(由于是上次写入的,4个路径节点中本次只更新了根节点); - expectedNodes = expectedNodes + 273 + 1 + randomInterval; - assertEquals(expectedNodes, kvs1.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - MerkleProof proof = null; - for (Long n : dataNodes.keySet()) { - proof = mkt.getProof(n.longValue()); - assertNotNull(proof); - assertEquals(dataNodes.get(n), proof.getHash(0)); - } - } - - /** - * 测试以单次提交的方式顺序地插入数据; - */ - @Test - public void testDataModify() { - CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(ClassicAlgorithm.SHA256.code()); - when(setting.getAutoVerifyHash()).thenReturn(true); - - // 保存所有写入的数据节点的 SN-Hash 映射表; - TreeMap dataNodes = new TreeMap<>(); - MerkleNode nd; - - // 测试从空的树开始,顺序增加数据节点; - ExistancePolicyKVStorageMap storage = new ExistancePolicyKVStorageMap(); - - // 创建空的的树; - MerkleTree mkt = new MerkleTree(setting, keyPrefix, storage); - - long sn = 0; - // 加入 4097 条数据记录,预期构成以一颗 4 层 16 叉树; - int count = 4097; - byte[] dataBuf = new byte[16]; - Random rand = new Random(); - for (int i = 0; i < count; i++) { - rand.nextBytes(dataBuf); - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - dataNodes.put(sn, nd.getNodeHash()); - sn++; - } - mkt.commit(); - - // 检查节点数; - assertEquals(count, mkt.getDataCount()); - - // 检查最大序列号的正确性; - long expectedMaxSN = 4096;// count-1; - long maxSN = mkt.getMaxSn(); - assertEquals(expectedMaxSN, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 4 层16叉树,由 3 层满16叉树扩展 1 新分支(4个路径节点)而形成; - long expectedNodes = getMaxPathNodeCount(3) + 4 + 4097; - assertEquals(expectedNodes, storage.getCount()); - - // 覆盖到每一路分支修改数据节点; - int storageDataCountBefore = storage.getCount(); - // maxSn = 4096; - int i; - for (i = 0; i <= maxSN; i += 16) { - rand.nextBytes(dataBuf); - sn = i; - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - dataNodes.put(sn, nd.getNodeHash()); - } - - mkt.commit(); - // 检查节点数; - assertEquals(count, mkt.getDataCount()); - - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - assertEquals(expectedMaxSN, maxSN); - - // 由于覆盖到每一个分支节点,全部分支节点都重新生成,因此: - // 新增节点数=修改的数据节点数 + 全部分支节点数; - long addCounts = i / 16 + getMaxPathNodeCount(3) + 4; - assertEquals(storageDataCountBefore + addCounts, storage.getCount()); - - // 验证每一个数据节点都产生了存在性证明; - MerkleProof proof = null; - for (Long n : dataNodes.keySet()) { - proof = mkt.getProof(n.longValue()); - assertNotNull(proof); - HashDigest expHash = dataNodes.get(n); - assertEquals(expHash.toBase58(), proof.getHash(0).toBase58()); - } - - } - - /** - * 测试单独修改版本而不变更数据时,是否能够正确地更新 merkle 树;; - */ - @Test - public void testDataVersionModify() { - CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(ClassicAlgorithm.SHA256.code()); - when(setting.getAutoVerifyHash()).thenReturn(true); - - // 保存所有写入的数据节点的 SN-Hash 映射表; - TreeMap dataNodes = new TreeMap<>(); - MerkleNode nd; - - // 测试从空的树开始,顺序增加数据节点; - ExistancePolicyKVStorageMap storage = new ExistancePolicyKVStorageMap(); - - // 创建空的的树; - MerkleTree mkt = new MerkleTree(setting, keyPrefix, storage); - - long sn = 0; - // 加入 4097 条数据记录,预期构成以一颗 4 层 16 叉树; - int count = 4097; - byte[] dataBuf = new byte[16]; - Random rand = new Random(); - for (int i = 0; i < count; i++) { - rand.nextBytes(dataBuf); - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - dataNodes.put(sn, nd.getNodeHash()); - sn++; - } - mkt.commit(); - byte[] dataOfMaxSnNode = Arrays.copyOf(dataBuf, dataBuf.length); - - // 检查节点数; - assertEquals(count, mkt.getDataCount()); - - // 检查最大序列号的正确性; - long expectedMaxSN = 4096;// count-1; - long maxSN = mkt.getMaxSn(); - assertEquals(expectedMaxSN, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 4 层16叉树,由 3 层满16叉树扩展 1 新分支(4个路径节点)而形成; - long expectedNodes = getMaxPathNodeCount(3) + 4 + 4097; - assertEquals(expectedNodes, storage.getCount()); - - // 仅仅更新最大的 sn 的数据节点的版本(由 0 升级为 1),预期将产生 4 个更新的路径节点和 1 个新的数据节点; - long currNodes = expectedNodes; - mkt.setData(maxSN, "KEY-" + maxSN, 1, dataOfMaxSnNode); - mkt.commit(); - - // 验证; - maxSN = mkt.getMaxSn(); - assertEquals(expectedMaxSN, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期将产生 4 个更新的路径节点和 1 个新的数据节点; - expectedNodes = currNodes + 4 + 1; - assertEquals(expectedNodes, storage.getCount()); - } - - /** - * 测试从存储重新加载 Merkle 树的正确性; - */ - /** - * - */ - @Test - public void testMerkleReload() { - CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(ClassicAlgorithm.SHA256.code()); - when(setting.getAutoVerifyHash()).thenReturn(true); - - // 保存所有写入的数据节点的 SN-Hash 映射表; - TreeMap expectedDataNodes = new TreeMap<>(); - MerkleNode nd; - - // 测试从空的树开始,顺序增加数据节点; - ExistancePolicyKVStorageMap storage = new ExistancePolicyKVStorageMap(); - - // 创建空的的树; - MerkleTree mkt = new MerkleTree(setting, keyPrefix, storage); - - long sn = 0; - // 加入 4097 条数据记录,预期构成以一颗 4 层 16 叉树; - int count = 4097; - byte[] dataBuf = new byte[16]; - Random rand = new Random(); - for (int i = 0; i < count; i++) { - rand.nextBytes(dataBuf); - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - expectedDataNodes.put(sn, nd.getNodeHash()); - sn++; - } - mkt.commit(); - - // 记录一次提交的根哈希以及部分节点信息,用于后续的加载校验; - HashDigest r1_rootHash = mkt.getRootHash(); - long r1_dataCount = mkt.getDataCount(); - long r1_maxSN = mkt.getMaxSn(); - long r1_sn1 = r1_maxSN; - String r1_proof1 = mkt.getProof(r1_sn1).toString(); - long r1_sn2 = 1024; - String r1_proof2 = mkt.getProof(r1_sn2).toString(); - - { - // 检查节点数; - assertEquals(count, mkt.getDataCount()); - - // 检查最大序列号的正确性; - long maxSN = mkt.getMaxSn(); - long expectedMaxSN = 4096;// count-1; - assertEquals(expectedMaxSN, maxSN); - - // 预期扩展到 4 层; - assertEquals(4, mkt.getLevel()); - - // 路径节点 + 数据节点; - // 预期扩展为 4 层16叉树,由 3 层满16叉树扩展 1 新分支(4个路径节点)而形成; - long expectedNodes = getMaxPathNodeCount(3) + 4 + 4097; - assertEquals(expectedNodes, storage.getCount()); - - //重新加载,判断数据是否正确; - MerkleTree r1_mkt = new MerkleTree(r1_rootHash, setting, keyPrefix, storage, true); - { - // 验证每一个数据节点都产生了存在性证明; - MerkleProof proof = null; - HashDigest expectedNodeHash = null; - MerkleDataNode reallyDataNode = null; - for (long n = 0; n < maxSN; n++) { - expectedNodeHash = expectedDataNodes.get(n); - reallyDataNode = r1_mkt.getData(n); - assertEquals(expectedNodeHash, reallyDataNode.getNodeHash()); - - proof = r1_mkt.getProof(n); - assertNotNull(proof); - assertEquals(expectedNodeHash, proof.getHash(0)); - } - } - } - - // 覆盖到每一路分支修改数据节点; - int storageDataCountBefore = storage.getCount(); - // maxSn = 4096; - long maxSN = mkt.getMaxSn(); - int i; - for (i = 0; i <= maxSN; i += 16) { - rand.nextBytes(dataBuf); - sn = i; - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - expectedDataNodes.put(sn, nd.getNodeHash()); - } - - mkt.commit(); - - // 记录一次提交的根哈希以及部分节点信息,用于后续的加载校验; - HashDigest r2_rootHash = mkt.getRootHash(); - long r2_dataCount = mkt.getDataCount(); - long r2_maxSN = mkt.getMaxSn(); - long r2_sn1 = r1_sn1; - String r2_proof1 = mkt.getProof(r2_sn1).toString(); - long r2_sn2 = r1_sn2; - String r2_proof2 = mkt.getProof(r2_sn2).toString(); - - { - // 检查节点数; - assertEquals(count, mkt.getDataCount()); - - assertEquals(r1_dataCount, r2_dataCount); - - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - long expectedMaxSN = 4096;// count-1; - assertEquals(expectedMaxSN, maxSN); - - // 由于覆盖到每一个分支节点,全部分支节点都重新生成,因此: - // 新增节点数=修改的数据节点数 + 全部分支节点数; - long addCounts = i / 16 + getMaxPathNodeCount(3) + 4; - assertEquals(storageDataCountBefore + addCounts, storage.getCount()); - } - - // 新插入数据; - final int NEW_INSERTED_COUNT = 18; - for (i = 0; i < NEW_INSERTED_COUNT; i++) { - rand.nextBytes(dataBuf); - sn = maxSN + 1 + i; - nd = mkt.setData(sn, "KEY-" + sn, 0, dataBuf); - expectedDataNodes.put(sn, nd.getNodeHash()); - } - mkt.commit(); - - { - // 验证每一个数据节点都产生了存在性证明; - MerkleProof proof = null; - for (Long n : expectedDataNodes.keySet()) { - proof = mkt.getProof(n.longValue()); - assertNotNull(proof); - assertEquals(expectedDataNodes.get(n), proof.getHash(0)); - } - } - - // 记录一次提交的根哈希以及部分节点信息,用于后续的加载校验; - HashDigest r3_rootHash = mkt.getRootHash(); - long r3_maxSN = mkt.getMaxSn(); - long r3_sn1 = r2_sn1; - String r3_proof1 = mkt.getProof(r3_sn1).toString(); - long r3_sn2 = r2_sn2; - String r3_proof2 = mkt.getProof(r3_sn2).toString(); - long r3_sn3 = 4096 + NEW_INSERTED_COUNT - 5; - String r3_proof3 = mkt.getProof(r3_sn3).toString(); - - { - // 检查节点数; - assertEquals(count + NEW_INSERTED_COUNT, mkt.getDataCount()); - - // 检查最大序列号的正确性; - maxSN = mkt.getMaxSn(); - long expectedMaxSN = 4096 + NEW_INSERTED_COUNT;// count-1; - assertEquals(expectedMaxSN, maxSN); - } - - // -------------------- - // 重新从存储加载生成新的 MerkleTree 实例,验证与初始实例的一致性; - // 从第 2 轮提交的 Merkle 根哈希加载; - MerkleTree r1_mkt = new MerkleTree(r1_rootHash, setting, keyPrefix, storage, true); - assertEquals(r1_maxSN, r1_mkt.getMaxSn()); - assertEquals(r1_rootHash, r1_mkt.getRootHash()); - assertEquals(r1_dataCount, r1_mkt.getDataCount()); - assertEquals(r1_proof1, r1_mkt.getProof(r1_sn1).toString()); - assertEquals(r1_proof2, r1_mkt.getProof(r1_sn2).toString()); - - - // 从第 2 轮提交的 Merkle 根哈希加载; - // 第 2 轮生成的 Merkle 树是对第 1 轮的数据的全部节点的修改,因此同一个 SN 的节点的证明是不同的; - MerkleTree r2_mkt = new MerkleTree(r2_rootHash, setting, keyPrefix, storage, true); - assertEquals(r1_maxSN, r2_mkt.getMaxSn()); - assertEquals(r1_dataCount, r2_mkt.getDataCount()); - - assertNotEquals(r1_rootHash, r2_mkt.getRootHash()); - assertNotEquals(r1_proof1, r2_mkt.getProof(r1_sn1).toString()); - assertNotEquals(r1_proof2, r2_mkt.getProof(r1_sn2).toString()); - - assertEquals(r2_maxSN, r2_mkt.getMaxSn()); - assertEquals(r2_rootHash, r2_mkt.getRootHash()); - assertEquals(r2_dataCount, r2_mkt.getDataCount()); - assertEquals(r2_proof1, r2_mkt.getProof(r2_sn1).toString()); - assertEquals(r2_proof2, r2_mkt.getProof(r2_sn2).toString()); - - // 从第 3 轮提交的 Merkle 根哈希加载; - // 第 3 轮生成的 Merkle 树是在第 2 轮的数据基础上做新增,因此非新增的同一个 SN 的节点的Merkle证明是相同的; - MerkleTree r3_mkt = new MerkleTree(r3_rootHash, setting, keyPrefix, storage, true); - assertEquals(r2_maxSN + NEW_INSERTED_COUNT, r3_mkt.getMaxSn()); - assertNotEquals(r2_rootHash, r3_mkt.getRootHash()); - assertEquals(r2_dataCount + NEW_INSERTED_COUNT, r3_mkt.getDataCount()); - - assertEquals(r3_maxSN, r3_mkt.getMaxSn()); - assertEquals(r3_rootHash, r3_mkt.getRootHash()); - assertEquals(r3_proof1, r3_mkt.getProof(r3_sn1).toString()); - assertEquals(r3_proof2, r3_mkt.getProof(r3_sn2).toString()); - assertEquals(r3_proof3, r3_mkt.getProof(r3_sn3).toString()); - - // 验证每一个数据节点都产生了存在性证明; - { - MerkleProof proof = null; - for (Long n : expectedDataNodes.keySet()) { - proof = r3_mkt.getProof(n.longValue()); - assertNotNull(proof); - assertEquals(expectedDataNodes.get(n), proof.getHash(0)); - } - } - } - - @SuppressWarnings("unused") - private static int getLevel(long dataCount) { - if (dataCount < 0) { - throw new IllegalArgumentException("The specified data count is negative!"); - } - int l = 1; - while (dataCount > power(MerkleTree.TREE_DEGREE, l)) { - l++; - } - return l; - } - - /** - * 计算整个 Merkle 树的路径节点的最大数量; - * - * @param level - * @return - */ - private static long getMaxPathNodeCount(int level) { - if (level < 1) { - throw new IllegalArgumentException("The specified level is less than 1!"); - } - long count = 0; - for (int i = 0; i < level; i++) { - count += power(MerkleTree.TREE_DEGREE, i); - } - return count; - } - - /** - * 计算 value 的 x 次方; - *

- * 注:此方法不处理溢出;调用者需要自行规避; - * - * @param value - * @param x 大于等于 0 的整数; - * @return - */ - private static long power(long value, int x) { - if (x == 0) { - return 1; - } - long r = value; - for (int i = 1; i < x; i++) { - r *= value; - } - return r; - } -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/RolePrivilegeDatasetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/RolePrivilegeDatasetTest.java deleted file mode 100644 index 18937fa0..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/RolePrivilegeDatasetTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.RolePrivileges; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.RolePrivilegeDataset; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; - -public class RolePrivilegeDatasetTest { - - private static final String[] SUPPORTED_PROVIDER_NAMES = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private static final CryptoAlgorithm HASH_ALGORITHM = Crypto.getAlgorithm("SHA256"); - - private static final CryptoProvider[] SUPPORTED_PROVIDERS = new CryptoProvider[SUPPORTED_PROVIDER_NAMES.length]; - static { - for (int i = 0; i < SUPPORTED_PROVIDER_NAMES.length; i++) { - SUPPORTED_PROVIDERS[i] = Crypto.getProvider(SUPPORTED_PROVIDER_NAMES[i]); - } - } - - @Test - public void testAddRolePrivilege() { - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setSupportedProviders(SUPPORTED_PROVIDERS); - cryptoConfig.setHashAlgorithm(HASH_ALGORITHM); - - MemoryKVStorage testStorage = new MemoryKVStorage(); - - String roleName = "DEFAULT"; - String prefix = "role-privilege/"; - RolePrivilegeDataset rolePrivilegeDataset = new RolePrivilegeDataset(cryptoConfig, prefix, testStorage, - testStorage); - rolePrivilegeDataset.addRolePrivilege(roleName, new LedgerPermission[] { LedgerPermission.REGISTER_USER }, - new TransactionPermission[] { TransactionPermission.CONTRACT_OPERATION }); - - rolePrivilegeDataset.commit(); - - RolePrivileges rolePrivilege = rolePrivilegeDataset.getRolePrivilege(roleName); - assertNotNull(rolePrivilege); - - HashDigest rootHash = rolePrivilegeDataset.getRootHash(); - RolePrivilegeDataset newRolePrivilegeDataset = new RolePrivilegeDataset(rootHash, cryptoConfig, prefix, - testStorage, testStorage, true); - rolePrivilege = newRolePrivilegeDataset.getRolePrivilege(roleName); - assertNotNull(rolePrivilege); - - assertTrue(rolePrivilege.getLedgerPrivilege().isEnable(LedgerPermission.REGISTER_USER)); - assertTrue(rolePrivilege.getTransactionPrivilege().isEnable(TransactionPermission.CONTRACT_OPERATION)); - - - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContract.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContract.java deleted file mode 100644 index 4cbe2784..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContract.java +++ /dev/null @@ -1,58 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEvent; - -@Contract -public interface TestContract { - - /** - * 发行资产; - * - * @param asset 资产代码; - * @param amount 本次发行的资产数量; - * @return 资产总量; - */ - @ContractEvent(name = "issue") - long issue(String asset, long amount); - - /** - * 获取资产总量; - * - * @param asset - * @return - */ - @ContractEvent(name = "get-amount") - long getAmount(String asset); - - /** - * 获取资产余额; - * - * @param address - * @param asset - * @return - */ - @ContractEvent(name = "get-balance") - long getBalance(String address, String asset); - - /** - * 向账户分配资产; - * - * @param address - * @param asset - * @param amount - */ - @ContractEvent(name = "assign") - void assign(String address, String asset, int amount); - - /** - * 转移资产; - * - * @param fromAddress - * @param toAddress - * @param asset - * @param amount - */ - @ContractEvent(name = "transfer") - void transfer(String fromAddress, String toAddress, String asset, long amount); -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContractImpl.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContractImpl.java deleted file mode 100644 index 339cb4fb..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContractImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -public interface TestContractImpl { - - /** - * 发行资产; - * - * @param asset 资产代码; - * @param amount 本次发行的资产数量; - * @return 资产总量; - */ - long issue(String asset, long amount); - - /** - * 获取资产总量; - * - * @param asset - * @return - */ - long getAmount(String asset); - - /** - * 获取资产余额; - * - * @param address - * @param asset - * @return - */ - long getBalance(String address, String asset); - - /** - * 向账户分配资产; - * - * @param address - * @param asset - * @param amount - */ - void assign(String address, String asset, int amount); - - /** - * 转移资产; - * - * @param fromAddress - * @param toAddress - * @param asset - * @param amount - */ - void transfer(String fromAddress, String toAddress, String asset, long amount); -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionBatchProcessorTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionBatchProcessorTest.java deleted file mode 100644 index a0e554e1..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionBatchProcessorTest.java +++ /dev/null @@ -1,453 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -import org.junit.Test; -import org.mockito.Mockito; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataAccountRegisterOperation; -import com.jd.blockchain.ledger.DataVersionConflictException; -import com.jd.blockchain.ledger.EndpointRequest; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.NodeRequest; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionContentBody; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.LedgerDataQuery; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerSecurityManager; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.ledger.core.LedgerTransactionalEditor; -import com.jd.blockchain.ledger.core.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionBatchProcessor; -import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; - -public class TransactionBatchProcessorTest { - static { - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - } - - private static final String LEDGER_KEY_PREFIX = "LDG://"; - - private HashDigest ledgerHash = null; - - private BlockchainKeypair parti0 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti1 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti2 = BlockchainKeyGenerator.getInstance().generate(); - private BlockchainKeypair parti3 = BlockchainKeyGenerator.getInstance().generate(); - - private BlockchainKeypair[] participants = { parti0, parti1, parti2, parti3 }; - - // TODO: 验证无效签名会被拒绝; - - @Test - public void testSingleTxProcess() { - final MemoryKVStorage STORAGE = new MemoryKVStorage(); - - // 初始化账本到指定的存储库; - ledgerHash = initLedger(STORAGE, parti0, parti1, parti2, parti3); - - // 加载账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); - - // 验证参与方账户的存在; - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(ledgerRepo.getLatestBlock()); - UserAccount user0 = previousBlockDataset.getUserAccountSet().getAccount(parti0.getAddress()); - assertNotNull(user0); - boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); - assertTrue(partiRegistered); - - // 生成新区块; - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - - OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - LedgerSecurityManager securityManager = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, - ledgerRepo, opReg); - - // 注册新用户; - BlockchainKeypair userKeypair = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest = LedgerTestUtils.createTxRequest_UserReg(userKeypair, ledgerHash, parti0, - parti0); - TransactionResponse txResp = txbatchProcessor.schedule(transactionRequest); - - LedgerBlock newBlock = newBlockEditor.prepare(); - newBlockEditor.commit(); - - // 验证正确性; - ledgerManager = new LedgerManager(); - ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); - - LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); - assertEquals(newBlock.getHash(), latestBlock.getHash()); - assertEquals(1, newBlock.getHeight()); - - assertEquals(TransactionState.SUCCESS, txResp.getExecutionState()); - } - - private static LedgerSecurityManager getSecurityManager() { - LedgerSecurityManager securityManager = Mockito.mock(LedgerSecurityManager.class); - - SecurityPolicy securityPolicy = Mockito.mock(SecurityPolicy.class); - when(securityPolicy.isEndpointEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isEndpointEnable(any(TransactionPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(TransactionPermission.class), any())).thenReturn(true); - - when(securityManager.createSecurityPolicy(any(), any())).thenReturn(securityPolicy); - - return securityManager; - } - - @Test - public void testMultiTxsProcess() { - final MemoryKVStorage STORAGE = new MemoryKVStorage(); - - // 初始化账本到指定的存储库; - ledgerHash = initLedger(STORAGE, parti0, parti1, parti2, parti3); - - // 加载账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); - - // 验证参与方账户的存在; - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(ledgerRepo.getLatestBlock()); - UserAccount user0 = previousBlockDataset.getUserAccountSet().getAccount(parti0.getAddress()); - assertNotNull(user0); - boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); - assertTrue(partiRegistered); - - // 生成新区块; - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - - OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - LedgerSecurityManager securityManager = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, - ledgerRepo, opReg); - - // 注册新用户; - BlockchainKeypair userKeypair1 = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest1 = LedgerTestUtils.createTxRequest_UserReg(userKeypair1, ledgerHash, - parti0, parti0); - TransactionResponse txResp1 = txbatchProcessor.schedule(transactionRequest1); - - BlockchainKeypair userKeypair2 = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest2 = LedgerTestUtils.createTxRequest_UserReg(userKeypair2, ledgerHash, - parti0, parti0); - TransactionResponse txResp2 = txbatchProcessor.schedule(transactionRequest2); - - LedgerBlock newBlock = newBlockEditor.prepare(); - newBlockEditor.commit(); - - assertEquals(TransactionState.SUCCESS, txResp1.getExecutionState()); - assertEquals(TransactionState.SUCCESS, txResp2.getExecutionState()); - - // 验证正确性; - ledgerManager = new LedgerManager(); - ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); - - LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); - assertEquals(newBlock.getHash(), latestBlock.getHash()); - assertEquals(1, newBlock.getHeight()); - - LedgerDataQuery ledgerDS = ledgerRepo.getLedgerData(latestBlock); - boolean existUser1 = ledgerDS.getUserAccountSet().contains(userKeypair1.getAddress()); - boolean existUser2 = ledgerDS.getUserAccountSet().contains(userKeypair2.getAddress()); - assertTrue(existUser1); - assertTrue(existUser2); - } - - @Test - public void testTxRollback() { - final MemoryKVStorage STORAGE = new MemoryKVStorage(); - - // 初始化账本到指定的存储库; - ledgerHash = initLedger(STORAGE, parti0, parti1, parti2, parti3); - - // 加载账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); - - // 验证参与方账户的存在; - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(ledgerRepo.getLatestBlock()); - UserAccount user0 = previousBlockDataset.getUserAccountSet().getAccount(parti0.getAddress()); - assertNotNull(user0); - boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); - assertTrue(partiRegistered); - - // 生成新区块; - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - - OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - LedgerSecurityManager securityManager = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, - ledgerRepo, opReg); - - // 注册新用户; - BlockchainKeypair userKeypair1 = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest1 = LedgerTestUtils.createTxRequest_UserReg(userKeypair1, ledgerHash, - parti0, parti0); - TransactionResponse txResp1 = txbatchProcessor.schedule(transactionRequest1); - - BlockchainKeypair userKeypair2 = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest2 = LedgerTestUtils - .createTxRequest_MultiOPs_WithNotExistedDataAccount(userKeypair2, ledgerHash, parti0, parti0); - TransactionResponse txResp2 = txbatchProcessor.schedule(transactionRequest2); - - BlockchainKeypair userKeypair3 = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest3 = LedgerTestUtils.createTxRequest_UserReg(userKeypair3, ledgerHash, - parti0, parti0); - TransactionResponse txResp3 = txbatchProcessor.schedule(transactionRequest3); - - LedgerBlock newBlock = newBlockEditor.prepare(); - newBlockEditor.commit(); - - assertEquals(TransactionState.SUCCESS, txResp1.getExecutionState()); - assertEquals(TransactionState.DATA_ACCOUNT_DOES_NOT_EXIST, txResp2.getExecutionState()); - assertEquals(TransactionState.SUCCESS, txResp3.getExecutionState()); - - // 验证正确性; - ledgerManager = new LedgerManager(); - ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); - - LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); - assertEquals(newBlock.getHash(), latestBlock.getHash()); - assertEquals(1, newBlock.getHeight()); - - LedgerTransaction tx1 = ledgerRepo.getTransactionSet() - .get(transactionRequest1.getTransactionContent().getHash()); - LedgerTransaction tx2 = ledgerRepo.getTransactionSet() - .get(transactionRequest2.getTransactionContent().getHash()); - LedgerTransaction tx3 = ledgerRepo.getTransactionSet() - .get(transactionRequest3.getTransactionContent().getHash()); - - assertNotNull(tx1); - assertEquals(TransactionState.SUCCESS, tx1.getExecutionState()); - assertNotNull(tx2); - assertEquals(TransactionState.DATA_ACCOUNT_DOES_NOT_EXIST, tx2.getExecutionState()); - assertNotNull(tx3); - assertEquals(TransactionState.SUCCESS, tx3.getExecutionState()); - - LedgerDataQuery ledgerDS = ledgerRepo.getLedgerData(latestBlock); - boolean existUser1 = ledgerDS.getUserAccountSet().contains(userKeypair1.getAddress()); - boolean existUser2 = ledgerDS.getUserAccountSet().contains(userKeypair2.getAddress()); - boolean existUser3 = ledgerDS.getUserAccountSet().contains(userKeypair3.getAddress()); - assertTrue(existUser1); - assertFalse(existUser2); - assertTrue(existUser3); - } - - @Test - public void testTxRollbackByVersionsConflict() { - final MemoryKVStorage STORAGE = new MemoryKVStorage(); - - // 初始化账本到指定的存储库; - ledgerHash = initLedger(STORAGE, parti0, parti1, parti2, parti3); - - // 加载账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); - - // 验证参与方账户的存在; - LedgerDataQuery previousBlockDataset = ledgerRepo.getLedgerData(ledgerRepo.getLatestBlock()); - UserAccount user0 = previousBlockDataset.getUserAccountSet().getAccount(parti0.getAddress()); - assertNotNull(user0); - boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); - assertTrue(partiRegistered); - - // 注册数据账户; - // 生成新区块; - LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - - OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - LedgerSecurityManager securityManager = getSecurityManager(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, - ledgerRepo, opReg); - - BlockchainKeypair dataAccountKeypair = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest transactionRequest1 = LedgerTestUtils.createTxRequest_DataAccountReg(dataAccountKeypair, - ledgerHash, parti0, parti0); - TransactionResponse txResp1 = txbatchProcessor.schedule(transactionRequest1); - LedgerBlock newBlock = newBlockEditor.prepare(); - newBlockEditor.commit(); - - assertEquals(TransactionState.SUCCESS, txResp1.getExecutionState()); - DataAccount dataAccount = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()); - assertNotNull(dataAccount); - - // 正确写入 KV 数据; - TransactionRequest txreq1 = LedgerTestUtils.createTxRequest_DataAccountWrite(dataAccountKeypair.getAddress(), - "K1", "V-1-1", -1, ledgerHash, parti0, parti0); - TransactionRequest txreq2 = LedgerTestUtils.createTxRequest_DataAccountWrite(dataAccountKeypair.getAddress(), - "K2", "V-2-1", -1, ledgerHash, parti0, parti0); - TransactionRequest txreq3 = LedgerTestUtils.createTxRequest_DataAccountWrite(dataAccountKeypair.getAddress(), - "K3", "V-3-1", -1, ledgerHash, parti0, parti0); - - // 连续写 K1,K1的版本将变为1; - TransactionRequest txreq4 = LedgerTestUtils.createTxRequest_DataAccountWrite(dataAccountKeypair.getAddress(), - "K1", "V-1-2", 0, ledgerHash, parti0, parti0); - - newBlockEditor = ledgerRepo.createNextBlock(); - previousBlockDataset = ledgerRepo.getLedgerData(ledgerRepo.getLatestBlock()); - txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, ledgerRepo, opReg); - - txbatchProcessor.schedule(txreq1); - txbatchProcessor.schedule(txreq2); - txbatchProcessor.schedule(txreq3); - txbatchProcessor.schedule(txreq4); - - newBlock = newBlockEditor.prepare(); - newBlockEditor.commit(); - - BytesValue v1_0 = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()).getDataset().getValue("K1", - 0); - BytesValue v1_1 = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()).getDataset().getValue("K1", - 1); - BytesValue v2 = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()).getDataset().getValue("K2", - 0); - BytesValue v3 = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()).getDataset().getValue("K3", - 0); - - - assertNotNull(v1_0); - assertNotNull(v1_1); - assertNotNull(v2); - assertNotNull(v3); - - assertEquals("V-1-1", v1_0.getBytes().toUTF8String()); - assertEquals("V-1-2", v1_1.getBytes().toUTF8String()); - assertEquals("V-2-1", v2.getBytes().toUTF8String()); - assertEquals("V-3-1", v3.getBytes().toUTF8String()); - - // 提交多笔数据写入的交易,包含存在数据版本冲突的交易,验证交易是否正确回滚; - // 先写一笔正确的交易; k3 的版本将变为 1 ; - TransactionRequest txreq5 = LedgerTestUtils.createTxRequest_DataAccountWrite(dataAccountKeypair.getAddress(), - "K3", "V-3-2", 0, ledgerHash, parti0, parti0); - // 指定冲突的版本号,正确的应该是版本1; - TransactionRequest txreq6 = LedgerTestUtils.createTxRequest_DataAccountWrite(dataAccountKeypair.getAddress(), - "K1", "V-1-3", 0, ledgerHash, parti0, parti0); - - newBlockEditor = ledgerRepo.createNextBlock(); - previousBlockDataset = ledgerRepo.getLedgerData(ledgerRepo.getLatestBlock()); - txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, ledgerRepo, opReg); - - txbatchProcessor.schedule(txreq5); - // 预期会产生版本冲突异常; DataVersionConflictionException; - DataVersionConflictException versionConflictionException = null; - try { - txbatchProcessor.schedule(txreq6); - } catch (DataVersionConflictException e) { - versionConflictionException = e; - } -// assertNotNull(versionConflictionException); - - newBlock = newBlockEditor.prepare(); - newBlockEditor.commit(); - - BytesValue v1 = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()).getDataset().getValue("K1"); - v3 = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()).getDataset().getValue("K3"); - - // k1 的版本仍然为1,没有更新; - long k1_version = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()) - .getDataset().getVersion("K1"); - assertEquals(1, k1_version); - - long k3_version = ledgerRepo.getDataAccountSet().getAccount(dataAccountKeypair.getAddress()) - .getDataset().getVersion("K3"); - assertEquals(1, k3_version); - - assertNotNull(v1); - assertNotNull(v3); - assertEquals("V-1-2", v1.getBytes().toUTF8String()); - assertEquals("V-3-2", v3.getBytes().toUTF8String()); - -// // 验证正确性; -// ledgerManager = new LedgerManager(); -// ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); -// -// LedgerBlock latestBlock = ledgerRepo.getLatestBlock(); -// assertEquals(newBlock.getHash(), latestBlock.getHash()); -// assertEquals(1, newBlock.getHeight()); -// -// LedgerTransaction tx1 = ledgerRepo.getTransactionSet() -// .get(transactionRequest1.getTransactionContent().getHash()); -// -// assertNotNull(tx1); -// assertEquals(TransactionState.SUCCESS, tx1.getExecutionState()); - - } - - private HashDigest initLedger(MemoryKVStorage storage, BlockchainKeypair... partiKeys) { - // 创建初始化配置; - LedgerInitSetting initSetting = LedgerTestUtils.createLedgerInitSetting(partiKeys); - - // 创建账本; - LedgerEditor ldgEdt = LedgerTransactionalEditor.createEditor(initSetting, LEDGER_KEY_PREFIX, storage, storage); - - TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(partiKeys); - LedgerTransactionContext genisisTxCtx = ldgEdt.newTransaction(genesisTxReq); - LedgerDataset ldgDS = genisisTxCtx.getDataset(); - - for (int i = 0; i < partiKeys.length; i++) { - UserAccount userAccount = ldgDS.getUserAccountSet().register(partiKeys[i].getAddress(), - partiKeys[i].getPubKey()); - userAccount.setProperty("Name", "参与方-" + i, -1); - userAccount.setProperty("Share", "" + (10 + i), -1); - } - - LedgerTransaction tx = genisisTxCtx.commit(TransactionState.SUCCESS); - - assertEquals(genesisTxReq.getTransactionContent().getHash(), tx.getTransactionContent().getHash()); - assertEquals(0, tx.getBlockHeight()); - - LedgerBlock block = ldgEdt.prepare(); - - assertEquals(0, block.getHeight()); - assertNotNull(block.getHash()); - assertNull(block.getPreviousHash()); - - // 创世区块的账本哈希为 null; - assertNull(block.getLedgerHash()); - assertNotNull(block.getHash()); - - // 提交数据,写入存储; - ldgEdt.commit(); - - HashDigest ledgerHash = block.getHash(); - return ledgerHash; - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionSetTest.java deleted file mode 100644 index 63ee3e64..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionSetTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Random; - -import com.jd.blockchain.ledger.*; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.DataAccountKVSetOperation.KVWriteEntry; -import com.jd.blockchain.ledger.core.LedgerTransactionData; -import com.jd.blockchain.ledger.core.TransactionQuery; -import com.jd.blockchain.ledger.core.TransactionSet; -import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.io.BytesUtils; - -public class TransactionSetTest { - - private static final String keyPrefix = ""; - - private Random rand = new Random(); - - @Test - public void test() { - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(ContractCodeDeployOperation.class); - DataContractRegistry.register(ContractEventSendOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - CryptoSetting defCryptoSetting = LedgerTestUtils.createDefaultCryptoSetting(); - - MemoryKVStorage testStorage = new MemoryKVStorage(); - - // Create a new TransactionSet, it's empty; - TransactionSet txset = new TransactionSet(defCryptoSetting, keyPrefix, testStorage, testStorage); - assertFalse(txset.isUpdated()); - assertFalse(txset.isReadonly()); - assertNull(txset.getRootHash()); - - // Build transaction request; - HashDigest ledgerHash = LedgerTestUtils.generateRandomHash(); - TxBuilder txBuilder = new TxBuilder(ledgerHash); - - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - UserRegisterOperation userRegOp = txBuilder.users().register(userKey.getIdentity()); - - BlockchainKeypair dataKey = BlockchainKeyGenerator.getInstance().generate(); - DataAccountRegisterOperation dataAccRegOp = txBuilder.dataAccounts().register(dataKey.getIdentity()); - - DataAccountKVSetOperation kvsetOP = txBuilder.dataAccount(dataKey.getAddress()).setText("A", "Value_A_0", -1) - .setText("B", "Value_B_0", -1).getOperation(); - - byte[] chainCode = new byte[128]; - rand.nextBytes(chainCode); - BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate(); - ContractCodeDeployOperation contractDplOP = txBuilder.contracts().deploy(contractKey.getIdentity(), chainCode); - - ContractEventSendOperation contractEvtSendOP = txBuilder.contractEvents().send(contractKey.getAddress(), "test", - BytesDataList.singleText("TestContractArgs")); - - TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); - - BlockchainKeypair sponsorKey = BlockchainKeyGenerator.getInstance().generate(); - txReqBuilder.signAsEndpoint(sponsorKey); - BlockchainKeypair gatewayKey = BlockchainKeyGenerator.getInstance().generate(); - txReqBuilder.signAsNode(gatewayKey); - - TransactionRequest txReq = txReqBuilder.buildRequest(); - - TransactionStagedSnapshot txSnapshot = new TransactionStagedSnapshot(); - HashDigest adminAccountHash = LedgerTestUtils.generateRandomHash(); - txSnapshot.setAdminAccountHash(adminAccountHash); - HashDigest userAccountSetHash = LedgerTestUtils.generateRandomHash(); - txSnapshot.setUserAccountSetHash(userAccountSetHash); - HashDigest dataAccountSetHash = LedgerTestUtils.generateRandomHash(); - txSnapshot.setDataAccountSetHash(dataAccountSetHash); - HashDigest contractAccountSetHash = LedgerTestUtils.generateRandomHash(); - txSnapshot.setContractAccountSetHash(contractAccountSetHash); - - long blockHeight = 8922L; - LedgerTransactionData tx = new LedgerTransactionData(blockHeight, txReq, TransactionState.SUCCESS, txSnapshot); - txset.add(tx); - - assertTrue(txset.isUpdated()); - - txset.commit(); - HashDigest txsetRootHash = txset.getRootHash(); - assertNotNull(txsetRootHash); - assertEquals(1, txset.getTotalCount()); - assertEquals(blockHeight, tx.getBlockHeight()); - assertEquals(ledgerHash, tx.getTransactionContent().getLedgerHash()); - assertEquals(5, tx.getTransactionContent().getOperations().length); - - // Reload ; - TransactionQuery reloadTxset = new TransactionSet(txsetRootHash, defCryptoSetting, keyPrefix, testStorage, - testStorage, true); - - assertEquals(1, reloadTxset.getTotalCount()); - - HashDigest txCtnHash = txReq.getTransactionContent().getHash(); - LedgerTransaction reloadTx = reloadTxset.get(txCtnHash); - assertNotNull(reloadTx); - - assertEquals(tx.getHash(), reloadTx.getHash()); - assertEquals(tx.getBlockHeight(), reloadTx.getBlockHeight()); - assertEquals(tx.getAdminAccountHash(), reloadTx.getAdminAccountHash()); - assertEquals(tx.getContractAccountSetHash(), reloadTx.getContractAccountSetHash()); - assertEquals(tx.getDataAccountSetHash(), reloadTx.getDataAccountSetHash()); - assertEquals(tx.getUserAccountSetHash(), reloadTx.getUserAccountSetHash()); - assertEquals(TransactionState.SUCCESS, reloadTx.getExecutionState()); - - DigitalSignature[] expEndpointSignatures = tx.getEndpointSignatures(); - DigitalSignature[] actualEndpointSignatures = reloadTx.getEndpointSignatures(); - assertEquals(expEndpointSignatures.length, actualEndpointSignatures.length); - for (int i = 0; i < actualEndpointSignatures.length; i++) { - assertEquals(expEndpointSignatures[i].getPubKey(), actualEndpointSignatures[i].getPubKey()); - assertEquals(expEndpointSignatures[i].getDigest(), actualEndpointSignatures[i].getDigest()); - } - - DigitalSignature[] expNodeSignatures = tx.getNodeSignatures(); - DigitalSignature[] actualNodeSignatures = reloadTx.getNodeSignatures(); - assertEquals(expNodeSignatures.length, actualNodeSignatures.length); - for (int i = 0; i < actualNodeSignatures.length; i++) { - assertEquals(expNodeSignatures[i].getPubKey(), actualNodeSignatures[i].getPubKey()); - assertEquals(expNodeSignatures[i].getDigest(), actualNodeSignatures[i].getDigest()); - } - - Operation[] expOperations = tx.getTransactionContent().getOperations(); - Operation[] actualOperations = reloadTx.getTransactionContent().getOperations(); - assertEquals(expOperations.length, actualOperations.length); - assertEquals(5, actualOperations.length); - assertTrue(actualOperations[0] instanceof UserRegisterOperation); - assertTrue(actualOperations[1] instanceof DataAccountRegisterOperation); - assertTrue(actualOperations[2] instanceof DataAccountKVSetOperation); - assertTrue(actualOperations[3] instanceof ContractCodeDeployOperation); - assertTrue(actualOperations[4] instanceof ContractEventSendOperation); - - UserRegisterOperation actualUserRegOp = (UserRegisterOperation) actualOperations[0]; - assertEquals(userRegOp.getUserID().getAddress(), actualUserRegOp.getUserID().getAddress()); - assertEquals(userRegOp.getUserID().getPubKey(), actualUserRegOp.getUserID().getPubKey()); - - DataAccountRegisterOperation actualDataAccRegOp = (DataAccountRegisterOperation) actualOperations[1]; - assertEquals(dataAccRegOp.getAccountID().getAddress(), actualDataAccRegOp.getAccountID().getAddress()); - assertEquals(dataAccRegOp.getAccountID().getPubKey(), actualDataAccRegOp.getAccountID().getPubKey()); - - DataAccountKVSetOperation actualKVSetOp = (DataAccountKVSetOperation) actualOperations[2]; - assertEquals(kvsetOP.getAccountAddress(), actualKVSetOp.getAccountAddress()); - - KVWriteEntry[] expKVWriteSet = kvsetOP.getWriteSet(); - KVWriteEntry[] acutualKVWriteSet = actualKVSetOp.getWriteSet(); - assertEquals(expKVWriteSet.length, acutualKVWriteSet.length); - for (int i = 0; i < acutualKVWriteSet.length; i++) { - assertEquals(expKVWriteSet[i].getKey(), acutualKVWriteSet[i].getKey()); - assertEquals(expKVWriteSet[i].getExpectedVersion(), acutualKVWriteSet[i].getExpectedVersion()); - assertTrue(BytesUtils.equals(expKVWriteSet[i].getValue().getBytes().toBytes(), - acutualKVWriteSet[i].getValue().getBytes().toBytes())); - } - - ContractCodeDeployOperation actualContractDplOp = (ContractCodeDeployOperation) actualOperations[3]; - assertEquals(contractDplOP.getContractID().getAddress(), actualContractDplOp.getContractID().getAddress()); - assertEquals(contractDplOP.getContractID().getPubKey(), actualContractDplOp.getContractID().getPubKey()); - assertTrue(BytesUtils.equals(contractDplOP.getChainCode(), actualContractDplOp.getChainCode())); - - ContractEventSendOperation actualContractEvtSendOp = (ContractEventSendOperation) actualOperations[4]; - assertEquals(contractEvtSendOP.getContractAddress(), actualContractEvtSendOp.getContractAddress()); - assertEquals(contractEvtSendOP.getEvent(), actualContractEvtSendOp.getEvent()); - assertEquals("test", actualContractEvtSendOp.getEvent()); - - byte[] expectedBytes = BinaryProtocol.encode(contractEvtSendOP.getArgs(), BytesValueList.class); - byte[] actualBytes = BinaryProtocol.encode(actualContractEvtSendOp.getArgs(), BytesValueList.class); - assertArrayEquals(expectedBytes, actualBytes); - - expectedBytes = BinaryProtocol.encode(BytesDataList.singleText("TestContractArgs"), BytesValueList.class); - actualBytes = BinaryProtocol.encode(actualContractEvtSendOp.getArgs(), BytesValueList.class); - assertArrayEquals(expectedBytes, actualBytes); - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionStagedSnapshotTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionStagedSnapshotTest.java deleted file mode 100644 index 9eebeafd..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionStagedSnapshotTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.TransactionStagedSnapshotTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午10:49 - * Description: - */ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class TransactionStagedSnapshotTest { - - private TransactionStagedSnapshot data; - - @Before - public void initTransactionStagedSnapshot() { - DataContractRegistry.register(LedgerDataSnapshot.class); - data = new TransactionStagedSnapshot(); - data.setAdminAccountHash(new HashDigest(ClassicAlgorithm.SHA256, "zhangsan".getBytes())); - data.setContractAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "lisi".getBytes())); - data.setDataAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "wangwu".getBytes())); - data.setUserAccountSetHash(new HashDigest(ClassicAlgorithm.SHA256, "zhaoliu".getBytes())); - } - - @Test - public void testSerialize_LedgerDataSnapshot() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, LedgerDataSnapshot.class); - LedgerDataSnapshot resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getAdminAccountHash(), data.getAdminAccountHash()); - assertEquals(resolvedData.getContractAccountSetHash(), data.getContractAccountSetHash()); - assertEquals(resolvedData.getDataAccountSetHash(), data.getDataAccountSetHash()); - assertEquals(resolvedData.getUserAccountSetHash(), data.getUserAccountSetHash()); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/UserRoleDatasetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/UserRoleDatasetTest.java deleted file mode 100644 index 44046ee6..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/UserRoleDatasetTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package test.com.jd.blockchain.ledger.core; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.UserRoles; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.UserRoleDataset; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; - -public class UserRoleDatasetTest { - - private static final String[] SUPPORTED_PROVIDER_NAMES = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private static final CryptoAlgorithm HASH_ALGORITHM = Crypto.getAlgorithm("SHA256"); - - private static final CryptoProvider[] SUPPORTED_PROVIDERS = new CryptoProvider[SUPPORTED_PROVIDER_NAMES.length]; - static { - for (int i = 0; i < SUPPORTED_PROVIDER_NAMES.length; i++) { - SUPPORTED_PROVIDERS[i] = Crypto.getProvider(SUPPORTED_PROVIDER_NAMES[i]); - } - } - - @Test - public void testAddUserRoles() { - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setSupportedProviders(SUPPORTED_PROVIDERS); - cryptoConfig.setHashAlgorithm(HASH_ALGORITHM); - - MemoryKVStorage testStorage = new MemoryKVStorage(); - String prefix = "user-roles/"; - UserRoleDataset userRolesDataset = new UserRoleDataset(cryptoConfig, prefix, testStorage, testStorage); - - BlockchainKeypair bckp = BlockchainKeyGenerator.getInstance().generate(); - String[] authRoles = { "DEFAULT", "MANAGER" }; - userRolesDataset.addUserRoles(bckp.getAddress(), RolesPolicy.UNION, authRoles); - - userRolesDataset.commit(); - - assertEquals(1, userRolesDataset.getUserCount()); - UserRoles userRoles = userRolesDataset.getUserRoles(bckp.getAddress()); - assertNotNull(userRoles); - String[] roles = userRoles.getRoles(); - assertEquals(2, roles.length); - assertArrayEquals(authRoles, roles); - assertEquals(RolesPolicy.UNION, userRoles.getPolicy()); - } - -} diff --git a/source/ledger/ledger-core/src/test/resources/contract-JDChain-Contract.jar b/source/ledger/ledger-core/src/test/resources/contract-JDChain-Contract.jar deleted file mode 100644 index fd926b15..00000000 Binary files a/source/ledger/ledger-core/src/test/resources/contract-JDChain-Contract.jar and /dev/null differ diff --git a/source/ledger/ledger-core/src/test/resources/logback-test.xml b/source/ledger/ledger-core/src/test/resources/logback-test.xml deleted file mode 100644 index 29013782..00000000 --- a/source/ledger/ledger-core/src/test/resources/logback-test.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractAware.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractAware.java deleted file mode 100644 index 87c51fec..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractAware.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.contract; - -/** - * 合约实现 {@link ContractAware} 的子接口可以监听运行时的生命周期事件; - * - * @author huanghaiquan - * - */ -public interface ContractAware { - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractEventContext.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractEventContext.java deleted file mode 100644 index e80a34b5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractEventContext.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jd.blockchain.contract; - -import java.util.Set; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValueList; -import com.jd.blockchain.ledger.TransactionRequest; - - -public interface ContractEventContext { - - /** - * 当前账本哈希; - * - * @return - */ - HashDigest getCurrentLedgerHash(); - - /** - * 执行合约事件的交易请求; - * - * @return - */ - TransactionRequest getTransactionRequest(); - - /** - * 交易的签署人集合; - * - * @return - */ - Set getTxSigners(); - - /** - * 事件名称; - * - * @return - */ - String getEvent(); - - /** - * 参数列表; - * - * @return - */ - BytesValueList getArgs(); - - /** - * 账本操作上下文; - * - * @return - */ - LedgerContext getLedger(); - - /** - * 合约的拥有者集合; - * - *
- * 合约的拥有者是部署合约时的签名者; - * - * @return - */ - Set getContracOwners(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractException.java deleted file mode 100644 index c5382d8e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.contract; - -import com.jd.blockchain.ledger.LedgerException; - -public class ContractException extends LedgerException { - - private static final long serialVersionUID = -4643365435848655115L; - - public ContractException(String message) { - super(message); - } - - public ContractException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractJarUtils.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractJarUtils.java deleted file mode 100644 index b2a3764b..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractJarUtils.java +++ /dev/null @@ -1,262 +0,0 @@ -package com.jd.blockchain.contract; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.utils.io.BytesUtils; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; - -import java.io.*; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; - -public class ContractJarUtils { - - public static final String BLACK_CONF = "blacks.conf"; - - public static final String WHITE_CONF = "whites.conf"; - - private static final String CONTRACT_MF = "META-INF/CONTRACT.MF"; - - private static final HashFunction HASH_FUNCTION = Crypto.getHashFunction("SHA256"); - - private static final Random FILE_RANDOM = new Random(); - - private static final byte[] JDCHAIN_MARK = "JDChain".getBytes(StandardCharsets.UTF_8); - - public static final String JDCHAIN_PACKAGE = "com.jd.blockchain"; - - public static boolean isJDChainPackage(String packageName) { - if (packageName.equals(JDCHAIN_PACKAGE)) { - return true; - } - return packageName.startsWith(JDCHAIN_PACKAGE + "."); - } - - public static List loadWhiteConf() { - - return resolveConfig(WHITE_CONF); - } - - public static List loadBlackConf() { - return resolveConfig(BLACK_CONF); - } - - public static List resolveConfig(String fileName) { - List configs = new ArrayList<>(); - - try { - List readLines = loadConfig(fileName); - if (!readLines.isEmpty()) { - for (String readLine : readLines) { - String[] lines = readLine.split(","); - configs.addAll(Arrays.asList(lines)); - } - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - - return configs; - } - - public static List loadConfig(String fileName) throws Exception { - - return IOUtils.readLines( - ContractJarUtils.class.getResourceAsStream(File.separator + fileName)); - } - - public static Map loadAllClasses(final File jar) throws Exception { - Map allClasses = new HashMap<>(); - JarFile jarFile = new JarFile(jar); - Enumeration jarEntries = jarFile.entries(); - while(jarEntries.hasMoreElements()){ - JarEntry jarEntry = jarEntries.nextElement(); - String entryName = jarEntry.getName(); - if (verify(entryName)) { - byte[] classContent = readStream(jarFile.getInputStream(jarEntry)); - if (classContent != null && classContent.length > 0) { - allClasses.put(entryName, classContent); - } - } - } - jarFile.close(); - - return allClasses; - } - - private static boolean verify(String entryName) { - - if (entryName.endsWith(".class") - && !entryName.startsWith("META-INF") - && !entryName.contains("-") - && entryName.contains("/")) { - return true; - } - return false; - } - - public static String dotClassName(String className) { - String dotClassName = className; - if (className.endsWith(".class")) { - dotClassName = className.substring(0, className.length() - 6); - } - dotClassName = dotClassName.replaceAll("/", "."); - return dotClassName; - } - - public static void verify(String contractPath, byte[] chainCode) { - if (chainCode == null || chainCode.length == 0) { - throw new IllegalStateException("Contract's chaincode is empty !!!"); - } - // 首先生成合约文件 - File jarFile = newJarTempFile(); - try { - FileUtils.writeByteArrayToFile(jarFile, chainCode); - // 校验合约文件 - verify(contractPath, jarFile); - } catch (Exception e) { - throw new IllegalStateException(e); - } finally { - // 删除文件 - try { - jarFile.deleteOnExit(); - } catch (Exception e) { - // DO NOTHING - } - } - } - - public static void verify(byte[] chainCode) { - verify(null, chainCode); - } - - private static void verify(String contractPath, File jarFile) throws Exception { - // 首先判断jarFile中是否含有META-INF/JDCHAIN.TXT,并将其读出 - URL jarUrl = new URL("jar:file:" + jarFile.getPath() + "!/" + CONTRACT_MF); - InputStream inputStream = jarUrl.openStream(); - if (inputStream == null) { - throw new IllegalStateException(CONTRACT_MF + " IS NULL !!!"); - } - byte[] bytes; - - try { - bytes = IOUtils.toByteArray(inputStream); - } finally { - inputStream.close(); - } - if (bytes == null || bytes.length == 0) { - throw new IllegalStateException(CONTRACT_MF + " IS Illegal !!!"); - } - // 获取对应的Hash内容 - String txt = new String(bytes, StandardCharsets.UTF_8); - - // 生成新的Jar包文件,该文件路径与JarFile基本一致 - File tempJar = newJarTempFile(); - try { - // 复制除JDCHAIN.TXT之外的部分 - copy(jarFile, tempJar, null, null, CONTRACT_MF); - - // 生成新Jar包对应的Hash内容 - String verifyTxt = contractMF(FileUtils.readFileToByteArray(tempJar)); - - // 校验Jar包内容 - if (!txt.equals(verifyTxt)) { - throw new IllegalStateException(String.format("Jar [%s] verify Illegal !!!", jarFile.getName())); - } - } finally { - try { - // 删除临时文件 - tempJar.deleteOnExit(); - } catch (Exception e) { - // DO NOTHING - } - } - } - - public static void copy(File srcJar, File dstJar) throws IOException { - copy(srcJar, dstJar, null, null, null); - } - - public static void copy(File srcJar, File dstJar, JarEntry addEntry, byte[] addBytes, String filter) throws IOException { - JarFile jarFile = new JarFile(srcJar); - Enumeration jarEntries = jarFile.entries(); - JarOutputStream jarOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dstJar))); - - while(jarEntries.hasMoreElements()){ - JarEntry jarEntry = jarEntries.nextElement(); - String entryName = jarEntry.getName(); - if (filter != null && filter.equals(entryName)) { - continue; - } - jarOut.putNextEntry(jarEntry); - jarOut.write(readStream(jarFile.getInputStream(jarEntry))); - jarOut.closeEntry(); - } - if (addEntry != null) { - jarOut.putNextEntry(addEntry); - jarOut.write(addBytes); - jarOut.closeEntry(); - } - - jarOut.flush(); - jarOut.finish(); - jarOut.close(); - jarFile.close(); - } - - public static String contractMF(byte[] content) { - HashDigest hashDigest = HASH_FUNCTION.hash(BytesUtils.concat(content, JDCHAIN_MARK)); - return "hash:" + hashDigest.toBase58(); - } - - public static JarEntry contractMFJarEntry() { - return new JarEntry(CONTRACT_MF); - } - - private static byte[] readStream(InputStream inputStream) { - try (ByteArrayOutputStream outSteam = new ByteArrayOutputStream()) { - byte[] buffer = new byte[1024]; - int len; - while ((len = inputStream.read(buffer)) != -1) { - outSteam.write(buffer, 0, len); - } - inputStream.close(); - return outSteam.toByteArray(); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - private static File newJarTempFile() { - - try { - return File.createTempFile("contract-" + - System.currentTimeMillis() + "-" + - System.nanoTime() + "-" + - FILE_RANDOM.nextInt(1024), ".jar"); - } catch (Exception e) { - throw new IllegalStateException(e); - } -// -// if (contractPath != null && contractPath.length() > 0) { -// return new File(contractPath + File.separator + -// "contract-" + -// System.currentTimeMillis() + "-" + -// System.nanoTime() + "-" + -// FILE_RANDOM.nextInt(1024) + -// ".jar"); -// } -// -// return new File("contract-" + -// System.currentTimeMillis() + "-" + -// System.nanoTime() + "-" + -// FILE_RANDOM.nextInt(1024) + -// ".jar"); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractLifecycleAware.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractLifecycleAware.java deleted file mode 100644 index 881de255..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractLifecycleAware.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.contract; - -/** - * 合约实现此接口可以监听合约应用的生命周期事件; - * - * - * @author huanghaiquan - * - */ -public interface ContractLifecycleAware extends ContractAware { - - void postConstruct(); - - void beforeDestroy(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractSerializeUtils.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractSerializeUtils.java deleted file mode 100644 index e7cc92ef..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractSerializeUtils.java +++ /dev/null @@ -1,165 +0,0 @@ -//package com.jd.blockchain.contract; -// -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//import com.jd.blockchain.binaryproto.BinaryProtocol; -//import com.jd.blockchain.binaryproto.DataContract; -//import com.jd.blockchain.binaryproto.DataContractRegistry; -//import com.jd.blockchain.contract.param.WRAP_BYTES; -//import com.jd.blockchain.contract.param.WRAP_INT; -//import com.jd.blockchain.contract.param.WRAP_LONG; -//import com.jd.blockchain.contract.param.WRAP_SHORT; -//import com.jd.blockchain.contract.param.WRAP_STRING; -//import com.jd.blockchain.ledger.BytesValue; -//import com.jd.blockchain.ledger.BytesValueList; -//import com.jd.blockchain.utils.io.BytesUtils; -// -//public class ContractSerializeUtils { -// -// final static int INT_LENGTH = 4; -// -// static Map, Class> MAP = new HashMap<>(); -// -// static { -// MAP.put(byte[].class, WRAP_BYTES.class); -// MAP.put(Short.class, WRAP_SHORT.class); -// MAP.put(short.class, WRAP_SHORT.class); -// MAP.put(Integer.class, WRAP_INT.class); -// MAP.put(int.class, WRAP_INT.class); -// MAP.put(Long.class, WRAP_LONG.class); -// MAP.put(long.class, WRAP_LONG.class); -// MAP.put(String.class, WRAP_STRING.class); -// -// DataContractRegistry.register(WRAP_BYTES.class); -// DataContractRegistry.register(WRAP_SHORT.class); -// DataContractRegistry.register(WRAP_INT.class); -// DataContractRegistry.register(WRAP_LONG.class); -// DataContractRegistry.register(WRAP_STRING.class); -// } -// -// public static boolean support(Class clazz) { -// if (clazz.isAnnotationPresent(DataContract.class) || MAP.containsKey(clazz)) { -// return true; -// } -// return false; -// } -// -// public static BytesValue serialize(Object data) { -// -// if (data == null) { -// return null; -// } -// -// Class clazz = data.getClass(); -// Class serialClass; -// Object wrapData = data; -// if (clazz.isAnnotationPresent(DataContract.class)) { -// serialClass = clazz; -// } else { -// // 判断类型是否可以序列化 -// Class wrapClass = MAP.get(clazz); -// if (wrapClass == null) { -// throw new IllegalArgumentException("There are Un-Support Type !!!"); -// } -// serialClass = wrapClass; -// -// if (wrapClass.equals(WRAP_BYTES.class)) { -// wrapData = (WRAP_BYTES) () -> (byte[]) data; -// } else if (wrapClass.equals(WRAP_INT.class)) { -// wrapData = (WRAP_INT) () -> (int) data; -// } else if (wrapClass.equals(WRAP_LONG.class)) { -// wrapData = (WRAP_LONG) () -> (long) data; -// } else if (wrapClass.equals(WRAP_SHORT.class)) { -// wrapData = (WRAP_SHORT) () -> (short) data; -// } else if (wrapClass.equals(WRAP_STRING.class)) { -// wrapData = (WRAP_STRING) () -> (String) data; -// } -// } -// // 按照对应接口进行序列化 -// // 生成该接口对应的对象 -// return BinaryProtocol.encode(wrapData, serialClass); -// } -// -// public static BytesValueList serializeArray(Object[] datas) { -// if (datas == null || datas.length == 0) { -// return null; -// } -// int contentBytesSize = 0; -// byte[] header = new byte[(datas.length + 1) * 4]; -// System.arraycopy(BytesUtils.toBytes(datas.length), 0, header, 0, INT_LENGTH); -// int offset = INT_LENGTH; -// -// List serialBytesList = new ArrayList<>(); -// for (Object data : datas) { -// // 按照对应接口进行序列化 -// byte[] currBytes = serialize(data); -// // 长度写入 -// System.arraycopy(BytesUtils.toBytes(currBytes.length), 0, header, offset, INT_LENGTH); -// serialBytesList.add(currBytes); -// contentBytesSize += currBytes.length; -// offset += INT_LENGTH; -// } -// -// // 填充content -// byte[] content = new byte[contentBytesSize]; -// offset = 0; -// for (byte[] bytes : serialBytesList) { -// System.arraycopy(bytes, 0, content, offset, bytes.length); -// offset += bytes.length; -// } -// // 将header和content组装 -// return BytesUtils.concat(header, content); -// } -// -// public static Object[] resolveArray(byte[] bytes) { -// if (bytes == null || bytes.length == 0) { -// return null; -// } -// byte[] lengthBytes = new byte[INT_LENGTH]; -// System.arraycopy(bytes, 0, lengthBytes, 0, INT_LENGTH); -// int length = BytesUtils.toInt(lengthBytes); -// Object[] datas = new Object[length]; -// -// int headerOffset = INT_LENGTH; -// int contentStart = (length + 1) * INT_LENGTH; -// -// for (int i = 0; i < length; i++) { -// byte[] currDataLengthBytes = new byte[INT_LENGTH]; -// System.arraycopy(bytes, headerOffset, currDataLengthBytes, 0, INT_LENGTH); -// int currDataLength = BytesUtils.toInt(currDataLengthBytes); -// // 读取 -// byte[] dataBytes = new byte[currDataLength]; -// System.arraycopy(bytes, contentStart, dataBytes, 0, currDataLength); -// -// datas[i] = resolve(dataBytes); -// -// contentStart += currDataLength; -// headerOffset += INT_LENGTH; -// } -// -// return datas; -// } -// -// public static Object resolve(BytesValue bytes) { -// // 反序列化该接口 -// Object currData = BinaryProtocol.decode(bytes); -// -// // 代理对象类型不能使用class判断,只能使用instanceof -// if (currData instanceof WRAP_STRING) { -// return ((WRAP_STRING) currData).getValue(); -// } else if (currData instanceof WRAP_INT) { -// return ((WRAP_INT) currData).getValue(); -// } else if (currData instanceof WRAP_LONG) { -// return ((WRAP_LONG) currData).getValue(); -// } else if (currData instanceof WRAP_BYTES) { -// return ((WRAP_BYTES) currData).getValue(); -// } else if (currData instanceof WRAP_SHORT) { -// return ((WRAP_SHORT) currData).getValue(); -// } else { -// return currData; -// } -// } -//} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractType.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractType.java deleted file mode 100644 index c8daa7e7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractType.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.jd.blockchain.contract; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import com.jd.blockchain.ledger.BytesValueEncoding; -import com.jd.blockchain.utils.IllegalDataException; - -public class ContractType { - - private String name; - - private Map events = new HashMap<>(); - - private Map handleMethods = new HashMap<>(); - - public String getName() { - return name; - } - - /** - * 返回声明的所有事件; - * - * @return - */ - public Set getEvents() { - return events.keySet(); - } - - /** - * 返回指定方法声明的事件;
- * - * 如果不存在,则返回 null; - * - * @param method - * @return - */ - public String getEvent(Method method) { - return handleMethods.get(method); - } - - /** - * 返回事件的处理方法;
- * - * 如果不存在,则返回 null; - * - * @param event - * @return - */ - public Method getHandleMethod(String event) { - return events.get(event); - } - - private ContractType() { - } - - /** - * 解析合约的声明; - * - * @param contractIntf 合约的声明接口,必须是 interface ; - * @return - */ - public static ContractType resolve(Class contractIntf) { - // TODO:方法会检查合约方法声明的类型和返回值类型; - // 如果是Class则首先获取其接口 - if (!contractIntf.isInterface()) { - Class realIntf = null; - Class[] interfaces = contractIntf.getInterfaces(); - for (Class intf : interfaces) { - if (intf.isAnnotationPresent(Contract.class)) { - realIntf = intf; - break; - } - } - if (realIntf == null) { - throw new IllegalDataException(String - .format("%s is not a Contract Type, because there is not @Contract !", contractIntf.getName())); - } - contractIntf = realIntf; - } - - // 接口上必须有注解 - Contract contract = contractIntf.getAnnotation(Contract.class); - if (contract == null) { - throw new IllegalDataException("It is not a Contract Type, because there is not @Contract !"); - } - - Method[] classMethods = contractIntf.getDeclaredMethods(); - - if (classMethods.length == 0) { - throw new IllegalDataException("This interface have not any methods !"); - } - - ContractType contractType = new ContractType(); - - // 设置合约显示名字为 - contractType.name = contract.name(); - - for (Method method : classMethods) { - - // if current method contains @ContractEvent,then put it in this map; - ContractEvent contractEvent = method.getAnnotation(ContractEvent.class); - - if (contractEvent != null) { - String eventName = contractEvent.name(); - // if annoMethodMap has contained the eventName, too many same eventNames exists - // probably, say NO! - if (contractType.events.containsKey(eventName)) { - throw new ContractException("there is repeat definition of contractEvent to @ContractEvent."); - } - // check param's type is fit for need. - Class[] paramTypes = method.getParameterTypes(); - for (Class currParamType : paramTypes) { - if (!BytesValueEncoding.supportType(currParamType)) { - throw new IllegalStateException( - String.format("Param Type = %s can not support !!!", currParamType.getName())); - } - } - - // 判断返回值是否可序列化 - Class returnType = method.getReturnType(); - if (!BytesValueEncoding.supportType(returnType)) { - throw new IllegalStateException( - String.format("Return Type = %s can not support !!!", returnType.getName())); - } - - contractType.events.put(eventName, method); - contractType.handleMethods.put(method, eventName); - } - } - // 最起码有一个ContractEvent - if (contractType.events.isEmpty()) { - throw new IllegalStateException( - String.format("Contract Interface[%s] have none method for annotation[@ContractEvent] !", contractIntf.getName())); - } - - return contractType; - } - - @Override - public String toString() { - return "ContractType{" + "name='" + name + '\'' + ", events=" + events + ", handleMethods=" + handleMethods - + '}'; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventProcessingAware.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventProcessingAware.java deleted file mode 100644 index 0e309dbd..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventProcessingAware.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.contract; - -/** - * @author huanghaiquan - * - */ -public interface EventProcessingAware extends ContractAware { - - /** - * 在事件处理方法执行之前调用; - * - * @param eventContext - */ - void beforeEvent(ContractEventContext eventContext); - - /** - * 在事件处理方法成功执行之后调用; - * - * @param eventContext - * 事件上下文; - * @param error - * 错误;如果事件处理正常结束,则此参数为 null;如果事件处理发生了错误,此参数非空; - */ - void postEvent(ContractEventContext eventContext, Exception error); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventResult.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventResult.java deleted file mode 100644 index 928d5979..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventResult.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jd.blockchain.contract; - -import com.jd.blockchain.utils.IllegalDataException; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - -public class EventResult { - - private static final long MAX_SECONDS = 30; - - private CompletableFuture data = new CompletableFuture<>(); - - private int opIndex; - - public EventResult() { - } - - public EventResult(int opIndex) { - this.opIndex = opIndex; - } - - public void done(T value) { - data.complete(value); - } - - public int opIndex() { - return this.opIndex; - } - - public T get() { - try { - // 防止长时间阻塞 - return data.get(MAX_SECONDS, TimeUnit.SECONDS); - } catch (Exception e) { - throw new IllegalDataException(e.getMessage()); - } - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/LedgerContext.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/LedgerContext.java deleted file mode 100644 index 196949ab..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/LedgerContext.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.contract; - -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.DataAccountOperator; -import com.jd.blockchain.transaction.UserOperator; - -public interface LedgerContext extends BlockchainQueryService, UserOperator, DataAccountOperator{ - - - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/LocalContractEventContext.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/LocalContractEventContext.java deleted file mode 100644 index 03263a1c..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/LocalContractEventContext.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.jd.blockchain.contract; - -import java.util.Set; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValueList; -import com.jd.blockchain.ledger.TransactionRequest; - -/** - * @Author zhaogw - * @Date 2018/9/5 17:43 - */ -public class LocalContractEventContext implements ContractEventContext,Cloneable { - private HashDigest ledgeHash; - private String event; - private BytesValueList args; - private TransactionRequest transactionRequest; - private Set txSigners; - private LedgerContext ledgerContext; - - public LocalContractEventContext(HashDigest ledgeHash, String event){ - this.ledgeHash = ledgeHash; - this.event = event; - } - - @Override - public HashDigest getCurrentLedgerHash() { - return ledgeHash; - } - - @Override - public TransactionRequest getTransactionRequest() { - return transactionRequest; - } - - @Override - public Set getTxSigners() { - return txSigners; - } - - @Override - public String getEvent() { - return event; - } - - @Override - public BytesValueList getArgs() { - return args; - } - - @Override - public LedgerContext getLedger() { - return ledgerContext; - } - - @Override - public Set getContracOwners() { - return null; - } - - public LocalContractEventContext setLedgeHash(HashDigest ledgeHash) { - this.ledgeHash = ledgeHash; - return this; - } - - public LocalContractEventContext setEvent(String event) { - this.event = event; - return this; - } - - public LocalContractEventContext setTransactionRequest(TransactionRequest transactionRequest) { - this.transactionRequest = transactionRequest; - return this; - } - - public LocalContractEventContext setTxSigners(Set txSigners) { - this.txSigners = txSigners; - return this; - } - - public LocalContractEventContext setLedgerContext(LedgerContext ledgerContext) { - this.ledgerContext = ledgerContext; - return this; - } - -// public byte[] getChainCode() { -// return chainCode; -// } -// -// public LocalContractEventContext setChainCode(byte[] chainCode) { -// this.chainCode = chainCode; -// return this; -// } - - public LocalContractEventContext setArgs(BytesValueList args) { - this.args = args; - return this; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Account.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Account.java deleted file mode 100644 index 28694160..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Account.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.utils.Dataset; - -public interface Account { - - BlockchainIdentity getID(); - - Dataset getDataset(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AccountHeader.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AccountHeader.java deleted file mode 100644 index fcc530de..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AccountHeader.java +++ /dev/null @@ -1,20 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import com.jd.blockchain.binaryproto.DataContract; -//import com.jd.blockchain.binaryproto.DataField; -//import com.jd.blockchain.binaryproto.PrimitiveType; -//import com.jd.blockchain.consts.DataCodes; -//import com.jd.blockchain.crypto.PubKey; -//import com.jd.blockchain.utils.Bytes; -// -//@Deprecated -//@DataContract(code= DataCodes.ACCOUNT_HEADER) -//public interface AccountHeader { //extends MerkleSnapshot{ -// -// @DataField(order = 1, primitiveType = PrimitiveType.BYTES) -// Bytes getAddress(); -// -// @DataField(order = 2, primitiveType=PrimitiveType.BYTES) -// PubKey getPubKey(); -// -//} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AuthorizationException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AuthorizationException.java deleted file mode 100644 index 94a374a8..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AuthorizationException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ledger; - -public class AuthorizationException extends LedgerException { - - private static final long serialVersionUID = -4418553411943356320L; - - - - public AuthorizationException(String message) { - super(message); - } - - public AuthorizationException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockBody.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockBody.java deleted file mode 100644 index 7c82b214..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockBody.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -@DataContract(code= DataCodes.BLOCK_BODY) -public interface BlockBody extends LedgerDataSnapshot{ - - @DataField(order=2, primitiveType = PrimitiveType.BYTES) - HashDigest getPreviousHash(); - - @DataField(order=3, primitiveType = PrimitiveType.BYTES) - HashDigest getLedgerHash(); - - @DataField(order=4, primitiveType= PrimitiveType.INT64) - long getHeight(); - - @DataField(order=5, primitiveType = PrimitiveType.BYTES) - HashDigest getTransactionSetHash(); - - @DataField(order=6, primitiveType = PrimitiveType.INT64) - long getTimestamp(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentity.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentity.java deleted file mode 100644 index 6dce8004..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentity.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.Bytes; - -@DataContract(code= DataCodes.BLOCK_CHAIN_IDENTITY) -public interface BlockchainIdentity { - - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - Bytes getAddress(); - - @DataField(order = 2, primitiveType=PrimitiveType.BYTES) - PubKey getPubKey(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesDataList.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesDataList.java deleted file mode 100644 index a7541a41..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesDataList.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.ledger; - -public class BytesDataList implements BytesValueList { - - private BytesValue[] bytesValues; - - public BytesDataList(BytesValue... bytesValues) { - this.bytesValues = bytesValues; - } - - @Override - public BytesValue[] getValues() { - return bytesValues; - } - - public static BytesValueList singleText(String value) { - return new BytesDataList(TypedValue.fromText(value)); - } - - public static BytesValueList singleLong(long value) { - return new BytesDataList(TypedValue.fromInt64(value)); - } - - public static BytesValueList singleInt(int value) { - return new BytesDataList(TypedValue.fromInt32(value)); - } - - public static BytesValueList singleBoolean(boolean value) { - return new BytesDataList(TypedValue.fromBoolean(value)); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValue.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValue.java deleted file mode 100644 index 47d4ad16..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValue.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Bytes; - -/** - * BytesValue is the base structure of Value in Blockchain Account; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.BYTES_VALUE) -public interface BytesValue { - - /** - * 数据类型; - * - * @return - */ - @DataField(order = 0, refEnum = true) - DataType getType(); - - /** - * 数据值的二进制序列; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - Bytes getBytes(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValueEncoding.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValueEncoding.java deleted file mode 100644 index 6579f1c4..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValueEncoding.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.ledger.resolver.BooleanToBytesValueResolver; -import com.jd.blockchain.ledger.resolver.BytesToBytesValueResolver; -import com.jd.blockchain.ledger.resolver.BytesValueResolver; -import com.jd.blockchain.ledger.resolver.IntegerToBytesValueResolver; -import com.jd.blockchain.ledger.resolver.LongToBytesValueResolver; -import com.jd.blockchain.ledger.resolver.ShortToBytesValueResolver; -import com.jd.blockchain.ledger.resolver.StringToBytesValueResolver; - -public class BytesValueEncoding { - - private static final Map, BytesValueResolver> CLASS_RESOLVER_MAP = new ConcurrentHashMap<>(); - - private static final Map DATA_TYPE_RESOLVER_MAP = new ConcurrentHashMap<>(); - - private static final Object[] EMPTY_OBJECTS = {}; - - static { - init(); - } - - private static void init() { - BytesValueResolver[] resolvers = new BytesValueResolver[] { new BooleanToBytesValueResolver(), - new BytesToBytesValueResolver(), new IntegerToBytesValueResolver(), new LongToBytesValueResolver(), - new ShortToBytesValueResolver(), new StringToBytesValueResolver() }; - - for (BytesValueResolver currResolver : resolvers) { - // 填充classMAP - Class[] supportClasses = currResolver.supportClasses(); - if (supportClasses != null && supportClasses.length > 0) { - for (Class clazz : supportClasses) { - CLASS_RESOLVER_MAP.put(clazz, currResolver); - } - } - - // 填充dataTypeMap - DataType[] supportDataTypes = currResolver.supportDataTypes(); - if (supportDataTypes != null && supportDataTypes.length > 0) { - for (DataType dataType : supportDataTypes) { - DATA_TYPE_RESOLVER_MAP.put(dataType, currResolver); - } - } - } - } - - public static BytesValue encodeSingle(Object value, Class type) { - if (value == null) { - return null; - } - if (type == null) { - type = value.getClass(); - } else if (type.equals(void.class) || type.equals(Void.class)) { - return null; - } - if (type.isInterface()) { - // 判断是否含有DataContract注解 - if (!type.isAnnotationPresent(DataContract.class)) { - throw new IllegalStateException( - String.format("Interface[%s] can not be serialize !!!", type.getName())); - } - // 将对象序列化 - byte[] serialBytes = BinaryProtocol.encode(value, type); - return TypedValue.fromType(DataType.DATA_CONTRACT, serialBytes); - } - BytesValueResolver bytesValueResolver = CLASS_RESOLVER_MAP.get(type); - if (bytesValueResolver == null) { - throw new IllegalStateException(String.format("Class[%s] can not find encoder !!!", type.getName())); - } - return bytesValueResolver.encode(value, type); - } - - public static BytesValueList encodeArray(Object[] values, Class[] types) { - if (values == null || values.length == 0) { - return null; - } - if (types != null && types.length != values.length) { - throw new IllegalStateException("Types can be null, or types's length must be equal BytesValue[]'s !!!"); - } - - BytesValueListData bytesValueListData = new BytesValueListData(); - for (int i = 0; i < values.length; i++) { - BytesValue bytesValue = encodeSingle(values[i], types == null ? null : types[i]); - bytesValueListData.add(bytesValue); - } - return bytesValueListData; - } - - public static Object decode(BytesValue value) { - return decode(value, null); - } - - public static Object decode(BytesValue value, Class type) { - DataType dataType = value.getType(); - BytesValueResolver valueResolver = DATA_TYPE_RESOLVER_MAP.get(dataType); - if (valueResolver == null) { - throw new IllegalStateException(String.format("DataType[%s] can not find encoder !!!", dataType.name())); - } - return type == null ? valueResolver.decode(value) : valueResolver.decode(value, type); - } - - public static Object[] decode(BytesValueList values, Class[] types) { - if (values == null) { - return EMPTY_OBJECTS; - } - BytesValue[] bytesValues = values.getValues(); - if (bytesValues == null || bytesValues.length == 0) { - return EMPTY_OBJECTS; - } - // 允许types为null,此时每个BytesValue按照当前的对象来处理 - // 若types不为null,则types's长度必须和bytesValues一致 - if (types != null && types.length != bytesValues.length) { - throw new IllegalStateException("Types can be null, or types's length must be equal BytesValue[]'s !!!"); - } - Object[] resolveObjs = new Object[bytesValues.length]; - if (types == null) { - // 按照默认方式解析 - for (int i = 0; i < bytesValues.length; i++) { - BytesValue bytesValue = bytesValues[i]; - DataType dataType = bytesValue.getType(); - BytesValueResolver valueResolver = DATA_TYPE_RESOLVER_MAP.get(dataType); - if (valueResolver == null) { - throw new IllegalStateException( - String.format("DataType[%s] can not find encoder !!!", dataType.name())); - } - resolveObjs[i] = valueResolver.decode(bytesValue); - } - return resolveObjs; - } - // 按照输入的Class进行解析 - for (int i = 0; i < bytesValues.length; i++) { - resolveObjs[i] = decode(bytesValues[i], types[i]); - } - return resolveObjs; - } - - public static Object getDefaultValue(Class type) { - if (type == void.class || type == Void.class) { - return null; - } - - if (!type.isPrimitive()) { - // 非基本类型 - return null; - } else { - // 基本类型需要处理返回值,目前采用枚举遍历方式 - // 八种基本类型:int, double, float, long, short, boolean, byte, char, void - if (type.equals(int.class)) { - return 0; - } else if (type.equals(double.class)) { - return 0.0D; - } else if (type.equals(float.class)) { - return 0F; - } else if (type.equals(long.class)) { - return 0L; - } else if (type.equals(short.class)) { - return (short) 0; - } else if (type.equals(boolean.class)) { - return Boolean.FALSE; - } else if (type.equals(byte.class)) { - return (byte) 0; - } else if (type.equals(char.class)) { - return (char) 0; - } - return null; - } - } - - public static boolean supportType(Class currParamType) { - // 支持空返回值 - if (currParamType.equals(void.class) || currParamType.equals(Void.class)) { - return true; - } - - if (currParamType.isInterface()) { - // 接口序列化必须实现DataContract注解 - if (!currParamType.isAnnotationPresent(DataContract.class)) { - throw new IllegalStateException( - String.format("Interface[%s] can not be annotated as a DataContract!!!", currParamType.getName())); - } - return true; - } - - if (currParamType.isArray() ) { - Class componentType = currParamType.getComponentType(); - if (componentType.isInterface()) { - // 接口序列化必须实现DataContract注解 - if (!componentType.isAnnotationPresent(DataContract.class)) { - throw new IllegalStateException( - String.format("Interface[%s] can not be annotated as a DataContract!!!", currParamType.getName())); - } - return true; - } - } - - return CLASS_RESOLVER_MAP.containsKey(currParamType); - } - - public static class BytesValueListData implements BytesValueList { - - private List bytesValues = new ArrayList<>(); - - public void add(BytesValue bytesValue) { - bytesValues.add(bytesValue); - } - - @Override - public BytesValue[] getValues() { - BytesValue[] bytesValueArray = new BytesValue[bytesValues.size()]; - return bytesValues.toArray(bytesValueArray); - } - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValueList.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValueList.java deleted file mode 100644 index e40e27d6..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValueList.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code = DataCodes.BYTES_VALUE_LIST) -public interface BytesValueList { - - @DataField(order = 0, refContract = true, list = true) - BytesValue[] getValues(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ConsensusNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ConsensusNode.java deleted file mode 100644 index 71eb0b26..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ConsensusNode.java +++ /dev/null @@ -1,38 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import com.jd.blockchain.base.data.TypeCodes; -//import com.jd.blockchain.binaryproto.DataContract; -//import com.jd.blockchain.binaryproto.DataField; -// -//import my.utils.ValueType; -// -///** -// * 共识节点;
-// * 以地址和端口一起作为唯一标识; -// * -// * @author huanghaiquan -// * -// */ -//@DataContract(code = TypeCodes.METADATA_CONSENSUS_NODE) -//public interface ConsensusNode { -// -// /** -// * 参与者ID; -// * -// * @return -// */ -// @DataField(order = 1, primitiveType = ValueType.INT32) -// int getId(); -// -//// /** -//// * 共识节点的主机地址; -//// * -//// *
-//// * 该节点以此地址参与共识服务; -//// * -//// * @return -//// */ -//// @DataField(order = 2, primitiveType = ValueType.BYTES) -//// NetworkAddress getConsensusAddress(); -// -//} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ConsensusSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ConsensusSetting.java deleted file mode 100644 index fae75065..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ConsensusSetting.java +++ /dev/null @@ -1,15 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import com.jd.blockchain.base.data.TypeCodes; -//import com.jd.blockchain.binaryproto.DataContract; -//import com.jd.blockchain.binaryproto.DataField; -// -//import my.utils.ValueType; -// -//@DataContract(code= TypeCodes.METADATA_CONSENSUS_SETTING) -//public interface ConsensusSetting { -// -// @DataField(order=2, primitiveType= ValueType.BYTES) -// byte[] getValue(); -// -//} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractDoesNotExistException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractDoesNotExistException.java deleted file mode 100644 index 687ef762..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractDoesNotExistException.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.ledger; - -public class ContractDoesNotExistException extends LedgerException { - - - private static final long serialVersionUID = 8685914012112243771L; - - public ContractDoesNotExistException(String message) { - super(message); - } - - public ContractDoesNotExistException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractEventSendOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractEventSendOperation.java deleted file mode 100644 index e9de0261..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractEventSendOperation.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Bytes; - -/** - * 发送合约事件的操作; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.TX_OP_CONTRACT_EVENT_SEND) -public interface ContractEventSendOperation extends Operation { - - /** - * 响应事件的合约地址; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - Bytes getContractAddress(); - - /** - * 事件名; - * - * @return - */ - @DataField(order = 3, primitiveType = PrimitiveType.TEXT) - String getEvent(); - - /** - * 事件参数; - * - * @return - */ - @DataField(order = 4, refContract = true) - BytesValueList getArgs(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractInfo.java deleted file mode 100644 index 047e3c51..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractInfo.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code= DataCodes.CONTRACT_ACCOUNT_HEADER) -public interface ContractInfo extends BlockchainIdentity, MerkleSnapshot { - - @DataField(order=4, primitiveType= PrimitiveType.BYTES) - byte[] getChainCode(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CryptoSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CryptoSetting.java deleted file mode 100644 index 9f24322c..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CryptoSetting.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.CryptoProvider; - -/** - * 默克尔树算法相关的配置; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA_CRYPTO_SETTING) -public interface CryptoSetting { - - /** - * 系统支持的密码服务提供者; - * - * @return - */ - @DataField(order = 0, refContract = true, list = true) - public CryptoProvider[] getSupportedProviders(); - - - - /** - * 系统中使用的 Hash 算法;
- * - * 对于历史数据,如果它未发生更改,则总是按照该数据产生时采用的算法进行校验,即使当时指定的Hash算法和当前的不同;
- * - * 如果对数据进行了更新,则采用新的 Hash 算法来计算生成完整性证明; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.INT16) - public short getHashAlgorithm(); - - /** - * 当有加载附带哈希摘要的数据时,是否重新计算哈希摘要进行完整性校验;
- * - * 如果为 true ,则自动进行校验,如果校验失败,会引发异常;
- * - * 注意:开启此选项将对性能会产生负面影响,因此使用者需要在性能和数据安全性之间做出权衡; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BOOLEAN) - public boolean getAutoVerifyHash(); - - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountDoesNotExistException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountDoesNotExistException.java deleted file mode 100644 index 428efffc..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountDoesNotExistException.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.ledger; - -public class DataAccountDoesNotExistException extends LedgerException { - - - private static final long serialVersionUID = -1889587937401974215L; - - public DataAccountDoesNotExistException(String message) { - super(message); - } - - public DataAccountDoesNotExistException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignatureBody.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignatureBody.java deleted file mode 100644 index de54970b..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignatureBody.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; - -/** - * 数字签名; - * - * @author huanghaiquan - * - */ -@DataContract(code= DataCodes.DIGITALSIGNATURE_BODY) -public interface DigitalSignatureBody { - - /** - * 公钥; - * - * 注:公钥的编码方式中包含了算法标识; - * - * @return - */ - @DataField(order=1, primitiveType = PrimitiveType.BYTES) - PubKey getPubKey(); - - /** - * 摘要; - * - * @return - */ - @DataField(order=2, primitiveType = PrimitiveType.BYTES ) - SignatureDigest getDigest(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashProof.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashProof.java deleted file mode 100644 index 4b2dd9c5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashProof.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.HashDigest; - -public interface HashProof { - /** - * 最大层级数;
- * 叶子节点(即数据节点)的层级为 0,数据节点之上的每一级父节点的层级加 1, 最大层级便是根节点的层级; - * - * @return - * - * @see MerkleTree#getLevel() - */ - int getLevels(); - - /** - * 返回证明中指定层级的节点的哈希; - *

- * - * @param level - * 参数值为 0 返回的是数据节点的哈希;
- * 参数值为 {@link #getLevels()} 返回的是根节点的哈希; - * @return - */ - HashDigest getHash(int level); - - /** - * 返回根节点的哈希; - * - * @return - */ - default HashDigest getRootHash() { - return getHash(getLevels()); - } - - /** - * 返回数据节点的哈希; - * - * @return - */ - default HashDigest getDataHash() { - return getHash(0); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/IllegalTransactionException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/IllegalTransactionException.java deleted file mode 100644 index 5a2bb5a1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/IllegalTransactionException.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.ledger; - -public class IllegalTransactionException extends RuntimeException { - - private static final long serialVersionUID = 6348921847690512944L; - - private TransactionState txState; - - public IllegalTransactionException(String message) { - super(message); - this.txState = TransactionState.SYSTEM_ERROR; - } - - public IllegalTransactionException(String message, TransactionState txState) { - super(message); - assert TransactionState.SUCCESS != txState; - this.txState = txState; - } - - public IllegalTransactionException(String message, Throwable cause) { - super(message, cause); - this.txState = TransactionState.SYSTEM_ERROR; - } - - public IllegalTransactionException(String message, Throwable cause, TransactionState txState) { - super(message, cause); - assert TransactionState.SUCCESS != txState; - this.txState = txState; - } - - public TransactionState getTxState() { - return txState; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/KVDataVO.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/KVDataVO.java deleted file mode 100644 index 10ffad7a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/KVDataVO.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jd.blockchain.ledger; - -/** - * @author zhaogw - * date 2019/5/14 14:17 - */ -public class KVDataVO { - private String key; - private long[] version; - - public KVDataVO() { - } - - public KVDataVO(String key, long[] version) { - this.key = key; - this.version = version; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public long[] getVersion() { - return version; - } - - public void setVersion(long[] version) { - this.version = version; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/KVInfoVO.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/KVInfoVO.java deleted file mode 100644 index 2077810d..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/KVInfoVO.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jd.blockchain.ledger; - -/** - * for BlockBrowserController.java, param is json ,then match it; - * @author zhaogw - * date 2019/5/14 14:19 - */ -public class KVInfoVO { - private KVDataVO[] data; - - public KVInfoVO() { - } - - public KVInfoVO(KVDataVO[] data) { - this.data = data; - } - - public KVDataVO[] getData() { - return data; - } - - public void setData(KVDataVO[] data) { - this.data = data; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminInfo.java deleted file mode 100644 index 62a2aa2f..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminInfo.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code=DataCodes.LEDGER_ADMIN_INFO) -public interface LedgerAdminInfo { - - @DataField(order=1, refContract = true) - LedgerMetadata_V2 getMetadata(); - - @DataField(order=2, refContract = true) - LedgerSettings getSettings(); - - @DataField(order=3, refContract = true, list = true) - ParticipantNode[] getParticipants(); - - @DataField(order=4, primitiveType = PrimitiveType.INT64) - long getParticipantCount(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminSettings.java deleted file mode 100644 index 2f4420fe..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminSettings.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.jd.blockchain.ledger; - -public interface LedgerAdminSettings extends LedgerAdminInfo { - - UserAuthorizationSettings getAuthorizations(); - - RolePrivilegeSettings getRolePrivileges(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerBlock.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerBlock.java deleted file mode 100644 index 1b58c8a7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerBlock.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -@DataContract(code = DataCodes.BLOCK) -public interface LedgerBlock extends BlockBody { - - /** - * 区块哈希; - * - *
- * 这是对 {@link BlockBody} 的哈希;
- * 对于创世区块而言,区块哈希是 {@link BlockBody#getPreviousHash()} 和 - * {@link BlockBody#getLedgerHash()} 属性均为 null 的情况下进行哈希计算得到的结果; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - HashDigest getHash(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerDataSnapshot.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerDataSnapshot.java deleted file mode 100644 index d6c9ecff..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerDataSnapshot.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -@DataContract(code=DataCodes.DATA_SNAPSHOT) -public interface LedgerDataSnapshot { - - @DataField(order=1, primitiveType = PrimitiveType.BYTES) - HashDigest getAdminAccountHash(); - - @DataField(order=2, primitiveType = PrimitiveType.BYTES) - HashDigest getUserAccountSetHash(); - - @DataField(order=3, primitiveType = PrimitiveType.BYTES) - HashDigest getDataAccountSetHash(); - - @DataField(order=4, primitiveType = PrimitiveType.BYTES) - HashDigest getContractAccountSetHash(); - -// HashDigest getUserPrivilegeHash(); - -// HashDigest getDataPrivilegeHash(); - -// HashDigest getContractPrivilegeHash(); - - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerException.java deleted file mode 100644 index d0edef01..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ledger; - -public class LedgerException extends RuntimeException { - - private static final long serialVersionUID = -4090881296855827888L; - - - - public LedgerException(String message) { - super(message); - } - - public LedgerException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInfo.java deleted file mode 100644 index 8ef4ac7d..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInfo.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.HashDigest; - -public class LedgerInfo { - - /** - * 账本哈希,这是账本的唯一标识; - * - * @return - */ - private HashDigest hash; - - private HashDigest latestBlockHash; - - private long latestBlockHeight; - - public HashDigest getHash() { - return hash; - } - - public void setHash(HashDigest hash) { - this.hash = hash; - } - - public HashDigest getLatestBlockHash() { - return latestBlockHash; - } - - public void setLatestBlockHash(HashDigest latestBlockHash) { - this.latestBlockHash = latestBlockHash; - } - - public long getLatestBlockHeight() { - return latestBlockHeight; - } - - public void setLatestBlockHeight(long latestBlockHeight) { - this.latestBlockHeight = latestBlockHeight; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitException.java deleted file mode 100644 index c3a31079..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ledger; - -public class LedgerInitException extends LedgerException{ - - private static final long serialVersionUID = 103724923689027144L; - - public LedgerInitException(String message) { - super(message); - } - - public LedgerInitException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitProperties.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitProperties.java deleted file mode 100644 index 120f6730..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitProperties.java +++ /dev/null @@ -1,520 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - -import com.jd.blockchain.consts.Global; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.LedgerInitProperties.CryptoProperties; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.PropertiesUtils; -import com.jd.blockchain.utils.StringUtils; -import com.jd.blockchain.utils.codec.HexUtils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class LedgerInitProperties { - - // 账本种子; - public static final String LEDGER_SEED = "ledger.seed"; - - // 账本名称 - public static final String LEDGER_NAME = "ledger.name"; - - // 声明的账本建立时间; - public static final String CREATED_TIME = "created-time"; - // 创建时间的格式; - public static final String CREATED_TIME_FORMAT = Global.DEFAULT_TIME_FORMAT; - - // 角色清单; - public static final String ROLES = "security.roles"; - // 角色的账本权限;用角色名称替代占位符; - public static final String ROLE_LEDGER_PRIVILEGES_PATTERN = "security.role.%s.ledger-privileges"; - // 角色的交易权限;用角色名称替代占位符; - public static final String ROLE_TX_PRIVILEGES_PATTERN = "security.role.%s.tx-privileges"; - - // 共识参与方的个数,后续以 part.id 分别标识每一个参与方的配置; - public static final String PART_COUNT = "cons_parti.count"; - // 共识参与方的名称的模式; - public static final String PART_ID_PATTERN = "cons_parti.%s"; - // 参与方的名称; - public static final String PART_NAME = "name"; - // 参与方的公钥文件路径; - public static final String PART_PUBKEY_PATH = "pubkey-path"; - // 参与方的公钥文件路径; - public static final String PART_PUBKEY = "pubkey"; - // 参与方的角色清单; - public static final String PART_ROLES = "roles"; - // 参与方的角色权限策略; - public static final String PART_ROLES_POLICY = "roles-policy"; - - // 共识参与方的账本初始服务的主机; - public static final String PART_INITIALIZER_HOST = "initializer.host"; - // 共识参与方的账本初始服务的端口; - public static final String PART_INITIALIZER_PORT = "initializer.port"; - // 共识参与方的账本初始服务是否开启安全连接; - public static final String PART_INITIALIZER_SECURE = "initializer.secure"; - - // 共识服务的参数配置;必须; - public static final String CONSENSUS_CONFIG = "consensus.conf"; - - // 共识服务提供者;必须; - public static final String CONSENSUS_SERVICE_PROVIDER = "consensus.service-provider"; - - // 密码服务提供者列表,以英文逗点“,”分隔;必须; - public static final String CRYPTO_SERVICE_PROVIDERS = "crypto.service-providers"; - // 从存储中加载账本数据时,是否校验哈希;可选; - public static final String CRYPTO_VRIFY_HASH = "crypto.verify-hash"; - // 哈希算法; - public static final String CRYPTO_HASH_ALGORITHM = "crypto.hash-algorithm"; - - public static final String CRYPTO_SERVICE_PROVIDERS_SPLITTER = ","; - - private byte[] ledgerSeed; - - private String ledgerName; - - private RoleInitData[] roles; - - private List consensusParticipants = new ArrayList<>(); - - private String consensusProvider; - - private Properties consensusConfig; - -// private String[] cryptoProviders; - - private CryptoProperties cryptoProperties = new CryptoProperties(); - - private long createdTime; - - public byte[] getLedgerSeed() { - return ledgerSeed.clone(); - } - - public String getLedgerName() { - return ledgerName; - } - - public long getCreatedTime() { - return createdTime; - } - - public Properties getConsensusConfig() { - return consensusConfig; - } - - public String getConsensusProvider() { - return consensusProvider; - } - - public int getConsensusParticipantCount() { - return consensusParticipants.size(); - } - - public List getConsensusParticipants() { - return consensusParticipants; - } - - public ParticipantNode[] getConsensusParticipantNodes() { - if (consensusParticipants.isEmpty()) { - return null; - } - ParticipantNode[] participantNodes = new ParticipantNode[consensusParticipants.size()]; - return consensusParticipants.toArray(participantNodes); - } - - public CryptoProperties getCryptoProperties() { - return cryptoProperties; - } - - public void setCryptoProperties(CryptoProperties cryptoProperties) { - if (cryptoProperties == null) { - cryptoProperties = new CryptoProperties(); - } - this.cryptoProperties = cryptoProperties; - } - - /** - * 返回参与者; - * - * @param id 从 1 开始; 小于等于 {@link #getConsensusParticipantCount()}; - * @return - */ - public ParticipantProperties getConsensusParticipant(int id) { - for (ParticipantProperties p : consensusParticipants) { - if (p.getId() == id) { - return p; - } - } - return null; - } - - /** - * 私有的构造器; - * - * @param ledgerSeed - */ - private LedgerInitProperties(byte[] ledgerSeed) { - this.ledgerSeed = ledgerSeed; - } - - public void addConsensusParticipant(ParticipantProperties participant) { - consensusParticipants.add(participant); - } - - private static String getKeyOfParticipant(int partId, String partPropKey) { - String partAddrStr = String.format(PART_ID_PATTERN, partId); - return String.format("%s.%s", partAddrStr, partPropKey); - } - - public static LedgerInitProperties resolve(String initSettingFile) { - Properties props = FileUtils.readProperties(initSettingFile, "UTF-8"); - File realFile = new File(initSettingFile); - return resolve(realFile.getParentFile().getPath(), props); - } - - public static LedgerInitProperties resolve(InputStream in) { - Properties props = FileUtils.readProperties(in, "UTF-8"); - return resolve(props); - } - - public static LedgerInitProperties resolve(Properties props) { - return resolve(null, props); - } - - /** - * 从属性表解析账本初始化参数; - * - * @param baseDirectory 基础路径;属性中涉及文件位置的相对路径以此参数指定的目录为父目录; - * @param props 要解析的属性表; - * @return - */ - public static LedgerInitProperties resolve(String baseDirectory, Properties props) { - String hexLedgerSeed = PropertiesUtils.getRequiredProperty(props, LEDGER_SEED).replace("-", ""); - byte[] ledgerSeed = HexUtils.decode(hexLedgerSeed); - LedgerInitProperties initProps = new LedgerInitProperties(ledgerSeed); - - // 解析账本信息; - // 账本名称 - String ledgerName = PropertiesUtils.getRequiredProperty(props, LEDGER_NAME); - initProps.ledgerName = ledgerName; - - // 创建时间; - String strCreatedTime = PropertiesUtils.getRequiredProperty(props, CREATED_TIME); - try { - initProps.createdTime = new SimpleDateFormat(CREATED_TIME_FORMAT).parse(strCreatedTime).getTime(); - } catch (ParseException ex) { - throw new IllegalArgumentException(ex.getMessage(), ex); - } - - // 解析角色清单; - String strRoleNames = PropertiesUtils.getOptionalProperty(props, ROLES); - String[] roles = StringUtils.splitToArray(strRoleNames, ","); - - Map rolesInitSettingMap = new TreeMap(); - // 解析角色权限表; - for (String role : roles) { - String ledgerPrivilegeKey = getKeyOfRoleLedgerPrivilege(role); - String strLedgerPermissions = PropertiesUtils.getOptionalProperty(props, ledgerPrivilegeKey); - LedgerPermission[] ledgerPermissions = resolveLedgerPermissions(strLedgerPermissions); - - String txPrivilegeKey = getKeyOfRoleTxPrivilege(role); - String strTxPermissions = PropertiesUtils.getOptionalProperty(props, txPrivilegeKey); - TransactionPermission[] txPermissions = resolveTransactionPermissions(strTxPermissions); - - if (ledgerPermissions.length > 0 || txPermissions.length > 0) { - RoleInitData rolesSettings = new RoleInitData(role, ledgerPermissions, txPermissions); - rolesInitSettingMap.put(role, rolesSettings); - } - } - RoleInitData[] rolesInitDatas = rolesInitSettingMap.values() - .toArray(new RoleInitData[rolesInitSettingMap.size()]); - initProps.setRoles(rolesInitDatas); - - // 解析共识相关的属性; - initProps.consensusProvider = PropertiesUtils.getRequiredProperty(props, CONSENSUS_SERVICE_PROVIDER); - String consensusConfigFilePath = PropertiesUtils.getRequiredProperty(props, CONSENSUS_CONFIG); - try { - File consensusConfigFile = FileUtils.getFile(baseDirectory, consensusConfigFilePath); - initProps.consensusConfig = FileUtils.readProperties(consensusConfigFile); - } catch (FileNotFoundException e) { - throw new IllegalArgumentException( - String.format("Consensus config file[%s] doesn't exist! ", consensusConfigFilePath), e); - } - - // 解析密码提供者列表; - String cryptoProviderNames = PropertiesUtils.getProperty(props, CRYPTO_SERVICE_PROVIDERS, true); - String[] cryptoProviders = cryptoProviderNames.split(CRYPTO_SERVICE_PROVIDERS_SPLITTER); - for (int i = 0; i < cryptoProviders.length; i++) { - cryptoProviders[i] = cryptoProviders[i].trim(); - } - initProps.cryptoProperties.setProviders(cryptoProviders); - // 哈希校验选项; - boolean verifyHash = PropertiesUtils.getBooleanOptional(props, CRYPTO_VRIFY_HASH, false); - initProps.cryptoProperties.setVerifyHash(verifyHash); - // 哈希算法; - String hashAlgorithm = PropertiesUtils.getOptionalProperty(props, CRYPTO_HASH_ALGORITHM); - initProps.cryptoProperties.setHashAlgorithm(hashAlgorithm); - - - // 解析参与方节点列表; - int partCount = getInt(PropertiesUtils.getRequiredProperty(props, PART_COUNT)); - if (partCount < 0) { - throw new IllegalArgumentException(String.format("Property[%s] is negative!", PART_COUNT)); - } - if (partCount < 4) { - throw new IllegalArgumentException(String.format("Property[%s] is less than 4!", PART_COUNT)); - } - for (int i = 0; i < partCount; i++) { - ParticipantProperties parti = new ParticipantProperties(); - - parti.setId(i); - - String nameKey = getKeyOfParticipant(i, PART_NAME); - parti.setName(PropertiesUtils.getRequiredProperty(props, nameKey)); - - String pubkeyPathKey = getKeyOfParticipant(i, PART_PUBKEY_PATH); - String pubkeyPath = PropertiesUtils.getProperty(props, pubkeyPathKey, false); - - String pubkeyKey = getKeyOfParticipant(i, PART_PUBKEY); - String base58PubKey = PropertiesUtils.getProperty(props, pubkeyKey, false); - if (base58PubKey != null) { - PubKey pubKey = KeyGenUtils.decodePubKey(base58PubKey); - parti.setPubKey(pubKey); - } else if (pubkeyPath != null) { - PubKey pubKey = KeyGenUtils.readPubKey(pubkeyPath); - parti.setPubKey(pubKey); - } else { - throw new IllegalArgumentException( - String.format("Property[%s] and property[%s] are all empty!", pubkeyKey, pubkeyPathKey)); - } - - // 解析参与方的角色权限配置; - String partiRolesKey = getKeyOfParticipant(i, PART_ROLES); - String strPartiRoles = PropertiesUtils.getOptionalProperty(props, partiRolesKey); - String[] partiRoles = StringUtils.splitToArray(strPartiRoles, ","); - parti.setRoles(partiRoles); - - String partiRolePolicyKey = getKeyOfParticipant(i, PART_ROLES_POLICY); - String strPartiPolicy = PropertiesUtils.getOptionalProperty(props, partiRolePolicyKey); - RolesPolicy policy = strPartiPolicy == null ? RolesPolicy.UNION - : RolesPolicy.valueOf(strPartiPolicy.trim()); - policy = policy == null ? RolesPolicy.UNION : policy; - parti.setRolesPolicy(policy); - - // 解析参与方的网络配置参数; - String initializerHostKey = getKeyOfParticipant(i, PART_INITIALIZER_HOST); - String initializerHost = PropertiesUtils.getRequiredProperty(props, initializerHostKey); - - String initializerPortKey = getKeyOfParticipant(i, PART_INITIALIZER_PORT); - int initializerPort = getInt(PropertiesUtils.getRequiredProperty(props, initializerPortKey)); - - String initializerSecureKey = getKeyOfParticipant(i, PART_INITIALIZER_SECURE); - boolean initializerSecure = Boolean - .parseBoolean(PropertiesUtils.getRequiredProperty(props, initializerSecureKey)); - NetworkAddress initializerAddress = new NetworkAddress(initializerHost, initializerPort, initializerSecure); - parti.setInitializerAddress(initializerAddress); - parti.setParticipantNodeState(ParticipantNodeState.ACTIVED); - initProps.addConsensusParticipant(parti); - } - - return initProps; - } - - private static TransactionPermission[] resolveTransactionPermissions(String strTxPermissions) { - String[] strPermissions = StringUtils.splitToArray(strTxPermissions, ","); - List permissions = new ArrayList(); - if (strPermissions != null) { - for (String pm : strPermissions) { - TransactionPermission permission = TransactionPermission.valueOf(pm); - if (permission != null) { - permissions.add(permission); - } - } - } - return permissions.toArray(new TransactionPermission[permissions.size()]); - } - - private static LedgerPermission[] resolveLedgerPermissions(String strLedgerPermissions) { - String[] strPermissions = StringUtils.splitToArray(strLedgerPermissions, ","); - List permissions = new ArrayList(); - if (strPermissions != null) { - for (String pm : strPermissions) { - LedgerPermission permission = LedgerPermission.valueOf(pm); - if (permission != null) { - permissions.add(permission); - } - } - } - return permissions.toArray(new LedgerPermission[permissions.size()]); - } - - private static String getKeyOfRoleLedgerPrivilege(String role) { - return String.format(ROLE_LEDGER_PRIVILEGES_PATTERN, role); - } - - private static String getKeyOfRoleTxPrivilege(String role) { - return String.format(ROLE_TX_PRIVILEGES_PATTERN, role); - } - - private static int getInt(String strInt) { - return Integer.parseInt(strInt.trim()); - } - - public RoleInitData[] getRoles() { - return roles; - } - - public void setRoles(RoleInitData[] roles) { - this.roles = roles; - } - - public static class CryptoProperties { - - private String[] providers; - - private boolean verifyHash; - - private String hashAlgorithm; - - public String[] getProviders() { - return providers; - } - - public void setProviders(String[] providers) { - this.providers = providers; - } - - public boolean isVerifyHash() { - return verifyHash; - } - - public void setVerifyHash(boolean verifyHash) { - this.verifyHash = verifyHash; - } - - public String getHashAlgorithm() { - return hashAlgorithm; - } - - public void setHashAlgorithm(String hashAlgorithm) { - this.hashAlgorithm = hashAlgorithm; - } - - } - - /** - * 参与方配置信息; - * - * @author huanghaiquan - * - */ - public static class ParticipantProperties implements ParticipantNode { - - private int id; - - private Bytes address; - - private String name; - - private PubKey pubKey; - - private String[] roles; - - private RolesPolicy rolesPolicy; - - // private NetworkAddress consensusAddress; - - private ParticipantNodeState participantNodeState; - - private NetworkAddress initializerAddress; - - @Override - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -// public String getPubKeyPath() { -// return pubKeyPath; -// } -// -// public void setPubKeyPath(String pubKeyPath) { -// this.pubKeyPath = pubKeyPath; -// } - - @Override - public ParticipantNodeState getParticipantNodeState() { - return participantNodeState; - } - - public void setParticipantNodeState(ParticipantNodeState participantNodeState) { - this.participantNodeState = participantNodeState; - } - - public NetworkAddress getInitializerAddress() { - return initializerAddress; - } - - public void setInitializerAddress(NetworkAddress initializerAddress) { - this.initializerAddress = initializerAddress; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - this.address = AddressEncoding.generateAddress(pubKey); - } - - public String[] getRoles() { - return roles; - } - - public void setRoles(String[] roles) { - this.roles = roles; - } - - public RolesPolicy getRolesPolicy() { - return rolesPolicy; - } - - public void setRolesPolicy(RolesPolicy rolesPolicy) { - this.rolesPolicy = rolesPolicy; - } - - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitSetting.java deleted file mode 100644 index d3ee5d1d..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitSetting.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Bytes; - -/** - * 账本初始化配置; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA_INIT_SETTING) -public interface LedgerInitSetting { - - /** - * 账本的种子; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - byte[] getLedgerSeed(); - - /** - * 共识参与方的列表; - * - * @return - */ - @DataField(order = 2, list = true, refContract = true) - ParticipantNode[] getConsensusParticipants(); - - /** - * 密码算法配置; - * - * @return - */ - @DataField(order = 3, refContract = true) - CryptoSetting getCryptoSetting(); - - @DataField(order = 4, primitiveType = PrimitiveType.TEXT) - String getConsensusProvider(); - - /** - * 共识算法配置; - * - * @return - */ - @DataField(order = 5, primitiveType = PrimitiveType.BYTES) - Bytes getConsensusSettings(); - - /** - * 账本创建时间; - * - * @return - */ - @DataField(order = 6, primitiveType = PrimitiveType.INT64) - long getCreatedTime(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata.java deleted file mode 100644 index f7108ff3..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -/** - * 账本的元数据; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA, name = "LEDGER-METADATA") -public interface LedgerMetadata { - - /** - * 账本的初始化种子; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - byte[] getSeed(); - - /** - * 共识参与方的默克尔树的根; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - HashDigest getParticipantsHash(); - - /** - * 账本配置的哈希; - * - * @return - */ - @DataField(order = 3, primitiveType = PrimitiveType.BYTES) - HashDigest getSettingsHash(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata_V2.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata_V2.java deleted file mode 100644 index 228019b7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata_V2.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -/** - * {@link LedgerMetadata_V2} 是 {@link LedgerMetadata} 的升级版本,新增加了 - * {@link #getRolePrivilegesHash()} 属性; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA_V2, name = "LEDGER-METADATA-V2") -public interface LedgerMetadata_V2 extends LedgerMetadata { - - /** - * 角色权限集合的根哈希;; - * - * @return - */ - @DataField(order = 4, primitiveType = PrimitiveType.BYTES) - HashDigest getRolePrivilegesHash(); - - /** - * 用户角色授权集合的根哈希; - * - * @return - */ - @DataField(order = 5, primitiveType = PrimitiveType.BYTES) - HashDigest getUserRolesHash(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermission.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermission.java deleted file mode 100644 index 799354f1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermission.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Int8Code; - -/** - * 账本相关的权限,这些权限属于全局性的; - * - * @author huanghaiquan - * - */ -@EnumContract(code = DataCodes.ENUM_LEDGER_PERMISSION) -public enum LedgerPermission implements Int8Code{ - - /** - * 配置角色的权限;
- */ - CONFIGURE_ROLES((byte) 0x01), - - /** - * 授权用户角色;
- */ - AUTHORIZE_USER_ROLES((byte) 0x02), - - /** - * 设置共识协议;
- */ - SET_CONSENSUS((byte) 0x03), - - /** - * 设置密码体系;
- */ - SET_CRYPTO((byte) 0x04), - - /** - * 注册参与方;
- */ - REGISTER_PARTICIPANT((byte) 0x05), - - /** - * 注册用户;
- * - * 如果不具备此项权限,则无法注册用户; - */ - REGISTER_USER((byte) 0x06), - - /** - * 注册数据账户;
- */ - REGISTER_DATA_ACCOUNT((byte) 0x07), - - /** - * 注册合约;
- */ - REGISTER_CONTRACT((byte) 0x08), - - /** - * 升级合约 - */ - UPGRADE_CONTRACT((byte) 0x14), - - /** - * 设置用户属性;
- */ - SET_USER_ATTRIBUTES((byte) 0x09), - - /** - * 写入数据账户;
- */ - WRITE_DATA_ACCOUNT((byte) 0x0A), - - /** - * 参与方核准交易;
- * - * 如果不具备此项权限,则无法作为节点签署由终端提交的交易; - *

- * 只对交易请求的节点签名列表{@link TransactionRequest#getNodeSignatures()}的用户产生影响; - */ - APPROVE_TX((byte) 0x0B), - - /** - * 参与方共识交易;
- * - * 如果不具备此项权限,则无法作为共识节点接入并对交易进行共识; - */ - CONSENSUS_TX((byte) 0x0C); - - @EnumField(type = PrimitiveType.INT8) - public final byte CODE; - - private LedgerPermission(byte code) { - this.CODE = code; - } - - @Override - public byte getCode() { - return CODE; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermissionException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermissionException.java deleted file mode 100644 index 21b3cee1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermissionException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ledger; - -public class LedgerPermissionException extends LedgerException { - - private static final long serialVersionUID = 6077975401474519117L; - - public LedgerPermissionException(String message) { - super(message); - } - - public LedgerPermissionException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPrivilege.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPrivilege.java deleted file mode 100644 index 01261cc2..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPrivilege.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.ledger; - -/** - * LedgerPrivilege 账本特权是授权给特定角色的权限代码序列; - * - * @author huanghaiquan - * - */ -public class LedgerPrivilege extends PrivilegeBitset { - - public LedgerPrivilege() { - } - - public LedgerPrivilege(byte[] codeBytes) { - super(codeBytes); - } - - @Override - public LedgerPrivilege clone() { - return (LedgerPrivilege) super.clone(); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSecurityException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSecurityException.java deleted file mode 100644 index 0b3e98a8..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSecurityException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ledger; - -public class LedgerSecurityException extends RuntimeException { - - private static final long serialVersionUID = -4090881296855827888L; - - - - public LedgerSecurityException(String message) { - super(message); - } - - public LedgerSecurityException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSettings.java deleted file mode 100644 index fd77685a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSettings.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.utils.Bytes; - -@DataContract(code = DataCodes.METADATA_LEDGER_SETTING) -public interface LedgerSettings { - - @DataField(order=0, primitiveType=PrimitiveType.TEXT) - String getConsensusProvider(); - - @DataField(order=1, primitiveType=PrimitiveType.BYTES) - Bytes getConsensusSetting(); - - @DataField(order=2, refContract=true) - CryptoSetting getCryptoSetting(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerTransaction.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerTransaction.java deleted file mode 100644 index 6514193e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerTransaction.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.consts.DataCodes; - -/** - * 账本的事务; - * - * TODO: refactor: replace {@link Transaction} to {@link LedgerTransaction} - * - * @author huanghaiquan - * - */ -@DataContract(code=DataCodes.TX_LEDGER) -public interface LedgerTransaction extends Transaction, LedgerDataSnapshot { - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleDataNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleDataNode.java deleted file mode 100644 index 43e9d32f..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleDataNode.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.utils.Bytes; - -public interface MerkleDataNode extends MerkleNode { - - long getSN(); - - Bytes getKey(); - - long getVersion(); - - HashDigest getValueHash(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleNode.java deleted file mode 100644 index b8eba626..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleNode.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.HashDigest; - -public interface MerkleNode { - - HashDigest getNodeHash(); - - /** - * 节点的深度; - * - * 叶子节点的深度为 0;每一级父节点的深度加 1 ; - * - * @return - */ - int getLevel(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleProof.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleProof.java deleted file mode 100644 index 75721f7f..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleProof.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jd.blockchain.ledger; - -public interface MerkleProof extends HashProof { - - /** - * 所证明的数据节点的序列号; - * - * @return - */ - long getSN(); - -// /** -// * 最大层级数;
-// * 叶子节点(即数据节点)的层级为 0,数据节点之上的每一级父节点的层级加 1, 最大层级便是根节点的层级; -// * -// * @return -// * -// * @see MerkleTree#getLevel() -// */ -// int getLevels(); -// -// /** -// * 返回证明中指定层级的节点的哈希; -// *

-// * -// * @param level -// * 参数值为 0 返回的是数据节点的哈希;
-// * 参数值为 {@link #getLevels()} 返回的是根节点的哈希; -// * @return -// */ -// HashDigest getHash(int level); - - MerkleNode getNode(int level); - - /** -// * 返回根节点的哈希; -// * -// * @return -// */ -// default HashDigest getRootHash() { -// return getHash(getLevels()); -// } -// -// /** -// * 返回数据节点的哈希; -// * -// * @return -// */ -// default HashDigest getDataHash() { -// return getHash(0); -// } - - default MerkleDataNode getDataNode() { - return (MerkleDataNode)getNode(0); - } - - /** - * 返回字符串形式的哈希路径; - * - * @return - */ - @Override - String toString(); -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleSnapshot.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleSnapshot.java deleted file mode 100644 index 1e195559..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleSnapshot.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -@DataContract(code = DataCodes.MERKLE_SNAPSHOT) -public interface MerkleSnapshot { - - @DataField(order = 0, primitiveType = PrimitiveType.BYTES) - HashDigest getRootHash(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Operation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Operation.java deleted file mode 100644 index ce78fa11..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Operation.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code= DataCodes.TX_OP) -public interface Operation { - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationResult.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationResult.java deleted file mode 100644 index b6c6c3bd..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationResult.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code = DataCodes.TX_OP_RESULT) -public interface OperationResult { - - @DataField(order = 1, primitiveType = PrimitiveType.INT32) - int getIndex(); - - @DataField(order = 2, refContract = true) - BytesValue getResult(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationResultData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationResultData.java deleted file mode 100644 index 336887cf..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationResultData.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.ledger; - - -public class OperationResultData implements OperationResult { - - private int index; - - private BytesValue result; - - public OperationResultData() { - } - - public OperationResultData(int index, BytesValue result) { - this.index = index; - this.result = result; - } - - @Override - public int getIndex() { - return index; - } - - @Override - public BytesValue getResult() { - return result; - } - - public void setIndex(int index) { - this.index = index; - } - - public void setResult(BytesValue result) { - this.result = result; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDataQuery.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDataQuery.java deleted file mode 100644 index 6ba0668e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDataQuery.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.utils.Bytes; - -public interface ParticipantDataQuery { - - HashDigest getRootHash(); - - MerkleProof getProof(Bytes key); - - long getParticipantCount(); - - boolean contains(Bytes address); - - /** - * 返回指定地址的参与方凭证; - * - *
- * 如果不存在,则返回 null; - * - * @param address - * @return - */ - ParticipantNode getParticipant(Bytes address); - - ParticipantNode[] getParticipants(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDoesNotExistException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDoesNotExistException.java deleted file mode 100644 index 54994dc7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDoesNotExistException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ledger; - -public class ParticipantDoesNotExistException extends LedgerException { - - private static final long serialVersionUID = 397450363050148898L; - - public ParticipantDoesNotExistException(String message) { - super(message); - } - - public ParticipantDoesNotExistException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantInfo.java deleted file mode 100644 index c366fdd3..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantInfo.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.net.NetworkAddress; - - -/** - * 参与方信息; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA_PARTICIPANT_INFO) -public interface ParticipantInfo { - - /** - * regist or unregist, temporarily not available to users - * - * @return - */ -// @DataField(order = 0, primitiveType = PrimitiveType.TEXT) -// String getFlag(); - - /** - * 参与者名称; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.TEXT) - String getName(); - - /** - * 公钥; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - PubKey getPubKey(); - - /** - * 共识协议的网络地址; - * - * @return - */ - @DataField(order = 3, primitiveType = PrimitiveType.BYTES) - NetworkAddress getNetworkAddress(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantInfoData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantInfoData.java deleted file mode 100644 index a5a6bc0a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantInfoData.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * 即将要注册的参与方的信息 - * @author zhangshuang - * @create 2019/7/8 - * @since 1.0.0 - */ -public class ParticipantInfoData implements ParticipantInfo { - - - private String name; - - private PubKey pubKey; - - private NetworkAddress networkAddress; - -// private String flag;//代表注册参与方或者删除参与方 - - public ParticipantInfoData(String name, PubKey pubKey, NetworkAddress networkAddress) { - this.name = name; - this.pubKey = pubKey; - this.networkAddress = networkAddress; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - } - - @Override - public NetworkAddress getNetworkAddress() { - return networkAddress; - } - - public void setNetworkAddress(NetworkAddress networkAddress) { - this.networkAddress = networkAddress; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java deleted file mode 100644 index 9be89492..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.Bytes; - -/** - * 参与方节点; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.METADATA_CONSENSUS_PARTICIPANT) -public interface ParticipantNode { - - /** - * 节点的顺序编号;
- * - * 注:此字段并非固定不变的;在序列化和反序列化时不包含此字段; - * - * @return - */ - @DataField(order = 0, primitiveType = PrimitiveType.INT32) - int getId(); - - /** - * 节点的虚拟地址,根据公钥生成; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - Bytes getAddress(); - - /** - * 参与者名称; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.TEXT) - String getName(); - - /** - * 节点消息认证的公钥; - * - * @return - */ - @DataField(order = 3, primitiveType = PrimitiveType.BYTES) - PubKey getPubKey(); - - /** - * 节点的状态:已注册/已参与共识 - * - * @return - */ - @DataField(order = 4, refEnum = true) - ParticipantNodeState getParticipantNodeState(); -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNodeState.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNodeState.java deleted file mode 100644 index f7b97fd1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNodeState.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - - -/** - * 参与方节点状态 - * @author zhangshuang - * @create 2019/7/8 - * @since 1.0.0 - */ -@EnumContract(code= DataCodes.ENUM_TYPE_PARTICIPANT_NODE_STATE) -public enum ParticipantNodeState { - - /** - * 已注册; - */ - REGISTERED((byte) 0), - - /** - * 已激活; - */ - ACTIVED((byte) 1); - - @EnumField(type= PrimitiveType.INT8) - public final byte CODE; - - private ParticipantNodeState(byte code) { - this.CODE = code; - } - - public static ParticipantNodeState valueOf(byte code) { - for (ParticipantNodeState tr : values()) { - if (tr.CODE == code) { - return tr; - } - } - throw new IllegalArgumentException("Unsupported participant node state code!"); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantRegisterOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantRegisterOperation.java deleted file mode 100644 index ec946593..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantRegisterOperation.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.net.NetworkAddress; - -@DataContract(code= DataCodes.TX_OP_PARTICIPANT_REG) -public interface ParticipantRegisterOperation extends Operation { - - @DataField(order = 0, primitiveType=PrimitiveType.TEXT) - String getParticipantName(); - - @DataField(order = 1, refContract = true) - BlockchainIdentity getParticipantRegisterIdentity(); - - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - NetworkAddress getNetworkAddress(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateInfo.java deleted file mode 100644 index 70c89f3f..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateInfo.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * 参与方状态更新信息; - * - * - */ -@DataContract(code = DataCodes.METADATA_PARTICIPANT_STATE_INFO) -public interface ParticipantStateUpdateInfo { - - /** - * 公钥; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - PubKey getPubKey(); - - /** - * 共识协议的网络地址; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - NetworkAddress getNetworkAddress(); - - /** - * 参与方状态; - * - * @return - */ - @DataField(order = 3, refEnum = true) - ParticipantNodeState getState(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateInfoData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateInfoData.java deleted file mode 100644 index 5e11c178..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateInfoData.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class ParticipantStateUpdateInfoData implements ParticipantStateUpdateInfo { - private PubKey pubKey; - private ParticipantNodeState state; - private NetworkAddress networkAddress; - - public ParticipantStateUpdateInfoData(PubKey pubKey, ParticipantNodeState state, NetworkAddress networkAddress) { - this.pubKey = pubKey; - this.state = state; - this.networkAddress = networkAddress; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - public void setNetworkAddress(NetworkAddress networkAddress) { - this.networkAddress = networkAddress; - } - - @Override - public NetworkAddress getNetworkAddress() { - return networkAddress; - } - - public void setState(ParticipantNodeState state) { - this.state = state; - } - - @Override - public ParticipantNodeState getState() { - return state; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateOperation.java deleted file mode 100644 index fa2791a7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantStateUpdateOperation.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.net.NetworkAddress; - -@DataContract(code= DataCodes.TX_OP_PARTICIPANT_STATE_UPDATE) -public interface ParticipantStateUpdateOperation extends Operation { - - @DataField(order = 0, refContract = true) - BlockchainIdentity getStateUpdateIdentity(); - - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - NetworkAddress getNetworkAddress(); - - @DataField(order = 2, refEnum = true) - ParticipantNodeState getState(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PreparedTransaction.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PreparedTransaction.java deleted file mode 100644 index 20d4d9ad..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PreparedTransaction.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.io.Closeable; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; - -/** - * 已就绪的交易; - * - * @author huanghaiquan - * - */ -public interface PreparedTransaction extends HashObject, Closeable { - - /** - * 交易内容的 Hash; - * - * @return - */ - @Override - HashDigest getHash(); - - /** - * 交易数据内容;
- * - *
- * 如果需要对交易进行外部签名,可以将此数据块发送到外部进行签名; - * - * @return - */ - TransactionContent getTransactionContent(); - - /** - * 对交易进行签名; - * - * @param address 签名账户的地址; - * @param privKey 签名账户的私钥; - * @return - */ - DigitalSignature sign(AsymmetricKeypair keyPair); - - /** - * 加入签名; - * - * @param address 签名账户的地址; - * @param digest Base64格式的签名摘要; - * @return - */ - void addSignature(DigitalSignature signature); - - /** - * 提交交易请求到共识节点;
- * - * 这是同步方法,将阻塞当前线程,直到交易处理完成并返回结果之后,此方法才返回给调用者; - * - */ - TransactionResponse commit(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privilege.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privilege.java deleted file mode 100644 index 4a77e0b9..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privilege.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jd.blockchain.ledger; - -public interface Privilege> { - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeBitset.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeBitset.java deleted file mode 100644 index 3b038fbb..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeBitset.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.util.BitSet; - -import com.jd.blockchain.utils.Int8Code; -import com.jd.blockchain.utils.io.BytesSerializable; - -/** - * PrivilegeBitset 定义了用位表示的权限码; - * - * @author huanghaiquan - * - */ -public abstract class PrivilegeBitset & Int8Code> implements Privilege, BytesSerializable, Cloneable { - // 加入1个字节的前缀位 0xF1,可避免序列化时输出空的字节数组; - private static final byte PREFIX = (byte) 0xF1; - private static final byte[] PREFIX_BYTES = { PREFIX }; - private static final int OFFSET = 8; - private static final int MAX_SIZE = 32; - - // 前缀中置为 1 的位数,值 0xF1 有 5 个比特位为 1; - private static final int PREFIX_CARDINALITY = 5; - - private BitSet permissionBits; - - public PrivilegeBitset() { - // 设置前缀; - this.permissionBits = BitSet.valueOf(PREFIX_BYTES); - } - - /** - * @param codeBytes 权限的字节位; - * @param codeIndexer - */ - public PrivilegeBitset(byte[] codeBytes) { - // 检查长度; - if (codeBytes.length == 0) { - throw new IllegalArgumentException("Empty code bytes!"); - } - if (codeBytes.length > MAX_SIZE) { - throw new IllegalArgumentException( - "The size of code bytes specified to PrivilegeBitset exceed the max size[" + MAX_SIZE + "]!"); - } - // 校验前缀; - if (codeBytes[0] != PREFIX) { - throw new IllegalArgumentException("The code bytes is not match the privilege prefix code!"); - } - - this.permissionBits = BitSet.valueOf(codeBytes); - } - - protected PrivilegeBitset(BitSet bits) { - this.permissionBits = bits; - } - - public boolean isEnable(E permission) { - return permissionBits.get(index(permission)); - } - - public void enable(E permission) { - permissionBits.set(index(permission)); - } - - public void disable(E permission) { - permissionBits.clear(index(permission)); - } - - @SuppressWarnings("unchecked") - public void enable(E... permissions) { - for (E p : permissions) { - permissionBits.set(index(p)); - } - } - - @SuppressWarnings("unchecked") - public void disable(E... permissions) { - for (E p : permissions) { - permissionBits.clear(index(p)); - } - } - - @Override - public byte[] toBytes() { - return permissionBits.toByteArray(); - } - - /** - * 把指定的权限合并到当前的权限中;
- * - * @param privileges - * @return - */ - @SuppressWarnings("unchecked") - public Privilege union(PrivilegeBitset... privileges) { - return union(privileges, 0, privileges.length); - } - - /** - * 把指定的权限合并到当前的权限中;
- * - * @param privileges - * @param offset - * @param count - * @return - */ - public Privilege union(PrivilegeBitset[] privileges, int offset, int count) { - BitSet bits = this.permissionBits; - for (int i = 0; i < count; i++) { - bits.or(privileges[i + offset].permissionBits); - } - return this; - } - - /** - * 保留当前的权限与指定权限的共同生效的部分,同时清除其它的权限位;
- * - * @param privileges - * @return - */ - @SuppressWarnings("unchecked") - public Privilege intersect(PrivilegeBitset... privileges) { - return intersect(privileges, 0, privileges.length); - } - - /** - * 保留当前的权限与指定权限的共同生效的部分,同时清除其它的权限位;
- * - * @param privileges - * @param offset - * @param count - * @return - */ - public Privilege intersect(PrivilegeBitset[] privileges, int offset, int count) { - BitSet bits = this.permissionBits; - for (int i = 0; i < count; i++) { - bits.and(privileges[i + offset].permissionBits); - } - return this; - } - - @Override - public Privilege clone() { - try { - BitSet bitSet = (BitSet) permissionBits.clone(); - @SuppressWarnings("unchecked") - PrivilegeBitset privilege = (PrivilegeBitset) super.clone(); - privilege.permissionBits = bitSet; - return privilege; - } catch (CloneNotSupportedException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - protected BitSet cloneBitSet() { - return (BitSet) permissionBits.clone(); - } - - private int index(E permission) { - return OFFSET + permission.getCode(); - } - - public int getPermissionCount() { - return permissionBits.cardinality() - PREFIX_CARDINALITY; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeSet.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeSet.java deleted file mode 100644 index bf0d3da7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeSet.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -/** - * 表示赋予角色的特权码; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.PRIVILEGE_SET, name = "PRIVILEGE-SET") -public interface PrivilegeSet { - - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - LedgerPrivilege getLedgerPrivilege(); - - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - TransactionPrivilege getTransactionPrivilege(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privileges.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privileges.java deleted file mode 100644 index 420cbf45..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privileges.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jd.blockchain.ledger; - -public class Privileges implements PrivilegeSet { - - private LedgerPrivilege ledgerPrivilege; - - private TransactionPrivilege txPrivilege; - - protected Privileges() { - this.ledgerPrivilege = new LedgerPrivilege(); - this.txPrivilege = new TransactionPrivilege(); - } - - protected Privileges(PrivilegeSet privilege) { - this.ledgerPrivilege = privilege.getLedgerPrivilege(); - this.txPrivilege = privilege.getTransactionPrivilege(); - } - - protected Privileges(LedgerPrivilege ledgerPrivilege, TransactionPrivilege txPrivilege) { - this.ledgerPrivilege = ledgerPrivilege; - this.txPrivilege = txPrivilege; - } - - @Override - public LedgerPrivilege getLedgerPrivilege() { - return ledgerPrivilege; - } - - public void setLedgerPrivilege(LedgerPrivilege ledgerPrivilege) { - this.ledgerPrivilege = ledgerPrivilege; - } - - @Override - public TransactionPrivilege getTransactionPrivilege() { - return txPrivilege; - } - - public void setTransactionPrivilege(TransactionPrivilege txPrivilege) { - this.txPrivilege = txPrivilege; - } - - public static Privileges configure() { - return new Privileges(); - } - - public Privileges enable(LedgerPermission...ledgerPermissions) { - this.ledgerPrivilege.enable(ledgerPermissions); - return this; - } - - public Privileges disable(LedgerPermission...ledgerPermissions) { - this.ledgerPrivilege.disable(ledgerPermissions); - return this; - } - - public Privileges enable(TransactionPermission...transactionPermissions) { - this.txPrivilege.enable(transactionPermissions); - return this; - } - - public Privileges disable(TransactionPermission...transactionPermissions) { - this.txPrivilege.disable(transactionPermissions); - return this; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitData.java deleted file mode 100644 index 090b19f8..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitData.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContractRegistry; - -public class RoleInitData implements RoleInitSettings { - - static { - DataContractRegistry.register(RoleInitSettings.class); - } - - private String roleName; - - private LedgerPermission[] ledgerPermissions; - - private TransactionPermission[] transactionPermissions; - - public RoleInitData() { - } - - public RoleInitData(String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] transactionPermissions) { - this.roleName = roleName; - this.ledgerPermissions = ledgerPermissions; - this.transactionPermissions = transactionPermissions; - } - - @Override - public String getRoleName() { - return roleName; - } - - @Override - public LedgerPermission[] getLedgerPermissions() { - return ledgerPermissions; - } - - @Override - public TransactionPermission[] getTransactionPermissions() { - return transactionPermissions; - } - - public void setRoleName(String roleName) { - this.roleName = roleName; - } - - public void setLedgerPermissions(LedgerPermission[] ledgerPermissions) { - this.ledgerPermissions = ledgerPermissions; - } - - public void setTransactionPermissions(TransactionPermission[] transactionPermissions) { - this.transactionPermissions = transactionPermissions; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitSettings.java deleted file mode 100644 index 71c6965b..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitSettings.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -/** - * 角色参数设置; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.SECURITY_ROLE_INIT_SETTING) -public interface RoleInitSettings { - - /** - * 角色名称; - * - * @return - */ - @DataField(order = 0, primitiveType = PrimitiveType.TEXT) - String getRoleName(); - - /** - * 角色的账本权限; - * - * @return - */ - @DataField(order = 1, refEnum = true, list = true) - LedgerPermission[] getLedgerPermissions(); - - /** - * 角色的交易权限; - * - * @return - */ - @DataField(order = 2, refEnum = true, list = true) - TransactionPermission[] getTransactionPermissions(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivilegeSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivilegeSettings.java deleted file mode 100644 index cdaa99e8..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivilegeSettings.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.jd.blockchain.ledger; - -public interface RolePrivilegeSettings { - - /** - * 角色名称的最大 Unicode 字符数; - */ - public static final int MAX_ROLE_NAME_LENGTH = 20; - - /** - * 角色的数量; - * - * @return - */ - long getRoleCount(); - - /** - * 查询角色权限; - * - *
- * 如果不存在,则返回 null; - * - * @param address - * @return - */ - RolePrivileges getRolePrivilege(String roleName); - - /** - * 返回指定位置的角色权限; - * - * @param index - * @param count - * @return - */ - RolePrivileges[] getRolePrivileges(int index, int count); - - /** - * 返回所有的角色权限; - * - * @return - */ - RolePrivileges[] getRolePrivileges(); - - /** - * 是否只读; - * - * @return - */ - boolean isReadonly(); - - /** - * 加入新的角色权限;
- * - * 如果指定的角色已经存在,则引发 {@link LedgerException} 异常; - * - * @param roleName 角色名称;不能超过 {@link #MAX_ROLE_NAME_LENGTH} 个 Unicode 字符; - * @param ledgerPrivilege - * @param txPrivilege - */ - long addRolePrivilege(String roleName, Privileges privileges); - - /** - * 加入新的角色权限;
- * - * 如果指定的角色已经存在,则引发 {@link LedgerException} 异常; - * - * @param roleName 角色名称;不能超过 {@link #MAX_ROLE_NAME_LENGTH} 个 Unicode 字符; - * @param ledgerPrivilege - * @param txPrivilege - */ - long addRolePrivilege(String roleName, LedgerPrivilege ledgerPrivilege, TransactionPrivilege txPrivilege); - - /** - * 加入新的角色权限;
- * - * 如果指定的角色已经存在,则引发 {@link LedgerException} 异常; - * - * @param roleName 角色名称;不能超过 {@link #MAX_ROLE_NAME_LENGTH} 个 Unicode - * 字符; - * @param ledgerPermissions 给角色授予的账本权限列表; - * @param txPermissions 给角色授予的交易权限列表; - * @return - */ - long addRolePrivilege(String roleName, LedgerPermission[] ledgerPermissions, TransactionPermission[] txPermissions); - - /** - * 更新角色权限;
- * 如果指定的角色不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; - * - * @param participant - */ - void updateRolePrivilege(RolePrivileges roleAuth); - - /** - * 授权角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - long enablePermissions(String roleName, LedgerPermission... permissions); - - /** - * 授权角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - long enablePermissions(String roleName, TransactionPermission... permissions); - - /** - * 禁止角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - long disablePermissions(String roleName, LedgerPermission... permissions); - - /** - * 禁止角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName 角色; - * @param permissions 权限列表; - * @return - */ - long disablePermissions(String roleName, TransactionPermission... permissions); - - /** - * 授权角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName - * @param ledgerPermissions - * @param txPermissions - * @return - */ - long enablePermissions(String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] txPermissions); - - /** - * 禁用角色指定的权限;
- * 如果角色不存在,则返回 -1; - * - * @param roleName - * @param ledgerPermissions - * @param txPermissions - * @return - */ - long disablePermissions(String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] txPermissions); - - boolean contains(String r); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivileges.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivileges.java deleted file mode 100644 index 1b0b32ba..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivileges.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.ledger; - -/** - * 对角色的授权; - * - * @author huanghaiquan - * - */ -public class RolePrivileges extends Privileges { - - private String roleName; - - private long version; - - public RolePrivileges(String roleName, long version) { - this.roleName = roleName; - this.version = version; - } - - public RolePrivileges(String roleName, long version, PrivilegeSet privilege) { - super(privilege); - this.roleName = roleName; - this.version = version; - } - - public RolePrivileges(String roleName, long version, LedgerPrivilege ledgerPrivilege, - TransactionPrivilege txPrivilege) { - super(ledgerPrivilege, txPrivilege); - this.roleName = roleName; - this.version = version; - } - - public String getRoleName() { - return roleName; - } - - public long getVersion() { - return version; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleSet.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleSet.java deleted file mode 100644 index a026c23f..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleSet.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -/** - * 角色集; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.ROLE_SET) -public interface RoleSet { - - @DataField(order = 1, refEnum = true) - RolesPolicy getPolicy(); - - @DataField(order = 2, primitiveType = PrimitiveType.TEXT, list = true) - String[] getRoles(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesPolicy.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesPolicy.java deleted file mode 100644 index 690d0be5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesPolicy.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; - -/** - * 多角色策略;
- * - * 表示如何处理一个对象被赋予多个角色时的综合权限; - * - * @author huanghaiquan - * - */ -@EnumContract(code = DataCodes.ENUM_MULTI_ROLES_POLICY, name = "USER-ROLE-POLICY") -public enum RolesPolicy { - - /** - * 合并权限;
- * - * 综合权限是所有角色权限的并集,即任何一个角色的权限都被继承; - */ - UNION((byte) 0), - - /** - * 交叉权限;
- * - * 综合权限是所有角色权限的交集,即只有全部角色共同拥有的权限才会被继承; - */ - INTERSECT((byte) 1); - - @EnumField(type = PrimitiveType.INT8) - public final byte CODE; - - private RolesPolicy(byte code) { - this.CODE = code; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitData.java deleted file mode 100644 index 90f51869..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitData.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.util.LinkedHashMap; -import java.util.Map; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.utils.Bytes; - -public class SecurityInitData implements SecurityInitSettings { - - static { - DataContractRegistry.register(SecurityInitSettings.class); - } - - - private Map roles = new LinkedHashMap<>(); - - private Map userAuthentications = new LinkedHashMap<>(); - - @Override - public RoleInitData[] getRoles() { - return roles.values().toArray(new RoleInitData[roles.size()]); - } - - public int getRolesCount() { - return roles.size(); - } - - public void setRoles(RoleInitData[] roles) { - Map newRoles = new LinkedHashMap<>(); - for (RoleInitData r : roles) { - newRoles.put(r.getRoleName(), r); - } - this.roles = newRoles; - } - - public boolean containsRole(String roleName) { - return roles.containsKey(roleName); - } - - public void addRole(String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] transactionPermissions) { - RoleInitData roleInitData = new RoleInitData(roleName, ledgerPermissions, transactionPermissions); - roles.put(roleName, roleInitData); - } - - @Override - public UserAuthInitData[] getUserAuthorizations() { - return userAuthentications.values().toArray(new UserAuthInitData[userAuthentications.size()]); - } - - public void addUserAuthencation(Bytes address, String[] roles, RolesPolicy policy) { - UserAuthInitData userAuth = new UserAuthInitData(); - userAuth.setUserAddress(address); - userAuth.setRoles(roles); - userAuth.setPolicy(policy); - - userAuthentications.put(address, userAuth); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitSettings.java deleted file mode 100644 index 8ca64d79..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitSettings.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.consts.DataCodes; - -/** - * 安全权限的初始化; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.SECURITY_INIT_SETTING) -public interface SecurityInitSettings { - - /** - * 角色列表; - * - * @return - */ - @DataField(order = 0, refContract = true, list = true) - RoleInitSettings[] getRoles(); - - @DataField(order = 1, refContract = true, list = true) - UserAuthInitSettings[] getUserAuthorizations(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityUtils.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityUtils.java deleted file mode 100644 index b0175fc5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityUtils.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.ledger; - -public class SecurityUtils { - - public static final int MAX_ROLE_NAMES = 20; - - /** - * 校验角色名称的有效性,并格式化角色名称:去掉两端空白字符,统一为大写字符; - * - * @param roleName - * @return - */ - public static String formatRoleName(String roleName) { - if (roleName == null) { - throw new IllegalArgumentException("Role name is empty!"); - } - roleName = roleName.trim(); - if (roleName.length() > MAX_ROLE_NAMES) { - throw new IllegalArgumentException("Role name exceeds max length!"); - } - if (roleName.length() == 0) { - throw new IllegalArgumentException("Role name is empty!"); - } - - return roleName.toUpperCase(); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContent.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContent.java deleted file mode 100644 index 96cdf58b..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContent.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -/** - * 交易内容; - * - * @author huanghaiquan - * - */ -@DataContract(code= DataCodes.TX_CONTENT) -public interface TransactionContent extends TransactionContentBody, HashObject { - @Override - @DataField(order=1, primitiveType = PrimitiveType.BYTES) - HashDigest getHash(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContentBody.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContentBody.java deleted file mode 100644 index 0c227ab5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContentBody.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -/** - * 交易内容; - * - * @author huanghaiquan - * - */ -@DataContract(code = DataCodes.TX_CONTENT_BODY) -public interface TransactionContentBody { - - /** - * 执行交易的账本地址; - * - * 注:除了账本的创世交易之外,任何交易的账本地址都不允许为 null; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - HashDigest getLedgerHash(); - - /** - * 操作列表; - * - * @return - */ - @DataField(order = 2, list = true, refContract = true, genericContract = true) - Operation[] getOperations(); - - /** - * 生成交易的时间;
- * 以毫秒为单位,表示距离 1970-1-1 00:00:00 (UTC) 的毫秒数;
- * - * @return - */ - @DataField(order = 3, primitiveType = PrimitiveType.INT64) - long getTimestamp(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPermission.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPermission.java deleted file mode 100644 index e251fac4..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPermission.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Int8Code; - -/** - * TxPermission 交易权限表示一个用户可以发起的交易类型; - * - * @author huanghaiquan - * - */ -@EnumContract(code = DataCodes.ENUM_TX_PERMISSION) -public enum TransactionPermission implements Int8Code { - - /** - * 交易中包含指令操作; - */ - DIRECT_OPERATION((byte) 0x01), - - /** - * 交易中包含合约操作; - */ - CONTRACT_OPERATION((byte) 0x02); - - @EnumField(type = PrimitiveType.INT8) - public final byte CODE; - - private TransactionPermission(byte code) { - this.CODE = code; - } - - @Override - public byte getCode() { - return CODE; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPrivilege.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPrivilege.java deleted file mode 100644 index dddd76d6..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPrivilege.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ledger; - -public class TransactionPrivilege extends PrivilegeBitset { - - public TransactionPrivilege() { - } - - public TransactionPrivilege(byte[] codeBytes) { - super(codeBytes); - } - - @Override - public TransactionPrivilege clone() { - return (TransactionPrivilege) super.clone(); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequest.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequest.java deleted file mode 100644 index c2fc42e1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.HashDigest; - -/** - * 交易请求; - * - * @author huanghaiquan - * - */ -@DataContract(code= DataCodes.REQUEST) -public interface TransactionRequest extends NodeRequest, HashObject { - - /** - * 交易请求的 hash ;
- * - * @return - */ - @Override - @DataField(order=1, primitiveType = PrimitiveType.BYTES) - HashDigest getHash(); -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRespHandle.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRespHandle.java deleted file mode 100644 index 3856f668..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRespHandle.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.ledger.core.impl.TransactionRespHandle - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/11/13 下午10:57 - * Description: - */ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.crypto.HashDigest; - -/** - * - * @author shaozhuguang - * @create 2018/11/13 - * @since 1.0.0 - */ - -public class TransactionRespHandle implements TransactionResponse { - - private TransactionRequest request; - - private TransactionState result; - - private LedgerBlock block; - - private TransactionState globalResult; - - private OperationResult[] operationResults; - - public TransactionRespHandle(TransactionRequest request, TransactionState result, TransactionState globalResult) { - this.request = request; - this.result = result; - this.globalResult = globalResult; - } - - public TransactionRequest getRequest() { - return request; - } - - public void setRequest(TransactionRequest request) { - this.request = request; - } - - public TransactionState getResult() { - return result; - } - - public void setResult(TransactionState result) { - this.result = result; - } - - public void setOperationResults(OperationResult[] operationResults) { - this.operationResults = operationResults; - } - - public LedgerBlock getBlock() { - return block; - } - - public void setBlock(LedgerBlock block) { - this.block = block; - } - - public TransactionState getGlobalResult() { - return globalResult; - } - - public void setGlobalResult(TransactionState globalResult) { - this.globalResult = globalResult; - } - - @Override - public HashDigest getContentHash() { - return this.request.getTransactionContent().getHash(); - } - - @Override - public TransactionState getExecutionState() { - return this.result; - } - - @Override - public HashDigest getBlockHash() { - return this.block == null ? null : this.block.getHash(); - } - - @Override - public long getBlockHeight() { - return this.block == null ? -1 : this.block.getHeight(); - } - - @Override - public boolean isSuccess() { - return globalResult == null ? result == TransactionState.SUCCESS : globalResult == TransactionState.SUCCESS; - } - - @Override - public OperationResult[] getOperationResults() { - return operationResults; - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java deleted file mode 100644 index 57ddde05..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; -import com.jd.blockchain.consts.DataCodes; - -/** - * 交易(事务)执行状态; - * - * @author huanghaiquan - * - */ -@EnumContract(code = DataCodes.ENUM_TYPE_TRANSACTION_STATE) -public enum TransactionState { - - /** - * 成功; - */ - SUCCESS((byte) 0), - - /** - * 账本错误; - */ - LEDGER_ERROR((byte) 0x01), - - /** - * 数据账户不存在; - */ - DATA_ACCOUNT_DOES_NOT_EXIST((byte) 0x02), - - /** - * 用户不存在; - */ - USER_DOES_NOT_EXIST((byte) 0x03), - - /** - * 合约不存在; - */ - CONTRACT_DOES_NOT_EXIST((byte) 0x04), - - /** - * 数据写入时版本冲突; - */ - DATA_VERSION_CONFLICT((byte) 0x05), - - /** - * 参与方不存在; - */ - PARTICIPANT_DOES_NOT_EXIST((byte) 0x06), - - /** - * 被安全策略拒绝; - */ - REJECTED_BY_SECURITY_POLICY((byte) 0x10), - - /** - * 由于在错误的账本上执行交易而被丢弃; - */ - IGNORED_BY_WRONG_LEDGER((byte) 0x40), - - /** - * 由于交易内容的验签失败而丢弃; - */ - IGNORED_BY_WRONG_CONTENT_SIGNATURE((byte) 0x41), - - /** - * 由于交易内容的验签失败而丢弃; - */ - IGNORED_BY_CONFLICTING_STATE((byte) 0x42), - - /** - * 由于交易的整体回滚而丢弃; - *

- * - * 注: “整体回滚”是指把交易引入的数据更改以及交易记录本身全部都回滚;
- * “部分回滚”是指把交易引入的数据更改回滚了,但是交易记录本身以及相应的“交易结果({@link TransactionState})”都会提交;
- */ - IGNORED_BY_TX_FULL_ROLLBACK((byte) 0x43), - - /** - * 由于区块的整体回滚而丢弃; - *

- * - * 注: “整体回滚”是指把交易引入的数据更改以及交易记录本身全部都回滚;
- * - * “部分回滚”是指把交易引入的数据更改回滚了,但是交易记录本身以及相应的“交易结果({@link TransactionState})”都会提交;
- */ - IGNORED_BY_BLOCK_FULL_ROLLBACK((byte) 0x44), - - /** - * - * 共识阶段加入新区块哈希预计算功能, 如果来自其他Peer的新区块哈希值不一致,本批次整体回滚 - * - */ - IGNORED_BY_CONSENSUS_PHASE_PRECOMPUTE_ROLLBACK((byte) 0x45), - - /** - * 系统错误; - */ - SYSTEM_ERROR((byte) 0x80), - - /** - * 超时; - */ - TIMEOUT((byte) 0x81), - - /** - * 共识错误; - */ - CONSENSUS_ERROR((byte) 0x82); - - @EnumField(type = PrimitiveType.INT8) - public final byte CODE; - - private TransactionState(byte code) { - this.CODE = code; - } - - public static TransactionState valueOf(byte code) { - for (TransactionState tr : values()) { - if (tr.CODE == code) { - return tr; - } - } - throw new IllegalArgumentException("Unsupported transaction result code!"); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedKVData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedKVData.java deleted file mode 100644 index dd06de98..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedKVData.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jd.blockchain.ledger; - -/** - * 强类型的“键-值”数据对象; - * - *

- * - * {@link TypedKVData} 被设计为只读对象; - * - * @author huanghaiquan - * - */ -public class TypedKVData implements TypedKVEntry { - - private String key; - - private long version; - - private DataType type; - - private Object value; - - public TypedKVData(String key, long version, DataType type, Object value) { - this.key = key; - this.version = version; - this.type = type; - this.value = value; - } - - public TypedKVData(String key, long version, BytesValue bytesValue) { - this.key = key; - this.version = version; - TypedValue typedValue; - if (bytesValue != null && bytesValue instanceof TypedValue) { - typedValue = (TypedValue) bytesValue; - } else { - typedValue = TypedValue.wrap(bytesValue); - } - this.type = typedValue.getType(); - this.value = typedValue.getValue(); - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.KVDataEntry#getKey() - */ - @Override - public String getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.KVDataEntry#getVersion() - */ - @Override - public long getVersion() { - return version; - } - - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.KVDataEntry#getType() - */ - @Override - public DataType getType() { - return type; - } - - @Override - public Object getValue() { - return value; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedKVEntry.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedKVEntry.java deleted file mode 100644 index 54165c61..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedKVEntry.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jd.blockchain.ledger; - -public interface TypedKVEntry { - - /** - * 键名; - * - * @return - */ - String getKey(); - - /** - * 版本; - *

- * 有效的版本大于等于 0 ; - *

- * 如果返回 -1 ,则表示此项数据无效; - * - * @return - */ - long getVersion(); - - /** - * 数据类型; - * - * @return - */ - DataType getType(); - - /** - * 值; - * @return - */ - Object getValue(); - - default long longValue() { - if (getType() == DataType.INT64) { - Object value = getValue(); - return value == null ? 0 : (long) value; - } - throw new IllegalStateException(String.format("Expected type [%s], but [%s]", DataType.INT64, getType())); - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedValue.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedValue.java deleted file mode 100644 index 65dbd298..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedValue.java +++ /dev/null @@ -1,454 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.math.BigInteger; -import java.util.Date; - -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * - * @author huanghaiquan - * - */ -public class TypedValue implements BytesValue { - - public static final BytesValue NIL = new TypedValue(); - - private DataType type; - private Bytes value; - - private TypedValue(DataType type, byte[] bytes) { - this.type = type; - this.value = new Bytes(bytes); - } - - private TypedValue(DataType type, Bytes bytes) { - this.type = type; - this.value = bytes; - } - - private TypedValue(BytesValue bytesValue) { - if (bytesValue == null) { - this.type = DataType.NIL; - } else { - this.type = bytesValue.getType(); - this.value = bytesValue.getBytes(); - } - } - - private TypedValue() { - this.type = DataType.NIL; - } - - @Override - public DataType getType() { - return this.type; - } - - @Override - public Bytes getBytes() { - return this.value; - } - - public Object getValue() { - if (isNil()) { - return null; - } - switch (type) { - case BOOLEAN: - return toBoolean(); - case INT8: - return toInt8(); - case INT16: - return toInt16(); - case INT32: - return toInt32(); - case INT64: - return toInt64(); - case BIG_INT: - return toBigInteger(); - case TIMESTAMP: - return toDatetime(); - case TEXT: - case JSON: - case XML: - return toText(); - - case BYTES: - case VIDEO: - case IMG: - case LOCATION: - case ENCRYPTED_DATA: - return toBytesArray(); - - case HASH_DIGEST: - return toHashDegist(); - case PUB_KEY: - return toPubKey(); - case SIGNATURE_DIGEST: - return toSignatureDigest(); - - case DATA_CONTRACT: - return toBytesArray(); - default: - throw new IllegalStateException(String.format("Type [%s] has not be supported!", type)); - } - } - - /** - * 是否为空值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#NIL} 时返回 true,其它情况返回 false; - *

- * - * @return - */ - public boolean isNil() { - return value == null || DataType.NIL == type; - } - - /** - * 返回 8 位整数值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT8} 有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public byte tinyValue() { - if (isNil()) { - return DataType.INT8_DEFAULT_VALUE; - } - if (DataType.INT8 == getType()) { - return toInt8(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int8!", type)); - } - - private byte toInt8() { - return value.toBytes()[0]; - } - - /** - * 返回 16 位整数值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT16} 有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public short shortValue() { - if (isNil()) { - return DataType.INT16_DEFAULT_VALUE; - } - if (DataType.INT16 == getType()) { - return toInt16(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int16!", type)); - } - - private short toInt16() { - return BytesUtils.toShort(value.toBytes(), 0); - } - - /** - * 返回 32 位整数值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT32} 有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public int intValue() { - if (isNil()) { - return DataType.INT32_DEFAULT_VALUE; - } - if (DataType.INT32 == getType()) { - return toInt32(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int32!", type)); - } - - private int toInt32() { - return BytesUtils.toInt(value.toBytes(), 0); - } - - /** - * 返回 64 位整数值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT64} 有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public long longValue() { - if (isNil()) { - return DataType.INT64_DEFAULT_VALUE; - } - if (DataType.INT64 == type) { - return toInt64(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int64!", type)); - - } - - private long toInt64() { - return BytesUtils.toLong(value.toBytes(), 0); - } - - /** - * 返回大整数值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#BIG_INT} 有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public BigInteger bigIntValue() { - if (isNil()) { - return null; - } - if (DataType.BIG_INT == type) { - return toBigInteger(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to BigInteger!", type)); - } - - private BigInteger toBigInteger() { - return new BigInteger(value.toBytes()); - } - - /** - * 返回布尔值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#BIG_INT} 有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public boolean boolValue() { - if (isNil()) { - return DataType.BOOLEAN_DEFAULT_VALUE; - } - if (DataType.BOOLEAN == type) { - return toBoolean(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to boolean!", type)); - } - - private boolean toBoolean() { - return BytesUtils.toBoolean(value.toBytes()[0]); - } - - /** - * 返回日期时间值; - *

- * - * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#TIMESTAMP} 有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public Date datetimeValue() { - if (isNil()) { - return null; - } - if (DataType.TIMESTAMP == type) { - return toDatetime(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to datetime!", type)); - } - - private Date toDatetime() { - long ts = BytesUtils.toLong(value.toBytes()); - return new Date(ts); - } - - /** - * 返回文本值; - *

- * - * 仅当数据类型 {@link #getType()} 为“文本类型”或“文本衍生类型”时有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public String stringValue() { - if (isNil()) { - return null; - } - if (type.isText()) { - return toText(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to text!", type)); - } - - private String toText() { - return value.toUTF8String(); - } - - /** - * 返回字节数组的值; - *

- * - * 仅当数据类型 {@link #getType()} 为“字节类型”或“字节衍生类型”时有效; - *

- * - * 无效类型将引发 {@link IllegalStateException} 异常; - * - * @return - */ - public byte[] bytesValue() { - if (isNil()) { - return null; - } - if (type.isBytes()) { - return toBytesArray(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to bytes!", type)); - } - - private byte[] toBytesArray() { - return value.toBytes(); - } - - public HashDigest hashDigestValue() { - if (isNil()) { - return null; - } - if (DataType.HASH_DIGEST == type) { - return toHashDegist(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to hash digest!", type)); - } - - private HashDigest toHashDegist() { - return new HashDigest(toBytesArray()); - } - - public PubKey pubKeyValue() { - if (isNil()) { - return null; - } - if (DataType.PUB_KEY == type) { - return toPubKey(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to pub key!", type)); - } - - private PubKey toPubKey() { - return new PubKey(toBytesArray()); - } - - public SignatureDigest signatureDigestValue() { - if (isNil()) { - return null; - } - if (DataType.SIGNATURE_DIGEST == type) { - return toSignatureDigest(); - } - throw new IllegalStateException(String.format("Type [%s] cannot be convert to signature digest!", type)); - } - - private SignatureDigest toSignatureDigest() { - return new SignatureDigest(toBytesArray()); - } - - public static TypedValue wrap(BytesValue value) { - return new TypedValue(value); - } - - public static TypedValue fromType(DataType type, byte[] value) { - return new TypedValue(type, value); - } - - public static TypedValue fromBytes(byte[] value) { - return new TypedValue(DataType.BYTES, value); - } - - public static TypedValue fromBytes(Bytes value) { - return new TypedValue(DataType.BYTES, value); - } - - public static TypedValue fromImage(byte[] value) { - return new TypedValue(DataType.IMG, value); - } - - public static TypedValue fromImage(Bytes value) { - return new TypedValue(DataType.IMG, value); - } - - /** - * 以 UTF-8 编码从字符串转换为字节数组值; - * - * @param value - * @return - */ - public static TypedValue fromText(String value) { - return new TypedValue(DataType.TEXT, BytesUtils.toBytes(value)); - } - - public static TypedValue fromJSON(String value) { - return new TypedValue(DataType.JSON, BytesUtils.toBytes(value)); - } - - public static TypedValue fromXML(String value) { - return new TypedValue(DataType.XML, BytesUtils.toBytes(value)); - } - - public static TypedValue fromInt32(int value) { - return new TypedValue(DataType.INT32, BytesUtils.toBytes(value)); - } - - public static TypedValue fromInt64(long value) { - return new TypedValue(DataType.INT64, BytesUtils.toBytes(value)); - } - - public static TypedValue fromInt16(short value) { - return new TypedValue(DataType.INT16, BytesUtils.toBytes(value)); - } - - public static TypedValue fromInt8(byte value) { - return new TypedValue(DataType.INT8, BytesUtils.toBytes(value)); - } - - public static TypedValue fromTimestamp(long value) { - return new TypedValue(DataType.TIMESTAMP, BytesUtils.toBytes(value)); - } - - public static TypedValue fromBoolean(boolean value) { - return new TypedValue(DataType.BOOLEAN, BytesUtils.toBytes(value)); - } - - public static TypedValue fromPubKey(PubKey pubKey) { - return new TypedValue(DataType.PUB_KEY, pubKey.toBytes()); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedValue_.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedValue_.java deleted file mode 100644 index 145344b5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TypedValue_.java +++ /dev/null @@ -1,472 +0,0 @@ -//package com.jd.blockchain.ledger; -// -//import java.math.BigInteger; -//import java.util.Date; -// -//import com.jd.blockchain.binaryproto.PrimitiveType; -//import com.jd.blockchain.crypto.HashDigest; -//import com.jd.blockchain.crypto.PubKey; -//import com.jd.blockchain.crypto.SignatureDigest; -//import com.jd.blockchain.utils.Bytes; -//import com.jd.blockchain.utils.io.BytesUtils; -// -//public class TypedValue_ { -// -// private BytesValue bytesValue; -// -// public TypedValue_(BytesValue bytesValue) { -// this.bytesValue = bytesValue; -// } -// -// public DataType getType() { -// return bytesValue == null ? DataType.NIL : bytesValue.getType(); -// } -// -// public Object getValue() { -// if (isNil()) { -// return null; -// } -// switch (bytesValue.getType()) { -// case BOOLEAN: -// return toBoolean(); -// case INT8: -// return toInt8(); -// case INT16: -// return toInt16(); -// case INT32: -// return toInt32(); -// case INT64: -// return toInt64(); -// case BIG_INT: -// return toBigInteger(); -// case TIMESTAMP: -// return toDatetime(); -// case TEXT: -// case JSON: -// case XML: -// return toText(); -// -// case BYTES: -// case VIDEO: -// case IMG: -// case LOCATION: -// case ENCRYPTED_DATA: -// return toBytesArray(); -// -// case HASH_DIGEST: -// return toHashDegist(); -// case PUB_KEY: -// return toPubKey(); -// case SIGNATURE_DIGEST: -// return toSignatureDigest(); -// -// case DATA_CONTRACT: -// return toBytesArray(); -// default: -// throw new IllegalStateException(String.format("Type [%s] has not be supported!", bytesValue.getType())); -// } -// } -// -// /** -// * 是否为空值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#NIL} 时返回 true,其它情况返回 false; -// *

-// * -// * @return -// */ -// public boolean isNil() { -// return bytesValue == null || DataType.NIL == bytesValue.getType(); -// } -// -// /** -// * 返回 8 位整数值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT8} 有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public byte tinyValue() { -// if (isNil()) { -// return DataType.INT8_DEFAULT_VALUE; -// } -// if (DataType.INT8 == getType()) { -// return toInt8(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int8!", bytesValue.getType())); -// } -// -// private byte toInt8() { -// return bytesValue.getValue().toBytes()[0]; -// } -// -// /** -// * 返回 16 位整数值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT16} 有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public short shortValue() { -// if (isNil()) { -// return DataType.INT16_DEFAULT_VALUE; -// } -// if (DataType.INT16 == getType()) { -// return toInt16(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int16!", bytesValue.getType())); -// } -// -// private short toInt16() { -// return BytesUtils.toShort(bytesValue.getValue().toBytes(), 0); -// } -// -// /** -// * 返回 32 位整数值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT32} 有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public int intValue() { -// if (isNil()) { -// return DataType.INT32_DEFAULT_VALUE; -// } -// if (DataType.INT32 == getType()) { -// return toInt32(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int32!", bytesValue.getType())); -// } -// -// private int toInt32() { -// return BytesUtils.toInt(bytesValue.getValue().toBytes(), 0); -// } -// -// /** -// * 返回 64 位整数值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#INT64} 有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public long longValue() { -// if (isNil()) { -// return DataType.INT64_DEFAULT_VALUE; -// } -// if (DataType.INT64 == bytesValue.getType()) { -// return toInt64(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to Int64!", bytesValue.getType())); -// -// } -// -// private long toInt64() { -// return BytesUtils.toLong(bytesValue.getValue().toBytes(), 0); -// } -// -// /** -// * 返回大整数值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#BIG_INT} 有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public BigInteger bigIntValue() { -// if (isNil()) { -// return null; -// } -// if (DataType.BIG_INT == bytesValue.getType()) { -// return toBigInteger(); -// } -// throw new IllegalStateException( -// String.format("Type [%s] cannot be convert to BigInteger!", bytesValue.getType())); -// } -// -// private BigInteger toBigInteger() { -// return new BigInteger(bytesValue.getValue().toBytes()); -// } -// -// /** -// * 返回布尔值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#BIG_INT} 有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public boolean boolValue() { -// if (isNil()) { -// return DataType.BOOLEAN_DEFAULT_VALUE; -// } -// if (DataType.BOOLEAN == bytesValue.getType()) { -// return toBoolean(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to boolean!", bytesValue.getType())); -// } -// -// private boolean toBoolean() { -// return BytesUtils.toBoolean(bytesValue.getValue().toBytes()[0]); -// } -// -// /** -// * 返回日期时间值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为 {@link PrimitiveType#TIMESTAMP} 有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public Date datetimeValue() { -// if (isNil()) { -// return null; -// } -// if (DataType.TIMESTAMP == bytesValue.getType()) { -// return toDatetime(); -// } -// throw new IllegalStateException( -// String.format("Type [%s] cannot be convert to datetime!", bytesValue.getType())); -// } -// -// private Date toDatetime() { -// long ts = BytesUtils.toLong(bytesValue.getValue().toBytes()); -// return new Date(ts); -// } -// -// /** -// * 返回文本值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为“文本类型”或“文本衍生类型”时有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public String stringValue() { -// if (isNil()) { -// return null; -// } -// DataType type = bytesValue.getType(); -// if (type.isText()) { -// return toText(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to text!", type)); -// } -// -// private String toText() { -// return bytesValue.getValue().toUTF8String(); -// } -// -// /** -// * 返回字节数组的值; -// *

-// * -// * 仅当数据类型 {@link #getType()} 为“字节类型”或“字节衍生类型”时有效; -// *

-// * -// * 无效类型将引发 {@link IllegalStateException} 异常; -// * -// * @return -// */ -// public byte[] bytesValue() { -// if (isNil()) { -// return null; -// } -// DataType type = bytesValue.getType(); -// if (type.isBytes()) { -// return toBytesArray(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to bytes!", type)); -// } -// -// private byte[] toBytesArray() { -// return bytesValue.getValue().toBytes(); -// } -// -// public HashDigest hashDigestValue() { -// if (isNil()) { -// return null; -// } -// if (DataType.HASH_DIGEST == bytesValue.getType()) { -// return toHashDegist(); -// } -// throw new IllegalStateException( -// String.format("Type [%s] cannot be convert to hash digest!", bytesValue.getType())); -// } -// -// private HashDigest toHashDegist() { -// return new HashDigest(toBytesArray()); -// } -// -// public PubKey pubKeyValue() { -// if (isNil()) { -// return null; -// } -// if (DataType.PUB_KEY == bytesValue.getType()) { -// return toPubKey(); -// } -// throw new IllegalStateException(String.format("Type [%s] cannot be convert to pub key!", bytesValue.getType())); -// } -// -// private PubKey toPubKey() { -// return new PubKey(toBytesArray()); -// } -// -// public SignatureDigest signatureDigestValue() { -// if (isNil()) { -// return null; -// } -// if (DataType.SIGNATURE_DIGEST == bytesValue.getType()) { -// return toSignatureDigest(); -// } -// throw new IllegalStateException( -// String.format("Type [%s] cannot be convert to signature digest!", bytesValue.getType())); -// } -// -// private SignatureDigest toSignatureDigest() { -// return new SignatureDigest(toBytesArray()); -// } -// -// public BytesValue convertToBytesValue() { -// return bytesValue == null ? TypedBytesValue.NIL : bytesValue; -// } -// -// public static TypedBytesValue fromText(String key, String value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromText(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromBoolean(String key, boolean value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromBoolean(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt8(String key, byte value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt8(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt16(String key, short value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt16(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt32(String key, int value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt32(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt64(String key, long value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt64(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromBytes(String key, byte[] value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromBytes(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromTimestamp(String key, long value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromTimestamp(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromJSON(String key, String value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromJSON(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromXML(String key, String value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromXML(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromImage(String key, byte[] value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromImage(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromText(Bytes key, String value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromText(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromBoolean(Bytes key, boolean value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromBoolean(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt8(Bytes key, byte value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt8(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt16(Bytes key, short value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt16(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt32(Bytes key, int value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt32(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromInt64(Bytes key, long value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromInt64(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromBytes(Bytes key, byte[] value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromBytes(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromTimestamp(Bytes key, long value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromTimestamp(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromJSON(Bytes key, String value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromJSON(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromXML(Bytes key, String value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromXML(value); -// return new TypedBytesValue(bytesValue); -// } -// -// public static TypedBytesValue fromImage(Bytes key, byte[] value, long version) { -// BytesValue bytesValue = TypedBytesValue.fromImage(value); -// return new TypedBytesValue(bytesValue); -// } -// -//} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAccountHeader.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAccountHeader.java deleted file mode 100644 index 8fc0e7a5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAccountHeader.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.crypto.PubKey; - -@DataContract(code= DataCodes.USER_ACCOUNT_HEADER) -public interface UserAccountHeader extends BlockchainIdentity { - - PubKey getDataPubKey(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitData.java deleted file mode 100644 index 81dd5587..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitData.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.utils.Bytes; - -public class UserAuthInitData implements UserAuthInitSettings { - - static { - DataContractRegistry.register(UserAuthInitSettings.class); - } - - private Bytes userAddress; - - private String[] roles; - - private RolesPolicy policy; - - public void setUserAddress(Bytes userAddress) { - this.userAddress = userAddress; - } - - public void setRoles(String[] roles) { - this.roles = roles; - } - - public void setPolicy(RolesPolicy policy) { - this.policy = policy; - } - - @Override - public Bytes getUserAddress() { - return userAddress; - } - - @Override - public String[] getRoles() { - return roles; - } - - @Override - public RolesPolicy getPolicy() { - return policy; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitSettings.java deleted file mode 100644 index 31a6033a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitSettings.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.binaryproto.PrimitiveType; -import com.jd.blockchain.consts.DataCodes; -import com.jd.blockchain.utils.Bytes; - -@DataContract(code = DataCodes.SECURITY_USER_AUTH_INIT_SETTING) -public interface UserAuthInitSettings { - - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - Bytes getUserAddress(); - - @DataField(order = 2, primitiveType = PrimitiveType.TEXT, list = true) - String[] getRoles(); - - @DataField(order = 3, refEnum = true) - RolesPolicy getPolicy(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizationSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizationSettings.java deleted file mode 100644 index 95e8755e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizationSettings.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.util.Collection; - -import com.jd.blockchain.utils.Bytes; - -public interface UserAuthorizationSettings { - - /** - * 单一用户可被授权的角色数量的最大值; - */ - public static final int MAX_ROLES_PER_USER = 20; - - /** - * 进行了授权的用户的数量; - * - * @return - */ - long getUserCount(); - - /** - * 查询角色授权; - * - *
- * 如果不存在,则返回 null; - * - * @param address - * @return - */ - UserRoles getUserRoles(Bytes userAddress); - - /** - * 返回全部的用户授权; - * - * @return - */ - UserRoles[] getUserRoles(); - - /** - * 是否只读; - * - * @return - */ - boolean isReadonly(); - - /** - * 加入新的用户角色授权;
- * - * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; - * - * @param userAddress - * @param rolesPolicy - * @param roles - */ - void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, String... roles); - - /** - * 加入新的用户角色授权;
- * - * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; - * - * @param userAddress - * @param rolesPolicy - * @param roles - */ - void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, Collection roles); - - /** - * 更新用户角色授权;
- * 如果指定用户的授权不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; - * - * @param userRoles - */ - void updateUserRoles(UserRoles userRoles); - - /** - * 设置用户的角色;
- * 如果用户的角色授权不存在,则创建新的授权; - * - * @param userAddress 用户; - * @param policy 角色策略; - * @param roles 角色列表; - * @return - */ - long setRoles(Bytes userAddress, RolesPolicy policy, String... roles); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserDoesNotExistException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserDoesNotExistException.java deleted file mode 100644 index 1775405f..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserDoesNotExistException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ledger; - -public class UserDoesNotExistException extends LedgerException { - - private static final long serialVersionUID = 397450363050148898L; - - public UserDoesNotExistException(String message) { - super(message); - } - - public UserDoesNotExistException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfo.java deleted file mode 100644 index c7b14d1a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.ledger; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.consts.DataCodes; - -@DataContract(code = DataCodes.USER_INFO) -public interface UserInfo extends UserAccountHeader { - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRoles.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRoles.java deleted file mode 100644 index 19f86ed8..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRoles.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.jd.blockchain.ledger; - -import java.util.Collection; -import java.util.Collections; -import java.util.Set; -import java.util.TreeSet; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.utils.Bytes; - -public class UserRoles implements RoleSet { - - static { - DataContractRegistry.register(RoleSet.class); - } - - private Bytes userAddress; - - private RolesPolicy policy; - - private Set roles; - - private long version; - - public UserRoles(Bytes userAddress, long version, RolesPolicy policy) { - this.userAddress = userAddress; - this.version = version; - this.policy = policy; - this.roles = new TreeSet(); - } - - public UserRoles(Bytes userAddress, long version, RoleSet roleSet) { - this.userAddress = userAddress; - this.version = version; - this.policy = roleSet.getPolicy(); - this.roles = initRoles(roleSet.getRoles()); - - } - - private Set initRoles(String[] roles) { - TreeSet roleset = new TreeSet(); - if (roles != null) { - for (String r : roles) { - roleset.add(r); - } - } - return roleset; - } - - public Bytes getUserAddress() { - return userAddress; - } - - @Override - public RolesPolicy getPolicy() { - return policy; - } - - public void setPolicy(RolesPolicy policy) { - this.policy = policy; - } - - public int getRoleCount() { - return roles.size(); - } - - @Override - public String[] getRoles() { - return roles.toArray(new String[roles.size()]); - } - - public Set getRoleSet(){ - return Collections.unmodifiableSet(roles); - } - - public long getVersion() { - return version; - } - - public void addRoles(String... roles) { - for (String r : roles) { - this.roles.add(r); - } - } - - public void addRoles(Collection roles) { - for (String r : roles) { - this.roles.add(r); - } - } - - public void removeRoles(String... roles) { - for (String r : roles) { - this.roles.remove(r); - } - } - - public void removeRoles(Collection roles) { - for (String r : roles) { - this.roles.remove(r); - } - } - - /** - * 设置角色集合;
- * 注意,这不是追加;现有的不在参数指定范围的角色将被移除; - * - * @param roles - */ - public void setRoles(String[] roles) { - TreeSet rs = new TreeSet(); - for (String r : roles) { - rs.add(r); - } - this.roles = rs; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ValueTypeCastException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ValueTypeCastException.java deleted file mode 100644 index 30da88cb..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ValueTypeCastException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ledger; - -public class ValueTypeCastException extends LedgerException { - - - private static final long serialVersionUID = 6641080037721006099L; - - - public ValueTypeCastException(String message) { - super(message); - } - - public ValueTypeCastException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/AbstractBytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/AbstractBytesValueResolver.java deleted file mode 100644 index d6ee0b98..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/AbstractBytesValueResolver.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; - -public abstract class AbstractBytesValueResolver implements BytesValueResolver { - - protected boolean isSupport(Class type) { - if (type == null) { - return false; - } - Class[] supports = supportClasses(); - if (supports != null && supports.length > 0) { - for (Class clazz : supports) { - if (type.equals(clazz)) { - return true; - } - } - } - return false; - } - - protected boolean isSupport(DataType dataType) { - if (dataType == null) { - return false; - } - DataType[] supports = supportDataTypes(); - if (supports != null && supports.length > 0) { - for (DataType dt : supports) { - if (dataType.equals(dt)) { - return true; - } - } - } - return false; - } - - @Override - public BytesValue encode(Object value) { - return encode(value, value.getClass()); - } - - @Override - public Object decode(BytesValue value) { - DataType dataType = value.getType(); - if (!isSupport(dataType)) { - throw new IllegalStateException(String.format("Un-support encode DataType[%s] Object !!!", dataType.name())); - } - return decode(value.getBytes()); - } - - protected abstract Object decode(Bytes value); -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BooleanToBytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BooleanToBytesValueResolver.java deleted file mode 100644 index 69285395..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BooleanToBytesValueResolver.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; - -import java.util.Set; - -public class BooleanToBytesValueResolver extends AbstractBytesValueResolver { - - private final Class[] supportClasses = { Boolean.class, boolean.class }; - - private final DataType[] supportDataTypes = { DataType.BOOLEAN }; - - private final Set> convertClasses = initBooleanConvertSet(); - - @Override - public BytesValue encode(Object value, Class type) { - if (!isSupport(type)) { - throw new IllegalStateException(String.format("Un-support encode Class[%s] Object !!!", type.getName())); - } - return TypedValue.fromBoolean((boolean) value); - } - - @Override - public Class[] supportClasses() { - return supportClasses; - } - - @Override - public DataType[] supportDataTypes() { - return supportDataTypes; - } - - @Override - protected Object decode(Bytes value) { - return BytesUtils.toInt(value.toBytes()); - } - - @Override - public Object decode(BytesValue value, Class clazz) { - // 支持转换为short、int、long - int intVal = (int) decode(value); - if (convertClasses.contains(clazz)) { - // 对于short和Short需要强制类型转换 - if (clazz.equals(short.class) || clazz.equals(Short.class)) { - return (short) intVal; - } else if (clazz.equals(long.class) || clazz.equals(Long.class)) { - return (long) intVal; - } - return intVal; - } else { - throw new IllegalStateException(String.format("Un-Support decode value to class[%s] !!!", clazz.getName())); - } - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BytesToBytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BytesToBytesValueResolver.java deleted file mode 100644 index fe71eee7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BytesToBytesValueResolver.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; - -import java.util.Set; - -public class BytesToBytesValueResolver extends AbstractBytesValueResolver { - - private final Class[] supportClasses = {Bytes.class, byte[].class}; - - private final DataType[] supportDataTypes = {DataType.BYTES}; - - private final Set> convertClasses = initByteConvertSet(); - - @Override - public BytesValue encode(Object value, Class type) { - if (!isSupport(type)) { - throw new IllegalStateException(String.format("Un-support encode Class[%s] Object !!!", type.getName())); - } - if (type.equals(byte[].class)) { - return TypedValue.fromBytes((byte[]) value); - } - return TypedValue.fromBytes((Bytes) value); - } - - @Override - public Class[] supportClasses() { - return supportClasses; - } - - @Override - public DataType[] supportDataTypes() { - return supportDataTypes; - } - - @Override - protected Object decode(Bytes value) { - return value; - } - - @Override - public Object decode(BytesValue value, Class clazz) { - Bytes bytesVal = (Bytes) decode(value); - if (!convertClasses.contains(clazz)) { - throw new IllegalStateException(String.format("Un-Support decode value to class[%s] !!!", clazz.getName())); - } - - if (clazz.equals(String.class)) { - return bytesVal.toUTF8String(); - } else if (clazz.equals(byte[].class)) { - return bytesVal.toBytes(); - } - return bytesVal; - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BytesValueResolver.java deleted file mode 100644 index 4c659567..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/BytesValueResolver.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public interface BytesValueResolver { - - /** - * Boolean相关的可转换Class集合 - */ - Class[] supportBooleanConvertClasses = { boolean.class, Boolean.class }; - - /** - * Int相关的可转换Class集合 - */ - Class[] supportIntConvertClasses = { short.class, Short.class, int.class, Integer.class, long.class, - Long.class }; - - /** - * 字节数组(字符串)相关可转换的Class集合 - */ - Class[] supportByteConvertClasses = { String.class, Bytes.class, byte[].class }; - - default Set> initBooleanConvertSet() { - return new HashSet<>(Arrays.asList(supportBooleanConvertClasses)); - } - - default Set> initIntConvertSet() { - return new HashSet<>(Arrays.asList(supportIntConvertClasses)); - } - - default Set> initByteConvertSet() { - return new HashSet<>(Arrays.asList(supportByteConvertClasses)); - } - - /** - * 将对象转换为BytesValue - * - * @param value - * @return - */ - BytesValue encode(Object value); - - /** - * 将对象转换为BytesValue - * - * @param value - * @param type - * @return - */ - BytesValue encode(Object value, Class type); - - /** - * 当前解析器支持的Class列表 - * - * @return - */ - Class[] supportClasses(); - - /** - * 当前解析器支持的DataType列表 - * - * @return - */ - DataType[] supportDataTypes(); - - /** - * 将BytesValue解析为对应的Object - * - * @param value - * @return - */ - Object decode(BytesValue value); - - /** - * 将BytesValue转换为指定Class的Object - * - * @param value - * @param clazz - * @return - */ - Object decode(BytesValue value, Class clazz); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/IntegerToBytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/IntegerToBytesValueResolver.java deleted file mode 100644 index 075d1f76..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/IntegerToBytesValueResolver.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; - -import java.util.Set; - -public class IntegerToBytesValueResolver extends AbstractBytesValueResolver { - - private final Class[] supportClasses = {Integer.class, int.class}; - - private final DataType[] supportDataTypes = {DataType.INT32}; - - private final Set> convertClasses = initIntConvertSet(); - - @Override - public BytesValue encode(Object value, Class type) { - if (!isSupport(type)) { - throw new IllegalStateException(String.format("Un-support encode Class[%s] Object !!!", type.getName())); - } - return TypedValue.fromInt32((int) value); - } - - @Override - public Class[] supportClasses() { - return supportClasses; - } - - @Override - public DataType[] supportDataTypes() { - return supportDataTypes; - } - - @Override - protected Object decode(Bytes value) { - return BytesUtils.toInt(value.toBytes()); - } - - @Override - public Object decode(BytesValue value, Class clazz) { - // 支持转换为short、int、long - int intVal = (int)decode(value); - if (convertClasses.contains(clazz)) { - // 对于short和Short需要强制类型转换 - if (clazz.equals(short.class) || clazz.equals(Short.class)) { - return (short) intVal; - } else if (clazz.equals(long.class) || clazz.equals(Long.class)) { - return (long) intVal; - } - return intVal; - } else { - throw new IllegalStateException(String.format("Un-Support decode value to class[%s] !!!", clazz.getName())); - } - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/LongToBytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/LongToBytesValueResolver.java deleted file mode 100644 index ce6dbaf9..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/LongToBytesValueResolver.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; - -import java.util.Set; - -public class LongToBytesValueResolver extends AbstractBytesValueResolver { - - private final Class[] supportClasses = {Long.class, long.class}; - - private final DataType[] supportDataTypes = {DataType.INT64}; - - private final Set> convertClasses = initIntConvertSet(); - - @Override - public BytesValue encode(Object value, Class type) { - if (!isSupport(type)) { - throw new IllegalStateException(String.format("Un-support encode Class[%s] Object !!!", type.getName())); - } - return TypedValue.fromInt64((long)value); - } - - @Override - public Class[] supportClasses() { - return supportClasses; - } - - @Override - public DataType[] supportDataTypes() { - return supportDataTypes; - } - - @Override - protected Object decode(Bytes value) { - return BytesUtils.toLong(value.toBytes()); - } - - @Override - public Object decode(BytesValue value, Class clazz) { - // 支持转换为short、int、long - long longVal = (long)decode(value); - if (convertClasses.contains(clazz)) { - // 对于short和Short需要强制类型转换 - if (clazz.equals(short.class) || clazz.equals(Short.class)) { - return (short) longVal; - } else if (clazz.equals(int.class) || clazz.equals(Integer.class)) { - return (int) longVal; - } - return longVal; - } else { - throw new IllegalStateException(String.format("Un-Support decode value to class[%s] !!!", clazz.getName())); - } - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/ShortToBytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/ShortToBytesValueResolver.java deleted file mode 100644 index ddbed5fb..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/ShortToBytesValueResolver.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; - -import java.util.Set; - -public class ShortToBytesValueResolver extends AbstractBytesValueResolver { - - private final Class[] supportClasses = {Short.class, short.class}; - - private final DataType[] supportDataTypes = {DataType.INT16}; - - private final Set> convertClasses = initIntConvertSet(); - - @Override - public BytesValue encode(Object value, Class type) { - if (!isSupport(type)) { - throw new IllegalStateException(String.format("Un-support encode Class[%s] Object !!!", type.getName())); - } - return TypedValue.fromInt16((short)value); - } - - @Override - public Class[] supportClasses() { - return supportClasses; - } - - @Override - public DataType[] supportDataTypes() { - return supportDataTypes; - } - - @Override - protected Object decode(Bytes value) { - return BytesUtils.toShort(value.toBytes()); - } - - @Override - public Object decode(BytesValue value, Class clazz) { - // 支持转换为short、int、long,由short转int、long无需转换 - short shortVal = (short)decode(value); - if (convertClasses.contains(clazz)) { - if (clazz.equals(int.class) || clazz.equals(Integer.class)) { - return (int) shortVal; - } else if (clazz.equals(long.class) || clazz.equals(Long.class)) { - return (long) shortVal; - } - return shortVal; - } else { - throw new IllegalStateException(String.format("Un-Support decode value to class[%s] !!!", clazz.getName())); - } - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/StringToBytesValueResolver.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/StringToBytesValueResolver.java deleted file mode 100644 index 0f08442e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/resolver/StringToBytesValueResolver.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jd.blockchain.ledger.resolver; - -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; - -import java.util.Set; - - -public class StringToBytesValueResolver extends AbstractBytesValueResolver { - - private final Class[] supportClasses = {String.class}; - - private final DataType[] supportDataTypes = {DataType.TEXT, DataType.XML, DataType.JSON}; - - private final Set> convertClasses = initByteConvertSet(); - - @Override - public BytesValue encode(Object value, Class type) { - if (!isSupport(type)) { - throw new IllegalStateException(String.format("Un-support encode Class[%s] Object !!!", type.getName())); - } - // 类型判断 - String valString = (String)value; - if (JSONSerializeUtils.isJSON(valString)) { - return TypedValue.fromJSON(valString); - } - // 暂不处理XML格式 - return TypedValue.fromText(valString); - } - - @Override - public Class[] supportClasses() { - return supportClasses; - } - - @Override - public DataType[] supportDataTypes() { - return supportDataTypes; - } - - @Override - protected Object decode(Bytes value) { - return BytesUtils.toString(value.toBytes()); - } - - @Override - public Object decode(BytesValue value, Class clazz) { - // 支持三种类型对象返回,String.class,byte[].class,Bytes.class - String textValue = (String)decode(value); - - if (!convertClasses.contains(clazz)) { - throw new IllegalStateException(String.format("Un-Support decode value to class[%s] !!!", clazz.getName())); - } - - if (clazz.equals(byte[].class)) { - return BytesUtils.toBytes(textValue); - } else if (clazz.equals(Bytes.class)) { - return Bytes.fromString(textValue); - } - return textValue; - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchProcess.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchProcess.java deleted file mode 100644 index 9ac5c78e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchProcess.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.service; - -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionState; - -public interface TransactionBatchProcess { - - /** - * 安排执行指定的交易请求; - * - *

- * - * 注意:此方法并不表示此交易请求立即得到完整执行,并理解获得最终有效的结果; - * - * 方法返回的 {@link TransactionResponse} 只是一个代理对象,其最终的值需要在整个批处理结果被成功地提交或者取消后才能确定。 - * - * @param request - * 交易请求; - * @return 交易执行回复; - */ - TransactionResponse schedule(TransactionRequest request); - - /** - * 完成本次批量执行;生成待提交的结果; - * - * @return - */ - TransactionBatchResultHandle prepare(); - - TransactionBatchResult cancel(TransactionState errorResult); - - long blockHeight(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchResult.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchResult.java deleted file mode 100644 index 3b7038a5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchResult.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.service; - -import java.util.Iterator; - -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.TransactionResponse; - -public interface TransactionBatchResult { - - LedgerBlock getBlock(); - - Iterator getResponses(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchResultHandle.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchResultHandle.java deleted file mode 100644 index 03caed25..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionBatchResultHandle.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jd.blockchain.service; - -import com.jd.blockchain.ledger.TransactionState; - -public interface TransactionBatchResultHandle extends TransactionBatchResult{ - - void commit(); - - void cancel(TransactionState errorResult); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionEngine.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionEngine.java deleted file mode 100644 index aad92209..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/service/TransactionEngine.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.service; - -import com.jd.blockchain.crypto.HashDigest; - -public interface TransactionEngine { - - TransactionBatchProcess createNextBatch(HashDigest ledgerHash); - - TransactionBatchProcess getBatch(HashDigest ledgerHash); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/setting/LedgerIncomingSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/setting/LedgerIncomingSetting.java deleted file mode 100644 index 0e110f12..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/setting/LedgerIncomingSetting.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.jd.blockchain.setting; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; - -/** - * 账本的接入设置; - * - * @author huanghaiquan - * - */ -public class LedgerIncomingSetting { - - private int gatewayId; - - private HashDigest ledgerHash; - - private CryptoSetting cryptoSetting; - - private String providerName; - - /** - * 节点是否已经启动; - */ - private boolean ready; - - /** - * Base64 编码的视图配置; - */ - private String clientSetting; - -// /** -// * Base64 编码的网关配置; -// */ -// private String gatewaySetting; - - public String getClientSetting() { - return clientSetting; - } - - public void setClientSetting(String clientSetting) { - this.clientSetting = clientSetting; - } - -// public String getGatewaySetting() { -// return gatewaySetting; -// } - -// public void setGatewaySetting(String gatewaySetting) { -// this.gatewaySetting = gatewaySetting; -// } - - public boolean isReady() { - return ready; - } - - public void setReady(boolean ready) { - this.ready = ready; - } - - public HashDigest getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(HashDigest ledgerHash) { - this.ledgerHash = ledgerHash; - } - - /** - * 在共识网络中给当前请求的网关分配的 ID ; - * - * @return - */ - public int getGatewayId() { - return gatewayId; - } - - public void setGatewayId(int gatewayId) { - this.gatewayId = gatewayId; - } - - /** - * 账本的当前密码配置; - * - * @return - */ - public CryptoSetting getCryptoSetting() { - return cryptoSetting; - } - - public void setCryptoSetting(CryptoSetting cryptoSetting) { - this.cryptoSetting = cryptoSetting; - } - - public String getProviderName() { - return providerName; - } - - public void setProviderName(String providerName) { - this.providerName = providerName; - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BooleanValueHolder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BooleanValueHolder.java deleted file mode 100644 index 480e3d30..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BooleanValueHolder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.transaction; - -public class BooleanValueHolder extends ValueHolderWrapper { - - BooleanValueHolder(OperationResultHolder resultHolder) { - super(resultHolder); - } - - /** - * 获取值;
- * - * 此方法不堵塞,调用立即返回;
- * - * 如果未完成时( {@link #isCompleted()} 为 false ),总是返回 false; - * - * @return - */ - public boolean get() { - return super.isCompleted() ? (boolean) super.getValue() : false; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ByteValueHolder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ByteValueHolder.java deleted file mode 100644 index d9c024ff..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ByteValueHolder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.transaction; - -public class ByteValueHolder extends ValueHolderWrapper { - - ByteValueHolder(OperationResultHolder resultHolder) { - super(resultHolder); - } - - /** - * 获取值;
- * - * 此方法不堵塞,调用立即返回;
- * - * 如果未完成时( {@link #isCompleted()} 为 false ),总是返回 0; - * - * @return - */ - public byte get() { - return super.isCompleted() ? (byte) super.getValue() : 0; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ClientOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ClientOperator.java deleted file mode 100644 index cba4569e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ClientOperator.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.transaction; - -/** - * 面向客户端的操作; - * - * @author huanghaiquan - * - */ -public interface ClientOperator - extends SecurityOperator, UserOperator, DataAccountOperator, ContractOperator, EventOperator, ParticipantOperator { - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ConsensusParticipantData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ConsensusParticipantData.java deleted file mode 100644 index e182ced1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ConsensusParticipantData.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.net.NetworkAddress; -import com.jd.blockchain.ledger.ParticipantNodeState; - -public class ConsensusParticipantData implements ParticipantNode { - - private int id; - - private Bytes address; - - private String name; - - private PubKey pubKey; - - private NetworkAddress hostAddress; - - private ParticipantNodeState participantNodeState; - - @Override - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public NetworkAddress getHostAddress() { - return hostAddress; - } - - public void setHostAddress(NetworkAddress hostAddress) { - this.hostAddress = hostAddress; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - } - - @Override - public Bytes getAddress() { - return address; - } - - public void setAddress(Bytes address) { - this.address = address; - } - - @Override - public ParticipantNodeState getParticipantNodeState() { - return participantNodeState; - } - - public void setParticipantState(ParticipantNodeState participantNodeState) { - this.participantNodeState = participantNodeState; - } - - } \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventExecutor.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventExecutor.java deleted file mode 100644 index 4cacf19c..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventExecutor.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.jd.blockchain.transaction; - -public interface ContractEventExecutor { - - T execute(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOpTemplate.java deleted file mode 100644 index de304958..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOpTemplate.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.BytesValueList; -import com.jd.blockchain.ledger.ContractEventSendOperation; -import com.jd.blockchain.utils.Bytes; - -public class ContractEventSendOpTemplate implements ContractEventSendOperation { - - static { - DataContractRegistry.register(ContractEventSendOperation.class); - } - - private Bytes contractAddress; - private BytesValueList args; - private String event; - - private ContractInvocation invocation; - - public ContractEventSendOpTemplate(Bytes contractAddress, String event, BytesValueList args) { - this.contractAddress = contractAddress; - this.event = event; - this.args = args; - } - - @Override - public Bytes getContractAddress() { - return contractAddress; - } - - @Override - public String getEvent() { - return event; - } - - @Override - public BytesValueList getArgs() { - return args; - } - - public ContractInvocation getInvocation() { - return invocation; - } - - public void setInvocation(ContractInvocation invocation) { - this.invocation = invocation; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocation.java deleted file mode 100644 index 2e27fca9..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocation.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jd.blockchain.transaction; - -import java.lang.reflect.Method; - -import com.jd.blockchain.contract.ContractType; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.BytesValueEncoding; - -/** - * ContractInvocation 包装了客户端发起的一次合约方法调用的相关信息,用于在客户端交易处理上下文进行共享处理状态; - * - * @author huanghaiquan - * - */ -class ContractInvocation extends OperationResultHolder { - - private Method method; - - private ContractType contractType; - - private int operationIndex = -1; - - public ContractInvocation(ContractType contractType, Method method) { - this.contractType = contractType; - this.method = method; - } - - public ContractType getContractType() { - return contractType; - } - - @Override - public int getOperationIndex() { - return operationIndex; - } - - public void setOperationIndex(int operationIndex) { - this.operationIndex = operationIndex; - } - - public Class getReturnType() { - return method.getReturnType(); - } - - @Override - protected Object decodeResult(BytesValue bytesValue) { - return BytesValueEncoding.decode(bytesValue, method.getReturnType()); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationHandler.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationHandler.java deleted file mode 100644 index 8b48d509..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationHandler.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jd.blockchain.transaction; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.Arrays; - -import com.jd.blockchain.contract.ContractException; -import com.jd.blockchain.contract.ContractType; -import com.jd.blockchain.ledger.BytesValueEncoding; -import com.jd.blockchain.ledger.BytesValueList; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.IllegalDataException; - -public class ContractInvocationHandler implements InvocationHandler { - - private Bytes contractAddress; - - private ContractType contractType; - - private ContractEventSendOperationBuilder sendOpBuilder; - - private int proxyHashCode; - - public ContractInvocationHandler(Bytes contractAddress, ContractType contractType, - ContractEventSendOperationBuilder sendOpBuilder) { - this.contractAddress = contractAddress; - if (contractType == null) { - throw new IllegalDataException("contractType == null, no invoke really."); - } - this.contractType = contractType; - this.sendOpBuilder = sendOpBuilder; - this.proxyHashCode = Arrays.deepHashCode(new Object[] { this, contractAddress, contractType, sendOpBuilder }); - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - // 判断是否是常规方法调用 - if (method.getName().equals("hashCode")) { - // 该处需要使用当前代理类的HashCode - return proxyHashCode; - } - if (method.getName().equals("toString")) { - // 该处使用当前代理类的toString - return this.toString(); - } - - String event = contractType.getEvent(method); - if (event == null) { - // 该方法不是合约可执行的方法 - throw new ContractException( - String.format("The invoking method [%s] is not annotated as event handle method by @ContractEvent!", - method.toString())); - } - // 序列化调用参数; - Class[] argTypes = method.getParameterTypes(); - BytesValueList argBytes = BytesValueEncoding.encodeArray(args, argTypes); - - // 定义合约调用操作; - ContractEventSendOpTemplate opTemplate = (ContractEventSendOpTemplate) sendOpBuilder.send(contractAddress, - event, argBytes); - - // 加入合约调用的额外信息; - ContractInvocation invocation = new ContractInvocation(contractType, method); - - // 传递给定义操作的上下文,以便在生成交易时,同步操作在交易中的索引位置; - opTemplate.setInvocation(invocation); - - // 传递给通过代理对象调用合约方法的调用者,以便可以同步操作在交易中的索引位置以及操作的返回值; - ContractInvocationStub.set(invocation); - - // 返回类型的默认值 - return BytesValueEncoding.getDefaultValue(method.getReturnType()); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationStub.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationStub.java deleted file mode 100644 index 661319b1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationStub.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.transaction; - -/** - * 用于在上下文中传递合约调用返回值的工具类; - * - * @author huanghaiquan - * - */ -class ContractInvocationStub { - - private static ThreadLocal stub = new ThreadLocal(); - - private ContractInvocationStub() { - } - - public static void set(ContractInvocation invocation) { - if (invocation == null) { - throw new IllegalArgumentException("Null stub value!"); - } - stub.set(invocation); - } - - public static ContractInvocation take() { - ContractInvocation subValue = stub.get(); - if (subValue == null) { - throw new IllegalStateException( - "The latest invocation of contract has not been stubbed! It may be caused by the wrong call sequence from the upper layer!"); - } - stub.remove(); - return subValue; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractOperator.java deleted file mode 100644 index cc0f7da4..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractOperator.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.transaction; - -public interface ContractOperator { - - /** - * 部署合约; - * @return - */ - ContractCodeDeployOperationBuilder contracts(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractReturnValue.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractReturnValue.java deleted file mode 100644 index 9fee9ea7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractReturnValue.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.jd.blockchain.transaction; - -public class ContractReturnValue { - - private ContractReturnValue() { - } - - /** - * 解析合约方法调用的返回值; - *

- * 用法示例:
- * - * import static com.jd.blockchain.transaction.ContractReturnValue.*;

- * - * - * ValueHolder - * - * PreparedTransaction prepTx = tx.prepare();
- * prepTx.sign(userKey);
- * prepTx.commit()

- * - * String retnValue = retnHolder.get(); //这是同步方法,会阻塞当前线程等待交易提交后返回结果;
- *
- * - * @param - * @param call - * @return - */ - public static GenericValueHolder decode(T call) { - ContractInvocation invocation = ContractInvocationStub.take(); - return new GenericValueHolder(invocation); - } - - /** - * 解析合约方法调用的返回值; - *

- * 用法示例:
- * - * import static com.jd.blockchain.transaction.ContractReturnValue.*;

- * - * - * LongValueHolder retnHolder = decode(contract.issue(assetKey, amount));
- * - * PreparedTransaction prepTx = tx.prepare();
- * prepTx.sign(userKey);
- * prepTx.commit()

- * - * long retnValue = retnHolder.get(); //这是同步方法,会阻塞当前线程等待交易提交后返回结果;
- *
- * - * @param call - * @return - */ - public static LongValueHolder decode(long call) { - ContractInvocation invocation = ContractInvocationStub.take(); - return new LongValueHolder(invocation); - } - - /** - * 解析合约方法调用的返回值; - *

- * 用法示例:
- * - * import static com.jd.blockchain.transaction.ContractReturnValue.*;

- * - * - * IntValueHolder retnHolder = decode(contract.issue(assetKey, amount));
- * - * PreparedTransaction prepTx = tx.prepare();
- * prepTx.sign(userKey);
- * prepTx.commit()

- * - * int retnValue = retnHolder.get(); //这是同步方法,会阻塞当前线程等待交易提交后返回结果;
- *
- * - * @param call - * @return - */ - public static IntValueHolder decode(int call) { - ContractInvocation invocation = ContractInvocationStub.take(); - return new IntValueHolder(invocation); - } - - /** - * 解析合约方法调用的返回值; - *

- * 用法示例:
- * - * import static com.jd.blockchain.transaction.ContractReturnValue.*;

- * - * - * ShortValueHolder retnHolder = decode(contract.issue(assetKey, amount));
- * - * PreparedTransaction prepTx = tx.prepare();
- * prepTx.sign(userKey);
- * prepTx.commit()

- * - * short retnValue = retnHolder.get(); //这是同步方法,会阻塞当前线程等待交易提交后返回结果;
- *
- * - * @param call - * @return - */ - public static ShortValueHolder decode(short call) { - ContractInvocation invocation = ContractInvocationStub.take(); - return new ShortValueHolder(invocation); - } - - /** - * 解析合约方法调用的返回值; - *

- * 用法示例:
- * - * import static com.jd.blockchain.transaction.ContractReturnValue.*;

- * - * - * ByteValueHolder retnHolder = decode(contract.issue(assetKey, amount));
- * - * PreparedTransaction prepTx = tx.prepare();
- * prepTx.sign(userKey);
- * prepTx.commit()

- * - * byte retnValue = retnHolder.get(); //这是同步方法,会阻塞当前线程等待交易提交后返回结果;
- *
- * - * @param call - * @return - */ - public static ByteValueHolder decode(byte call) { - ContractInvocation invocation = ContractInvocationStub.take(); - return new ByteValueHolder(invocation); - } - - /** - * 解析合约方法调用的返回值; - *

- * 用法示例:
- * - * import static com.jd.blockchain.transaction.ContractReturnValue.*;

- * - * - * BooleanValueHolder retnHolder = decode(contract.issue(assetKey, amount));
- * - * PreparedTransaction prepTx = tx.prepare();
- * prepTx.sign(userKey);
- * prepTx.commit()

- * - * boolean retnValue = retnHolder.get(); //这是同步方法,会阻塞当前线程等待交易提交后返回结果;
- *
- * - * @param call - * @return - */ - public static BooleanValueHolder decode(boolean call) { - ContractInvocation invocation = ContractInvocationStub.take(); - return new BooleanValueHolder(invocation); - } - - - //----------------------- 内部类型 ----------------------- - - - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountOperator.java deleted file mode 100644 index 89ea895e..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountOperator.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.utils.Bytes; - -public interface DataAccountOperator { - - /** - * 数据账户; - * - * @return - */ - - DataAccountRegisterOperationBuilder dataAccounts(); - - /** - * 写入数据;
- * - * @param accountAddress - * @return - */ - DataAccountKVSetOperationBuilder dataAccount(String accountAddress); - - /** - * 写入数据; - * - * @param accountAddress - * @return - */ - DataAccountKVSetOperationBuilder dataAccount(Bytes accountAddress); -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/EventOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/EventOperator.java deleted file mode 100644 index 8540a470..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/EventOperator.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.utils.Bytes; - -public interface EventOperator { - - /** - * 创建调用合约的代理实例; - * - * @param address - * @param contractIntf - * @return - */ - T contract(String address, Class contractIntf); - - /** - * 创建调用合约的代理实例; - * - * @param address - * @param contractIntf - * @return - */ - T contract(Bytes address, Class contractIntf); - -// /** -// * 执行合约异步等待应答结果 -// * -// * @param execute -// * @return -// */ -// EventResult result(ContractEventExecutor execute); -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/GenericValueHolder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/GenericValueHolder.java deleted file mode 100644 index 1832f315..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/GenericValueHolder.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.transaction; - -public class GenericValueHolder extends ValueHolderWrapper { - - GenericValueHolder(OperationResultHolder resultHolder) { - super(resultHolder); - } - - /** - * 获取值;
- * - * 此方法不堵塞,调用立即返回;
- * - * 如果未完成时( {@link #isCompleted()} 为 false ),总是返回 null; - * - * @return - */ - @SuppressWarnings("unchecked") - public T get() { - return (T) super.getValue(); - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/IntValueHolder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/IntValueHolder.java deleted file mode 100644 index 5e490ca3..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/IntValueHolder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.transaction; - -public class IntValueHolder extends ValueHolderWrapper { - - IntValueHolder(OperationResultHolder resultHolder) { - super(resultHolder); - } - - /** - * 获取值;
- * - * 此方法不堵塞,调用立即返回;
- * - * 如果未完成时( {@link #isCompleted()} 为 false ),总是返回 0; - * - * @return - */ - public int get() { - return super.isCompleted() ? (int) super.getValue() : 0; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/KVData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/KVData.java deleted file mode 100644 index de93fcc8..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/KVData.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataAccountKVSetOperation.KVWriteEntry; - -public class KVData implements KVWriteEntry { - - private String key; - - private BytesValue value; - - private long expectedVersion; - - public KVData(String key, BytesValue value, long expectedVersion) { - this.key = key; - this.value = value; - this.expectedVersion = expectedVersion; - } - - @Override - public String getKey() { - return key; - } - - @Override - public BytesValue getValue() { - return value; - } - - @Override - public long getExpectedVersion() { - return expectedVersion; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitData.java deleted file mode 100644 index 656b4aa3..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitData.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.UserAuthInitSettings; -import com.jd.blockchain.utils.Bytes; - -public class LedgerInitData implements LedgerInitSetting { - - static { - DataContractRegistry.register(LedgerInitSetting.class); - } - - private byte[] ledgerSeed; - - private ParticipantNode[] consensusParticipants; - - private CryptoSetting cryptoSetting; - - private String consensusProvider; - - private Bytes consensusSettings; - - private long createdTime; - - @Override - public byte[] getLedgerSeed() { - return ledgerSeed; - } - - @Override - public ParticipantNode[] getConsensusParticipants() { - return consensusParticipants; - } - - @Override - public CryptoSetting getCryptoSetting() { - return cryptoSetting; - } - - @Override - public Bytes getConsensusSettings() { - return consensusSettings; - } - - public void setLedgerSeed(byte[] ledgerSeed) { - this.ledgerSeed = ledgerSeed; - } - - public void setConsensusParticipants(ParticipantNode[] consensusParticipants) { - this.consensusParticipants = consensusParticipants; - } - - public void setCryptoSetting(CryptoSetting cryptoSetting) { - this.cryptoSetting = cryptoSetting; - } - - public void setConsensusSettings(Bytes consensusSettings) { - this.consensusSettings = consensusSettings; - } - - public void setConsensusSettings(byte[] consensusSettings) { - this.consensusSettings = new Bytes(consensusSettings); - } - - @Override - public String getConsensusProvider() { - return consensusProvider; - } - - public void setConsensusProvider(String consensusProvider) { - this.consensusProvider = consensusProvider; - } - - @Override - public long getCreatedTime() { - return createdTime; - } - - public void setCreatedTime(long createdTime) { - this.createdTime = createdTime; - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperator.java deleted file mode 100644 index 62c4f293..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperator.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jd.blockchain.transaction; - -public interface LedgerInitOperator { - - /** - * 注册账户操作; - * - * @return - */ - - LedgerInitOperationBuilder ledgers(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LongValueHolder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LongValueHolder.java deleted file mode 100644 index e5409f29..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LongValueHolder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.transaction; - -public class LongValueHolder extends ValueHolderWrapper { - - LongValueHolder(OperationResultHolder resultHolder) { - super(resultHolder); - } - - /** - * 获取值;
- * - * 此方法不堵塞,调用立即返回;
- * - * 如果未完成时( {@link #isCompleted()} 为 false ),总是返回 0; - * - * @return - */ - public long get() { - return super.isCompleted() ? (long) super.getValue() : 0; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationCompletedContext.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationCompletedContext.java deleted file mode 100644 index 1197f95b..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationCompletedContext.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.BytesValue; - -public class OperationCompletedContext { - - private int operationIndex; - - private BytesValue returnBytesValue; - - public OperationCompletedContext(int operationIndex, BytesValue returnBytesValue) { - this.operationIndex = operationIndex; - this.returnBytesValue = returnBytesValue; - } - - public int getOperationIndex() { - return operationIndex; - } - - public BytesValue getReturnBytesValue() { - return returnBytesValue; - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationCompletedListener.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationCompletedListener.java deleted file mode 100644 index c11f27dd..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationCompletedListener.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.transaction; - -/** - * 操作完成监听器; - * - * @author huanghaiquan - * - */ -public interface OperationCompletedListener { - - /** - * 当操作完成时发生; - * - * @param retnValue 返回值; - * @param error 异常;如果值为非空,则表示由异常导致结束; - * @param context 上下文对象; - */ - void onCompleted(Object retnValue, Throwable error, OperationCompletedContext context); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationResultHandle.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationResultHandle.java deleted file mode 100644 index 12bc7b33..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationResultHandle.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.BytesValue; - -/** - * 操作返回值处理器; - * - * @author huanghaiquan - * - */ -interface OperationResultHandle { - - /** - * 操作的索引位置; - * - * @return - */ - int getOperationIndex(); - - /** - * 正常地完成; - * - * @param returnBytesValue - * @return - */ - Object complete(BytesValue returnBytesValue); - - /** - * 以异常方式完成; - * - * @param error - */ - void complete(Throwable error); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationResultHolder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationResultHolder.java deleted file mode 100644 index 2f8ec8e6..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/OperationResultHolder.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.utils.event.EventMulticaster; - -abstract class OperationResultHolder implements OperationResultHandle { - - private Object value; - - private Throwable error; - - private volatile boolean completed; - - private EventMulticaster listenerMulticaster = - new EventMulticaster<>(OperationCompletedListener.class); - - /** - * 导致结束的错误; - * - * @return - */ - public Throwable getError() { - return error; - } - - /** - * 是否已经处理完成; - * - * @return - */ - public boolean isCompleted() { - return completed; - } - - /** - * 获取操作的返回值;
- * 在操作未完成之前,总是返回 null;
- * 可以通过 {@link #isCompleted()} 方法判断操作是否已经完成;
- * 可以通过 {@link #addCompletedListener(OperationCompletedListener)} - * 方法添加监听器来监听操作完成的事件; - * - * @return - */ - public Object getResult() { - return value; - } - - /** - * 添加操作完成监听器; - * - * @param listener - */ - public void addCompletedListener(OperationCompletedListener listener) { - listenerMulticaster.addListener(listener); - } - - protected abstract Object decodeResult(BytesValue bytesValue); - - @Override - public Object complete(BytesValue bytesValue) { - if (this.completed) { - throw new IllegalStateException( - "Contract invocation has been completed, and is not allowed to be completed again!"); - } - this.completed = true; - this.value = decodeResult(bytesValue); - OperationCompletedContext context = new OperationCompletedContext(getOperationIndex(), null); - listenerMulticaster.getBroadcaster().onCompleted(value, null, context); - return null; - } - - @Override - public void complete(Throwable error) { - if (completed) { - return; - } - this.completed = true; - this.error = error; - OperationCompletedContext context = new OperationCompletedContext(getOperationIndex(), null); - listenerMulticaster.getBroadcaster().onCompleted(null, error, context); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantOperator.java deleted file mode 100644 index 83c1524a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantOperator.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jd.blockchain.transaction; - -public interface ParticipantOperator { - - /** - * 注册参与方操作; - * - * @return - */ - ParticipantRegisterOperationBuilder participants(); - - /** - * 参与方状态更新操作; - * - * @return - */ - ParticipantStateUpdateOperationBuilder states(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOpTemplate.java deleted file mode 100644 index 925b8338..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOpTemplate.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantRegisterOperation; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class ParticipantRegisterOpTemplate implements ParticipantRegisterOperation { - - static { - DataContractRegistry.register(ParticipantRegisterOperation.class); - } - - private String participantName; - private BlockchainIdentity participantRegisterIdentity; - private NetworkAddress networkAddress; - - public ParticipantRegisterOpTemplate(String participantName, BlockchainIdentity participantRegisterIdentity, NetworkAddress networkAddress) { - this.participantName = participantName; - this.participantRegisterIdentity = participantRegisterIdentity; - this.networkAddress = networkAddress; - - } - - @Override - public String getParticipantName() { - return participantName; - } - - @Override - public BlockchainIdentity getParticipantRegisterIdentity() { - return participantRegisterIdentity; - } - - @Override - public NetworkAddress getNetworkAddress() { - return networkAddress; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOperationBuilder.java deleted file mode 100644 index 26f54c5b..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOperationBuilder.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantRegisterOperation; -import com.jd.blockchain.utils.net.NetworkAddress; - -public interface ParticipantRegisterOperationBuilder { - - /** - * 注册; - * - * @param - * - * @param - * - * @return - */ - ParticipantRegisterOperation register(String participantName, BlockchainIdentity participantPubKey, NetworkAddress networkAddress); - - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOperationBuilderImpl.java deleted file mode 100644 index 34b126d1..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantRegisterOperationBuilderImpl.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.ParticipantInfo; -import com.jd.blockchain.ledger.ParticipantRegisterOperation; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class ParticipantRegisterOperationBuilderImpl implements ParticipantRegisterOperationBuilder { - @Override - public ParticipantRegisterOperation register(String participantName, BlockchainIdentity participantPubKey, NetworkAddress networkAddress) { - return new ParticipantRegisterOpTemplate(participantName, participantPubKey, networkAddress); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateOperator.java deleted file mode 100644 index 22554031..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateOperator.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jd.blockchain.transaction; - -public interface ParticipantStateOperator { - /** - * 参与方状态更新操作; - * - * @return - */ - ParticipantStateUpdateOperationBuilder states(); -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOpTemplate.java deleted file mode 100644 index ff91eba5..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOpTemplate.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.ledger.ParticipantStateUpdateOperation; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class ParticipantStateUpdateOpTemplate implements ParticipantStateUpdateOperation { - - static { - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - } - - private BlockchainIdentity stateUpdateIdentity; - private NetworkAddress networkAddress; - private ParticipantNodeState participantNodeState; - - public ParticipantStateUpdateOpTemplate(BlockchainIdentity stateUpdateIdentity, NetworkAddress networkAddress, ParticipantNodeState participantNodeState) { - - this.stateUpdateIdentity = stateUpdateIdentity; - this.networkAddress = networkAddress; - this.participantNodeState = participantNodeState; - } - - - @Override - public BlockchainIdentity getStateUpdateIdentity() { - return stateUpdateIdentity; - } - - @Override - public NetworkAddress getNetworkAddress() { - return networkAddress; - } - - @Override - public ParticipantNodeState getState() { - return participantNodeState; - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOperationBuilder.java deleted file mode 100644 index d6c69dc3..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOperationBuilder.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.ledger.ParticipantStateUpdateInfo; -import com.jd.blockchain.ledger.ParticipantStateUpdateOperation; -import com.jd.blockchain.utils.net.NetworkAddress; - -public interface ParticipantStateUpdateOperationBuilder { - - /** - * 更新参与方状态,已注册->参与共识; - * - * @param - * - * @param - * - * @return - */ - ParticipantStateUpdateOperation update(BlockchainIdentity blockchainIdentity, NetworkAddress networkAddress, ParticipantNodeState participantNodeState); -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOperationBuilderImpl.java deleted file mode 100644 index 9c84e181..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ParticipantStateUpdateOperationBuilderImpl.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.ledger.ParticipantStateUpdateInfo; -import com.jd.blockchain.ledger.ParticipantStateUpdateOperation; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class ParticipantStateUpdateOperationBuilderImpl implements ParticipantStateUpdateOperationBuilder { - - @Override - public ParticipantStateUpdateOperation update(BlockchainIdentity blockchainIdentity, NetworkAddress networkAddress, ParticipantNodeState participantNodeState) { - return new ParticipantStateUpdateOpTemplate(blockchainIdentity, networkAddress, participantNodeState); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolePrivilegeConfigurer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolePrivilegeConfigurer.java deleted file mode 100644 index 13539536..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolePrivilegeConfigurer.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.TransactionPermission; - -public interface RolePrivilegeConfigurer extends RolesConfigure { - - String getRoleName(); - - RolePrivilegeConfigurer disable(TransactionPermission... permissions); - - RolePrivilegeConfigurer enable(TransactionPermission... permissions); - - RolePrivilegeConfigurer disable(LedgerPermission... permissions); - - RolePrivilegeConfigurer enable(LedgerPermission... permissions); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigure.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigure.java deleted file mode 100644 index 4626fa5a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigure.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jd.blockchain.transaction; - -public interface RolesConfigure { - - RolePrivilegeConfigurer configure(String roleName); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigurer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigurer.java deleted file mode 100644 index 0621a626..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigurer.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.RolesConfigureOperation; - -public interface RolesConfigurer extends RolesConfigure { - - RolesConfigureOperation getOperation(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilderImpl.java deleted file mode 100644 index ce271fce..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilderImpl.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.transaction; - -public class SecurityOperationBuilderImpl implements SecurityOperationBuilder{ - - @Override - public RolesConfigurer roles() { - return new RolesConfigureOpTemplate(); - } - - @Override - public UserAuthorizer authorziations() { - return new UserAuthorizeOpTemplate(); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperator.java deleted file mode 100644 index a636c577..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperator.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.transaction; - -/** - * 与安全配置相关的操作门面; - * - *
- * - * 只能通过客户端接口直接操作;不支持通过合约操作; - * - * @author huanghaiquan - * - */ -public interface SecurityOperator { - - /** - * 注册账户操作; - * - * @return - */ - - SecurityOperationBuilder security(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ShortValueHolder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ShortValueHolder.java deleted file mode 100644 index f9867d65..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ShortValueHolder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.transaction; - -public class ShortValueHolder extends ValueHolderWrapper { - - ShortValueHolder(OperationResultHolder resultHolder) { - super(resultHolder); - } - - /** - * 获取值;
- * - * 此方法不堵塞,调用立即返回;
- * - * 如果未完成时( {@link #isCompleted()} 为 false ),总是返回 0; - * - * @return - */ - public short get() { - return super.isCompleted() ? (short) super.getValue() : 0; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SignatureUtils.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SignatureUtils.java deleted file mode 100644 index a0c99733..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SignatureUtils.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.TransactionContent; - -public class SignatureUtils { - - public static DigitalSignature sign(TransactionContent txContent, AsymmetricKeypair keyPair) { - SignatureDigest signatureDigest = sign(txContent, keyPair.getPrivKey()); - return new DigitalSignatureBlob(keyPair.getPubKey(), signatureDigest); - } - - public static SignatureDigest sign(TransactionContent txContent, PrivKey privKey) { - return Crypto.getSignatureFunction(privKey.getAlgorithm()).sign(privKey, txContent.getHash().toBytes()); - } - - public static boolean verifySignature(TransactionContent txContent, SignatureDigest signDigest, PubKey pubKey) { - if (!TxBuilder.verifyTxContentHash(txContent, txContent.getHash())) { - return false; - } - return verifyHashSignature(txContent.getHash(), signDigest, pubKey); - } - - public static boolean verifyHashSignature(HashDigest hash, SignatureDigest signDigest, PubKey pubKey) { - return Crypto.getSignatureFunction(pubKey.getAlgorithm()).verify(signDigest, pubKey, hash.toBytes()); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TransactionCancelledExeption.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TransactionCancelledExeption.java deleted file mode 100644 index 69e37b24..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TransactionCancelledExeption.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.transaction; - -public class TransactionCancelledExeption extends RuntimeException { - - private static final long serialVersionUID = -2577951411093171806L; - - public TransactionCancelledExeption(String message) { - super(message); - } - - public TransactionCancelledExeption(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxBuilder.java deleted file mode 100644 index 0421b265..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxBuilder.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.jd.blockchain.transaction; - -import java.util.Collection; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.TransactionBuilder; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionContentBody; -import com.jd.blockchain.ledger.TransactionRequestBuilder; -import com.jd.blockchain.utils.Bytes; - -public class TxBuilder implements TransactionBuilder { - - static { - DataContractRegistry.register(TransactionContentBody.class); - } - - private BlockchainOperationFactory opFactory = new BlockchainOperationFactory(); - - private static final String DEFAULT_HASH_ALGORITHM = "SHA256"; - - private HashDigest ledgerHash; - - public TxBuilder(HashDigest ledgerHash) { - this.ledgerHash = ledgerHash; - } - - @Override - public HashDigest getLedgerHash() { - return ledgerHash; - } - - @Override - public TransactionRequestBuilder prepareRequest() { - return prepareRequest(System.currentTimeMillis()); - } - - @Override - public TransactionContent prepareContent() { - return prepareContent(System.currentTimeMillis()); - } - - @Override - public TransactionRequestBuilder prepareRequest(long time) { - TransactionContent txContent = prepareContent(time); - return new TxRequestBuilder(txContent); - } - - @Override - public TransactionContent prepareContent(long time) { - TxContentBlob txContent = new TxContentBlob(ledgerHash); - txContent.addOperations(opFactory.getOperations()); - txContent.setTime(time); - - HashDigest contentHash = computeTxContentHash(txContent); - txContent.setHash(contentHash); - - return txContent; - } - - public static HashDigest computeTxContentHash(TransactionContent txContent) { - byte[] contentBodyBytes = BinaryProtocol.encode(txContent, TransactionContentBody.class); - HashDigest contentHash = Crypto.getHashFunction(DEFAULT_HASH_ALGORITHM).hash(contentBodyBytes); - return contentHash; - } - - public static boolean verifyTxContentHash(TransactionContent txContent, HashDigest verifiedHash) { - HashDigest hash = computeTxContentHash(txContent); - return hash.equals(verifiedHash); - } - - public Collection getReturnValuehandlers() { - return opFactory.getReturnValuetHandlers(); - } - - @Override - public SecurityOperationBuilder security() { - return opFactory.security(); - } - - @Override - public LedgerInitOperationBuilder ledgers() { - return opFactory.ledgers(); - } - - @Override - public UserRegisterOperationBuilder users() { - return opFactory.users(); - } - - @Override - public DataAccountRegisterOperationBuilder dataAccounts() { - return opFactory.dataAccounts(); - } - - @Override - public DataAccountKVSetOperationBuilder dataAccount(String accountAddress) { - return opFactory.dataAccount(accountAddress); - } - - @Override - public DataAccountKVSetOperationBuilder dataAccount(Bytes accountAddress) { - return opFactory.dataAccount(accountAddress); - } - - @Override - public ContractCodeDeployOperationBuilder contracts() { - return opFactory.contracts(); - } - - public ContractEventSendOperationBuilder contractEvents() { - return opFactory.contractEvents(); - } - - @Override - public ParticipantRegisterOperationBuilder participants() {return opFactory.participants(); } - - @Override - public ParticipantStateUpdateOperationBuilder states() {return opFactory.states(); } - - @Override - public T contract(Bytes address, Class contractIntf) { - return opFactory.contract(address, contractIntf); - } - - @Override - public T contract(String address, Class contractIntf) { - return opFactory.contract(address, contractIntf); - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxContentBlob.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxContentBlob.java deleted file mode 100644 index 7413a5ff..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxContentBlob.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.jd.blockchain.transaction; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.utils.io.NumberMask; - -/** - * 交易内容的数据块; - *

- * - * 包含原始交易请求的数据块; - * - * @author huanghaiquan - * - */ -public class TxContentBlob implements TransactionContent { - - /** - * 操作数量的最大值; - */ - public static final int MAX_OP_COUNT = NumberMask.SHORT.MAX_BOUNDARY_SIZE; - - private List operationList = new ArrayList(); - - private HashDigest hash; - - private HashDigest ledgerHash; - - private long time; - - public TxContentBlob(HashDigest ledgerHash) { - this.ledgerHash = ledgerHash; - } - - /** - * 交易内容的哈希值; - */ - @Override - public HashDigest getHash() { - return this.hash; - } - - /** - * 更新交易内容的哈希值; - *

- * 注:当前对象只充当值对象,不校验指定哈希值的完整性,调用者应该在外部实施完整性校验; - * - * @param hash - */ - public void setHash(HashDigest hash) { - this.hash = hash; - } - - /** - * 交易请求链的hash - * - * @return - */ - @Override - public HashDigest getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(HashDigest ledgerHash) { - this.ledgerHash = ledgerHash; - } - - @Override - public Operation[] getOperations() { - return operationList.toArray(new Operation[operationList.size()]); - } - - public void setOperations(Object[] operations) { - // in array's case ,cast will failed! - for (Object operation : operations) { - Operation op = (Operation) operation; - addOperation(op); - } - } - - @Override - public long getTimestamp() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public void addOperation(Operation operation) { - operationList.add(operation); - } - - public void addOperations(Collection operations) { - operationList.addAll(operations); - } -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxStateManager.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxStateManager.java deleted file mode 100644 index db799f1d..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxStateManager.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jd.blockchain.transaction; - -class TxStateManager { - - private State state = State.OPERABLE; - - public void operate() { - if (state != State.OPERABLE) { - throw new IllegalStateException(String.format("Cannot define operations in %s state!", state)); - } - } - - public void prepare() { - if (state != State.OPERABLE) { - throw new IllegalStateException( - String.format("Cannot switch to %s state in %s state!", State.PREPARED, state)); - } - state = State.PREPARED; - } - - public void commit() { - if (state != State.PREPARED) { - throw new IllegalStateException( - String.format("Cannot switch to %s state in %s state!", State.COMMITTED, state)); - } - state = State.COMMITTED; - } - - public void complete() { - if (state != State.COMMITTED) { - throw new IllegalStateException(String.format("Cannot complete normally in %s state!", state)); - } - state = State.CLOSED; - } - - /** - * 关闭交易; - * - * @param error - * @return 此次操作前是否已经处于关闭状态;
- * 如果返回 true ,则表示之前已经处于关闭状态,此次操作将被忽略;
- * 如果返回 fasle,则表示之前处于非关闭状态,此次操作将切换为关闭状态; - */ - public boolean close() { - if (state == State.CLOSED) { - return true; - } - state = State.CLOSED; - return false; - } - - private static enum State { - - /** - * 可操作; - */ - OPERABLE, - - /** - * 就绪; - */ - PREPARED, - - /** - * 已提交; - */ - COMMITTED, - - /** - * 已关闭; - */ - CLOSED - - } - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorize.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorize.java deleted file mode 100644 index ecaaa7ef..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorize.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.utils.Bytes; - -public interface UserAuthorize { - - UserRolesAuthorizer forUser(BlockchainIdentity... userId); - - UserRolesAuthorizer forUser(Bytes... userAddress); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizer.java deleted file mode 100644 index 66f083c7..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizer.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.UserAuthorizeOperation; - -public interface UserAuthorizer extends UserAuthorize { - - UserAuthorizeOperation getOperation(); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserOperator.java deleted file mode 100644 index fdd82668..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserOperator.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jd.blockchain.transaction; - -public interface UserOperator { - - /** - * 注册账户操作; - * - * @return - */ - - UserRegisterOperationBuilder users(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRolesAuthorizer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRolesAuthorizer.java deleted file mode 100644 index 2a58858a..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRolesAuthorizer.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jd.blockchain.transaction; - -import com.jd.blockchain.ledger.RolesPolicy; - -public interface UserRolesAuthorizer extends UserAuthorize { - - UserRolesAuthorizer authorize(String... roles); - - UserRolesAuthorizer unauthorize(String... roles); - - UserRolesAuthorizer setPolicy(RolesPolicy rolePolicy); - -} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ValueHolderWrapper.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ValueHolderWrapper.java deleted file mode 100644 index 42c4f86b..00000000 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ValueHolderWrapper.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jd.blockchain.transaction; - -class ValueHolderWrapper { - private OperationResultHolder valueHolder; - - protected ValueHolderWrapper(OperationResultHolder valueHolder) { - this.valueHolder = valueHolder; - } - - public boolean isCompleted() { - return valueHolder.isCompleted(); - } - - public Throwable getError() { - return valueHolder.getError(); - } - - /** - * 获取值;
- * - * 此方法不堵塞,调用立即返回;
- * - * 如果未完成时( {@link #isCompleted()} 为 false ),总是返回 null; - * - * @return - */ - protected Object getValue() { - return valueHolder.getResult(); - } - - public void addCompletedListener(OperationCompletedListener listener) { - valueHolder.addCompletedListener(listener); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/AddressEncodingTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/AddressEncodingTest.java deleted file mode 100644 index aab1dbef..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/AddressEncodingTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import java.util.Random; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; - -public class AddressEncodingTest { - - public static void main(String[] args) { - BlockchainKeypair bkp = BlockchainKeyGenerator.getInstance().generate(); - PubKey pk = bkp.getPubKey(); - byte[] data =new byte[64]; - Random rand = new Random(); - rand.nextBytes(data); - int round = 5; - for (int r = 0; r < round; r++) { - System.out.println("================== round[" + r + "] ==================="); - int count = 100000; - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - AddressEncoding.generateAddress(pk); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("Compute Count=%s; Total time=%s ms; TPS=%.2f", count, elapsedTS, - ((count * 1000.0D) / elapsedTS))); - } - } - - // @Test - // public void testGenerateAddress() { - // fail("Not yet implemented"); - // } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesToBytesValueResolverTest.java deleted file mode 100644 index 2dfa0dbd..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesToBytesValueResolverTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.ledger.resolver.BytesToBytesValueResolver; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import static org.junit.Assert.*; -import org.junit.Test; - -public class BytesToBytesValueResolverTest { - - private BytesToBytesValueResolver resolver = new BytesToBytesValueResolver(); - - @Test - public void test() { - String text = "www.jd.com"; - - byte[] bytes = BytesUtils.toBytes(text); - - Bytes bytesObj = Bytes.fromString(text); - - BytesValue bytesValue = resolver.encode(bytes); - - assertNotNull(bytesValue); - - assertEquals(bytesValue.getType(), DataType.BYTES); - - assertEquals(bytesObj, bytesValue.getBytes()); - - Bytes resolveBytesObj = (Bytes)resolver.decode(bytesValue); - - assertEquals(bytesObj, resolveBytesObj); - - byte[] resolveBytes = (byte[])resolver.decode(bytesValue, byte[].class); - - assertArrayEquals(bytes, resolveBytes); - - String resolveText = (String)resolver.decode(bytesValue, String.class); - - assertEquals(text, resolveText); - } -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesValueEncodingTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesValueEncodingTest.java deleted file mode 100644 index f572a831..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesValueEncodingTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.utils.Bytes; -import static org.junit.Assert.*; -import org.junit.Test; - -public class BytesValueEncodingTest { - @Test - public void testSupport() { - assertTrue(BytesValueEncoding.supportType(byte[].class)); - assertTrue(BytesValueEncoding.supportType(int.class)); - assertTrue(BytesValueEncoding.supportType(Integer.class)); - assertTrue(BytesValueEncoding.supportType(short.class)); - assertTrue(BytesValueEncoding.supportType(Short.class)); - assertTrue(BytesValueEncoding.supportType(long.class)); - assertTrue(BytesValueEncoding.supportType(Long.class)); - assertTrue(BytesValueEncoding.supportType(String.class)); - assertTrue(BytesValueEncoding.supportType(Bytes.class)); - assertTrue(BytesValueEncoding.supportType(Operation.class)); - assertFalse(BytesValueEncoding.supportType(byte.class)); - } - - @Test - public void testSingle() { - long longVal = 1024L; - BytesValue longBytesVal1 = BytesValueEncoding.encodeSingle(longVal, null); - BytesValue longBytesVal2 = BytesValueEncoding.encodeSingle(longVal, long.class); - BytesValue longBytesVal3 = BytesValueEncoding.encodeSingle(longVal, Long.class); - - assertEquals(longBytesVal1.getBytes(), longBytesVal2.getBytes()); - assertEquals(longBytesVal1.getType(), longBytesVal2.getType()); - assertEquals(longBytesVal2.getBytes(), longBytesVal3.getBytes()); - assertEquals(longBytesVal2.getType(), longBytesVal3.getType()); - - long resolveLongVal1 = (long)BytesValueEncoding.decode(longBytesVal1); - long resolveLongVal2 = (long)BytesValueEncoding.decode(longBytesVal2); - long resolveLongVal3 = (long)BytesValueEncoding.decode(longBytesVal3); - - assertEquals(resolveLongVal1, 1024L); - assertEquals(resolveLongVal2, 1024L); - assertEquals(resolveLongVal3, 1024L); - } - - @Test - public void testArray() { - Object[] values = new Object[]{1024L, "zhangsan", "lisi".getBytes(), 16}; - Class[] classes = new Class[]{long.class, String.class, byte[].class, int.class}; - - BytesValueList bytesValueList = BytesValueEncoding.encodeArray(values, null); - BytesValueList bytesValueList1 = BytesValueEncoding.encodeArray(values, classes); - - assertEquals(bytesValueList1.getValues().length, values.length); - - - BytesValue[] bytesValues = bytesValueList.getValues(); - assertEquals(bytesValues.length, values.length); - - assertEquals(DataType.INT64, bytesValues[0].getType()); - assertEquals(DataType.TEXT, bytesValues[1].getType()); - assertEquals(DataType.BYTES, bytesValues[2].getType()); - assertEquals(DataType.INT32, bytesValues[3].getType()); - - Object[] resolveObjs = BytesValueEncoding.decode(bytesValueList, classes); - - assertArrayEquals(resolveObjs, values); - } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractCodeDeployOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractCodeDeployOpTemplateTest.java deleted file mode 100644 index 5c6b24d2..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractCodeDeployOpTemplateTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.ContractCodeDeployOpTemplateTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午10:53 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainIdentityData; -import com.jd.blockchain.ledger.ContractCodeDeployOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.transaction.ContractCodeDeployOpTemplate; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class ContractCodeDeployOpTemplateTest { - - private ContractCodeDeployOpTemplate data; - - @Before - public void initContractCodeDeployOpTemplate() { - DataContractRegistry.register(ContractCodeDeployOperation.class); - DataContractRegistry.register(Operation.class); - SignatureFunction signFunc = Crypto.getSignatureFunction("ED25519"); - PubKey pubKey = signFunc.generateKeypair().getPubKey(); - BlockchainIdentity contractID = new BlockchainIdentityData(pubKey); - byte[] chainCode = "jd-test".getBytes(); - data = new ContractCodeDeployOpTemplate(contractID, chainCode); - } - - @Test - public void testSerialize_ContractCodeDeployOperation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, ContractCodeDeployOperation.class); - ContractCodeDeployOperation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertArrayEquals(resolvedData.getChainCode(), data.getChainCode()); - assertEquals(resolvedData.getContractID().getAddress(), data.getContractID().getAddress()); - assertEquals(resolvedData.getContractID().getPubKey(), data.getContractID().getPubKey()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_Operation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, ContractCodeDeployOperation.class); - ContractCodeDeployOperation resolvedData = BinaryProtocol.decode(serialBytes); - BlockchainIdentity expCodeId = data.getContractID(); - BlockchainIdentity actualCodeId = resolvedData.getContractID(); - - assertEquals(expCodeId.getAddress().toBase58(), actualCodeId.getAddress().toBase58()); - assertEquals(expCodeId.getPubKey().toBase58(), actualCodeId.getPubKey().toBase58()); - assertTrue(BytesUtils.equals(data.getChainCode(), resolvedData.getChainCode())); - - System.out.println("------Assert start ------"); - System.out.println("serialBytesLength=" + serialBytes.length); - System.out.println(resolvedData); - System.out.println("------Assert OK ------"); - } - - // test复杂场景; - -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractEventSendOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractEventSendOpTemplateTest.java deleted file mode 100644 index 506d86d4..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractEventSendOpTemplateTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.ContractEventSendOpTemplateTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午10:56 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.BytesDataList; -import com.jd.blockchain.ledger.BytesValueList; -import com.jd.blockchain.ledger.ContractEventSendOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.transaction.ContractEventSendOpTemplate; -import com.jd.blockchain.utils.Bytes; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class ContractEventSendOpTemplateTest { - - private ContractEventSendOpTemplate data; - - @Before - public void initContractEventSendOpTemplate() { - DataContractRegistry.register(BytesValueList.class); - DataContractRegistry.register(ContractEventSendOperation.class); - DataContractRegistry.register(Operation.class); - String contractAddress = "zhangsan-address", event = "zhangsan-event"; - BytesValueList args = new BytesDataList(TypedValue.fromText("zhangsan-args")); - data = new ContractEventSendOpTemplate(Bytes.fromString(contractAddress), event, args); - } - - @Test - public void testSerialize_ContractEventSendOperation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, ContractEventSendOperation.class); - ContractEventSendOperation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getContractAddress(), data.getContractAddress()); - assertEquals(resolvedData.getEvent(), data.getEvent()); - byte[] expectedBytes = BinaryProtocol.encode(resolvedData.getArgs(), BytesValueList.class); - byte[] actualBytes = BinaryProtocol.encode(data.getArgs(), BytesValueList.class); - assertArrayEquals(expectedBytes, actualBytes); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_Operation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, Operation.class); - Operation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - System.out.println(resolvedData); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractTypeTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractTypeTest.java deleted file mode 100644 index d6a49c9c..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractTypeTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; -import java.util.Set; - -import org.junit.Test; - -import com.jd.blockchain.contract.ContractException; -import com.jd.blockchain.contract.ContractType; - -public class ContractTypeTest { - - /** - * 正常测试; - * @throws SecurityException - * @throws NoSuchMethodException - */ - @Test - public void normalTest() throws NoSuchMethodException, SecurityException { - ContractType contractType = ContractType.resolve(NormalContract.class); - - assertEquals("NORMAL-CONTRACT", contractType.getName()); - - Set events = contractType.getEvents(); - assertEquals(5, events.size()); - assertTrue(events.contains("issue")); - assertTrue(events.contains("get_amount")); - assertTrue(events.contains("get_balance")); - assertTrue(events.contains("assign")); - assertTrue(events.contains("transfer")); - - Method issueMethod = contractType.getHandleMethod("issue"); - assertNotNull(issueMethod); - Method getAmountMethod = contractType.getHandleMethod("get_amount"); - assertNotNull(getAmountMethod); - Method getBalanceMethod = contractType.getHandleMethod("get_balance"); - assertNotNull(getBalanceMethod); - Method assignMethod = contractType.getHandleMethod("assign"); - assertNotNull(assignMethod); - Method transferMethod = contractType.getHandleMethod("transfer"); - assertNotNull(transferMethod); - - assertEquals("issue", contractType.getEvent(issueMethod)); - assertEquals("get_amount", contractType.getEvent(getAmountMethod)); - assertEquals("get_balance", contractType.getEvent(getBalanceMethod)); - assertEquals("assign", contractType.getEvent(assignMethod)); - assertEquals("transfer", contractType.getEvent(transferMethod)); - - Method toStringMethod = NormalContractImpl.class.getMethod("toString"); - assertNull(contractType.getEvent(toStringMethod)); - assertNull(contractType.getHandleMethod("NotExist")); - - //解析非合约声明接口类型时,应该正常,只需要实现接口(该接口定义了具体的合约类型)即可 - ContractException ex = null; - try { - ContractType.resolve(NormalContractImpl.class); - } catch (ContractException e) { - ex = e; - } - assertNull(ex); - } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountKVSetOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountKVSetOpTemplateTest.java deleted file mode 100644 index 6c1d4f57..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountKVSetOpTemplateTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.DataAccountKVSetOpTemplateTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午10:59 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.transaction.DataAccountKVSetOpTemplate; -import com.jd.blockchain.transaction.KVData; -import com.jd.blockchain.utils.Bytes; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ -public class DataAccountKVSetOpTemplateTest { - - private DataAccountKVSetOpTemplate data; - - @Before - public void initDataAccountKVSetOpTemplate() { - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class); - DataContractRegistry.register(Operation.class); - String accountAddress = "zhangsandhakhdkah"; - data = new DataAccountKVSetOpTemplate(Bytes.fromString(accountAddress)); - KVData kvData1 = - new KVData("test1", TypedValue.fromText("zhangsan"), 9999L); - KVData kvData2 = - new KVData("test2", TypedValue.fromText("lisi"), 9990L); - KVData kvData3 = - new KVData("test3", TypedValue.fromText("wangwu"), 1990L); - data.set(kvData1); - data.set(kvData2); - data.set(kvData3); - } - - - @Test - public void testSerialize_DataAccountKVSetOperation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, DataAccountKVSetOperation.class); - DataAccountKVSetOperation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getAccountAddress(), data.getAccountAddress()); - DataAccountKVSetOperation.KVWriteEntry[] resolvedKv = resolvedData.getWriteSet(); - DataAccountKVSetOperation.KVWriteEntry[] dataKv = data.getWriteSet(); - assertEquals(dataKv.length, resolvedKv.length); - for (int i = 0; i < dataKv.length; i++) { - assertEquals(dataKv[i].getKey(), resolvedKv[i].getKey()); - assertArrayEquals(dataKv[i].getValue().getBytes().toBytes(), resolvedKv[i].getValue().getBytes().toBytes()); - assertEquals(dataKv[i].getValue().getType().CODE, resolvedKv[i].getValue().getType().CODE); - - assertEquals(dataKv[i].getExpectedVersion(), resolvedKv[i].getExpectedVersion()); - } - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_Operation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, Operation.class); - Operation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - System.out.println(resolvedData); - System.out.println("serialBytesLength=" + serialBytes.length); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountRegisterOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountRegisterOpTemplateTest.java deleted file mode 100644 index e13bad09..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountRegisterOpTemplateTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.DataAccountRegisterOpTemplateTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午11:03 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainIdentityData; -import com.jd.blockchain.ledger.DataAccountRegisterOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.transaction.DataAccountRegisterOpTemplate; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class DataAccountRegisterOpTemplateTest { - - private DataAccountRegisterOpTemplate data; - - @Before - public void initDataAccountRegisterOpTemplate() { - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(Operation.class); - SignatureFunction signFunc = Crypto.getSignatureFunction("ED25519"); - PubKey pubKey = signFunc.generateKeypair().getPubKey(); - BlockchainIdentity contractID = new BlockchainIdentityData(pubKey); - data = new DataAccountRegisterOpTemplate(contractID); - - } - - @Test - public void testSerialize_DataAccountRegisterOperation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, DataAccountRegisterOperation.class); - DataAccountRegisterOperation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getAccountID().getAddress(), data.getAccountID().getAddress()); - assertEquals(resolvedData.getAccountID().getPubKey(), data.getAccountID().getPubKey()); - - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_Operation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, Operation.class); - Operation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - System.out.println("serialBytesLength=" + serialBytes.length); - System.out.println(resolvedData); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DigitalSignatureBlobTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DigitalSignatureBlobTest.java deleted file mode 100644 index 068a4040..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DigitalSignatureBlobTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.DigitalSignatureBlobTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 下午2:12 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.DigitalSignatureBody; -import com.jd.blockchain.transaction.DigitalSignatureBlob; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class DigitalSignatureBlobTest { - - private DigitalSignatureBlob data; - - @Before - public void initDigitalSignatureBlob() throws Exception { - DataContractRegistry.register(DigitalSignature.class); - DataContractRegistry.register(DigitalSignatureBody.class); - SignatureFunction signFunc = Crypto.getSignatureFunction("ED25519"); - AsymmetricKeypair kp = signFunc.generateKeypair(); - PubKey pubKey = kp.getPubKey(); - - SignatureDigest digest = signFunc.sign(kp.getPrivKey(), "zhangsan".getBytes()); - data = new DigitalSignatureBlob(pubKey, digest); - } - - @Test - public void testSerialize_DigitalSignature() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, DigitalSignature.class); - DigitalSignature resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getDigest(), data.getDigest()); - assertEquals(resolvedData.getPubKey(), data.getPubKey()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_DigitalSignatureBody() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, DigitalSignatureBody.class); - DigitalSignatureBody resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getDigest(), data.getDigest()); - assertEquals(resolvedData.getPubKey(), data.getPubKey()); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ED25519SignatureTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ED25519SignatureTest.java deleted file mode 100644 index a9a187ab..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ED25519SignatureTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import java.util.Random; - -import org.junit.Test; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.utils.security.Ed25519Utils; - -public class ED25519SignatureTest { - -// @Test - public void perfomanceTest() { - Random rand = new Random(); - byte[] data = new byte[64]; - rand.nextBytes(data); - - SignatureFunction signFunc = Crypto.getSignatureFunction("ED25519"); - AsymmetricKeypair key = signFunc.generateKeypair(); - byte[] pubKey = key.getPubKey().getRawKeyBytes(); - byte[] privKey = key.getPrivKey().getRawKeyBytes(); - - int count = 10000; - - System.out.println("=================== do sign test ==================="); - byte[] sign = null; - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sign = Ed25519Utils.sign_512(data, privKey); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("Siging Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - Ed25519Utils.verify(data, pubKey, sign); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/IntegerToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/IntegerToBytesValueResolverTest.java deleted file mode 100644 index dd9d4632..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/IntegerToBytesValueResolverTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.ledger.resolver.IntegerToBytesValueResolver; -import static org.junit.Assert.*; - -import com.jd.blockchain.utils.Bytes; -import org.junit.Test; - -public class IntegerToBytesValueResolverTest { - - private IntegerToBytesValueResolver resolver = new IntegerToBytesValueResolver(); - - @Test - public void test() { - int intVal = 1024; - - BytesValue intBytesValue = resolver.encode(intVal); - - BytesValue intBytesValue1 = resolver.encode(intVal, int.class); - - BytesValue intBytesValue2 = resolver.encode(intVal, Integer.class); - - assertEquals(intBytesValue.getBytes(), intBytesValue1.getBytes()); - - assertEquals(intBytesValue.getBytes(), intBytesValue2.getBytes()); - - Bytes intBytes = Bytes.fromInt(intVal); - - assertEquals(intBytes, intBytesValue.getBytes()); - - assertEquals(intBytesValue.getType(), DataType.INT32); - - int resolveInt = (int)resolver.decode(intBytesValue); - - assertEquals(intVal, resolveInt); - - short resolveShort = (short) resolver.decode(intBytesValue, short.class); - assertEquals(resolveShort, 1024); - Short resolveShortObj = (Short) resolver.decode(intBytesValue, Short.class); - assertEquals((short)resolveShortObj, resolveShort); - - long resolveLong = (long) resolver.decode(intBytesValue, long.class); - assertEquals(resolveLong, 1024L); - - Long resolveLongObj = (Long) resolver.decode(intBytesValue, Long.class); - assertEquals(resolveLong, (long) resolveLongObj); - - } -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/KVDataTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/KVDataTest.java deleted file mode 100644 index 3d54f16c..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/KVDataTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.KVDataTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午11:08 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.TypedValue; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.transaction.DataAccountKVSetOpTemplate; -import com.jd.blockchain.transaction.KVData; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class KVDataTest { - private KVData kvData; - - @Before - public void initKVData() throws Exception { - DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class); - String key = "test-key"; - byte[] value = "test-value".getBytes(); - long expectedVersion = 9999L; - - kvData = new KVData(key, TypedValue.fromBytes(value), expectedVersion); - } - - @Test - public void testSerialize_KVEntry() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(kvData, DataAccountKVSetOperation.KVWriteEntry.class); - DataAccountKVSetOpTemplate.KVWriteEntry resolvedKvData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedKvData.getKey(), kvData.getKey()); - assertEquals(resolvedKvData.getExpectedVersion(), kvData.getExpectedVersion()); - assertArrayEquals(resolvedKvData.getValue().getBytes().toBytes(), kvData.getValue().getBytes().toBytes()); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LedgerInitPropertiesTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LedgerInitPropertiesTest.java deleted file mode 100644 index ea17f4d2..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LedgerInitPropertiesTest.java +++ /dev/null @@ -1,203 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.RoleInitData; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.utils.codec.HexUtils; - -public class LedgerInitPropertiesTest { - - - static { - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - } - - public static final String PASSWORD = "abc"; - - public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; - - public static final String[] PRIV_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - - - private static String expectedCreatedTimeStr = "2019-08-01 14:26:58.069+0800"; - - private static String expectedCreatedTimeStr1 = "2019-08-01 13:26:58.069+0700"; - - @Test - public void testTimeFormat() throws ParseException { - SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); - timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); - // 或者设置全局的默认时区; - // TimeZone.setDefault(TimeZone.getTimeZone("GMT+08:00")); - - Date time = timeFormat.parse(expectedCreatedTimeStr); - String actualTimeStr = timeFormat.format(time); - assertEquals(expectedCreatedTimeStr, actualTimeStr); - - Date time1 = timeFormat.parse(expectedCreatedTimeStr1); - String actualTimeStr1 = timeFormat.format(time1); - assertEquals(expectedCreatedTimeStr, actualTimeStr1); - } - - @Test - public void testProperties() throws IOException, ParseException { - // 加载用于测试的账本初始化配置; - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger.init"); - InputStream in = ledgerInitSettingResource.getInputStream(); - try { - LedgerInitProperties initProps = LedgerInitProperties.resolve(in); - - // 验证账本信息; - String expectedLedgerSeed = "932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe" - .replace("-", ""); - String actualLedgerSeed = HexUtils.encode(initProps.getLedgerSeed()); - assertEquals(expectedLedgerSeed, actualLedgerSeed); - - SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); - timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); - long expectedTs = timeFormat.parse(expectedCreatedTimeStr).getTime(); - assertEquals(expectedTs, initProps.getCreatedTime()); - - String createdTimeStr = timeFormat.format(new Date(initProps.getCreatedTime())); - assertEquals(expectedCreatedTimeStr, createdTimeStr); - - // 验证角色配置; - RoleInitData[] roles = initProps.getRoles(); - assertEquals(4, roles.length); - Map rolesInitDatas = new HashMap(); - for (RoleInitData r : roles) { - rolesInitDatas.put(r.getRoleName(), r); - } - // 初始化配置的角色最终也是有序排列的,按照角色名称的自然顺序; - String[] expectedRolesNames = { "DEFAULT", "ADMIN", "MANAGER", "GUEST" }; - Arrays.sort(expectedRolesNames); - assertEquals(expectedRolesNames[0], roles[0].getRoleName()); - assertEquals(expectedRolesNames[1], roles[1].getRoleName()); - assertEquals(expectedRolesNames[2], roles[2].getRoleName()); - assertEquals(expectedRolesNames[3], roles[3].getRoleName()); - - RoleInitData roleDefault = rolesInitDatas.get("DEFAULT"); - assertArrayEquals( - new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, - roleDefault.getLedgerPermissions()); - assertArrayEquals(new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, - TransactionPermission.CONTRACT_OPERATION }, roleDefault.getTransactionPermissions()); - - RoleInitData roleAdmin = rolesInitDatas.get("ADMIN"); - assertArrayEquals( - new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.AUTHORIZE_USER_ROLES, - LedgerPermission.SET_CONSENSUS, LedgerPermission.SET_CRYPTO, - LedgerPermission.REGISTER_PARTICIPANT, LedgerPermission.REGISTER_USER }, - roleAdmin.getLedgerPermissions()); - assertArrayEquals(new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION }, - roleAdmin.getTransactionPermissions()); - - RoleInitData roleManager = rolesInitDatas.get("MANAGER"); - assertArrayEquals( - new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.AUTHORIZE_USER_ROLES, - LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT, - LedgerPermission.REGISTER_CONTRACT, LedgerPermission.UPGRADE_CONTRACT, - LedgerPermission.SET_USER_ATTRIBUTES, LedgerPermission.WRITE_DATA_ACCOUNT }, - roleManager.getLedgerPermissions()); - assertArrayEquals(new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, - TransactionPermission.CONTRACT_OPERATION }, roleManager.getTransactionPermissions()); - - RoleInitData roleGuest = rolesInitDatas.get("GUEST"); - assertTrue(roleGuest.getLedgerPermissions() == null || roleGuest.getLedgerPermissions().length == 0); - assertArrayEquals(new TransactionPermission[] { TransactionPermission.CONTRACT_OPERATION }, - roleGuest.getTransactionPermissions()); - - // 验证共识和密码配置; - assertEquals("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider", - initProps.getConsensusProvider()); - - String[] cryptoProviders = initProps.getCryptoProperties().getProviders(); - assertEquals(2, cryptoProviders.length); - assertEquals("com.jd.blockchain.crypto.service.classic.ClassicCryptoService", cryptoProviders[0]); - assertEquals("com.jd.blockchain.crypto.service.sm.SMCryptoService", cryptoProviders[1]); - - // 验证参与方信息; - assertEquals(4, initProps.getConsensusParticipantCount()); - - ParticipantProperties part0 = initProps.getConsensusParticipant(0); - assertEquals("jd.com", part0.getName()); - PubKey pubKey0 = KeyGenUtils.decodePubKey("3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9"); - assertEquals(pubKey0, part0.getPubKey()); - assertEquals("127.0.0.1", part0.getInitializerAddress().getHost()); - assertEquals(8800, part0.getInitializerAddress().getPort()); - assertEquals(true, part0.getInitializerAddress().isSecure()); - assertArrayEquals(new String[] { "ADMIN", "MANAGER" }, part0.getRoles()); - assertEquals(RolesPolicy.UNION, part0.getRolesPolicy()); - - ParticipantProperties part1 = initProps.getConsensusParticipant(1); - assertEquals(false, part1.getInitializerAddress().isSecure()); - PubKey pubKey1 = KeyGenUtils.decodePubKey("3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX"); - assertEquals(pubKey1, part1.getPubKey()); - assertArrayEquals(new String[] { "MANAGER" }, part1.getRoles()); - assertEquals(RolesPolicy.UNION, part1.getRolesPolicy()); - - ParticipantProperties part2 = initProps.getConsensusParticipant(2); - assertEquals("7VeRAr3dSbi1xatq11ZcF7sEPkaMmtZhV9shonGJWk9T4pLe", part2.getPubKey().toBase58()); - assertArrayEquals(new String[] { "MANAGER" }, part2.getRoles()); - assertEquals(RolesPolicy.UNION, part2.getRolesPolicy()); - - ParticipantProperties part3 = initProps.getConsensusParticipant(3); - PubKey pubKey3 = KeyGenUtils.decodePubKey("3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk"); - assertEquals(pubKey3, part3.getPubKey()); - assertArrayEquals(new String[] { "GUEST" }, part3.getRoles()); - assertEquals(RolesPolicy.INTERSECT, part3.getRolesPolicy()); - - } finally { - in.close(); - } - } - - @Test - public void testPubKeyAddress() { - String[] pubKeys = PUB_KEYS; - int index = 0; - for (String pubKeyStr : pubKeys) { - System.out.println("[" + index + "][配置] = " + pubKeyStr); - PubKey pubKey = KeyGenUtils.decodePubKey(pubKeyStr); - System.out.println("[" + index + "][公钥Base58] = " + pubKey.toBase58()); - System.out.println("[" + index + "][地址] = " + AddressEncoding.generateAddress(pubKey).toBase58()); - System.out.println("--------------------------------------------------------------------"); - index++; - } - } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LongToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LongToBytesValueResolverTest.java deleted file mode 100644 index b4d20b4c..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LongToBytesValueResolverTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.ledger.resolver.IntegerToBytesValueResolver; -import com.jd.blockchain.ledger.resolver.LongToBytesValueResolver; -import com.jd.blockchain.utils.Bytes; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class LongToBytesValueResolverTest { - - private LongToBytesValueResolver resolver = new LongToBytesValueResolver(); - - @Test - public void test() { - long longVal = 65536L; - - BytesValue longBytesValue = resolver.encode(longVal); - - BytesValue longBytesValue1 = resolver.encode(longVal, long.class); - - BytesValue longBytesValue2 = resolver.encode(longVal, Long.class); - - assertEquals(longBytesValue.getBytes(), longBytesValue1.getBytes()); - - assertEquals(longBytesValue.getBytes(), longBytesValue2.getBytes()); - - Bytes longBytes = Bytes.fromLong(longVal); - - assertEquals(longBytes, longBytesValue.getBytes()); - - assertEquals(longBytesValue.getType(), DataType.INT64); - - long resolveLong = (long)resolver.decode(longBytesValue); - - assertEquals(longVal, resolveLong); - - short resolveShort = (short) resolver.decode(longBytesValue, short.class); - assertEquals(resolveShort, (short)65536); - - Short resolveShortObj = (Short) resolver.decode(longBytesValue, Short.class); - assertEquals((short)resolveShortObj, resolveShort); - - int resolveInt = (int) resolver.decode(longBytesValue, int.class); - assertEquals(resolveInt, 65536); - - Integer resolveIntObj = (Integer) resolver.decode(longBytesValue, Integer.class); - assertEquals(resolveInt, (int) resolveIntObj); - } -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContract.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContract.java deleted file mode 100644 index 12324b42..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContract.java +++ /dev/null @@ -1,58 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEvent; - -@Contract(name="NORMAL-CONTRACT") -public interface NormalContract { - - /** - * 发行资产; - * - * @param asset 资产代码; - * @param amount 本次发行的资产数量; - * @return 资产总量; - */ - @ContractEvent(name="issue") - long issue(String asset, long amount); - - /** - * 获取资产总量; - * - * @param asset - * @return - */ - @ContractEvent(name="get_amount") - long getAmount(String asset); - - /** - * 获取资产余额; - * - * @param address - * @param asset - * @return - */ - @ContractEvent(name="get_balance") - long getBalance(String address, String asset); - - /** - * 向账户分配资产; - * - * @param address - * @param asset - * @param amount - */ - @ContractEvent(name="assign") - void assign(String address, String asset, int amount); - - /** - * 转移资产; - * - * @param fromAddress - * @param toAddress - * @param asset - * @param amount - */ - @ContractEvent(name="transfer") - void transfer(String fromAddress, String toAddress, String asset, long amount); -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContractImpl.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContractImpl.java deleted file mode 100644 index d2ba8714..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContractImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -package test.com.jd.blockchain.ledger; - -public class NormalContractImpl implements NormalContract{ - - @Override - public long issue(String asset, long amount) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public long getAmount(String asset) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public long getBalance(String address, String asset) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void assign(String address, String asset, int amount) { - // TODO Auto-generated method stub - - } - - @Override - public void transfer(String fromAddress, String toAddress, String asset, long amount) { - // TODO Auto-generated method stub - - } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/PrivilegesTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/PrivilegesTest.java deleted file mode 100644 index 10f964c0..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/PrivilegesTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.PrivilegeSet; -import com.jd.blockchain.ledger.Privileges; -import com.jd.blockchain.ledger.TransactionPermission; - -public class PrivilegesTest { - - @Test - public void test() { - // 正常情形; - { - Privileges privileges = Privileges.configure() - .enable(LedgerPermission.REGISTER_USER, LedgerPermission.APPROVE_TX) - .enable(TransactionPermission.DIRECT_OPERATION); - - byte[] bytes = BinaryProtocol.encode(privileges, PrivilegeSet.class); - - PrivilegeSet decodePrivileges = BinaryProtocol.decode(bytes); - - assertNotNull(decodePrivileges.getLedgerPrivilege()); - assertNotNull(decodePrivileges.getTransactionPrivilege()); - - for (LedgerPermission p : LedgerPermission.values()) { - if (p == LedgerPermission.REGISTER_USER || p == LedgerPermission.APPROVE_TX) { - assertTrue(decodePrivileges.getLedgerPrivilege().isEnable(p)); - } else { - assertFalse(decodePrivileges.getLedgerPrivilege().isEnable(p)); - } - } - for (TransactionPermission p : TransactionPermission.values()) { - if (p == TransactionPermission.DIRECT_OPERATION) { - assertTrue(decodePrivileges.getTransactionPrivilege().isEnable(p)); - } else { - assertFalse(decodePrivileges.getTransactionPrivilege().isEnable(p)); - } - } - } - // 只定义账本权限的情形; - { - Privileges privileges = Privileges.configure().enable(LedgerPermission.REGISTER_USER, - LedgerPermission.APPROVE_TX); - - byte[] bytes = BinaryProtocol.encode(privileges, PrivilegeSet.class); - - PrivilegeSet decodePrivileges = BinaryProtocol.decode(bytes); - - assertNotNull(decodePrivileges.getLedgerPrivilege()); - assertNotNull(decodePrivileges.getTransactionPrivilege()); - - for (LedgerPermission p : LedgerPermission.values()) { - if (p == LedgerPermission.REGISTER_USER || p == LedgerPermission.APPROVE_TX) { - assertTrue(decodePrivileges.getLedgerPrivilege().isEnable(p)); - } else { - assertFalse(decodePrivileges.getLedgerPrivilege().isEnable(p)); - } - } - for (TransactionPermission p : TransactionPermission.values()) { - assertFalse(decodePrivileges.getTransactionPrivilege().isEnable(p)); - } - } - // 只定义交易权限的情形; - { - Privileges privileges = Privileges.configure().enable(TransactionPermission.CONTRACT_OPERATION); - - byte[] bytes = BinaryProtocol.encode(privileges, PrivilegeSet.class); - - PrivilegeSet decodePrivileges = BinaryProtocol.decode(bytes); - - assertNotNull(decodePrivileges.getLedgerPrivilege()); - assertNotNull(decodePrivileges.getTransactionPrivilege()); - - for (LedgerPermission p : LedgerPermission.values()) { - assertFalse(decodePrivileges.getLedgerPrivilege().isEnable(p)); - } - for (TransactionPermission p : TransactionPermission.values()) { - if (p == TransactionPermission.CONTRACT_OPERATION) { - assertTrue(decodePrivileges.getTransactionPrivilege().isEnable(p)); - } else { - assertFalse(decodePrivileges.getTransactionPrivilege().isEnable(p)); - } - } - } - } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SecurityInitDataTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SecurityInitDataTest.java deleted file mode 100644 index c573fcf6..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SecurityInitDataTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.SecurityInitData; -import com.jd.blockchain.ledger.SecurityInitSettings; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; - -public class SecurityInitDataTest { - - @Test - public void testEnumsSerialization() { - LedgerPermission[] permissions = JSONSerializeUtils.deserializeFromJSON("[\"REGISTER_USER\",\"REGISTER_DATA_ACCOUNT\"]", LedgerPermission[].class); - assertNotNull(permissions); - assertEquals(2, permissions.length); - assertEquals(LedgerPermission.REGISTER_USER, permissions[0]); - assertEquals(LedgerPermission.REGISTER_DATA_ACCOUNT, permissions[1]); - - LedgerPermission[] permissions2 = JSONSerializeUtils.deserializeFromJSON("['REGISTER_USER', 'REGISTER_DATA_ACCOUNT']", LedgerPermission[].class); - assertNotNull(permissions2); - assertEquals(2, permissions2.length); - assertEquals(LedgerPermission.REGISTER_USER, permissions2[0]); - assertEquals(LedgerPermission.REGISTER_DATA_ACCOUNT, permissions2[1]); - - LedgerPermission[] allLedgerPermissions = LedgerPermission.values(); - String jsonLedgerPersioms = JSONSerializeUtils.serializeToJSON(allLedgerPermissions); - - TransactionPermission[] allTransactionPermissions = TransactionPermission.values(); - String jsonTransactionPersioms = JSONSerializeUtils.serializeToJSON(allTransactionPermissions); - - System.out.println("----------- Ledger Permissions JSON ------------"); - System.out.println(jsonLedgerPersioms); - System.out.println("-----------------------"); - System.out.println("----------- Transaction Permissions JSON ------------"); - System.out.println(jsonTransactionPersioms); - System.out.println("-----------------------"); - } - - @Test - public void testSecurityInitDataSerialization() { - - SecurityInitData securityInitData = new SecurityInitData(); - - securityInitData.addRole("DEFAULT", - new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, - new TransactionPermission[] { TransactionPermission.CONTRACT_OPERATION }); - securityInitData.addRole("ADMIN", - new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, - new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, - TransactionPermission.CONTRACT_OPERATION }); - securityInitData.addRole("R1", - new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, - null); - securityInitData.addRole("R2", null, new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, - TransactionPermission.CONTRACT_OPERATION }); - - String json = JSONSerializeUtils.serializeToJSON(securityInitData, true); - System.out.println("----------- JSON ------------"); - System.out.println(json); - System.out.println("-----------------------"); - - SecurityInitData desSecurityInitData = JSONSerializeUtils.deserializeFromJSON(json, SecurityInitData.class); - - String json2 = JSONSerializeUtils.serializeToJSON(desSecurityInitData, true); - System.out.println("----------- JSON2 ------------"); - System.out.println(json2); - System.out.println("-----------------------"); - - assertEquals(json, json2); - - byte[] bytes = BinaryProtocol.encode(securityInitData, SecurityInitSettings.class); - - SecurityInitSettings securityInitData2 = BinaryProtocol.decode(bytes); - - byte[] bytes2 = BinaryProtocol.encode(securityInitData2, SecurityInitSettings.class); - - assertArrayEquals(bytes, bytes2); - - assertEquals(4, securityInitData2.getRoles().length); - assertEquals(securityInitData.getRoles().length, securityInitData2.getRoles().length); - assertEquals(LedgerPermission.REGISTER_USER, securityInitData2.getRoles()[1].getLedgerPermissions()[0]); - assertEquals(securityInitData.getRoles()[1].getLedgerPermissions()[0], securityInitData2.getRoles()[1].getLedgerPermissions()[0]); - assertEquals(securityInitData.getRoles()[1].getLedgerPermissions()[1], securityInitData2.getRoles()[1].getLedgerPermissions()[1]); - - } - -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ShortToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ShortToBytesValueResolverTest.java deleted file mode 100644 index 2e8e46be..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ShortToBytesValueResolverTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.ledger.resolver.ShortToBytesValueResolver; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class ShortToBytesValueResolverTest { - - private ShortToBytesValueResolver resolver = new ShortToBytesValueResolver(); - - @Test - public void test() { - short shortVal = 64; - - BytesValue shortBytesValue = resolver.encode(shortVal); - - Bytes shortBytes = new Bytes(BytesUtils.toBytes(shortVal)); - - assertEquals(shortBytes, shortBytesValue.getBytes()); - - assertEquals(shortBytesValue.getType(), DataType.INT16); - - short resolveShort = (short)resolver.decode(shortBytesValue); - - assertEquals(shortVal, resolveShort); - - int resolveInt = (int) resolver.decode(shortBytesValue, int.class); - assertEquals(resolveInt, 64); - Integer resolveIntObj = (Integer) resolver.decode(shortBytesValue, Integer.class); - assertEquals((int)resolveIntObj, resolveShort); - - long resolveLong = (long) resolver.decode(shortBytesValue, long.class); - assertEquals(resolveLong, 64L); - - Long resolveLongObj = (Long) resolver.decode(shortBytesValue, Long.class); - assertEquals(resolveLong, (long) resolveLongObj); - } -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/StringToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/StringToBytesValueResolverTest.java deleted file mode 100644 index 544f06bb..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/StringToBytesValueResolverTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import com.alibaba.fastjson.JSON; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.ledger.resolver.StringToBytesValueResolver; -import com.jd.blockchain.utils.Bytes; -import static org.junit.Assert.*; - -import com.jd.blockchain.utils.io.BytesUtils; -import org.junit.Test; - -public class StringToBytesValueResolverTest { - - private StringToBytesValueResolver resolver = new StringToBytesValueResolver(); - - @Test - public void testText() { - String textVal = "JDChain"; - - BytesValue textBytesValue = resolver.encode(textVal); - - assertEquals(Bytes.fromString(textVal), textBytesValue.getBytes()); - - assertEquals(textBytesValue.getType(), DataType.TEXT); - - String resolveText = (String)resolver.decode(textBytesValue); - - assertEquals(resolveText, textVal); - - byte[] resolveBytes = (byte[]) resolver.decode(textBytesValue, byte[].class); - - assertArrayEquals(resolveBytes, BytesUtils.toBytes(textVal)); - - Bytes resolveBytesObj = (Bytes) resolver.decode(textBytesValue, Bytes.class); - - assertEquals(resolveBytesObj, Bytes.fromString(textVal)); - - } - - @Test - public void testJson() { - Person person = new Person("zhangsan", 80); - String personJson = JSON.toJSONString(person); - BytesValue textBytesValue = resolver.encode(personJson); - assertEquals(Bytes.fromString(personJson), textBytesValue.getBytes()); - assertEquals(textBytesValue.getType(), DataType.JSON); - } - - public static class Person { - private String name; - - private int age; - - public Person() { - } - - public Person(String name, int age) { - this.name = name; - this.age = age; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - } -} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxRequestMessageTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxRequestMessageTest.java deleted file mode 100644 index 533eb0b7..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxRequestMessageTest.java +++ /dev/null @@ -1,210 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.TxRequestMessageTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/3 下午3:07 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertEquals; - -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.EndpointRequest; -import com.jd.blockchain.ledger.HashObject; -import com.jd.blockchain.ledger.NodeRequest; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.transaction.BlockchainOperationFactory; -import com.jd.blockchain.transaction.DigitalSignatureBlob; -import com.jd.blockchain.transaction.TxContentBlob; -import com.jd.blockchain.transaction.TxRequestMessage; - -/** - * - * @author shaozhuguang - * @create 2018/9/3 - * @since 1.0.0 - */ - -public class TxRequestMessageTest { - - private TxRequestMessage data; - - @Before - public void initTxRequestMessage() throws Exception { - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(HashObject.class); - - data = new TxRequestMessage(initTransactionContent()); - - SignatureFunction signFunc = Crypto.getSignatureFunction("ED25519"); - AsymmetricKeypair key1 = signFunc.generateKeypair(); - AsymmetricKeypair key2 = signFunc.generateKeypair(); - AsymmetricKeypair key3 = signFunc.generateKeypair(); - AsymmetricKeypair key4 = signFunc.generateKeypair(); - - SignatureDigest digest1 = signFunc.sign(key1.getPrivKey(), "zhangsan".getBytes()); - SignatureDigest digest2 = signFunc.sign(key2.getPrivKey(), "lisi".getBytes()); - DigitalSignatureBlob endPoint1 = new DigitalSignatureBlob(key1.getPubKey(), digest1); - DigitalSignatureBlob endPoint2 = new DigitalSignatureBlob(key2.getPubKey(), digest2); - data.addEndpointSignatures(endPoint1); - data.addEndpointSignatures(endPoint2); - - SignatureDigest digest3 = signFunc.sign(key3.getPrivKey(), "wangwu".getBytes()); - SignatureDigest digest4 = signFunc.sign(key4.getPrivKey(), "zhaoliu".getBytes()); - DigitalSignatureBlob node1 = new DigitalSignatureBlob(key3.getPubKey(), digest3); - DigitalSignatureBlob node2 = new DigitalSignatureBlob(key4.getPubKey(), digest4); - data.addNodeSignatures(node1); - data.addNodeSignatures(node2); - - HashDigest hash = Crypto.getHashFunction("SHA256").hash("DATA".getBytes()); - data.setHash(hash); - } - - @Test - public void testSerialize_TransactionRequest() { - byte[] serialBytes = BinaryProtocol.encode(data, TransactionRequest.class); - TransactionRequest resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getEndpointSignatures().length, data.getEndpointSignatures().length); - assertEquals(resolvedData.getNodeSignatures().length, data.getNodeSignatures().length); - - // EndpointSignatures 验证 - DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures(); - DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures(); - for (int i = 0; i < dataEndpointSignatures.length; i++) { - assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey()); - assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest()); - } - - // NodeSignatures 验证 - DigitalSignature[] dataNodeSignatures = data.getNodeSignatures(); - DigitalSignature[] resolvedNodeSignatures = resolvedData.getNodeSignatures(); - for (int i = 0; i < dataNodeSignatures.length; i++) { - assertEquals(dataNodeSignatures[i].getPubKey(), resolvedNodeSignatures[i].getPubKey()); - assertEquals(dataNodeSignatures[i].getDigest(), resolvedNodeSignatures[i].getDigest()); - } - - TransactionContent dataTxContent = data.getTransactionContent(); - TransactionContent resolvedTxContent = data.getTransactionContent(); - - Operation[] dataOperations = dataTxContent.getOperations(); - Operation[] resolvedOperations = resolvedTxContent.getOperations(); - assertEquals(dataOperations.length, resolvedOperations.length); - for (int i = 0; i < dataOperations.length; i++) { - assertEquals(dataOperations[i], resolvedOperations[i]); - } - assertEqual(dataTxContent, resolvedTxContent); - - assertEquals(resolvedData.getHash(), data.getHash()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_NodeRequest() { - byte[] serialBytes = BinaryProtocol.encode(data, NodeRequest.class); - NodeRequest resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getEndpointSignatures().length, data.getEndpointSignatures().length); - assertEquals(resolvedData.getNodeSignatures().length, data.getNodeSignatures().length); - - // EndpointSignatures 验证 - DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures(); - DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures(); - for (int i = 0; i < dataEndpointSignatures.length; i++) { - assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey()); - assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest()); - } - - // NodeSignatures 验证 - DigitalSignature[] dataNodeSignatures = data.getNodeSignatures(); - DigitalSignature[] resolvedNodeSignatures = resolvedData.getNodeSignatures(); - for (int i = 0; i < dataNodeSignatures.length; i++) { - assertEquals(dataNodeSignatures[i].getPubKey(), resolvedNodeSignatures[i].getPubKey()); - assertEquals(dataNodeSignatures[i].getDigest(), resolvedNodeSignatures[i].getDigest()); - } - - TransactionContent dataTxContent = data.getTransactionContent(); - TransactionContent resolvedTxContent = data.getTransactionContent(); - - Operation[] dataOperations = dataTxContent.getOperations(); - Operation[] resolvedOperations = resolvedTxContent.getOperations(); - assertEquals(dataOperations.length, resolvedOperations.length); - for (int i = 0; i < dataOperations.length; i++) { - assertEquals(dataOperations[i], resolvedOperations[i]); - } - assertEqual(dataTxContent, resolvedTxContent); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_EndpointRequest() { - byte[] serialBytes = BinaryProtocol.encode(data, EndpointRequest.class); - EndpointRequest resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getEndpointSignatures().length, data.getEndpointSignatures().length); - DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures(); - DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures(); - for (int i = 0; i < dataEndpointSignatures.length; i++) { - assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey()); - assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest()); - } - TransactionContent dataTxContent = data.getTransactionContent(); - TransactionContent resolvedTxContent = data.getTransactionContent(); - - Operation[] dataOperations = dataTxContent.getOperations(); - Operation[] resolvedOperations = resolvedTxContent.getOperations(); - assertEquals(dataOperations.length, resolvedOperations.length); - for (int i = 0; i < dataOperations.length; i++) { - assertEquals(dataOperations[i], resolvedOperations[i]); - } - assertEqual(dataTxContent, resolvedTxContent); - System.out.println("------Assert OK ------"); - } - - private void assertEqual(TransactionContent dataTxContent, TransactionContent resolvedTxContent) { - assertEquals(dataTxContent.getHash(), resolvedTxContent.getHash()); - assertEquals(dataTxContent.getLedgerHash(), resolvedTxContent.getLedgerHash()); - // assertEquals(dataTxContent.getSequenceNumber(), - // resolvedTxContent.getSequenceNumber()); - // assertEquals(dataTxContent.getSubjectAccount(), - // resolvedTxContent.getSubjectAccount()); - } - - private TransactionContent initTransactionContent() throws Exception { - TxContentBlob contentBlob = null; - BlockchainKeypair id = BlockchainKeyGenerator.getInstance().generate("ED25519"); - HashFunction hashFunc = Crypto.getHashFunction("SHA256"); - HashDigest ledgerHash = hashFunc.hash(UUID.randomUUID().toString().getBytes("UTF-8")); - BlockchainOperationFactory opFactory = new BlockchainOperationFactory(); - contentBlob = new TxContentBlob(ledgerHash); - contentBlob.setHash(hashFunc.hash("jd.com".getBytes())); - // contentBlob.setSubjectAccount(id.getAddress()); - // contentBlob.setSequenceNumber(1); - DataAccountKVSetOperation kvsetOP = opFactory.dataAccount(id.getAddress()) - .setText("Name","AAA", -1).getOperation(); - contentBlob.addOperation(kvsetOP); - return contentBlob; - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxResponseMessageTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxResponseMessageTest.java deleted file mode 100644 index bcd50191..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxResponseMessageTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.TxResponseMessageTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/6 上午11:00 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.transaction.TxResponseMessage; - -/** - * - * @author shaozhuguang - * @create 2018/9/6 - * @since 1.0.0 - */ - -public class TxResponseMessageTest { - - private TxResponseMessage data; - - @Before - public void initTxRequestMessage() throws Exception { - DataContractRegistry.register(TransactionResponse.class); - HashFunction hashFunc = Crypto.getHashFunction("SHA256"); - HashDigest contentHash = hashFunc.hash("jd-content".getBytes()); - - HashDigest blockHash = hashFunc.hash("jd-block".getBytes()); - - long blockHeight = 9999L; - data = new TxResponseMessage(contentHash); - data.setBlockHash(blockHash); - data.setBlockHeight(blockHeight); - data.setExecutionState(TransactionState.SUCCESS); - } - - @Test - public void testSerialize_TransactionResponse() { - byte[] serialBytes = BinaryProtocol.encode(data, TransactionResponse.class); - TransactionResponse resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(resolvedData.getBlockHash(), data.getBlockHash()); - assertEquals(resolvedData.getBlockHeight(), data.getBlockHeight()); - assertEquals(resolvedData.getContentHash(), data.getContentHash()); - assertEquals(resolvedData.getExecutionState(), data.getExecutionState()); - assertEquals(resolvedData.isSuccess(), data.isSuccess()); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/UserRegisterOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/UserRegisterOpTemplateTest.java deleted file mode 100644 index 95be8d5c..00000000 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/UserRegisterOpTemplateTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.ledger.data.UserRegisterOpTemplateTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/8/30 上午11:04 - * Description: - */ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainIdentityData; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.transaction.UserRegisterOpTemplate; - -/** - * - * @author shaozhuguang - * @create 2018/8/30 - * @since 1.0.0 - */ - -public class UserRegisterOpTemplateTest { - - private UserRegisterOpTemplate data; - - @Before - public void initUserRegisterOpTemplate() { - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(Operation.class); - AsymmetricKeypair key = Crypto.getSignatureFunction("ED25519").generateKeypair(); - PubKey pubKey = key.getPubKey(); - BlockchainIdentity contractID = new BlockchainIdentityData(pubKey); - data = new UserRegisterOpTemplate(contractID); - } - - @Test - public void testSerialize_UserRegisterOperation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, UserRegisterOperation.class); - UserRegisterOperation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - assertEquals(data.getUserID().getAddress(), resolvedData.getUserID().getAddress()); - assertEquals(data.getUserID().getPubKey(), resolvedData.getUserID().getPubKey()); - System.out.println("------Assert OK ------"); - } - - @Test - public void testSerialize_Operation() throws Exception { - byte[] serialBytes = BinaryProtocol.encode(data, Operation.class); - Operation resolvedData = BinaryProtocol.decode(serialBytes); - System.out.println("------Assert start ------"); - System.out.println("serialBytesLength=" + serialBytes.length); - System.out.println(resolvedData); - System.out.println("------Assert OK ------"); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/resources/bftsmart.config b/source/ledger/ledger-model/src/test/resources/bftsmart.config deleted file mode 100644 index df69caf5..00000000 --- a/source/ledger/ledger-model/src/test/resources/bftsmart.config +++ /dev/null @@ -1,144 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#Configuration of all node servers; -#PubKey of node server with specified ID, with base58 encoding. -system.server.0.pubkey= -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=8900 -system.server.0.network.secure=false - -system.server.1.pubkey= -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=8910 -system.server.1.network.secure=false - -system.server.2.pubkey= -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=8920 -system.server.2.network.secure=false - -system.server.3.pubkey= -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=8920 -system.server.3.network.secure=false diff --git a/source/ledger/ledger-model/src/test/resources/keys/parti2.pub b/source/ledger/ledger-model/src/test/resources/keys/parti2.pub deleted file mode 100644 index dde44b8e..00000000 --- a/source/ledger/ledger-model/src/test/resources/keys/parti2.pub +++ /dev/null @@ -1 +0,0 @@ -3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/resources/ledger.init b/source/ledger/ledger-model/src/test/resources/ledger.init deleted file mode 100644 index 9ff0a35c..00000000 --- a/source/ledger/ledger-model/src/test/resources/ledger.init +++ /dev/null @@ -1,164 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name=test - -#声明账本的创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - - -#----------------------------------------------- -# 初始的角色名称列表;可选项; -# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; -# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; -# -# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; -# -security.roles=DEFAULT, ADMIN, MANAGER, GUEST - -# 赋予角色的账本权限清单;可选项; -# 可选的权限如下; -# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, -# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, -# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -# APPROVE_TX, CONSENSUS_TX -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT - -# 赋予角色的交易权限清单;可选项; -# 可选的权限如下; -# DIRECT_OPERATION, CONTRACT_OPERATION -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 其它角色的配置示例; -# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; -security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER -security.role.ADMIN.tx-privileges=DIRECT_OPERATION - -# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; -security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; -security.role.GUEST.ledger-privileges= -security.role.GUEST.tx-privileges=CONTRACT_OPERATION - - - -#----------------------------------------------- -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - -#从存储中加载账本数据时,是否校验哈希;可选; -crypto.verify-hash=true - -#哈希算法; -crypto.hash-algorithm=SHA256 - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的角色清单;可选项; -cons_parti.0.roles=ADMIN, MANAGER -#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.0.roles-policy=UNION -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=true -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=true - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的角色清单;可选项; -cons_parti.1.roles=MANAGER -#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.1.roles-policy=UNION -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=classpath:keys/parti2.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey= -#第2个参与方的角色清单;可选项; -cons_parti.2.roles=MANAGER -#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.2.roles-policy=UNION -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=true - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的角色清单;可选项; -cons_parti.3.roles=GUEST -#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.3.roles-policy=INTERSECT -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/BinaryMessageConverter.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/BinaryMessageConverter.java deleted file mode 100644 index 0814de76..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/BinaryMessageConverter.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.jd.blockchain.web.converters; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.ClientIdentifications; -import com.jd.blockchain.consensus.action.ActionRequest; -import com.jd.blockchain.consensus.action.ActionResponse; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.utils.io.BytesUtils; - -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.MediaType; -import org.springframework.http.converter.AbstractHttpMessageConverter; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.http.converter.HttpMessageNotWritableException; - -import com.jd.blockchain.binaryproto.BinaryProtocol; - -/** - * 针对二进制对象的序列化和反序列化的 HTTP 消息转换器; - * - * @author huanghaiquan - * - */ -public class BinaryMessageConverter extends AbstractHttpMessageConverter { - - public static final String CONTENT_TYPE_VALUE = "application/bin-obj;charset=UTF-8"; - - static { - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class); - - DataContractRegistry.register(Operation.class); - DataContractRegistry.register(ContractCodeDeployOperation.class); - DataContractRegistry.register(ContractEventSendOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - - DataContractRegistry.register(ActionRequest.class); - DataContractRegistry.register(ActionResponse.class); - DataContractRegistry.register(ClientIdentifications.class); - DataContractRegistry.register(ClientIdentification.class); - } - - public BinaryMessageConverter() { - super(MediaType.valueOf(CONTENT_TYPE_VALUE)); - } - - @Override - protected boolean supports(Class aClass) { - return true; - } - - @Override - protected boolean canRead(MediaType mediaType) { - if (mediaType == null) { - return false; - } - for (MediaType supportedMediaType : getSupportedMediaTypes()) { - if (supportedMediaType.includes(mediaType)) { - return true; - } - } - return false; - } - - @Override - protected boolean canWrite(MediaType mediaType) { - if (mediaType == null) { - return false; - } else if (MediaType.ALL.equals(mediaType)) { - return true; - } - for (MediaType supportedMediaType : getSupportedMediaTypes()) { - if (supportedMediaType.isCompatibleWith(mediaType)) { - return true; - } - } - return false; - } - - @Override - public Object readInternal(Class clazz, HttpInputMessage inputMessage) - throws IOException, HttpMessageNotReadableException { - InputStream in = inputMessage.getBody(); - byte[] serializeBytes = BytesUtils.readBytes(in); - Object resolvedObj = BinaryProtocol.decode(serializeBytes); - return resolvedObj; - } - - @Override - public void writeInternal(Object t, HttpOutputMessage outputMessage) - throws IOException, HttpMessageNotWritableException { - OutputStream out = outputMessage.getBody(); - if (t instanceof TransactionResponse) { - byte[] serializeBytes = BinaryProtocol.encode(t, TransactionResponse.class); - out.write(serializeBytes); - out.flush(); - } - } -} diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/BytesInputConverter.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/BytesInputConverter.java deleted file mode 100644 index 7223c718..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/BytesInputConverter.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.converters.HashDigestInputConverter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/11 下午5:05 - * Description: - */ -package com.jd.blockchain.web.converters; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.utils.codec.Base58Utils; - -import org.springframework.core.convert.converter.Converter; - -/** - * - * @author shaozhuguang - * @create 2018/9/11 - * @since 1.0.0 - */ - -public class BytesInputConverter implements Converter { - - @Override - public HashDigest convert(String inText) { - byte[] hashBytes = Base58Utils.decode(inText); - return new HashDigest(hashBytes); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/HashDigestInputConverter.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/HashDigestInputConverter.java deleted file mode 100644 index 5a2fec6e..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/converters/HashDigestInputConverter.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.peer.converters.HashDigestInputConverter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/27 下午2:51 - * Description: - */ -package com.jd.blockchain.web.converters; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.utils.codec.Base58Utils; - -import org.springframework.core.convert.converter.Converter; - -/** - * - * @author shaozhuguang - * @create 2018/9/27 - * @since 1.0.0 - */ - -public class HashDigestInputConverter implements Converter { - - @Override - public HashDigest convert(String inText) { - byte[] hashBytes = Base58Utils.decode(inText); - return new HashDigest(hashBytes); - } -} \ No newline at end of file diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonDeserializer.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonDeserializer.java deleted file mode 100644 index c0384183..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonDeserializer.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jd.blockchain.web.serializes; - -import com.alibaba.fastjson.parser.DefaultJSONParser; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesSlice; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Type; -import java.util.Map; - -public class ByteArrayObjectJsonDeserializer extends JavaBeanDeserializer { - - private ByteArrayObjectJsonDeserializer(Class clazz) { - super(ParserConfig.global, clazz); - } - - public static ByteArrayObjectJsonDeserializer getInstance(Class clazz) { - return new ByteArrayObjectJsonDeserializer(clazz); - } - - @SuppressWarnings("unchecked") - @Override - public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { - if (type instanceof Class && clazz.isAssignableFrom((Class) type)) { - String parseText = parser.parseObject(String.class); - byte[] hashBytes = Base58Utils.decode(parseText); - if (clazz == HashDigest.class) { - return (T) new HashDigest(hashBytes); - } else if (clazz == PubKey.class) { - return (T) new HashDigest(hashBytes); - } else if (clazz == SignatureDigest.class) { - return (T) new SignatureDigest(hashBytes); - } else if (clazz == Bytes.class) { - return (T) new Bytes(hashBytes); - } else if (clazz == BytesSlice.class) { - return (T) new BytesSlice(hashBytes); - } - -// else if (clazz == BytesValue.class) { -// ByteArrayObjectJsonSerializer.BytesValueJson valueJson = JSON.parseObject(parseText, ByteArrayObjectJsonSerializer.BytesValueJson.class); -// DataType dataType = valueJson.getType(); -// Object dataVal = valueJson.getValue(); -// byte[] bytes = null; -// switch (dataType) { -// case BYTES: -// bytes = ByteArray.fromHex((String) dataVal); -// break; -// case TEXT: -// bytes = ((String) dataVal).getBytes(); -// break; -// case INT64: -// bytes = BytesUtils.toBytes((Long) dataVal); -// break; -// case JSON: -// bytes = ((String) dataVal).getBytes(); -// break; -// } -// BytesValue bytesValue = new BytesValueImpl(dataType, bytes); -// return (T) bytesValue; -// } - } - return (T) parser.parse(fieldName); - } - - @Override - public Object createInstance(Map map, ParserConfig config) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - if (map == null || map.isEmpty()) { - return null; - } - for (Map.Entry entry : map.entrySet()) { - Object value = entry.getValue(); - if (value instanceof String) { - byte[] hashBytes = Base58Utils.decode((String) value); - if (clazz == HashDigest.class) { - return new HashDigest(hashBytes); - } else if (clazz == PubKey.class) { - return new PubKey(hashBytes); - } else if (clazz == SignatureDigest.class) { - return new SignatureDigest(hashBytes); - } else if (clazz == Bytes.class) { - return new Bytes(hashBytes); - } else if (clazz == BytesSlice.class) { - return new BytesSlice(hashBytes); - } - } - } - return null; - } - - @Override - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonSerializer.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonSerializer.java deleted file mode 100644 index e4a82b13..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonSerializer.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.jd.blockchain.web.serializes; - -import com.alibaba.fastjson.serializer.JSONSerializer; -import com.alibaba.fastjson.serializer.ObjectSerializer; -import com.jd.blockchain.binaryproto.BaseType; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesSlice; - -import java.lang.reflect.Type; - -public class ByteArrayObjectJsonSerializer implements ObjectSerializer { - - private Class clazz; - - private ByteArrayObjectJsonSerializer(Class clazz) { - this.clazz = clazz; - } - - public static ByteArrayObjectJsonSerializer getInstance(Class clazz) { - return new ByteArrayObjectJsonSerializer(clazz); - } - - @Override - public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) { - if (object.getClass() != clazz) { - serializer.writeNull(); - return; - } - if (object instanceof HashDigest) { - serializer.write(new HashDigestJson(((HashDigest) object).toBase58())); - } else if (object instanceof PubKey) { - serializer.write(new HashDigestJson(((PubKey) object).toBase58())); - } else if (object instanceof SignatureDigest) { - serializer.write(new HashDigestJson(((SignatureDigest) object).toBase58())); - } else if (object instanceof Bytes) { - serializer.write(new HashDigestJson(((Bytes) object).toBase58())); - } else if (object instanceof BytesSlice) { - serializer.write(Base58Utils.encode(((BytesSlice) object).toBytes())); - } - -// else if (object instanceof BytesValue) { -// DataType dataType = ((BytesValue) object).getType(); -// BytesSlice bytesValue = ((BytesValue) object).getValue(); -// Object realVal; -// switch (dataType) { -// case NIL: -// realVal = null; -// break; -// case TEXT: -// realVal = bytesValue.getString(); -// break; -// case BYTES: -// realVal = ByteArray.toHex(bytesValue.toBytes()); -// break; -// case INT32: -// realVal = bytesValue.getInt(); -// break; -// case INT64: -// realVal = bytesValue.getLong(); -// break; -// case JSON: -// realVal = bytesValue.getString(); -// break; -// default: -// realVal = ByteArray.toHex(bytesValue.toBytes()); -// break; -// } -// serializer.write(new BytesValueJson(dataType, realVal)); -// } - } - - private static class HashDigestJson { - - String value; - - public HashDigestJson(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - } - - public static class BytesValueJson { - - public BytesValueJson(BaseType type, Object value) { - this.type = type; - this.value = value; - } - - BaseType type; - - Object value; - - public BaseType getType() { - return type; - } - - public void setType(BaseType type) { - this.type = type; - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - this.value = value; - } - } -} diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectUtil.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectUtil.java deleted file mode 100644 index e6d23910..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectUtil.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.web.serializes.ByteArrayObjectUtil - * Author: shaozhuguang - * Department: Y事业部 - * Date: 2019/3/27 上午11:23 - * Description: - */ -package com.jd.blockchain.web.serializes; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; - -/** - * - * @author shaozhuguang - * @create 2019/3/27 - * @since 1.0.0 - */ - -public class ByteArrayObjectUtil { - - public static final Class[] BYTEARRAY_JSON_SERIALIZE_CLASS = new Class[] { - HashDigest.class, - PubKey.class, - SignatureDigest.class, - Bytes.class, - BytesSlice.class}; - - public static void init() { - for (Class byteArrayClass : BYTEARRAY_JSON_SERIALIZE_CLASS) { - JSONSerializeUtils.configSerialization(byteArrayClass, - ByteArrayObjectJsonSerializer.getInstance(byteArrayClass), - ByteArrayObjectJsonDeserializer.getInstance(byteArrayClass)); - } - } -} \ No newline at end of file diff --git a/source/manager/manager-booter/src/main/java/com/jd/blockchain/ump/UmpBooter.java b/source/manager/manager-booter/src/main/java/com/jd/blockchain/ump/UmpBooter.java deleted file mode 100644 index bf13fa58..00000000 --- a/source/manager/manager-booter/src/main/java/com/jd/blockchain/ump/UmpBooter.java +++ /dev/null @@ -1,322 +0,0 @@ -package com.jd.blockchain.ump; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Properties; - - -public class UmpBooter { - - private static final String ARG_HOME = "-home"; - - private static final String ARG_PORT = "-p"; - - private static final String ARG_HOST = "-h"; - - private static final String PROTOCOL_FILE = "file:"; - - private static final String TOOLS_JAR = "tools.jar"; - - private static final String PATH_INNER_JARS = "/"; - - private static final String CONFIG = "config.properties"; - - private static final String CONFIG_APPLICATION = "application.properties"; - - private static final String CONFIG_PROP_HOST = "server.host"; - - private static final String CONFIG_PROP_HOST_DEFAULT = "0.0.0.0"; - - private static final String CONFIG_PROP_PORT = "server.port"; - - private static final String CONFIG_PROP_PORT_DEFAULT = "8080"; - - private static final String CONFIG_PROP_DB_URL = "db.url"; - - private static final String CONFIG_PROP_DB_URL_DEFAULT = "rocksdb://#project#/jumpdb"; - - private static final String UMP_START_CLASS = "com.jd.blockchain.ump.UmpApplicationStarter"; - - private static String HOME_DIR = null; - - public static void main(String[] args) { - try { - // 设置相关参数 - Server server = server(args); - // 加载libs/manager下的jar包 - loadJars(); - // 启动Server - startServer(server); - System.out.println("JDChain Manager Server Start SUCCESS !!!"); - } catch (Exception e) { - System.err.println(e); - } - } - - /** - * 启动Server - * - * @param server - * @throws Exception - */ - private static void startServer(Server server) throws Exception { - - List argList = new ArrayList<>(); - argList.add(String.format("--server.address=%s", server.host)); - argList.add(String.format("--server.port=%s", server.port)); - argList.add(String.format("--db.url=%s", server.dbUrl)); - - String[] args = argList.toArray(new String[argList.size()]); - - InputStream inputStream = UmpBooter.class.getResourceAsStream(PATH_INNER_JARS + CONFIG_APPLICATION); - if (inputStream == null) { - System.err.printf("File [%s]' inputStream is NULL !!! \r\n", CONFIG_APPLICATION); - } - Properties props = new Properties(); - try { - props.load(inputStream); - } catch (IOException e) { - System.err.println(e); - } - - /** - * 通过ClassLoader调用如下方法 - * {@link UmpApplicationStarter#start(String[], Properties)} - * - */ - Class applicationClass = Thread.currentThread().getContextClassLoader() - .loadClass(UMP_START_CLASS); - - Method startMethod = applicationClass.getDeclaredMethod("start", String[].class, Properties.class); - - startMethod.invoke(null, args, props); - } - - /** - * 根据入参加载Server对象(配置) - * - * @param args - * @return - * @throws Exception - */ - private static Server server(String[] args) throws Exception { - Server defaultServer = serverFromConfig(); - if (args == null || args.length == 0) { - - // 获取当前Class所在路径 - HOME_DIR = UmpBooter.class.getResource("").toURI().getPath(); - return defaultServer; - } - String host = null; - - int port = 0; - - // 读取参数列表 - for (int i = 0; i < args.length; i++) { - String arg = args[i]; - if (arg.equals(ARG_HOST)) { - host = args[i + 1]; - } else if (arg.equals(ARG_PORT)) { - port = Integer.parseInt(args[i + 1]); - } else if (arg.equals(ARG_HOME)) { - HOME_DIR = args[i + 1]; - } - } - - // 参数列表中的数据不完整,则剩余部分数据从配置文件中获取 - if (host == null) { - host = defaultServer.host; - } - if (port == 0) { - port = defaultServer.port; - } - - return new Server(host, port, defaultServer.dbUrl); - } - - /** - * 配置文件中加载Server对象 - * - * @return - */ - private static Server serverFromConfig() { - try { - InputStream inputStream = UmpBooter.class.getResourceAsStream(PATH_INNER_JARS + CONFIG); - if (inputStream == null) { - System.err.printf("File [%s]' inputStream is NULL !!! \r\n", CONFIG); - } - Properties props = new Properties(); - props.load(inputStream); - String host = props.getProperty(CONFIG_PROP_HOST, CONFIG_PROP_HOST_DEFAULT); - int port = Integer.parseInt( - props.getProperty(CONFIG_PROP_PORT, CONFIG_PROP_PORT_DEFAULT)); - String dbUrl = props.getProperty(CONFIG_PROP_DB_URL, CONFIG_PROP_DB_URL_DEFAULT); - return new Server(host, port, dbUrl); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - /** - * 自定义ClassLoader加载Jar包 - * - */ - private static void loadJars() throws Exception { - // 获取两个路径下所有的正确的Jar包 - URL[] totalJars = totalURLs(); - - // 自定义URLClassLoader - URLClassLoader totalClassLoader = new URLClassLoader(totalJars, - Thread.currentThread().getContextClassLoader().getParent()); - - // 设置当前线程ClassLoader - Thread.currentThread().setContextClassLoader(totalClassLoader); - } - - /** - * 获取指定路径下的所有Jar - * - * @return - */ - public static URL[] totalURLs() throws Exception { - List totalURLs = new ArrayList<>(); - totalURLs.addAll(libsPathURLs()); - totalURLs.addAll(managerPathURLs()); - URL toolsJarURL = toolsJarURL(); - if (toolsJarURL != null) { - totalURLs.add(toolsJarURL); - System.out.printf("Loaded tools.jar[%s]! \r\n", toolsJarURL); - } - URL[] totalURLArray = new URL[totalURLs.size()]; - return totalURLs.toArray(totalURLArray); - } - - /** - * 加载JAVA_HOME下的tools.jar文件 - * - * @return - */ - public static URL toolsJarURL() throws Exception { - // tools.jar位于JAVA_HOME/....../lib/tools.jar - // 首先从classpath下进行加载 - String classPath = System.getProperty("java.class.path"); - String[] paths = classPath.split(":"); - for (String path : paths) { - if (path.endsWith("/" + TOOLS_JAR)) { - // 当前路径即为tools.jar所在路径 - return new URL(PROTOCOL_FILE + path); - } - } - - // 获取其JAVA_HOME路径 - String javaHome = System.getenv("JAVA_HOME"); - if (javaHome != null && javaHome.length() > 0) { - String toolsJarPath = javaHome + File.separator + "lib" + File.separator + TOOLS_JAR; - File toolsJar = new File(toolsJarPath); - if (toolsJar.exists()) { - return new URL(PROTOCOL_FILE + toolsJarPath); - } - } - - return null; - } - - /** - * 获取libs目录下的相关Jar - * 排除JDChain项目中默认的其他booter对应的Jar包 - * - * @return - */ - public static List libsPathURLs() { - try { - File libsDir = new File(HOME_DIR + File.separator + "libs"); - File[] jars = libsDir.listFiles(f -> - f.getName().endsWith(".jar") && - f.isFile() && - !f.getName().contains("-booter-") && - !f.getName().contains("tools-initializer") - ); - List libsPathURLs = new ArrayList<>(); - if (jars != null && jars.length > 0) { - for (int i = 0; i < jars.length; i++) { - URL jarURL = jars[i].toURI().toURL(); - libsPathURLs.add(jarURL); - System.out.printf("Loaded libsPath Jar[%s]! \r\n", jarURL); - } - } - return libsPathURLs; - } catch (MalformedURLException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - /** - * 加载manager下的所有Jar - * - * @return - */ - public static List managerPathURLs() { - try { - File managerDir = new File(HOME_DIR + File.separator + "manager"); - File[] jars = managerDir.listFiles(f -> f.getName().endsWith(".jar") && f.isFile()); - List managerPathURLs = new ArrayList<>(); - if (jars != null && jars.length > 0) { - for (int i = 0; i < jars.length; i++) { - URL jarURL = jars[i].toURI().toURL(); - managerPathURLs.add(jarURL); - System.out.printf("Loaded ManagerPath Jar[%s]! \r\n", jarURL); - } - } - return managerPathURLs; - } catch (MalformedURLException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private static class Server { - - private String host; - - private int port; - - private String dbUrl; - - public Server(String host, int port, String dbUrl) { - this.host = host; - this.port = port; - this.dbUrl = dbUrl; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getDbUrl() { - return dbUrl; - } - - public void setDbUrl(String dbUrl) { - this.dbUrl = dbUrl; - } - } -} diff --git a/source/manager/manager-booter/src/main/resources/META-INF/MANIFEST.MF b/source/manager/manager-booter/src/main/resources/META-INF/MANIFEST.MF deleted file mode 100644 index b08cf0d7..00000000 --- a/source/manager/manager-booter/src/main/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,10 +0,0 @@ -Manifest-Version: 1.0 -Created-By: 1.8.0 -Built-By: shaozhuguang@jd.com -Extension-Name: JDChain -Specification-Title: JDChain -Specification-Vendor: JD Software Foundation -Implementation-Vendor: JD Software Foundation -Implementation-URL: http://ledger.jd.com -Build-Jdk: 1.8.0 - diff --git a/source/manager/manager-booter/src/main/resources/application.properties b/source/manager/manager-booter/src/main/resources/application.properties deleted file mode 100644 index a8959472..00000000 --- a/source/manager/manager-booter/src/main/resources/application.properties +++ /dev/null @@ -1,8 +0,0 @@ -server.tomcat.uri-encoding=utf-8 - -spring.mvc.favicon.enabled=false - -logging.config=classpath:log4j2-jump.xml - -schema.retrieval.url=http://127.0.0.1:8082 -task.retrieval.url=http://127.0.0.1:10005 \ No newline at end of file diff --git a/source/manager/manager-booter/src/main/resources/assembly.xml b/source/manager/manager-booter/src/main/resources/assembly.xml deleted file mode 100644 index 8fd114ba..00000000 --- a/source/manager/manager-booter/src/main/resources/assembly.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - ${project.version} - - zip - - false - - - src/main/resources/scripts - bin - - - - - false - true - ext - - com.jd.blockchain:ump-booter - - - - \ No newline at end of file diff --git a/source/manager/manager-booter/src/main/resources/banner.txt b/source/manager/manager-booter/src/main/resources/banner.txt deleted file mode 100644 index c39618bd..00000000 --- a/source/manager/manager-booter/src/main/resources/banner.txt +++ /dev/null @@ -1,13 +0,0 @@ - - ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄ -▐░░░░░░░░░░░▌▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░▌ ▐░▌ - ▀▀▀▀▀█░█▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░▌░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ - ▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▐░▌ -▐░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░░▌ - ▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀ - diff --git a/source/manager/manager-booter/src/main/resources/config.properties b/source/manager/manager-booter/src/main/resources/config.properties deleted file mode 100644 index bc4e3dc2..00000000 --- a/source/manager/manager-booter/src/main/resources/config.properties +++ /dev/null @@ -1,11 +0,0 @@ -# Tomcat启动的HOST,默认为0.0.0.0 -server.host=0.0.0.0 - -# Tomcat启动监听端口号 -server.port=8080 - -# 本地数据库存储位置 -db.url=rocksdb://#project#/jumpdb - -schema.retrieval.url=http://127.0.0.1:8082 -task.retrieval.url=http://127.0.0.1:10005 \ No newline at end of file diff --git a/source/manager/manager-booter/src/main/resources/log4j2-jump.xml b/source/manager/manager-booter/src/main/resources/log4j2-jump.xml deleted file mode 100644 index 7ea93dbd..00000000 --- a/source/manager/manager-booter/src/main/resources/log4j2-jump.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/DBConnection.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/DBConnection.java deleted file mode 100644 index a90248cc..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/DBConnection.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.ump.dao; - -public interface DBConnection { - - String dbSchema(); - - DBConnection initDbUrl(String dbUrl); - - void put(String key, String value); - - void put(String key, Object value, Class type); - - String get(String key); - - T get(String key, Class type); - - void delete(String key); - - boolean exist(String dbUrl); -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/DBConnectionProvider.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/DBConnectionProvider.java deleted file mode 100644 index d029a411..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/DBConnectionProvider.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ump.dao; - -import org.reflections.Reflections; - -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -public class DBConnectionProvider { - - private static final Map dbConnections = new ConcurrentHashMap<>(); - - static { - init(); - } - - public static DBConnection dbConnection(String dbUrl) { - String dbSchema = dbSchema(dbUrl); - if (!dbConnections.containsKey(dbSchema)) { - throw new IllegalStateException( - String.format("Can not find DBConnection by {%s} !", dbUrl)); - } - - DBConnection dbConnection = dbConnections.get(dbSchema); - return dbConnection.initDbUrl(dbUrl); - } - - - private static String dbSchema(String dbUrl) { - // rocksdb:///home/xxx -> rocksdb - return dbUrl.split("://")[0]; - - } - - private static void init() { - // 初始化所有实现类 - Reflections reflections = new Reflections("com.jd.blockchain.ump.dao"); - - Set> dbConnectionSet = - reflections.getSubTypesOf(DBConnection.class); - - for (Class clazz : dbConnectionSet) { - - if (!clazz.isInterface() && !clazz.equals(UmpDaoHandler.class)) { - try { - // 根据class生成对象 - DBConnection dbConnection = clazz.newInstance(); - String dbSchema = dbConnection.dbSchema(); - if (dbSchema != null && dbSchema.length() > 0) { - dbConnections.put(dbSchema, dbConnection); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - } - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/MemoryDBConnection.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/MemoryDBConnection.java deleted file mode 100644 index 49fe9857..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/MemoryDBConnection.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ump.dao; - -import com.alibaba.fastjson.JSON; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class MemoryDBConnection implements DBConnection { - - private static final String MEMORY_SCHEMA = "memory"; - - private final Map memory = new ConcurrentHashMap<>(); - - @Override - public String dbSchema() { - return MEMORY_SCHEMA; - } - - @Override - public DBConnection initDbUrl(String dbUrl) { - return this; - } - - @Override - public void put(String key, String value) { - memory.put(key, value); - } - - @Override - public void put(String key, Object value, Class type) { - String json = JSON.toJSONString(value); - put(key, json); - } - - @Override - public String get(String key) { - return memory.get(key); - } - - @Override - public boolean exist(String dbUrl) { - if (dbUrl.startsWith(MEMORY_SCHEMA)) { - return true; - } - return false; - } - - @Override - public T get(String key, Class type) { - String record = memory.get(key); - return JSON.parseObject(record,type); - } - - @Override - public void delete(String key) { - memory.remove(key); - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/RocksDBConnection.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/RocksDBConnection.java deleted file mode 100644 index 893f6e67..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/RocksDBConnection.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.jd.blockchain.ump.dao; - - -import com.alibaba.fastjson.JSON; -import org.apache.commons.io.FileUtils; -import org.rocksdb.*; -import org.rocksdb.util.SizeUnit; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import static java.nio.charset.StandardCharsets.UTF_8; - -public class RocksDBConnection implements DBConnection { - - public static final String SCHEMA = "rocksdb"; - - public static final String PROTOCOL_SPLIT = "://"; - - public static final String ROCKSDB_PROTOCOL = SCHEMA + PROTOCOL_SPLIT; - - static { - RocksDB.loadLibrary(); - } - - private RocksDB rocksDB; - - @Override - public String dbSchema() { - return SCHEMA; - } - - @Override - public DBConnection initDbUrl(String dbUrl) { - if (!dbUrl.startsWith(dbSchema())) { - throw new IllegalStateException(String.format("Unsupport DBConnection by URL {%s} !!!", dbUrl)); - } - String dbSavePath = dbUrl.split(PROTOCOL_SPLIT)[1]; - initDBConnection(dbSavePath); - return this; - } - - @Override - public void put(String key, String value) { - if (this.rocksDB == null) { - throw new IllegalStateException("Rocksdb is NULL, Please initDbUrl first !!!"); - } - try { - this.rocksDB.put(key.getBytes(UTF_8), value.getBytes(UTF_8)); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - @Override - public void put(String key, Object value, Class type) { - // 使用JSON序列化 - String json = JSON.toJSONString(value); - put(key, json); - } - - @Override - public String get(String key) { - try { - byte[] value = this.rocksDB.get(key.getBytes(UTF_8)); - if (value != null && value.length > 0) { - return new String(value, UTF_8); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - return null; - } - - @Override - public T get(String key, Class type) { - try { - byte[] value = this.rocksDB.get(key.getBytes(UTF_8)); - if (value != null && value.length > 0) { - String strObj = new String(value, UTF_8); - return JSON.parseObject(strObj,type); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - return null; - } - - @Override - public void delete(String key) { - try { - byte[] value = this.rocksDB.get(key.getBytes(UTF_8)); - if (value != null && value.length > 0) { - this.rocksDB.delete(value); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - @Override - public boolean exist(String dbUrl) { - // 首先该dbUrl是Rocksdb - if (dbUrl.startsWith(ROCKSDB_PROTOCOL)) { - // 判断File是否存在,并且是文件夹 - File dbPath = new File(dbUrl.substring(ROCKSDB_PROTOCOL.length())); - if (dbPath.exists() && dbPath.isDirectory()) { - return true; - } - } - return false; - } - - private void initDBConnection(String dbUrl) { - try { - File dbPath = new File(dbUrl); - File dbParentPath = dbPath.getParentFile(); - if (!dbParentPath.exists()) { - FileUtils.forceMkdir(dbParentPath); - } - this.rocksDB = RocksDB.open(initOptions(), dbUrl); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private Options initOptions() { - final Filter bloomFilter = new BloomFilter(32); - final BlockBasedTableConfig tableOptions = new BlockBasedTableConfig() - .setFilter(bloomFilter) - .setBlockSize(4 * SizeUnit.KB) - .setBlockSizeDeviation(10) - .setBlockCacheSize(64 * SizeUnit.GB) - .setNoBlockCache(false) - .setCacheIndexAndFilterBlocks(true) - .setBlockRestartInterval(16) - ; - final List compressionLevels = new ArrayList<>(); - compressionLevels.add(CompressionType.NO_COMPRESSION); // 0-1 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 1-2 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 2-3 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 3-4 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 4-5 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 5-6 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 6-7 - - Options options = new Options() - .setAllowConcurrentMemtableWrite(true) - .setEnableWriteThreadAdaptiveYield(true) - .setCreateIfMissing(true) - .setMaxWriteBufferNumber(3) - .setTableFormatConfig(tableOptions) - .setMaxBackgroundCompactions(10) - .setMaxBackgroundFlushes(4) - .setBloomLocality(10) - .setMinWriteBufferNumberToMerge(4) - .setCompressionPerLevel(compressionLevels) - .setNumLevels(7) - .setCompressionType(CompressionType.SNAPPY_COMPRESSION) - .setCompactionStyle(CompactionStyle.UNIVERSAL) - .setMemTableConfig(new SkipListMemTableConfig()) - ; - return options; - } - - public static void main(String[] args) { - String path = "rocksdb:///zhangsan/lisi"; - System.out.println(path.substring(ROCKSDB_PROTOCOL.length())); - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/UmpDao.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/UmpDao.java deleted file mode 100644 index 1da5d48b..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/UmpDao.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.jd.blockchain.ump.dao; - -public interface UmpDao { -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/UmpDaoHandler.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/UmpDaoHandler.java deleted file mode 100644 index 3e261577..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/dao/UmpDaoHandler.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.jd.blockchain.ump.dao; - -import com.jd.blockchain.ump.model.UmpConstant; -import org.springframework.boot.CommandLineRunner; -import org.springframework.stereotype.Repository; - -import java.io.File; - -@Repository -public class UmpDaoHandler implements UmpDao, CommandLineRunner, DBConnection { - - public final String PROJECT_FLAG = "#project#"; - - private static final String PROTOCOL_FILE = "file:"; - - private static final String INNER_FILE_SEPARATOR = "!"; - - private static final String PROTOCOL_SEPARATOR = "://"; - - private DBConnection dbConnection; - - @Override - public void run(String... args) { - - String dbUrl = RocksDBConnection.SCHEMA + PROTOCOL_SEPARATOR + - PROJECT_FLAG + File.separator + UmpConstant.DB_NAME; - - if (args != null && args.length > 0) { - for (String arg : args) { - if (arg.startsWith("--db.url")) { - dbUrl = arg.split("=")[1]; - } - } - } - - dbConnection = DBConnectionProvider.dbConnection(realPath(dbUrl)); - - initProjectPath(); - } - - private void initProjectPath() { - UmpConstant.PROJECT_PATH = projectPath(); - System.out.printf("Init Project Path = %s \r\n", UmpConstant.PROJECT_PATH); - } - - @Override - public String dbSchema() { - return null; - } - - @Override - public DBConnection initDbUrl(String dbUrl) { - return dbConnection; - } - - @Override - public void put(String key, String value) { - dbConnection.put(key, value); - } - - @Override - public void put(String key, Object value, Class type) { - dbConnection.put(key, value, type); - } - - @Override - public String get(String key) { - return dbConnection.get(key); - } - - @Override - public T get(String key, Class type) { - return dbConnection.get(key,type); - } - - @Override - public void delete(String key) { - dbConnection.delete(key); - } - - @Override - public boolean exist(String dbUrl) { - try { - return dbConnection.exist(dbUrl); - } catch (Exception e) { - // 不关心异常 - System.err.println(e); - return false; - } - } - - private String realPath(String dbUrl) { - if (dbUrl.contains(PROJECT_FLAG)) { - // 获取当前jar包路径 - try { - String projectPath = projectPath(); - return dbUrl.replaceAll(PROJECT_FLAG, projectPath); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - return dbUrl; - } - - private String projectPath() { - File jarDirectory = new File(jarRootPath()); - return jarDirectory.getParentFile().getParentFile().getPath(); - } - - private String jarRootPath() { - // 获取Jar包所在路径 - String jarRootPath = UmpDaoHandler.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - - // 处理打包到SpringBoot后路径问题:file: - if (jarRootPath.startsWith(PROTOCOL_FILE)) { - jarRootPath = jarRootPath.substring(PROTOCOL_FILE.length()); - } - // 处理打包到SpringBoot后内部分隔符问题:! - if (jarRootPath.contains(INNER_FILE_SEPARATOR)) { - jarRootPath = jarRootPath.substring(0, jarRootPath.indexOf(INNER_FILE_SEPARATOR)); - } - - return jarRootPath; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/ApiResult.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/ApiResult.java deleted file mode 100644 index 4632bc04..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/ApiResult.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jd.blockchain.ump.model; - -/** - * @author zhaogw - * date 2019/7/10 15:31 - */ -public class ApiResult { - /** - * 错误码,对应{@link ErrorCode},表示一种错误类型 - * 如果是成功,则code为1 - */ - private int code; - /** - * 具体解释 - */ - private String message; - /** - * 返回的结果包装在value中,value可以是单个对象 - */ - private Object value; - - public ApiResult (){ } - - public ApiResult (Object obj){ - this.value = obj; - } - - public ApiResult (int code, String message){ - this.code = code; - this.message = message; - } - - public ApiResult(ErrorCode errorCode){ - this.code = errorCode.getCode(); - this.message = errorCode.getMsg(); - } - - public ApiResult(ErrorCode errorCode, Object obj){ - this.code = errorCode.getCode(); - this.message = errorCode.getMsg(); - this.value = obj; - } - - public ApiResult (int code, String message, Object value){ - this.code = code; - this.message = message; - this.value = value; - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - this.value = value; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/ErrorCode.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/ErrorCode.java deleted file mode 100644 index 1e0031d6..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/ErrorCode.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.ump.model; - -/** - * @author zhaogw - * date 2019/7/10 15:32 - */ -public enum ErrorCode { - SUCCESS(1,"成功"), - NO_PERMISSION(2,"权限不足"), - SERVER_ERROR(3,"服务器异常"), - AUTH_ERROR(4,"认证失败"), - PARAMS_ERROR(5,"参数错误"), - JSON_PARSE_ERROR(6,"Json解析错误"), - ILLEAGAL_STRING(7,"非法字符串"), - GEN_KEY_INPUT_LACK(8,"缺少必要的输入参数:name/randomSeed/basePath/password"), - UNKNOW_ERROR(10000,"未知错误"); - - private int code; - private String msg; - - ErrorCode(int code,String msg){ - this.code = code; - this.msg = msg; - } - - public int getCode() { - return code; - } - - public String getMsg() { - return msg; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/MasterAddr.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/MasterAddr.java deleted file mode 100644 index 700cef0b..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/MasterAddr.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jd.blockchain.ump.model; - -public class MasterAddr { - - private String ipAddr; - - private int port; - - public MasterAddr() { - } - - public MasterAddr(String ipAddr, int port) { - this.ipAddr = ipAddr; - this.port = port; - } - - public String getIpAddr() { - return ipAddr; - } - - public void setIpAddr(String ipAddr) { - this.ipAddr = ipAddr; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public static MasterAddr newInstance(String ipAddr, int port) { - return new MasterAddr(ipAddr, port); - } - - public String toHttpUrl() { - return "http://" + ipAddr + ":" + port; - } - - public boolean legal() { - if (this.ipAddr == null || this.ipAddr.length() == 0 || this.port == 0) { - return false; - } - return true; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/PartiNode.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/PartiNode.java deleted file mode 100644 index 574f1ee2..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/PartiNode.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.jd.blockchain.ump.model; - -import java.util.ArrayList; -import java.util.List; - -public class PartiNode { - - private int id; - - private String name; - - private String pubKey; - - private String initHost; - - private int initPort; - - private boolean isSecure; - - public List toConfigChars(List partiRoleConfigs) { - - List configCharList = new ArrayList<>(); - - configCharList.add(formatConfig(UmpConstant.PARTINODE_NAME_FORMAT, name)); - - configCharList.add(formatConfig(UmpConstant.PARTINODE_PUBKEY_FORMAT, pubKey)); - - if (partiRoleConfigs != null && !partiRoleConfigs.isEmpty()) { - configCharList.addAll(partiRoleConfigs); - } - - configCharList.add(formatConfig(UmpConstant.PARTINODE_INIT_HOST_FORMAT, initHost)); - - configCharList.add(formatConfig(UmpConstant.PARTINODE_INIT_PORT_FORMAT, initPort)); - - configCharList.add(formatConfig(UmpConstant.PARTINODE_INIT_SECURE_FORMAT, isSecure)); - - return configCharList; - } - - private String formatConfig(String formatter, Object value) { - return String.format(formatter, id) + "=" + value; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPubKey() { - return pubKey; - } - - public void setPubKey(String pubKey) { - this.pubKey = pubKey; - } - - public String getInitHost() { - return initHost; - } - - public void setInitHost(String initHost) { - this.initHost = initHost; - } - - public int getInitPort() { - return initPort; - } - - public void setInitPort(int initPort) { - this.initPort = initPort; - } - - public boolean isSecure() { - return isSecure; - } - - public void setSecure(boolean secure) { - isSecure = secure; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/PeerSharedConfigs.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/PeerSharedConfigs.java deleted file mode 100644 index 75675709..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/PeerSharedConfigs.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.jd.blockchain.ump.model; - -import com.jd.blockchain.ump.model.config.LedgerInitConfig; -import com.jd.blockchain.ump.model.config.MasterConfig; -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.config.PeerSharedConfig; -import com.jd.blockchain.ump.model.state.LedgerMasterInstall; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -public class PeerSharedConfigs { - - /** - * 默认的一次邀请码最长等待时间,单位分钟,默认30分钟 - */ - private static final int MAX_WAIT_MINUTE = 30; - - private CountDownLatch latch = null; - - private Lock lock = new ReentrantLock(); - - private Lock waitLock = new ReentrantLock(); - - private Condition sizeCondition = waitLock.newCondition(); - - private List sharedConfigs = new ArrayList<>(); - - private int waitNodeSize; - - private String consensusProvider; - - private String sharedKey; - - private String ledgerName; - - private LedgerInitConfig ledgerInitConfig; - - public synchronized PeerSharedConfigs addConfig(PeerLocalConfig sharedConfig) { - - // 判断内容是否存在重复 - for (PeerSharedConfig innerSharedConfig : sharedConfigs) { - if (innerSharedConfig.getName().equals(sharedConfig.getName()) - || innerSharedConfig.getPubKey().equals(sharedConfig.getPubKey())) { - return null; - } - } - - if (sharedConfig.getMasterConfig().isMaster()) { - initDataByMaster(sharedConfig); - } - - sharedConfigs.add(sharedConfig); - - if (latch != null) { - // 不管是Master还是普通用户都需要-1 - latch.countDown(); - } - return this; - } - - /** - * 由Master节点传入的信息对数据进行初始化 - * - * @param sharedConfig - */ - private void initDataByMaster(PeerLocalConfig sharedConfig) { - - MasterConfig masterConfig = sharedConfig.getMasterConfig(); - - // master需要对数据进行组织 - if (latch == null) { - latch = new CountDownLatch(masterConfig.getNodeSize() - sharedConfigs.size()); - } - if (consensusProvider == null) { - consensusProvider = sharedConfig.getConsensusProvider(); - } - if (sharedKey == null) { - sharedKey = sharedConfig.getSharedKey(); - } - if (ledgerName == null) { - ledgerName = masterConfig.getLedgerName(); - } - waitNodeSize = masterConfig.getNodeSize(); - } - - /** - * 线程等待 - * 一直处于等待状态(30分钟),直到有线程调用single方法 - * - */ - public void await() { - waitLock.lock(); - try { - sizeCondition.await(MAX_WAIT_MINUTE, TimeUnit.MINUTES); - } catch (Exception e) { - throw new IllegalStateException(e); - } finally { - waitLock.unlock(); - } - } - - /** - * 通知其他线程等待状态结束 - * - */ - public void single() { - waitLock.lock(); - try { - sizeCondition.signalAll(); - } catch (Exception e) { - throw new IllegalStateException(e); - } finally { - waitLock.unlock(); - } - } - - /** - * Master线程调用,等待数据满足后通知其他线程 - * - */ - public void waitAndNotify() { - if (this.latch == null) { - throw new IllegalStateException("Please init MasterConfig first !!!"); - } - try { - latch.await(MAX_WAIT_MINUTE, TimeUnit.MINUTES); - single(); // 通知其他线程释放 - } catch (Exception e) { - if (sharedConfigs.size() >= waitNodeSize) { - // 成功 - single(); - } - } - } - - public synchronized LedgerInitConfig ledgerInitConfig(String seed, String createTime, - List securityConfigs, List partiRoleConfigs) { - if (ledgerInitConfig != null) { - return ledgerInitConfig; - } - - // 处理该ledgerInitConfig - ledgerInitConfig = new LedgerInitConfig(seed, ledgerName, createTime, consensusProvider, waitNodeSize, - securityConfigs, partiRoleConfigs); - - // 添加参与方 - for (int i = 0; i < sharedConfigs.size(); i++) { - PeerLocalConfig sharedConfig = sharedConfigs.get(i); - ledgerInitConfig.addPartiNode(sharedConfig.toPartiNode(i)); - } - - return ledgerInitConfig; - } - - public String getConsensusProvider() { - return consensusProvider; - } - - public void setConsensusProvider(String consensusProvider) { - this.consensusProvider = consensusProvider; - } - - public String getSharedKey() { - return sharedKey; - } - - public void setSharedKey(String sharedKey) { - this.sharedKey = sharedKey; - } - - public Lock getLock() { - return lock; - } - - public String getLedgerName() { - return ledgerName; - } - - public void setLedgerName(String ledgerName) { - this.ledgerName = ledgerName; - } - - public List getSharedConfigs() { - return sharedConfigs; - } - - public void setSharedConfigs(List sharedConfigs) { - this.sharedConfigs = sharedConfigs; - } - - public LedgerInitConfig getLedgerInitConfig() { - return ledgerInitConfig; - } - - public void setLedgerInitConfig(LedgerInitConfig ledgerInitConfig) { - this.ledgerInitConfig = ledgerInitConfig; - } - - public LedgerMasterInstall toLedgerMasterInstall() { - - // String ledgerKey, String sharedKey, int totalNodeSize - LedgerMasterInstall masterInstall = new LedgerMasterInstall( - ledgerInitConfig.ledgerKey(), sharedConfigs.size()) - .initCreateTime(ledgerInitConfig.getCreateTime()); - - for (PeerLocalConfig sharedConfig : sharedConfigs) { - - masterInstall.add(sharedConfig.toPeerInstall()); - } - - return masterInstall; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/UmpConstant.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/UmpConstant.java deleted file mode 100644 index 7903620c..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/UmpConstant.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.jd.blockchain.ump.model; - -import java.io.File; - -public class UmpConstant { - - public static String PROJECT_PATH = ""; - - public static final String DB_NAME = "jumpdb"; - - public static final String URL_SEPARATOR = "/"; - - public static final String URL_MASTER = "/master"; - - public static final String URL_PEER = "/peer"; - - public static final String PRIVATE_KEY_SUFFIX = ".priv"; - - public static final String PUBLIC_KEY_SUFFIX = ".pub"; - - public static final String PWD_SUFFIX = ".pwd"; - - public static final String REQUEST_SHARED_URL = URL_MASTER + URL_SEPARATOR + "share"; - - public static final String REQUEST_STATE_URL = URL_MASTER + URL_SEPARATOR + "receive"; - - public static final String PARTINODE_COUNT = "cons_parti.count"; - - public static final String PARTINODE_FORMAT = "cons_parti.%s"; - - public static final String PARTINODE_NAME_FORMAT = PARTINODE_FORMAT + ".name"; - - public static final String PARTINODE_PUBKEY_FORMAT = PARTINODE_FORMAT + ".pubkey"; - - public static final String PARTINODE_ROLES_FORMAT = PARTINODE_FORMAT + ".roles"; - - public static final String PARTINODE_ROLES_POLICY_FORMAT = PARTINODE_FORMAT + ".roles-policy"; - - public static final String PARTINODE_INIT_FORMAT = PARTINODE_FORMAT + ".initializer"; - - public static final String PARTINODE_INIT_HOST_FORMAT = PARTINODE_INIT_FORMAT + ".host"; - - public static final String PARTINODE_INIT_PORT_FORMAT = PARTINODE_INIT_FORMAT + ".port"; - - public static final String PARTINODE_INIT_SECURE_FORMAT = PARTINODE_INIT_FORMAT + ".secure"; - - public static final String LEDGER_PREFIX = "ledger"; - - public static final String LEDGER_SEED_PREFIX = LEDGER_PREFIX + ".seed"; - - public static final String LEDGER_NAME_PREFIX = LEDGER_PREFIX + ".name"; - - public static final String CREATE_TIME_PREFIX = "created-time"; - - public static final String SECURITY_PREFIX = "security"; - - public static final String SECURITY_ROLES = SECURITY_PREFIX + ".roles"; - - public static final String SECURITY_ROLES_PRIVILEGES_LEDGER_FORMAT = SECURITY_ROLES + ".%s.ledger-privileges"; - - public static final String SECURITY_ROLES_PRIVILEGES_TX_FORMAT = SECURITY_ROLES + ".%s.tx-privileges"; - - public static final String SECURITY_PARTI_PREFIX = "participant.default"; - - public static final String SECURITY_PARTI_ROLES = SECURITY_PARTI_PREFIX + ".roles"; - - public static final String SECURITY_PARTI_ROLES_POLICY = SECURITY_PARTI_PREFIX + ".roles-policy"; - - public static final String CRYPTO_PREFIX = "crypto"; - - public static final String CRYPTO_HASH_VERIFY = CRYPTO_PREFIX + ".verify-hash"; - - public static final String CRYPTO_HASH_ALGORITHM = CRYPTO_PREFIX + ".hash-algorithm"; - - public static final String CONSENSUS_PREFIX = "consensus"; - - public static final String CONSENSUS_PROVIDER_PREFIX = CONSENSUS_PREFIX + ".service-provider"; - - public static final String CONSENSUS_CONF_PREFIX = CONSENSUS_PREFIX + ".conf"; - - public static final String CRYPTO_PROVIDERS_PREFIX = CRYPTO_PREFIX + ".service-providers"; - - public static final String LOCAL_PREFIX = "local"; - - public static final String LOCAL_PARTI_PREFIX = LOCAL_PREFIX + ".parti"; - - public static final String LOCAL_PARTI_ID_PREFIX = LOCAL_PARTI_PREFIX + ".id"; - - public static final String LOCAL_PARTI_PUBKEY_PREFIX = LOCAL_PARTI_PREFIX + ".pubkey"; - - public static final String LOCAL_PARTI_PRIVKEY_PREFIX = LOCAL_PARTI_PREFIX + ".privkey"; - - public static final String LOCAL_PARTI_PWD_PREFIX = LOCAL_PARTI_PREFIX + ".pwd"; - - public static final String LEDGER_BINDING_OUT_PREFIX = LEDGER_PREFIX + ".binding.out"; - - public static final String LEDGER_DB_URI_PREFIX = LEDGER_PREFIX + ".db.uri"; - - public static final String LEDGER_DB_PWD_PREFIX = LEDGER_PREFIX + ".db.pwd"; - - public static final String CMD_LEDGER_INIT = "/bin/bash %s -monitor"; - - public static final String CMD_START_UP_FORMAT = "/bin/bash %s"; - - public static final String PATH_BIN = File.separator + "bin"; - - public static final String PATH_LEDGER_INIT_BIN = PATH_BIN + File.separator + "ledger-init.sh"; - - public static final String PATH_PEER_STARTUP_BIN = PATH_BIN + File.separator + "peer-startup.sh"; - - public static final String PATH_LIBS = File.separator + "libs"; - - public static final String PATH_SYSTEM = File.separator + "system"; - - public static final String PATH_CONFIG = File.separator + "config"; - - public static final String PATH_CONFIG_KEYS = PATH_CONFIG + File.separator + "keys"; - - public static final String PATH_LEDGER_BINDING_CONFIG = PATH_CONFIG + File.separator + "ledger-binding.conf"; - - public static final String PATH_CONFIG_INIT = PATH_CONFIG + File.separator + "init"; - - public static final String PATH_LOCAL_CONFIG = PATH_CONFIG_INIT + File.separator + "local.conf"; - - public static final String PATH_LEDGER_INIT_CONFIG = PATH_CONFIG_INIT + File.separator + "ledger.init"; - - public static final String PEER_HOST_IP = "peerHostIp"; - public static final String INIT_PORT = "iPort"; - public static final String CONSENSUS_PORT = "cPort"; - public static final String DELIMETER_QUESTION = "?"; //逗号分隔符; - public static final String LEDGER_LIST = "ledger_list"; //the key that save all the ledger hash in the rocksdb; - public static final int MEMORY_MAP_MAX_COUNT=10000; - public static final int MEMORY_MAP_REMOVE_COUNT=50; - public static final String ALL_LEDGER="all_ledger"; - public static final String DELIMETER_MINUS = "-"; - public static final String SCHEMA_PREFIX = "schema_"; - public static final String SCHEMA_RETRIEVAL_URL = "schema.retrieval.url"; - public static final String TASK_RETRIEVAL_URL = "task.retrieval.url"; -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/UmpQueue.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/UmpQueue.java deleted file mode 100644 index 509fb4a5..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/UmpQueue.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jd.blockchain.ump.model; - -import com.jd.blockchain.ump.model.state.InstallSchedule; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -public class UmpQueue { - - private final BlockingQueue QUEUE_INSTALL_SCHEDULE = new LinkedBlockingQueue<>(); - - public void put(InstallSchedule installSchedule, MasterAddr masterAddr) throws InterruptedException { - QUEUE_INSTALL_SCHEDULE.put(new InstallScheduleRequest(installSchedule, masterAddr)); - } - - public InstallScheduleRequest take() throws InterruptedException { - return QUEUE_INSTALL_SCHEDULE.take(); - } - - public static class InstallScheduleRequest { - - private InstallSchedule installSchedule; - - private MasterAddr masterAddr; - - public InstallScheduleRequest() { - } - - public InstallScheduleRequest(InstallSchedule installSchedule, MasterAddr masterAddr) { - this.installSchedule = installSchedule; - this.masterAddr = masterAddr; - } - - public InstallSchedule getInstallSchedule() { - return installSchedule; - } - - public void setInstallSchedule(InstallSchedule installSchedule) { - this.installSchedule = installSchedule; - } - - public MasterAddr getMasterAddr() { - return masterAddr; - } - - public void setMasterAddr(MasterAddr masterAddr) { - this.masterAddr = masterAddr; - } - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/ConsensusConfig.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/ConsensusConfig.java deleted file mode 100644 index e6963c2f..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/ConsensusConfig.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.ump.model.config; - -public class ConsensusConfig { - - private String confPath; - - private byte[] content; - - public String getConfPath() { - return confPath; - } - - public void setConfPath(String confPath) { - this.confPath = confPath; - } - - public byte[] getContent() { - return content; - } - - public void setContent(byte[] content) { - this.content = content; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerConfig.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerConfig.java deleted file mode 100644 index 2b435f93..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jd.blockchain.ump.model.config; - -public class LedgerConfig { - - private LedgerInitConfig initConfig; - - /** - * 共识文件配置信息,Base58格式 - */ - private String consensusConfig; - - - public LedgerConfig() { - } - - /** - * 包装一下,使用JSON处理过程 - * - * @param ledgerConfig - */ - public LedgerConfig(LedgerConfig ledgerConfig) { - this.consensusConfig = ledgerConfig.getConsensusConfig(); - - } - - public LedgerConfig(LedgerInitConfig initConfig, String consensusConfig) { - this.initConfig = initConfig; - this.consensusConfig = consensusConfig; - } - - public LedgerInitConfig getInitConfig() { - return initConfig; - } - - public void setInitConfig(LedgerInitConfig initConfig) { - this.initConfig = initConfig; - } - - public String getConsensusConfig() { - return consensusConfig; - } - - public void setConsensusConfig(String consensusConfig) { - this.consensusConfig = consensusConfig; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerIdentification.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerIdentification.java deleted file mode 100644 index 1b724dc7..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerIdentification.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.jd.blockchain.ump.model.config; - -import com.jd.blockchain.ump.model.MasterAddr; - -public class LedgerIdentification { - - private String ledgerKey; - - private String ledgerAndNodeKey; - - private MasterAddr masterAddr; - - private int nodeId; - - private PeerLocalConfig localConfig; - - private LedgerInitConfig initConfig; - - public LedgerIdentification() { - } - - public LedgerIdentification(int nodeId, PeerLocalConfig localConfig, MasterAddr masterAddr, String ledgerAndNodeKey, LedgerInitConfig initConfig) { - this.nodeId = nodeId; - this.localConfig = localConfig; - this.masterAddr = masterAddr; - this.ledgerKey = initConfig.ledgerKey(); - this.ledgerAndNodeKey = ledgerAndNodeKey; - this.initConfig = initConfig; - init(); - } - - private void init() { - // 初始化部分配置信息 - MasterConfig masterConfig = localConfig.getMasterConfig(); - // 设置账本名称 - if (masterConfig.getLedgerName() == null || masterConfig.getLedgerName().length() == 0) { - masterConfig.setLedgerName(initConfig.getName()); - } - // 设置NodeSize - if (masterConfig.getNodeSize() == 0) { - masterConfig.setNodeSize(initConfig.getNodeSize()); - } - } - - public String getLedgerKey() { - return ledgerKey; - } - - public void setLedgerKey(String ledgerKey) { - this.ledgerKey = ledgerKey; - } - - public String getLedgerAndNodeKey() { - return ledgerAndNodeKey; - } - - public void setLedgerAndNodeKey(String ledgerAndNodeKey) { - this.ledgerAndNodeKey = ledgerAndNodeKey; - } - - public MasterAddr getMasterAddr() { - return masterAddr; - } - - public void setMasterAddr(MasterAddr masterAddr) { - this.masterAddr = masterAddr; - } - - public int getNodeId() { - return nodeId; - } - - public void setNodeId(int nodeId) { - this.nodeId = nodeId; - } - - public PeerLocalConfig getLocalConfig() { - return localConfig; - } - - public void setLocalConfig(PeerLocalConfig localConfig) { - this.localConfig = localConfig; - } - - public LedgerInitConfig getInitConfig() { - return initConfig; - } - - public void setInitConfig(LedgerInitConfig initConfig) { - this.initConfig = initConfig; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerInitConfig.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerInitConfig.java deleted file mode 100644 index 476ff1e3..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/LedgerInitConfig.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.jd.blockchain.ump.model.config; - -import com.jd.blockchain.ump.model.PartiNode; -import com.jd.blockchain.ump.model.UmpConstant; - -import java.util.ArrayList; -import java.util.List; - -public class LedgerInitConfig { - - private String seed; - - private String name; - - private String createTime; - - private String consensusProvider; - - private int nodeSize; - - private String cryptoProviders = - "com.jd.blockchain.crypto.service.classic.ClassicCryptoService, " + - "com.jd.blockchain.crypto.service.sm.SMCryptoService"; - - List securityConfigs = null; - - List partiRolesConfigs = null; - - - private List partiNodes = new ArrayList<>(); - - public LedgerInitConfig() { - } - - public LedgerInitConfig(String seed, String name, String createTime, String consensusProvider, int nodeSize, - List securityConfigs, List partiRolesConfigs) { - this.seed = seed; - this.name = name; - this.createTime = createTime; - this.consensusProvider = consensusProvider; - this.nodeSize = nodeSize; - this.securityConfigs = securityConfigs; - this.partiRolesConfigs = partiRolesConfigs; - } - - public List toConfigChars(String consensusConf) { - - List configChars = new ArrayList<>(); - - configChars.add(toConfigChars(UmpConstant.LEDGER_SEED_PREFIX, seed)); - - configChars.add(toConfigChars(UmpConstant.LEDGER_NAME_PREFIX, name)); - - configChars.add(toConfigChars(UmpConstant.CREATE_TIME_PREFIX, createTime)); - - configChars.add(toConfigChars(UmpConstant.CONSENSUS_PROVIDER_PREFIX, consensusProvider)); - - configChars.add(toConfigChars(UmpConstant.CONSENSUS_CONF_PREFIX, consensusConf)); - - configChars.add(toConfigChars(UmpConstant.CRYPTO_PROVIDERS_PREFIX, cryptoProviders)); - - configChars.add(toConfigChars(UmpConstant.PARTINODE_COUNT, partiNodes.size())); - - if (securityConfigs != null && !securityConfigs.isEmpty()) { - configChars.addAll(securityConfigs); - } - - for (PartiNode partiNode : partiNodes) { - configChars.addAll(partiNode.toConfigChars(this.partiRolesConfigs)); - } - - return configChars; - } - - public String ledgerKey() { - return seed + "-" + name; - } - - public int nodeId(String pubKey) { - for (int i = 0; i < partiNodes.size(); i++) { - PartiNode partiNode = partiNodes.get(i); - if (partiNode.getPubKey().equals(pubKey)) { - return i; - } - } - throw new IllegalStateException(String.format("Can not find PubKey = %s !", pubKey)); - } - - private String toConfigChars(String prefix, Object value) { - return prefix + "=" + value; - } - - public String getSeed() { - return seed; - } - - public void setSeed(String seed) { - this.seed = seed; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public String getConsensusProvider() { - return consensusProvider; - } - - public void setConsensusProvider(String consensusProvider) { - this.consensusProvider = consensusProvider; - } - - public int getNodeSize() { - return nodeSize; - } - - public void setNodeSize(int nodeSize) { - this.nodeSize = nodeSize; - } - - public String getCryptoProviders() { - return cryptoProviders; - } - - public void setCryptoProviders(String cryptoProviders) { - this.cryptoProviders = cryptoProviders; - } - - public List getPartiNodes() { - return partiNodes; - } - - public void setPartiNodes(List partiNodes) { - this.partiNodes = partiNodes; - } - - public void addPartiNode(PartiNode partiNode) { - this.partiNodes.add(partiNode); - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/MasterConfig.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/MasterConfig.java deleted file mode 100644 index f3807773..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/MasterConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jd.blockchain.ump.model.config; - -import com.jd.blockchain.ump.model.MasterAddr; - -public class MasterConfig { - - private String masterAddr; - - private int masterPort; - - private String ledgerName; - - private int nodeSize; - - private boolean isMaster = false; - - public MasterConfig() { - } - - public String getMasterAddr() { - return masterAddr; - } - - public void setMasterAddr(String masterAddr) { - this.masterAddr = masterAddr; - } - - public int getMasterPort() { - return masterPort; - } - - public void setMasterPort(int masterPort) { - this.masterPort = masterPort; - } - - public String getLedgerName() { - return ledgerName; - } - - public void setLedgerName(String ledgerName) { - this.ledgerName = ledgerName; - } - - public int getNodeSize() { - return nodeSize; - } - - public void setNodeSize(int nodeSize) { - this.nodeSize = nodeSize; - } - - public boolean isMaster() { - return isMaster; - } - - public void setMaster(boolean master) { - isMaster = master; - } - - public MasterConfig buildIsMaster(boolean isMaster) { - setMaster(isMaster); - return this; - } - - public MasterConfig buildNodeSize(int nodeSize) { - setNodeSize(nodeSize); - return this; - } - - public MasterConfig buildLedgerName(String ledgerName) { - setLedgerName(ledgerName); - return this; - } - - public MasterConfig buildMasterAddr(String masterAddr) { - setMasterAddr(masterAddr); - return this; - } - - public MasterConfig buildMasterPort(int masterPort) { - setMasterPort(masterPort); - return this; - } - - - public MasterAddr toMasterAddr() { - return MasterAddr.newInstance(masterAddr, masterPort); - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerLocalConfig.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerLocalConfig.java deleted file mode 100644 index bb4778f7..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerLocalConfig.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.jd.blockchain.ump.model.config; - - -import com.jd.blockchain.ump.model.MasterAddr; -import com.jd.blockchain.ump.model.PartiNode; -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.model.state.LedgerMasterInstall; -import com.jd.blockchain.ump.model.state.LedgerPeerInstall; - -import java.io.File; - -/** - * Peer本地配置信息 - */ -public class PeerLocalConfig extends PeerSharedConfig { - - private String peerPath; - - private String consensusConf = "bftsmart.default.config"; // 默认为bftsmart配置 - - private String privKey; - - private String encodePwd; - - private String dbName; - - private MasterConfig masterConfig; - - public String bindingOutPath() { - return peerPath + UmpConstant.PATH_CONFIG; - } - - public String localConfPath() { - return peerPath + UmpConstant.PATH_LOCAL_CONFIG; - } - - public String ledgerInitConfPath() { - return peerPath + UmpConstant.PATH_LEDGER_INIT_CONFIG; - } - - public String consensusConfPath() { - return peerPath + UmpConstant.PATH_CONFIG_INIT + File.separator + consensusConf; - } - - public String libsDirectory() { - return peerPath + UmpConstant.PATH_LIBS; - } - - public String getPeerPath() { - return peerPath; - } - - public void setPeerPath(String peerPath) { - this.peerPath = peerPath; - } - - public String getConsensusConf() { - return consensusConf; - } - - public void setConsensusConf(String consensusConf) { - this.consensusConf = consensusConf; - } - - public String getPrivKey() { - return privKey; - } - - public void setPrivKey(String privKey) { - this.privKey = privKey; - } - - public String getEncodePwd() { - return encodePwd; - } - - public void setEncodePwd(String encodePwd) { - this.encodePwd = encodePwd; - } - - public String getDbName() { - return dbName; - } - - public void setDbName(String dbName) { - this.dbName = dbName; - } - - public MasterConfig getMasterConfig() { - return masterConfig; - } - - public void setMasterConfig(MasterConfig masterConfig) { - this.masterConfig = masterConfig; - } - - public synchronized PartiNode toPartiNode(int nodeId) { - if (this.partiNode != null) { - return partiNode; - } - partiNode = new PartiNode(); - partiNode.setId(nodeId); - partiNode.setName(name); - partiNode.setInitHost(initAddr); - partiNode.setInitPort(initPort); - partiNode.setPubKey(pubKey); - partiNode.setSecure(false); - return partiNode; - } - - public LedgerPeerInstall toLedgerPeerInstall(int totalNodeSize) { - return new LedgerPeerInstall(name, sharedKey, peerPath, totalNodeSize); - } - - public LedgerMasterInstall.PeerInstall toPeerInstall() { - return new LedgerMasterInstall.PeerInstall(name, pubKey, initAddr, initPort, consensusNode, consensusProvider); - } - - public void verify() { - - // 主要校验dbName地址是否存在 - String dbPath = peerPath + File.separator + dbName; - File dbDir = new File(dbPath); - if (dbDir.exists()) { - throw new IllegalStateException(String.format("DB name = %s, path = %s is exist !!!", dbName, dbPath)); - } - - // 其他配置信息是否正确 - if (masterConfig == null) { - // Master不能为空 - throw new IllegalStateException("Master Config can not be NULL !!!"); - } - if (masterConfig.isMaster()) { - // 账本名字及NodeSize不能为空 - if (masterConfig.getLedgerName() == null || masterConfig.getLedgerName().length() == 0) { - throw new IllegalStateException("Master 's LedgerName can not be empty !!!"); - } - if (masterConfig.getNodeSize() == 0) { - throw new IllegalStateException("Master 's NodeSize can not be Zero !!!"); - } - } else { - // 普通Peer需要检查Master的IP地址及端口 - if (masterConfig.getMasterAddr() == null || masterConfig.getMasterAddr().length() == 0) { - throw new IllegalStateException("Master 's IP Address can not be empty !!!"); - } - - if (masterConfig.getMasterPort() == 0) { - throw new IllegalStateException("Master 's Port must be Set !!!"); - } - } - } - - public boolean master() { - return masterConfig.isMaster(); - } - - public MasterAddr masterAddr() { - return masterConfig.toMasterAddr(); - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerSharedConfig.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerSharedConfig.java deleted file mode 100644 index cf5d71ef..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerSharedConfig.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.jd.blockchain.ump.model.config; - -import com.jd.blockchain.ump.model.PartiNode; - -public class PeerSharedConfig { - - public static final String DB_ROCKSDB_SUFFIX = "rocksdb_"; - - protected String sharedKey; - - protected String name; - - protected String initAddr; - - protected String pubKey; - - protected int initPort; - - protected String consensusNode; - - protected String consensusProvider = "com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"; - - protected PartiNode partiNode; - - public String getSharedKey() { - return sharedKey; - } - - public void setSharedKey(String sharedKey) { - this.sharedKey = sharedKey; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getInitAddr() { - return initAddr; - } - - public void setInitAddr(String initAddr) { - this.initAddr = initAddr; - } - - public String getPubKey() { - return pubKey; - } - - public void setPubKey(String pubKey) { - this.pubKey = pubKey; - } - - public int getInitPort() { - return initPort; - } - - public void setInitPort(int initPort) { - this.initPort = initPort; - } - - public String addr() { - return initAddr + "-" + initPort; - } - - public String getConsensusNode() { - return consensusNode; - } - - public void setConsensusNode(String consensusNode) { - this.consensusNode = consensusNode; - } - - public String getConsensusProvider() { - return consensusProvider; - } - - public void setConsensusProvider(String consensusProvider) { - this.consensusProvider = consensusProvider; - } - - -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerSharedConfigVv.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerSharedConfigVv.java deleted file mode 100644 index 6e536b32..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/config/PeerSharedConfigVv.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.jd.blockchain.ump.model.config; - - -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.model.user.UserKeys; - -/** - * - */ -public class PeerSharedConfigVv { - - private String sharedKey; - - private String name; - - private int userId; - - private String pubKey; - - private String initAddr; - - private int initPort; - - private String consensusNode; - - private String peerPath = UmpConstant.PROJECT_PATH; - - private String dbName; - - private int nodeSize; - - private String masterAddr; - - private int masterPort; - - private String ledgerName; - - public String getSharedKey() { - return sharedKey; - } - - public void setSharedKey(String sharedKey) { - this.sharedKey = sharedKey; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getUserId() { - return userId; - } - - public void setUserId(int userId) { - this.userId = userId; - } - - public String getInitAddr() { - return initAddr; - } - - public String getPubKey() { - return pubKey; - } - - public void setPubKey(String pubKey) { - this.pubKey = pubKey; - } - - public void setInitAddr(String initAddr) { - this.initAddr = initAddr; - } - - public int getInitPort() { - return initPort; - } - - public void setInitPort(int initPort) { - this.initPort = initPort; - } - - public String getConsensusNode() { - return consensusNode; - } - - public void setConsensusNode(String consensusNode) { - this.consensusNode = consensusNode; - } - - public String getPeerPath() { - return peerPath; - } - - public void setPeerPath(String peerPath) { - this.peerPath = peerPath; - } - - public String getDbName() { - return dbName; - } - - public void setDbName(String dbName) { - this.dbName = dbName; - } - - public int getNodeSize() { - return nodeSize; - } - - public void setNodeSize(Integer nodeSize) { - this.nodeSize = nodeSize; - } - - public String getMasterAddr() { - return masterAddr; - } - - public void setMasterAddr(String masterAddr) { - this.masterAddr = masterAddr; - } - - public int getMasterPort() { - return masterPort; - } - - public void setMasterPort(Integer masterPort) { - this.masterPort = masterPort; - } - - public String getLedgerName() { - return ledgerName; - } - - public void setLedgerName(String ledgerName) { - this.ledgerName = ledgerName; - } - - public PeerLocalConfig toPeerLocalConfig(UserKeys userKeys) { - - PeerLocalConfig localConfig = new PeerLocalConfig(); - - localConfig.setSharedKey(sharedKey); - localConfig.setName(name); - localConfig.setInitAddr(initAddr); - localConfig.setInitPort(initPort); - localConfig.setConsensusNode(consensusNode); - localConfig.setPubKey(userKeys.getPubKey()); - localConfig.setPrivKey(userKeys.getPrivKey()); - localConfig.setEncodePwd(userKeys.getEncodePwd()); - localConfig.setPeerPath(peerPath); - localConfig.setDbName(dbName); - - MasterConfig masterConfig = new MasterConfig(); - - if (master()) { - masterConfig.buildIsMaster(true) - .buildLedgerName(ledgerName) - .buildNodeSize(nodeSize); - } else { - masterConfig.buildIsMaster(false) - .buildMasterAddr(masterAddr) - .buildMasterPort(masterPort); - } - - localConfig.setMasterConfig(masterConfig); - - return localConfig; - } - - private boolean master() { - if (masterAddr == null || masterAddr.length() == 0) { - return true; - } - return false; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/DataAccountSchema.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/DataAccountSchema.java deleted file mode 100644 index a2b43d70..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/DataAccountSchema.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jd.blockchain.ump.model.penetrate; - -import java.util.List; - -/** - * 数据账户信息 - * @author zhaogw - * date 2019/7/26 14:49 - */ -public class DataAccountSchema { - private String ledgerHash; - private String dataAccount; - private String memo; - private List fieldSchemaList; - - public String getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(String ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public String getDataAccount() { - return dataAccount; - } - - public void setDataAccount(String dataAccount) { - this.dataAccount = dataAccount; - } - - public String getMemo() { - return memo; - } - - public void setMemo(String memo) { - this.memo = memo; - } - - public List getFieldSchemaList() { - return fieldSchemaList; - } - - public void setFieldSchemaList(List fieldSchemaList) { - this.fieldSchemaList = fieldSchemaList; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/FieldSchema.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/FieldSchema.java deleted file mode 100644 index 40605128..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/FieldSchema.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jd.blockchain.ump.model.penetrate; - -/** - * ump中记录的字段信息; - * @author zhaogw - * date 2019/7/26 14:50 - */ -public class FieldSchema { - private String code; - private String fieldType; - private boolean isPrimary; - //备注; - private String memo; - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getFieldType() { - return fieldType; - } - - public void setFieldType(String fieldType) { - this.fieldType = fieldType; - } - - public boolean isPrimary() { - return isPrimary; - } - - public void setPrimary(boolean primary) { - isPrimary = primary; - } - - public String getMemo() { - return memo; - } - - public void setMemo(String memo) { - this.memo = memo; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/LeaderDomain.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/LeaderDomain.java deleted file mode 100644 index cfb5ed58..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/LeaderDomain.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jd.blockchain.ump.model.penetrate; - -import com.alibaba.fastjson.annotation.JSONField; - -import java.util.List; - -/** - * mediator's domain; - * @author zhaogw - * date 2019/7/2 18:02 - */ -public class LeaderDomain { - - @JSONField(name="host") - private String host; - - @JSONField(name="port") - private String port; - - @JSONField(name="createTime") - private String createTime; - - @JSONField(name="ledgerSeed") - private String ledgerSeed; - - @JSONField(name="peerDomainList") - private List peerDomainList; - - @JSONField(name="ledgerHash") - private String ledgerHash; - - public List getPeerDomainList() { - return peerDomainList; - } - - public void setPeerDomainList(List peerDomainList) { - this.peerDomainList = peerDomainList; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public String getLedgerSeed() { - return ledgerSeed; - } - - public void setLedgerSeed(String ledgerSeed) { - this.ledgerSeed = ledgerSeed; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public String getPort() { - return port; - } - - public void setPort(String port) { - this.port = port; - } - - public String getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(String ledgerHash) { - this.ledgerHash = ledgerHash; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/PeerDomain.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/PeerDomain.java deleted file mode 100644 index 96379e15..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/PeerDomain.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.jd.blockchain.ump.model.penetrate; - -import com.alibaba.fastjson.annotation.JSONField; - -/** - * @author zhaogw - * date 2019/7/2 10:10 - */ -public class PeerDomain { - @JSONField(name="peerId") - private int peerId; - - private String basePath; - - @JSONField(name="peerName") - private String peerName; - - @JSONField(name="host") - private String host; - - private String serverPort; - - @JSONField(name="initPort") - private String initPort; - - @JSONField(name="consensusPort") - private String consensusPort; - - @JSONField(name="visitPort") - private String visitPort; - - @JSONField(name="mediatorUrl") - private String mediatorUrl; - - private String dbUri; - - private boolean gatewayBindPeer; - - //the random String from front input by mouse device; - private String randomSeed; - - @JSONField(name="peerPubKey") - private String peerPubKey; - - private String peerPrivKey; - - private String peerRawPasswd; - private String peerPasswd; - - public int getPeerId() { - return peerId; - } - - public void setPeerId(int peerId) { - this.peerId = peerId; - } - - public String getBasePath() { - return basePath; - } - - public void setBasePath(String basePath) { - this.basePath = basePath; - } - - public String getPeerName() { - return peerName; - } - - public void setPeerName(String peerName) { - this.peerName = peerName; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public String getServerPort() { - return serverPort; - } - - public void setServerPort(String serverPort) { - this.serverPort = serverPort; - } - - public String getInitPort() { - return initPort; - } - - public void setInitPort(String initPort) { - this.initPort = initPort; - } - - public String getConsensusPort() { - return consensusPort; - } - - public void setConsensusPort(String consensusPort) { - this.consensusPort = consensusPort; - } - - public String getVisitPort() { - return visitPort; - } - - public void setVisitPort(String visitPort) { - this.visitPort = visitPort; - } - - public String getMediatorUrl() { - return mediatorUrl; - } - - public void setMediatorUrl(String mediatorUrl) { - this.mediatorUrl = mediatorUrl; - } - - public String getDbUri() { - return dbUri; - } - - public void setDbUri(String dbUri) { - this.dbUri = dbUri; - } - - public boolean isGatewayBindPeer() { - return gatewayBindPeer; - } - - public void setGatewayBindPeer(boolean gatewayBindPeer) { - this.gatewayBindPeer = gatewayBindPeer; - } - - public String getRandomSeed() { - return randomSeed; - } - - public void setRandomSeed(String randomSeed) { - this.randomSeed = randomSeed; - } - - public String getPeerPubKey() { - return peerPubKey; - } - - public void setPeerPubKey(String peerPubKey) { - this.peerPubKey = peerPubKey; - } - - public String getPeerPrivKey() { - return peerPrivKey; - } - - public void setPeerPrivKey(String peerPrivKey) { - this.peerPrivKey = peerPrivKey; - } - - public String getPeerRawPasswd() { - return peerRawPasswd; - } - - public void setPeerRawPasswd(String peerRawPasswd) { - this.peerRawPasswd = peerRawPasswd; - } - - public String getPeerPasswd() { - return peerPasswd; - } - - public void setPeerPasswd(String peerPasswd) { - this.peerPasswd = peerPasswd; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/SchemaDomain.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/SchemaDomain.java deleted file mode 100644 index 2e9d986c..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/SchemaDomain.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.jd.blockchain.ump.model.penetrate; - -import com.alibaba.fastjson.annotation.JSONField; -import com.jd.blockchain.ump.model.UmpConstant; -import org.springframework.util.CollectionUtils; - -import java.util.List; - -/** - * @author zhaogw - * date 2019/7/19 11:33 - */ -public class SchemaDomain { - - @JSONField(serialize = false) - private String schemaId; - - @JSONField(serialize = false) - private String schemaAllId; - - @JSONField(name="ledger") - private String ledgerHash; - - @JSONField(name="associate_account") - private String dataAccount; - - @JSONField(serialize = false) - private List fieldSchemaList; - - private String content; - - public String getSchemaId() { - return schemaId; - } - - public void setSchemaId(String schemaId) { - this.schemaId = schemaId; - } - - public String getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(String ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public String getDataAccount() { - return dataAccount; - } - - public void setDataAccount(String dataAccount) { - this.dataAccount = dataAccount; - } - - public String getContent() { - if(CollectionUtils.isEmpty(fieldSchemaList)){ - throw new IllegalStateException("content is empty! you must choose the field first!"); - } - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append("type "+this.schemaId).append("{").append(" "); - for(FieldSchema fieldSchema : fieldSchemaList){ - if(fieldSchema.isPrimary()){ - stringBuffer.append(fieldSchema.getCode()+"(isPrimaryKey: Boolean = true):"+fieldSchema.getFieldType()).append(" "); - }else { - stringBuffer.append(fieldSchema.getCode()+":"+fieldSchema.getFieldType()).append(" "); - } - } - stringBuffer.append("}"); - return stringBuffer.toString(); - } - - public void setContent(String content) { - this.content = content; - } - - public List getFieldSchemaList() { - return fieldSchemaList; - } - - public void setFieldSchemaList(List fieldSchemaList) { - this.fieldSchemaList = fieldSchemaList; - } - - public String getSchemaAllId() { - this.schemaAllId = schemaId+ UmpConstant.DELIMETER_MINUS+ledgerHash.substring(0,6)+ - UmpConstant.DELIMETER_MINUS+ dataAccount.substring(0,6); - return schemaAllId; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/store/MemQueue.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/store/MemQueue.java deleted file mode 100644 index 315b6ba5..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/store/MemQueue.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jd.blockchain.ump.model.penetrate.store; - -import com.jd.blockchain.ump.model.UmpConstant; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * 通过枚举的方式来实现内存队列;避免大并发时引起的不必要的多次实例化; - * - * @author zhaoguangwei - * - */ -public enum MemQueue { - instance; - private BlockingQueue queue = null; - - private MemQueue() { - queue = new LinkedBlockingQueue(); - } - - /** - * 记录放入内存队列; - * @param key - * @return - */ - public boolean put(String key) { - boolean rtn = false; - try { - while (queue.size() >= UmpConstant.MEMORY_MAP_MAX_COUNT) { - queue.remove(); - } - queue.add(key); - rtn = true; - } catch (Exception e) { - e.printStackTrace(); - } - return rtn; - } - - /** - * 从内存队列取出一条记录; - * - * @return - */ - public String get() { - String record = null; - try { - record = queue.take(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return record; - } - - /** - * 内存队列清除; - */ - public void clear() { - queue.clear(); - } - - /** - * 获得记录数; - * - * @return - */ - public int size() { - return queue.size(); - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/store/MemStore.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/store/MemStore.java deleted file mode 100644 index 99d2a06c..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/penetrate/store/MemStore.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jd.blockchain.ump.model.penetrate.store; - -import com.jd.blockchain.ump.model.UmpConstant; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import static com.jd.blockchain.ump.model.UmpConstant.MEMORY_MAP_MAX_COUNT; -import static com.jd.blockchain.ump.model.UmpConstant.MEMORY_MAP_REMOVE_COUNT; - -/** - * @author zhaogw - * date 2019/7/17 17:10 - */ -public enum MemStore { - instance; - - private Map records = null; - - MemStore(){ - records = new ConcurrentHashMap(); - } - - public Object get(String key){ - return records.get(key); - } - - public Object remove(String key){ - return records.remove(key); - } - - public boolean put(String key, Object obj){ - boolean rtn = false; - MemQueue.instance.put(key); - if(records.size()>MEMORY_MAP_MAX_COUNT){ - //clear 50 records; - for(int i=0; i< MEMORY_MAP_REMOVE_COUNT; i++){ - String _key = MemQueue.instance.get(); - if(_key.equals(UmpConstant.ALL_LEDGER)){ - //don't remove the all_ledger; - continue; - } - records.remove(_key); - } - } - records.put(key,obj); - return true; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/InstallProcess.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/InstallProcess.java deleted file mode 100644 index a373f5be..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/InstallProcess.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -public class InstallProcess { - - private String content; - - public InstallProcess() { - } - - public InstallProcess(String content) { - this.content = content; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/InstallSchedule.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/InstallSchedule.java deleted file mode 100644 index 66f26ebb..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/InstallSchedule.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -public class InstallSchedule { - - private String ledgerKey; - - private String ledgerAndNodeKey; - - private InstallProcess process; - - private ScheduleState state; - - public InstallSchedule() { - } - - public InstallSchedule(String ledgerKey, String ledgerAndNodeKey, InstallProcess process, ScheduleState state) { - this.ledgerKey = ledgerKey; - this.ledgerAndNodeKey = ledgerAndNodeKey; - this.process = process; - this.state = state; - } - - public String getLedgerKey() { - return ledgerKey; - } - - public void setLedgerKey(String ledgerKey) { - this.ledgerKey = ledgerKey; - } - - public String getLedgerAndNodeKey() { - return ledgerAndNodeKey; - } - - public void setLedgerAndNodeKey(String ledgerAndNodeKey) { - this.ledgerAndNodeKey = ledgerAndNodeKey; - } - - public InstallProcess getProcess() { - return process; - } - - public void setProcess(InstallProcess process) { - this.process = process; - } - - public ScheduleState getState() { - return state; - } - - public void setState(ScheduleState state) { - this.state = state; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerBindingConf.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerBindingConf.java deleted file mode 100644 index 7843dade..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerBindingConf.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -import java.util.Set; - -public class LedgerBindingConf { - - private Set ledgerHashs; - - private long lastTime; - - public LedgerBindingConf() { - } - - public LedgerBindingConf(long lastTime) { - this.lastTime = lastTime; - } - - public Set getLedgerHashs() { - return ledgerHashs; - } - - public void setLedgerHashs(Set ledgerHashs) { - this.ledgerHashs = ledgerHashs; - } - - public long getLastTime() { - return lastTime; - } - - public void setLastTime(long lastTime) { - this.lastTime = lastTime; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerInited.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerInited.java deleted file mode 100644 index 64445781..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerInited.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -public class LedgerInited { - - private String ledgerHash; - - private String ledgerName; - - private String partiName; - - private String partiAddress; - - private String dbUri; - - private StartupState startupState = StartupState.UNKNOWN; - - public LedgerInited() { - } - - public LedgerInited(String ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public String getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(String ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public String getLedgerName() { - return ledgerName; - } - - public void setLedgerName(String ledgerName) { - this.ledgerName = ledgerName; - } - - public String getPartiName() { - return partiName; - } - - public void setPartiName(String partiName) { - this.partiName = partiName; - } - - public String getPartiAddress() { - return partiAddress; - } - - public void setPartiAddress(String partiAddress) { - this.partiAddress = partiAddress; - } - - public String getDbUri() { - return dbUri; - } - - public void setDbUri(String dbUri) { - this.dbUri = dbUri; - } - - public StartupState getStartupState() { - return startupState; - } - - public void setStartupState(StartupState startupState) { - this.startupState = startupState; - } - - public LedgerInited buildLedgerHash(String ledgerHash) { - setLedgerHash(ledgerHash); - return this; - } - - public LedgerInited buildLedgerName(String ledgerName) { - setLedgerName(ledgerName); - return this; - } - - public LedgerInited buildPartiName(String partiName) { - setPartiName(partiName); - return this; - } - - public LedgerInited buildPartiAddress(String partiAddress) { - setPartiAddress(partiAddress); - return this; - } - - public LedgerInited buildDbUri(String dbUri) { - setDbUri(dbUri); - return this; - } - - public LedgerInited buildStartupState(StartupState startupState) { - setStartupState(startupState); - return this; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerMasterInstall.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerMasterInstall.java deleted file mode 100644 index 76ca3d41..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerMasterInstall.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -public class LedgerMasterInstall { - - private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - private String ledgerKey; - - private int totalNodeSize; - - private String createTime; - - private List peerInstalls = new ArrayList<>(); - - public LedgerMasterInstall() { - } - - public LedgerMasterInstall(String ledgerKey, int totalNodeSize) { - this.ledgerKey = ledgerKey; - this.totalNodeSize = totalNodeSize; - } - - public LedgerMasterInstall initCreateTime(String createTime) { - this.createTime = createTime; - return this; - } - - public LedgerMasterInstall initCreateTime(Date date) { - this.createTime = SDF.format(date); - return this; - } - - public LedgerMasterInstall add(PeerInstall peerInstall) { - peerInstalls.add(peerInstall); - return this; - } - - public LedgerMasterInstall add(String name, String pubKey, String ipAddr, int initPort, - String consensusNode, String consensusProvider) { - PeerInstall peerInstall = new PeerInstall( - name, pubKey, ipAddr, initPort, consensusNode, consensusProvider); - return add(peerInstall); - } - - public String getLedgerKey() { - return ledgerKey; - } - - public void setLedgerKey(String ledgerKey) { - this.ledgerKey = ledgerKey; - } - - public int getTotalNodeSize() { - return totalNodeSize; - } - - public void setTotalNodeSize(int totalNodeSize) { - this.totalNodeSize = totalNodeSize; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public List getPeerInstalls() { - return peerInstalls; - } - - public void setPeerInstalls(List peerInstalls) { - this.peerInstalls = peerInstalls; - } - - public static class PeerInstall { - - private String name; - - private String pubKey; - - private String ipAddr; - - private int initPort; - - private String consensusNode; - - private String consensusProvider; - - public PeerInstall() { - } - - public PeerInstall(String name, String pubKey, String ipAddr, int initPort, String consensusNode, String consensusProvider) { - this.name = name; - this.pubKey = pubKey; - this.ipAddr = ipAddr; - this.initPort = initPort; - this.consensusNode = consensusNode; - this.consensusProvider = consensusProvider; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPubKey() { - return pubKey; - } - - public void setPubKey(String pubKey) { - this.pubKey = pubKey; - } - - public String getIpAddr() { - return ipAddr; - } - - public void setIpAddr(String ipAddr) { - this.ipAddr = ipAddr; - } - - public int getInitPort() { - return initPort; - } - - public void setInitPort(int initPort) { - this.initPort = initPort; - } - - public String getConsensusNode() { - return consensusNode; - } - - public void setConsensusNode(String consensusNode) { - this.consensusNode = consensusNode; - } - - public String getConsensusProvider() { - return consensusProvider; - } - - public void setConsensusProvider(String consensusProvider) { - this.consensusProvider = consensusProvider; - } - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerPeerInited.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerPeerInited.java deleted file mode 100644 index 7026aa57..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerPeerInited.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -public class LedgerPeerInited { - - private String ledgerHash; - - private LedgerPeerInstall peerInstall; - - private StartupState startupState; - - public LedgerPeerInited() { - } - - public LedgerPeerInited(String ledgerHash, LedgerPeerInstall peerInstall) { - this.ledgerHash = ledgerHash; - this.peerInstall = peerInstall; - } - - public String getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(String ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public LedgerPeerInstall getPeerInstall() { - return peerInstall; - } - - public void setPeerInstall(LedgerPeerInstall peerInstall) { - this.peerInstall = peerInstall; - } - - public StartupState getStartupState() { - return startupState; - } - - public void setStartupState(StartupState startupState) { - this.startupState = startupState; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerPeerInstall.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerPeerInstall.java deleted file mode 100644 index 932d621c..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/LedgerPeerInstall.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -import com.jd.blockchain.ump.model.MasterAddr; - -import java.text.SimpleDateFormat; -import java.util.Date; - -public class LedgerPeerInstall { - - private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - private String ledgerKey; - - private String ledgerAndNodeKey; - - private String nodeName; - - private String sharedKey; - - private String peerPath; - - private int totalNodeSize; - - private MasterAddr masterAddr; - - private String createTime; - - public LedgerPeerInstall() { - } - - public LedgerPeerInstall(String nodeName, String sharedKey, String peerPath, int totalNodeSize) { - this.nodeName = nodeName; - this.sharedKey = sharedKey; - this.peerPath = peerPath; - this.totalNodeSize = totalNodeSize; - } - - public LedgerPeerInstall initKey(String ledgerKey, String ledgerAndNodeKey) { - this.ledgerKey = ledgerKey; - this.ledgerAndNodeKey = ledgerAndNodeKey; - return this; - } - - public LedgerPeerInstall initMasterAddr(MasterAddr masterAddr) { - this.masterAddr = masterAddr; - return this; - } - - public LedgerPeerInstall initCreateTime(Date date) { - createTime = SDF.format(date); - return this; - } - - public String getLedgerKey() { - return ledgerKey; - } - - public void setLedgerKey(String ledgerKey) { - this.ledgerKey = ledgerKey; - } - - public String getLedgerAndNodeKey() { - return ledgerAndNodeKey; - } - - public void setLedgerAndNodeKey(String ledgerAndNodeKey) { - this.ledgerAndNodeKey = ledgerAndNodeKey; - } - - public String getNodeName() { - return nodeName; - } - - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } - - public String getSharedKey() { - return sharedKey; - } - - public void setSharedKey(String sharedKey) { - this.sharedKey = sharedKey; - } - - public String getPeerPath() { - return peerPath; - } - - public void setPeerPath(String peerPath) { - this.peerPath = peerPath; - } - - public int getTotalNodeSize() { - return totalNodeSize; - } - - public void setTotalNodeSize(int totalNodeSize) { - this.totalNodeSize = totalNodeSize; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public MasterAddr getMasterAddr() { - return masterAddr; - } - - public void setMasterAddr(MasterAddr masterAddr) { - this.masterAddr = masterAddr; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerInstallSchedule.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerInstallSchedule.java deleted file mode 100644 index dc85343a..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerInstallSchedule.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -public class PeerInstallSchedule { - - private InstallProcess process; - - private ScheduleState state; - - public PeerInstallSchedule() { - } - - public PeerInstallSchedule(InstallProcess process, ScheduleState state) { - this.process = process; - this.state = state; - } - - public InstallProcess getProcess() { - return process; - } - - public void setProcess(InstallProcess process) { - this.process = process; - } - - public ScheduleState getState() { - return state; - } - - public void setState(ScheduleState state) { - this.state = state; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerInstallSchedules.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerInstallSchedules.java deleted file mode 100644 index d6aaa7b1..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerInstallSchedules.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -import com.jd.blockchain.ump.model.config.LedgerIdentification; - -import java.util.ArrayList; -import java.util.List; - -public class PeerInstallSchedules { - - private String ledgerHash; - - private LedgerIdentification identification; - - private List installSchedules = new ArrayList<>(); - - public PeerInstallSchedules() { - } - - public PeerInstallSchedules(LedgerIdentification identification) { - this.identification = identification; - } - - public PeerInstallSchedules(LedgerIdentification identification, String ledgerHash) { - this.identification = identification; - this.ledgerHash = ledgerHash; - } - - public PeerInstallSchedules addInstallSchedule(PeerInstallSchedule installSchedule) { - this.installSchedules.add(installSchedule); - return this; - } - - public PeerInstallSchedules initLedgerHash(String ledgerHash) { - setLedgerHash(ledgerHash); - return this; - } - - public String getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(String ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public LedgerIdentification getIdentification() { - return identification; - } - - public void setIdentification(LedgerIdentification identification) { - this.identification = identification; - } - - public List getInstallSchedules() { - return installSchedules; - } - - public void setInstallSchedules(List installSchedules) { - this.installSchedules = installSchedules; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerStartupSchedules.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerStartupSchedules.java deleted file mode 100644 index ba9ac9da..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/PeerStartupSchedules.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -import java.util.ArrayList; -import java.util.List; - -public class PeerStartupSchedules { - - private String peerPath; - - private List installSchedules = new ArrayList<>(); - - public PeerStartupSchedules() { - } - - public PeerStartupSchedules(String peerPath) { - this.peerPath = peerPath; - } - - - public PeerStartupSchedules addInstallSchedule(PeerInstallSchedule installSchedule) { - this.installSchedules.add(installSchedule); - return this; - } - - public List getInstallSchedules() { - return installSchedules; - } - - public void setInstallSchedules(List installSchedules) { - this.installSchedules = installSchedules; - } - - public String getPeerPath() { - return peerPath; - } - - public void setPeerPath(String peerPath) { - this.peerPath = peerPath; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/ScheduleState.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/ScheduleState.java deleted file mode 100644 index 6307e498..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/ScheduleState.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -public enum ScheduleState { - - /** - * 加载内容,包括获取各种数据列表 - */ - LOAD, - LOAD_SUCCESS, // 加载成功 - LOAD_FAIL, // 加载失败 - - /** - * 将获取的数据写入文件 - * - */ - WRITE, - WRITE_SUCCESS, // 写入文件成功 - WRITE_FAIL, // 写入文件失败 - - /** - * Ledger_INIT:账本初始化过程 - * 主要是调用SHELL - * - */ - INIT, - INIT_SUCCESS, // 账本初始化成功 - INIT_FAIL, // 账本初始化失败 - - /** - * 无须启动PEER,等待PEER自动更新账本信息 - */ - NO_STARTUP, - - /** - * 启动Peer节点 - */ - STARTUP_START, - STARTUP_OVER, - STARTUP_SUCCESS, // Peer节点启动成功 - STARTUP_FAIL, // Peer节点启动失败 - ; - -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/StartupState.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/StartupState.java deleted file mode 100644 index d605ccd8..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/state/StartupState.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jd.blockchain.ump.model.state; - -public enum StartupState { - - /** - * UNEXIST - * 不存在,描述该账本Hash曾经创建,但目前在LedgerBinding.conf文件中不存在 - * 此状态不支持任何其他操作 - */ - UNEXIST, - - /** - * UNLOAD - * 账本存在,但未加载 - * 此状态可以启动,不能停止 - */ - UNLOAD, - - /** - * LOADING - * 账本加载中,说明程序已经启动,但尚未加载该程序 - * 此状态不可以启动,不建议停止 - */ - LOADING, - - /** - * LOADED - * 账本已加载 - * 此状态不可以启动,后续可以支持停止操作 - */ - LOADED, - - /** - * UNKNOWN - * 未知,常见于命令检测执行错误或程序启动,但账本尚未加载完成 - * 此状态不支持任何其他操作 - */ - UNKNOWN, - - /** - * DB_UNEXIST - * 该账本对应的数据库不存在 - * 此状态不支持任何其他操作 - */ - DB_UNEXIST, - - ; -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeyBuilder.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeyBuilder.java deleted file mode 100644 index e3967c01..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeyBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jd.blockchain.ump.model.user; - -public class UserKeyBuilder { - - private String name; - - private String seed; - - private String pwd; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getSeed() { - return seed; - } - - public void setSeed(String seed) { - this.seed = seed; - } - - public String getPwd() { - return pwd; - } - - public void setPwd(String pwd) { - this.pwd = pwd; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeys.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeys.java deleted file mode 100644 index 121d3ed7..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeys.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jd.blockchain.ump.model.user; - -public class UserKeys { - - private int id; - - private String name; - - private String privKey; - - private String pubKey; - - private String encodePwd; - - public UserKeys() { - } - - public UserKeys(String name, String privKey, String pubKey, String encodePwd) { - this.name = name; - this.privKey = privKey; - this.pubKey = pubKey; - this.encodePwd = encodePwd; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPrivKey() { - return privKey; - } - - public void setPrivKey(String privKey) { - this.privKey = privKey; - } - - public String getPubKey() { - return pubKey; - } - - public void setPubKey(String pubKey) { - this.pubKey = pubKey; - } - - public String getEncodePwd() { - return encodePwd; - } - - public void setEncodePwd(String encodePwd) { - this.encodePwd = encodePwd; - } - - public UserKeysVv toUserKeysVv() { - return new UserKeysVv(id, name, privKey, pubKey); - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeysVv.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeysVv.java deleted file mode 100644 index 90eaae9c..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/user/UserKeysVv.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jd.blockchain.ump.model.user; - -public class UserKeysVv { - - public static final int PRIVKEY_HEADER_LENGTH = 4; - - public static final int PRIVKEY_TAIL_LENGTH = 8; - - public static final String PRIVKEY_HIDE_CONTENT = "******"; - - private int id; - - private String name; - - private String privKey; - - private String pubKey; - - public UserKeysVv() { - } - - public UserKeysVv(int id, String name, String privKey, String pubKey) { - this.id = id; - this.name = name; - this.privKey = encodePrivKey(privKey); - this.pubKey = pubKey; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPrivKey() { - return privKey; - } - - public void setPrivKey(String privKey) { - this.privKey = privKey; - } - - public String getPubKey() { - return pubKey; - } - - public void setPubKey(String pubKey) { - this.pubKey = pubKey; - } - - private String encodePrivKey(final String privKey) { - if (privKey != null && privKey.length() > (PRIVKEY_HEADER_LENGTH + PRIVKEY_TAIL_LENGTH)) { - return privKey.substring(0, PRIVKEY_HEADER_LENGTH) + - PRIVKEY_HIDE_CONTENT + - privKey.substring(privKey.length() - PRIVKEY_TAIL_LENGTH); - } - return privKey; - } -} diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/web/ErrorCode.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/web/ErrorCode.java deleted file mode 100644 index ca023e05..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/web/ErrorCode.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.ump.model.web; - -/** - * 错误代码; - */ -public enum ErrorCode { - - UNEXPECTED(5000), - ; - - private int value; - - ErrorCode(int value) { - this.value = value; - } - - public int getValue() { - return value; - } -} \ No newline at end of file diff --git a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/web/WebResponse.java b/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/web/WebResponse.java deleted file mode 100644 index 29890518..00000000 --- a/source/manager/manager-model/src/main/java/com/jd/blockchain/ump/model/web/WebResponse.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.jd.blockchain.ump.model.web; - -public class WebResponse { - - private boolean success; - - private T data; - - private ErrorMessage error; - - private WebResponse(){ - - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public ErrorMessage getError() { - return error; - } - - public void setError(ErrorMessage error) { - this.error = error; - } - - public static WebResponse createSuccessResult(Object data){ - WebResponse responseResult = new WebResponse(); - responseResult.setSuccess(true); - responseResult.setData(data); - return responseResult; - } - - public static WebResponse createFailureResult(int code, String message){ - ErrorMessage errorMessage = new ErrorMessage(code, message); - return createFailureResult(errorMessage); - } - - public static WebResponse createFailureResult(ErrorMessage errorMessage){ - WebResponse responseResult = new WebResponse(); - responseResult.setSuccess(false); - responseResult.setError(errorMessage); - return responseResult; - } - - - - /** - * 错误消息实体 - * - * @author liuxrb - * - */ - public static class ErrorMessage { - - private int errorCode; - - private String errorMessage; - - public ErrorMessage() { - - } - - public ErrorMessage(int errorCode, String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - public int getErrorCode() { - return errorCode; - } - - public void setErrorCode(int errorCode) { - this.errorCode = errorCode; - } - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataAccountUmpService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataAccountUmpService.java deleted file mode 100644 index 2f1a8457..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataAccountUmpService.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.service.DataRetrievalService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/15 下午3:08 - * Description: - */ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.penetrate.DataAccountSchema; - -/** - * data account ump store; - */ -public interface DataAccountUmpService { - /** - * 整体新增dataAccountSchema,单独某个field不会更新;如果原先库中有记录,则更新为最新内容; - * @param dataAccountSchema - */ - boolean addDataAccountSchema(DataAccountSchema dataAccountSchema); - - void deleteDataAcccountSchema(String ledgerHash, String dataAccount); - - DataAccountSchema findDataAccountSchema(String ledgerHash, String dataAccount); -} \ No newline at end of file diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataAccountUmpServiceImpl.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataAccountUmpServiceImpl.java deleted file mode 100644 index 4940c663..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataAccountUmpServiceImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.dao.DBConnection; -import com.jd.blockchain.ump.model.penetrate.DataAccountSchema; -import com.jd.blockchain.ump.model.penetrate.store.MemStore; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import static com.jd.blockchain.ump.model.UmpConstant.SCHEMA_PREFIX; -import static com.jd.blockchain.utils.BaseConstant.DELIMETER_UNDERLINE; - -/** - * @author zhaogw - * date 2019/7/26 15:14 - */ -@Service -public class DataAccountUmpServiceImpl implements DataAccountUmpService { - @Autowired - private DBConnection dbConnection; - - @Override - public boolean addDataAccountSchema(DataAccountSchema dataAccountSchema) { - dbConnection.put(SCHEMA_PREFIX+dataAccountSchema.getLedgerHash()+ - DELIMETER_UNDERLINE+dataAccountSchema.getDataAccount(),dataAccountSchema,DataAccountSchema.class); - return true; -// return MemStore.instance.put(SCHEMA_PREFIX+dataAccountSchema.getLedgerHash()+ -// DELIMETER_UNDERLINE+dataAccountSchema.getDataAccount(),dataAccountSchema); - } - - @Override - public void deleteDataAcccountSchema(String ledgerHash, String dataAccount) { - dbConnection.delete(SCHEMA_PREFIX+ledgerHash+ DELIMETER_UNDERLINE+dataAccount); -// MemStore.instance.remove(SCHEMA_PREFIX+ledgerHash+ DELIMETER_UNDERLINE+dataAccount); - } - - @Override - public DataAccountSchema findDataAccountSchema(String ledgerHash, String dataAccount) { - return dbConnection.get(SCHEMA_PREFIX+ledgerHash+ DELIMETER_UNDERLINE+dataAccount,DataAccountSchema.class); -// return (DataAccountSchema)MemStore.instance.get(SCHEMA_PREFIX+ledgerHash+ DELIMETER_UNDERLINE+dataAccount); - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataRetrievalService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataRetrievalService.java deleted file mode 100644 index 8a335872..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataRetrievalService.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.service.DataRetrievalService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/15 下午3:08 - * Description: - */ -package com.jd.blockchain.ump.service; - -import com.alibaba.fastjson.JSONObject; - -import java.util.Map; - -/** - * - * @author shaozhuguang - * @create 2019/1/15 - * @since 1.0.0 - */ - -public interface DataRetrievalService { - - String retrieval(String url) throws Exception; - String retrievalPost(String url, JSONObject jsonObject) throws Exception; - String retrievalPost(String url, String queryString) throws Exception; - String delete(String url) throws Exception; -} \ No newline at end of file diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataRetrievalServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataRetrievalServiceHandler.java deleted file mode 100644 index 55e05470..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/DataRetrievalServiceHandler.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.service.DeepQueryServiceImpl - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/15 下午3:09 - * Description: - */ -package com.jd.blockchain.ump.service; - -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.ump.util.HttpClientPool; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * - * @author shaozhuguang - * @create 2019/1/15 - * @since 1.0.0 - */ -@Component -public class DataRetrievalServiceHandler implements DataRetrievalService { - - @Override - public String retrieval(String url) throws Exception { - return HttpClientPool.get(url); - } - - @Override - public String retrievalPost(String url, JSONObject jsonObject) throws Exception { - return HttpClientPool.jsonPost(url,jsonObject.toJSONString()); - } - - @Override - public String delete(String url) throws Exception { - return HttpClientPool.delete(url); - } - - @Override - public String retrievalPost(String url, String queryString) throws Exception { - return HttpClientPool.jsonPost(url,queryString); - } -} \ No newline at end of file diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/LedgerService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/LedgerService.java deleted file mode 100644 index 77c11016..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/LedgerService.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.state.LedgerBindingConf; -import com.jd.blockchain.ump.model.state.LedgerInited; - -import java.util.List; - -public interface LedgerService { - - String randomSeed(); - - String currentCreateTime(); - - String ledgerInitCommand(String peerPath); - - String peerStartCommand(String peerPath); - - LedgerBindingConf allLedgerHashs(String peerPath); - - LedgerBindingConf allLedgerHashs(long lastTime, String peerPath); - - List allLedgerIniteds(String peerPath); - - boolean dbExist(String peerPath, String ledgerHash); - - String peerVerifyKey(String peerPath); - - void save(String ledgerAndNodeKey, String ledgerHash); - - String readLedgerHash(String ledgerAndNodeKey); -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/LedgerServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/LedgerServiceHandler.java deleted file mode 100644 index 7ff587d7..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/LedgerServiceHandler.java +++ /dev/null @@ -1,310 +0,0 @@ -package com.jd.blockchain.ump.service; - - -import com.jd.blockchain.ump.dao.DBConnection; -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.model.state.LedgerBindingConf; -import com.jd.blockchain.ump.model.state.LedgerInited; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.io.FileUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.text.SimpleDateFormat; -import java.util.*; - -@Service -public class LedgerServiceHandler implements LedgerService { - - private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); - - private static final String LEDGER_HASHS_FLAG = "ledger.bindings"; - - private static final String LEDGER_NAME_FORMAT = "binding.%s.name"; - - private static final String LEDGER_PARTI_ADDRESS_FORMAT = "binding.%s.parti.address"; - - private static final String LEDGER_PARTI_NAME_FORMAT = "binding.%s.parti.name"; - - private static final String LEDGER_DB_FORMAT = "binding.%s.db.uri"; - - private static final String FILE_PEER_FLAG = "deployment-peer"; - - private static final String JAR_SUFFIX = "jar"; - - private static final int SEED_BYTES_LENGTH = 32; - - private static final int NAME_BYTES_LENGTH = 8; - - private static final int SEED_PART_LENGTH = 8; - - private static final Random LEDGER_RANDOM = new Random(); - - @Autowired - private UmpStateService umpStateService; - - @Autowired - private DBConnection dbConnection; - - @Override - public String randomSeed() { - byte[] seedBytes = new byte[SEED_BYTES_LENGTH]; - - LEDGER_RANDOM.nextBytes(seedBytes); - - char[] seedChars = Hex.encodeHex(seedBytes); - - StringBuilder sBuilder = new StringBuilder(); - - for (int i = 0; i < seedChars.length; i++) { - if (i != 0 && i % SEED_PART_LENGTH == 0) { - sBuilder.append("-"); - } - sBuilder.append(seedChars[i]); - } - - return sBuilder.toString(); - } - - @Override - public String currentCreateTime() { - return SDF.format(new Date()); - } - - @Override - public String ledgerInitCommand(String peerPath) { - - return String.format(UmpConstant.CMD_LEDGER_INIT, - peerPath + UmpConstant.PATH_LEDGER_INIT_BIN); - } - - @Override - public String peerStartCommand(String peerPath) { - return String.format(UmpConstant.CMD_START_UP_FORMAT, - peerPath + UmpConstant.PATH_PEER_STARTUP_BIN); - } - - @Override - public LedgerBindingConf allLedgerHashs(String peerPath) { - - return allLedgerHashs(0L, peerPath); - } - - @Override - public LedgerBindingConf allLedgerHashs(long lastTime, String peerPath) { - - // 读取LedgerBingConf文件,假设该文件不存在则返回空值 - Set allLedgerHashs = new HashSet<>(); - - PropAndTime propAndTime = loadLedgerBindingConf(lastTime, peerPath); - - Properties props = propAndTime.getProp(); - - if (props != null) { - - String ledgerHashChars = props.getProperty(LEDGER_HASHS_FLAG); - - if (ledgerHashChars != null && ledgerHashChars.length() > 0) { - String[] ledgerHashArray = ledgerHashChars.split(","); - if (ledgerHashArray.length > 0) { - for (String ledgerHash : ledgerHashArray) { - allLedgerHashs.add(ledgerHash.trim()); - } - } - } - } - - LedgerBindingConf ledgerBindingConf = new LedgerBindingConf(propAndTime.getLastTime()); - - ledgerBindingConf.setLedgerHashs(allLedgerHashs); - - return ledgerBindingConf; - } - - @Override - public List allLedgerIniteds(String peerPath) { - - List ledgerIniteds = new ArrayList<>(); - - PropAndTime propAndTime = loadLedgerBindingConf(0L, peerPath); - - Properties props = propAndTime.getProp(); - - if (props != null) { - - String ledgerHashChars = props.getProperty(LEDGER_HASHS_FLAG); - - Set ledgerHashSet = new HashSet<>(); - - if (ledgerHashChars != null && ledgerHashChars.length() > 0) { - String[] ledgerHashArray = ledgerHashChars.split(","); - if (ledgerHashArray.length > 0) { - for (String ledgerHash : ledgerHashArray) { - ledgerHashSet.add(ledgerHash.trim()); - } - } - } - - // 根据Hash值,遍历Prop - for (String hash : ledgerHashSet) { - - LedgerInited ledgerInited = new LedgerInited(hash); - - String ledgerName = props.getProperty(String.format(LEDGER_NAME_FORMAT, hash)); - - String partiAddress = props.getProperty(String.format(LEDGER_PARTI_ADDRESS_FORMAT, hash)); - - String partiName = props.getProperty(String.format(LEDGER_PARTI_NAME_FORMAT, hash)); - - String dbUri = props.getProperty(String.format(LEDGER_DB_FORMAT, hash)); - - ledgerIniteds.add( - ledgerInited - .buildLedgerName(ledgerName) - .buildPartiAddress(partiAddress) - .buildPartiName(partiName) - .buildDbUri(dbUri)); - } - } - return ledgerIniteds; - } - - @Override - public synchronized boolean dbExist(String peerPath, String ledgerHash) { - // 检查该账本对应的数据库是否存在 - - PropAndTime propAndTime = loadLedgerBindingConf(0L, peerPath); - - // binding.j5faRYSqSqSRmSVgdmPsgq7Hzd1yP7yAGPWkTihekWms94.db.uri=rocksdb:///Users/shaozhuguang/Documents/ideaProjects/jdchain-patch/source/test/test-integration/rocks.db/rocksdb4.db - Properties props = propAndTime.getProp(); - - if (props != null) { - String dbKey = String.format(LEDGER_DB_FORMAT, ledgerHash); - - String dbUri = props.getProperty(dbKey); - - if (dbUri != null && dbUri.length() > 0) { - - return dbConnection.exist(dbUri); - } - } - - return false; - } - - @Override - public String peerVerifyKey(String peerPath) { - // 从libs中读取对应的Peer.jar的文件名称,配合全路径 - File libsDirectory = new File(peerPath + UmpConstant.PATH_SYSTEM); - - Collection jars = FileUtils.listFiles(libsDirectory, new String[]{JAR_SUFFIX}, false); - - String peerVerifyKey = null; - - if (!jars.isEmpty()) { - for (File jar : jars) { - String jarName = jar.getName(); - if (jarName.startsWith(FILE_PEER_FLAG)) { - peerVerifyKey = jar.getPath(); - break; - } - } - } - - return peerVerifyKey; - } - - @Override - public void save(String ledgerAndNodeKey, String ledgerHash) { - // 保存LedgerAndNodeKey与账本关系 - umpStateService.saveLedgerHash(ledgerAndNodeKey, ledgerHash); - } - - @Override - public String readLedgerHash(String ledgerAndNodeKey) { - - return umpStateService.readLedgerHash(ledgerAndNodeKey); - } - - private PropAndTime loadLedgerBindingConf(long lastTime, String peerPath) { - - File ledgerBindingConf = new File(peerPath + UmpConstant.PATH_LEDGER_BINDING_CONFIG); - - PropAndTime propAndTime = new PropAndTime(lastTime); - - // 说明被修改过 - if (ledgerBindingConf.exists() && ledgerBindingConf.lastModified() > lastTime) { - - propAndTime.lastTime = ledgerBindingConf.lastModified(); - - try (InputStream inputStream = new FileInputStream(ledgerBindingConf)) { - - Properties props = new Properties(); - - props.load(inputStream); - - propAndTime.prop = props; - - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - return propAndTime; - } - - private static class PropAndTime { - - private Properties prop; - - private long lastTime; - - public PropAndTime() { - } - - public PropAndTime(long lastTime) { - this.lastTime = lastTime; - } - - public Properties getProp() { - return prop; - } - - public void setProp(Properties prop) { - this.prop = prop; - } - - public long getLastTime() { - return lastTime; - } - - public void setLastTime(long lastTime) { - this.lastTime = lastTime; - } - } - -// private Properties loadLedgerBindingConf(String peerPath) { -// -// File ledgerBindingConf = new File(peerPath + UmpConstant.PATH_LEDGER_BINDING_CONFIG); -// -// if (ledgerBindingConf.exists()) { -// -// try (InputStream inputStream = new FileInputStream(ledgerBindingConf)) { -// -// Properties props = new Properties(); -// -// props.load(inputStream); -// -// return props; -// -// } catch (Exception e) { -// throw new IllegalStateException(e); -// } -// } -// -// return null; -// } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/SecurityService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/SecurityService.java deleted file mode 100644 index af560deb..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/SecurityService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.ump.service; - -import java.util.List; - -public interface SecurityService { - - List securityConfigs(); - - List participantRoleConfigs(); - - void init(); -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/SecurityServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/SecurityServiceHandler.java deleted file mode 100644 index d65a06da..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/SecurityServiceHandler.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.UmpConstant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -@Service -public class SecurityServiceHandler implements SecurityService { - - private static final String PATH_INNER = "/"; - - private static final Logger LOGGER = LoggerFactory.getLogger(SecurityServiceHandler.class); - - static final String SECURITY_FILE = "security.default.config"; - - private List securityConfigs = new ArrayList<>(); - - private List participantRoleConfigs = new ArrayList<>(); - - public SecurityServiceHandler() { - init(); - } - - @Override - public List securityConfigs() { - return securityConfigs; - } - - @Override - public List participantRoleConfigs() { - return participantRoleConfigs; - } - - @Override - public void init() { - - try { - // 读取配置文件中的内容 - InputStream currentFileInputStream = SecurityServiceHandler.class.getResourceAsStream( - PATH_INNER + SECURITY_FILE); - - Properties currentProps = new Properties(); - - currentProps.load(currentFileInputStream); - - // 将配置文件内容写入securityConfigs - write(currentProps); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - private void write(Properties currentProps) { - // 获取ROLES - String roles = currentProps.getProperty(UmpConstant.SECURITY_ROLES, ""); - - if (roles.length() > 0) { - - securityConfigs.add(propBuild(UmpConstant.SECURITY_ROLES, roles)); - - String[] rolesArray = roles.split(","); - for (String role : rolesArray) { - String roleRealm = role.trim(); - String roleLedgerKey = String.format(UmpConstant.SECURITY_ROLES_PRIVILEGES_LEDGER_FORMAT, roleRealm); - String roleLedgerValue = currentProps.getProperty(roleLedgerKey, ""); - securityConfigs.add(propBuild(roleLedgerKey, roleLedgerValue)); - - String roleTxKey = String.format(UmpConstant.SECURITY_ROLES_PRIVILEGES_TX_FORMAT, roleRealm); - String roleTxValue = currentProps.getProperty(roleTxKey, ""); - securityConfigs.add(propBuild(roleTxKey, roleTxValue)); - } - - // 将参与方信息写入 - String partiRolesValue = currentProps.getProperty(UmpConstant.SECURITY_PARTI_ROLES, ""); - String partiRolesPolicyValue = currentProps.getProperty(UmpConstant.SECURITY_PARTI_ROLES_POLICY, ""); - - participantRoleConfigs.add(propBuild(UmpConstant.SECURITY_PARTI_ROLES, partiRolesValue)); - participantRoleConfigs.add(propBuild(UmpConstant.SECURITY_PARTI_ROLES_POLICY, partiRolesPolicyValue)); - - } else { - // 打印日志即可 - LOGGER.error("Can not find Properties from {}", SECURITY_FILE); - } - } - - private String propBuild(String key, String value) { - return key + "=" + value; - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpService.java deleted file mode 100644 index 08e1ee4a..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpService.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.MasterAddr; -import com.jd.blockchain.ump.model.PeerSharedConfigs; -import com.jd.blockchain.ump.model.config.*; -import com.jd.blockchain.ump.model.state.PeerInstallSchedules; -import com.jd.blockchain.ump.model.state.PeerStartupSchedules; - - -public interface UmpService { - - PeerSharedConfigs loadPeerSharedConfigs(PeerLocalConfig sharedConfig); - - LedgerConfig response(PeerSharedConfigs peerSharedConfigs, PeerLocalConfig localConfig); - - String save(MasterAddr masterAddr, LedgerConfig ledgerConfig, PeerLocalConfig localConfig); - - String ledgerAndNodeKey(LedgerConfig ledgerConfig, PeerSharedConfig sharedConfig); - - PeerInstallSchedules install(LedgerIdentification identification, PeerLocalConfig localConfig, String ledgerAndNodeKey); - - PeerInstallSchedules install(String ledgerAndNodeKey); - - PeerInstallSchedules init(String ledgerAndNodeKey); - - PeerInstallSchedules init(LedgerIdentification identification, PeerLocalConfig localConfig, String ledgerAndNodeKey); - -// PeerInstallSchedules startup(String ledgerAndNodeKey); - - PeerStartupSchedules startup(); - - boolean stop(String ledgerAndNodeKey); - - boolean stop(); - -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpServiceHandler.java deleted file mode 100644 index 54ed8a9e..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpServiceHandler.java +++ /dev/null @@ -1,929 +0,0 @@ -package com.jd.blockchain.ump.service; - - -import com.jd.blockchain.ump.dao.DBConnection; -import com.jd.blockchain.ump.dao.RocksDBConnection; -import com.jd.blockchain.ump.model.MasterAddr; -import com.jd.blockchain.ump.model.PeerSharedConfigs; -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.model.config.*; -import com.jd.blockchain.ump.model.state.*; -import com.jd.blockchain.ump.service.consensus.ConsensusService; -import com.jd.blockchain.ump.util.Base58Utils; -import com.jd.blockchain.ump.util.CommandUtils; -import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.Lock; - -@Service -public class UmpServiceHandler implements UmpService { - - private final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - private static final String SUCCESS = "SUCCESS"; - - private static final String ROCKSDB_PROTOCOL = RocksDBConnection.ROCKSDB_PROTOCOL; - - private static final int DB_SUFFIX_LENGTH = 4; - - private static final Random DB_RANDOM = new Random(); - - private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmssSSS");//yyyy-MM-dd HH:mm:ss为目标的样式 - - private final Map ledgerConfigs = new ConcurrentHashMap<>(); - - private final Map masterConfigs = new ConcurrentHashMap<>(); - - private final Map peerShareds = new ConcurrentHashMap<>(); - - private final Map ledgerConfigMemory = new ConcurrentHashMap<>(); - - @Autowired - private ConsensusService consensusService; - - @Autowired - private LedgerService ledgerService; - - @Autowired - private DBConnection dbConnection; - - @Autowired - private UmpStateService umpStateService; - - @Autowired - private SecurityService securityService; - - @Override - public synchronized PeerSharedConfigs loadPeerSharedConfigs(PeerLocalConfig sharedConfig) { - - String sharedKey = sharedConfig.getSharedKey(); - - PeerSharedConfigs peerSharedConfigs = peerShareds.get(sharedKey); - - if (peerSharedConfigs == null) { - peerSharedConfigs = new PeerSharedConfigs(); - peerShareds.put(sharedKey, peerSharedConfigs); - } - - return peerSharedConfigs.addConfig(sharedConfig); - } - - @Override - public LedgerConfig response(PeerSharedConfigs sharedConfigs, PeerLocalConfig localConfig) { - try { - // 对于Master和Peer处理方式不同 - if (localConfig.getMasterConfig().isMaster()) { - - // Master节点需要等待完成后通知其他线程 - sharedConfigs.waitAndNotify(); - } else { - - // 等待Master节点通知 - sharedConfigs.await(); - } - - // 此处需要防止并发 - final String sharedKey = sharedConfigs.getSharedKey(); - - LedgerConfig savedLedgerConfig = ledgerConfigMemory.get(sharedKey); - - if (savedLedgerConfig != null) { - return savedLedgerConfig; - } - - // 获取当前对象锁(所有节点请求使用同一个对象) - final Lock lock = sharedConfigs.getLock(); - - lock.lock(); - - try { - // 执行到此表示获取到锁,此时需要判断是否有数据 - // Double Check !!! - savedLedgerConfig = ledgerConfigMemory.get(sharedKey); - - if (savedLedgerConfig != null) { - return savedLedgerConfig; - } - - // 校验 - verify(sharedConfigs); - - // 所有数据到达之后生成返回的应答 - LedgerInitConfig initConfig = sharedConfigs.ledgerInitConfig( - ledgerService.randomSeed(), ledgerService.currentCreateTime(), - securityService.securityConfigs(), securityService.participantRoleConfigs()); - - // 生成共识文件 - String consensusConfig = consensusService.initConsensusConf( - sharedConfigs.getConsensusProvider(), sharedConfigs.getSharedConfigs()); - - LedgerConfig ledgerConfig = new LedgerConfig(initConfig, consensusConfig); - - // 将本次LedgerKey信息写入数据库 - String ledgerKey = initConfig.ledgerKey(); - - dbConnection.put(ledgerKey, ledgerConfig, LedgerConfig.class); - - // 将节点的Key信息写入数据库 - umpStateService.save(ledgerKey, sharedConfigKeys(ledgerKey, sharedConfigs)); - - // 将本地生成数据的信息写入数据库 - LedgerMasterInstall masterInstall = sharedConfigs.toLedgerMasterInstall(); - - umpStateService.save(masterInstall); - - // 将数据放入内存 - ledgerConfigMemory.put(sharedKey, ledgerConfig); - - return ledgerConfig; - } finally { - lock.unlock(); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - @Override - public String save(MasterAddr masterAddr, LedgerConfig ledgerConfig, PeerLocalConfig localConfig) { - - String ledgerAndNodeKey = ledgerAndNodeKey(ledgerConfig, localConfig); - - ledgerConfigs.put(ledgerAndNodeKey, ledgerConfig); - - // 保存本次需要发送的Master地址 - masterConfigs.put(ledgerAndNodeKey, localConfig.getMasterConfig()); - - // 保存所有的信息至本地 - umpStateService.save(ledgerAndNodeKey, localConfig); - - // 保存当前同步信息至数据库 - LedgerPeerInstall peerInstall = localConfig.toLedgerPeerInstall(ledgerConfig.getInitConfig().getNodeSize()); - - // init相关配置信息 - peerInstall - .initKey(ledgerConfig.getInitConfig().ledgerKey(), ledgerAndNodeKey) - .initCreateTime(new Date()) - .initMasterAddr(masterAddr); - - // 写入数据库 - umpStateService.save(peerInstall); - - return ledgerAndNodeKey; - } - - @Override - public String ledgerAndNodeKey(LedgerConfig ledgerConfig, PeerSharedConfig sharedConfig) { - - return ledgerAndNodeKey(ledgerConfig.getInitConfig().ledgerKey(), sharedConfig); - } - - @Override - public PeerInstallSchedules install(LedgerIdentification identification, PeerLocalConfig localConfig, String ledgerAndNodeKey) { - - // 初始化Peer节点数据 - PeerInstallSchedules installSchedules = init(identification, localConfig, ledgerAndNodeKey); - - // Peer节点启动 - peerStart(localConfig.getPeerPath(), installSchedules); - - return installSchedules; - } - - @Override - public PeerInstallSchedules install(String ledgerAndNodeKey) { - - PeerLocalConfig localConfig = umpStateService.readConfig(ledgerAndNodeKey); - - if (localConfig != null) { - - // 获取LedgerIdentification - LedgerIdentification identification = umpStateService.readIdentification(ledgerAndNodeKey); - - return install(identification, localConfig, ledgerAndNodeKey); - } - throw new IllegalStateException("Can not find LocalConfig from DataBase !!!"); - } - - @Override - public PeerInstallSchedules init(LedgerIdentification identification, PeerLocalConfig localConfig, String ledgerAndNodeKey) { - - PeerInstallSchedules installSchedules = new PeerInstallSchedules(identification); - - MasterAddr masterAddr = loadMaster(localConfig); - - LedgerConfig ledgerConfig = ledgerConfigs.get(ledgerAndNodeKey); - - if (ledgerConfig == null || ledgerConfig.getInitConfig() == null) { - saveInstallSchedule(installSchedules, masterAddr, "", ledgerAndNodeKey, - String.format("Ledger Key = [%s] can not find Ledger-Config !!!", ledgerAndNodeKey), - ScheduleState.LOAD_FAIL); - throw new IllegalStateException(String.format("Ledger Key = [%s] can not find Ledger-Config !!!", ledgerAndNodeKey)); - } - - LedgerInitConfig initConfig = ledgerConfig.getInitConfig(); - - String ledgerKey = initConfig.ledgerKey(); - - List localConfContents, ledgerInitContents; - - try { - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Find LedgerConfig from Memory for Key [%s] -> %s", ledgerAndNodeKey, SUCCESS), - ScheduleState.LOAD); - - // 首先获取当前节点的ID - int nodeId = initConfig.nodeId(localConfig.getPubKey()); - - // 生成local.conf文件内容 - localConfContents = localConfContents(localConfig, nodeId); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Init Local.Conf's Content -> %s", SUCCESS), - ScheduleState.LOAD); - - // 生成LedgerInit内容 - ledgerInitContents = initConfig.toConfigChars(localConfig.consensusConfPath()); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Init Ledger.Init's Content -> %s", SUCCESS), - ScheduleState.LOAD); - } catch (Exception e) { - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - "Load Config's Content !!!", - ScheduleState.LOAD_FAIL); - throw new IllegalStateException(e); - } - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - "Load Config's Content !!!", - ScheduleState.LOAD_SUCCESS); - - try { - // 将该文件内容写入Local.Conf - forceWrite(localConfContents, new File(localConfig.localConfPath())); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Write And Backup File local.conf -> %s", SUCCESS), - ScheduleState.WRITE); - - // 将文件内容写入Ledger-Init - forceWrite(ledgerInitContents, new File(localConfig.ledgerInitConfPath())); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Write And Backup File ledger.init -> %s", SUCCESS), - ScheduleState.WRITE); - - // 将共识内容写入文件,例如bftsmart.conf - String consensusFileName = writeConsensusContent(ledgerConfig.getConsensusConfig(), - new File(localConfig.consensusConfPath())); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Write And Backup Consensus File %s -> %s", consensusFileName, SUCCESS), - ScheduleState.WRITE); - - } catch (Exception e) { - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - "Write Config's Content to Config File !!!", - ScheduleState.WRITE_FAIL); - throw new IllegalStateException(e); - } - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - "Write Config's Content to Config File !!!", - ScheduleState.WRITE_SUCCESS); - - // 账本初始化 - String ledgerHash = ledgerInit(localConfig.getPeerPath(), installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey); - - // 设置账本Hash - installSchedules.setLedgerHash(ledgerHash); - - return installSchedules; - } - - @Override - public PeerInstallSchedules init(String ledgerAndNodeKey) { - - PeerLocalConfig localConfig = umpStateService.readConfig(ledgerAndNodeKey); - - if (localConfig != null) { - - // 获取LedgerIdentification - LedgerIdentification identification = umpStateService.readIdentification(ledgerAndNodeKey); - - return init(identification, localConfig, ledgerAndNodeKey); - } - throw new IllegalStateException("Can not find LocalConfig from DataBase !!!"); - } - - -// @Override -// public PeerInstallSchedules startup(String ledgerAndNodeKey) { -// -// PeerLocalConfig localConfig = umpStateService.readConfig(ledgerAndNodeKey); -// -// if (localConfig != null) { -// -// PeerInstallSchedules installSchedules = umpStateService.loadState(ledgerAndNodeKey); -// -// // Peer节点启动 -// return peerStart(localConfig.getPeerPath(), installSchedules); -// -// } -// throw new IllegalStateException("Can not find LocalConfig from DataBase !!!"); -// } - - @Override - public PeerStartupSchedules startup() { - - PeerStartupSchedules startupSchedules = new PeerStartupSchedules(UmpConstant.PROJECT_PATH); - - return peerStart(startupSchedules); - } - - @Override - public boolean stop(String ledgerAndNodeKey) { - PeerLocalConfig localConfig = umpStateService.readConfig(ledgerAndNodeKey); - - if (localConfig != null) { - - // Peer节点停止 - return peerStop(localConfig.getPeerPath()); - } - throw new IllegalStateException("Can not find LocalConfig from DataBase !!!"); - } - - @Override - public boolean stop() { - - return peerStop(UmpConstant.PROJECT_PATH); - } - - private MasterAddr loadMaster(PeerLocalConfig localConfig) { - - // 开始安装之后则可以将内存中的数据释放 - String sharedKey = localConfig.getSharedKey(); - - if (sharedKey != null) { - ledgerConfigMemory.remove(sharedKey); - } - - if (localConfig.master()) { - return null; - } - - return localConfig.masterAddr(); - } - - private List sharedConfigKeys(String ledgerKey, PeerSharedConfigs sharedConfigs) { - - List sharedConfigKeys = new ArrayList<>(); - - List pscs = sharedConfigs.getSharedConfigs(); - - for(PeerSharedConfig psc : pscs) { - sharedConfigKeys.add(ledgerAndNodeKey(ledgerKey, psc)); - } - - return sharedConfigKeys; - } - - private String ledgerAndNodeKey(String ledgerKey, PeerSharedConfig sharedConfig) { - - return ledgerKey + "-" + sharedConfig.getName(); - } - - private String ledgerInit(String peerPath, PeerInstallSchedules installSchedules, MasterAddr masterAddr, String ledgerKey, String ledgerAndNodeKey) { - - String newLedgerHash = ""; - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - "Steps to start processing LedgerInit !!!", - ScheduleState.INIT); - - // 获取当前已经存在的Ledger列表 - LedgerBindingConf ledgerBindingConf = ledgerService.allLedgerHashs(peerPath); - - Set currentLedgerHashs = ledgerBindingConf.getLedgerHashs(); - - long lastTime = ledgerBindingConf.getLastTime(); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Find History Ledger's Size = %s", currentLedgerHashs.size()), - ScheduleState.INIT); - - String ledgerInitCommand = ledgerService.ledgerInitCommand(peerPath); - - try { - - LOGGER.info("Execute Ledger-Init's Shell {}", ledgerInitCommand); - - Process ledgerInitProcess; - - try { - // 调用ledgerInit初始化脚本 - ledgerInitProcess = CommandUtils.execute(CommandUtils.toCommandList(ledgerInitCommand)); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Execute LedgerInit's Command -> %s", SUCCESS), - ScheduleState.INIT); - } catch (Exception e) { - LOGGER.error("Execute Ledger-Init's Shell !!!", e); - throw new IllegalStateException(e); - } - - int maxSize = 512; - - boolean isInitSuccess = false; - - int checkIndex = 1; - - while (maxSize > 0) { - // 时延 - Thread.sleep(6000); - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("%s Check LedgerInit's Status ...... ", checkIndex++), - ScheduleState.INIT); - - // 检查账本是否增加 - CurrentLedger currentLedger = checkNewLedger(lastTime, peerPath, currentLedgerHashs); - - lastTime = currentLedger.getLastTime(); - - newLedgerHash = currentLedger.getLedgerHash(); - - if (newLedgerHash != null && newLedgerHash.length() > 0) { - isInitSuccess = true; - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Find New Ledger = %s", newLedgerHash), - ScheduleState.INIT); - break; - } - maxSize --; - } - - // 完成后,不管是否处理完,都将命令停止 - // 为防止其他应用仍在访问,延时6秒停止 - try { - Thread.sleep(6000); - ledgerInitProcess = ledgerInitProcess.destroyForcibly(); - if (ledgerInitProcess.isAlive()) { - // 再尝试一次 - ledgerInitProcess.destroyForcibly(); - } - } catch (Exception e) { - // 暂时打印日志 - LOGGER.error("Stop Ledger Init Command !!!", e); - } - - // 再次判断是否初始化账本成功 - if (newLedgerHash == null) { - - CurrentLedger currentLedger = checkNewLedger(lastTime, peerPath, currentLedgerHashs); - - newLedgerHash = currentLedger.getLedgerHash(); - - if (newLedgerHash != null && newLedgerHash.length() > 0) { - isInitSuccess = true; - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Final Find New Ledger = %s", newLedgerHash), - ScheduleState.INIT); - } - } - - if (!isInitSuccess) { - // 失败则抛出异常 - throw new IllegalStateException("Can Not Find New Ledger !!!"); - } - } catch (Exception e) { - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - "Execute Ledger-Init Command Fail !!!", - ScheduleState.INIT_FAIL); - LOGGER.error("Execute Ledger-Init Command Fail !!!", e); - throw new IllegalStateException(e); - } - - saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, - String.format("Steps to processing LedgerInit -> %s", SUCCESS), - ScheduleState.INIT_SUCCESS); - - // 将账本Hash写入数据库 - ledgerService.save(ledgerAndNodeKey, newLedgerHash); - - return newLedgerHash; - } - - private CurrentLedger checkNewLedger(long lastTime, String peerPath, Set currentLedgerHashs) { - // 再次判断是否初始化账本成功 - LedgerBindingConf ledgerBindingConf = ledgerService.allLedgerHashs(lastTime, peerPath); - - Set newLedgerHashs = ledgerBindingConf.getLedgerHashs(); - - CurrentLedger currentLedger = new CurrentLedger(ledgerBindingConf.getLastTime()); - - if (newLedgerHashs.size() > currentLedgerHashs.size()) { - // 获取其新安装的LedgerHash - for (String ledgerHash : newLedgerHashs) { - if (!currentLedgerHashs.contains(ledgerHash)) { - // 新获取的LedgerHash为当前值 - currentLedger.ledgerHash = ledgerHash; - break; - } - } - } - return currentLedger; - } - - - private PeerInstallSchedules peerStart(String peerPath, PeerInstallSchedules installSchedules) { - - saveInstallSchedule(installSchedules, - "Steps to start processing PeerNodeStart !!!", - ScheduleState.STARTUP_START); - // 启动Peer - // 说明初始化成功 - // 判断是否需要启动Peer - String peerVerify = ledgerService.peerVerifyKey(peerPath); - - try { - if (!CommandUtils.isActive(peerVerify)) { - // 不存在,则需要再启动 - String peerStartCmd = ledgerService.peerStartCommand(peerPath); - - LOGGER.info("Execute Peer-Startup's Shell {}", peerStartCmd); - - if (!CommandUtils.executeAndVerify(CommandUtils.toCommandList(peerStartCmd), peerVerify)) { - // Peer节点启动失败 - throw new IllegalStateException("Peer Node Start UP Fail !!!"); - } - saveInstallSchedule(installSchedules, - String.format("Peer's process %s start -> %s", peerVerify, SUCCESS), - ScheduleState.STARTUP_SUCCESS); - } else { - // 命令已经存在 - saveInstallSchedule(installSchedules, - String.format("Peer's process is exist -> %s", peerVerify), - ScheduleState.NO_STARTUP); - } - } catch (Exception e) { - saveInstallSchedule(installSchedules, - e.getMessage(), - ScheduleState.STARTUP_FAIL); - throw new IllegalStateException(e); - } - - saveInstallSchedule(installSchedules, - "Steps to start processing PeerNodeStart over !!!", - ScheduleState.STARTUP_OVER); - - return installSchedules; - } - - private PeerStartupSchedules peerStart(PeerStartupSchedules startupSchedules) { - - String peerPath = startupSchedules.getPeerPath(); - - saveStartupSchedules(startupSchedules, - "Steps to start processing PeerNodeStart !!!", - ScheduleState.STARTUP_START); - // 启动Peer - // 说明初始化成功 - // 判断是否需要启动Peer - String peerVerify = ledgerService.peerVerifyKey(peerPath); - - try { - if (!CommandUtils.isActive(peerVerify)) { - // 不存在,则需要再启动 - String peerStartCmd = ledgerService.peerStartCommand(peerPath); - - LOGGER.info("Execute Peer-Startup's Shell {}", peerStartCmd); - - if (!CommandUtils.executeAndVerify(CommandUtils.toCommandList(peerStartCmd), peerVerify)) { - // Peer节点启动失败 - throw new IllegalStateException("Peer Node Start UP Fail !!!"); - } - saveStartupSchedules(startupSchedules, - String.format("Peer's process %s start -> %s", peerVerify, SUCCESS), - ScheduleState.STARTUP_SUCCESS); - } else { - // 命令已经存在 - saveStartupSchedules(startupSchedules, - String.format("Peer's process is exist -> %s", peerVerify), - ScheduleState.NO_STARTUP); - } - } catch (Exception e) { - saveStartupSchedules(startupSchedules, - e.getMessage(), - ScheduleState.STARTUP_FAIL); - throw new IllegalStateException(e); - } - - saveStartupSchedules(startupSchedules, - "Steps to start processing PeerNodeStart over !!!", - ScheduleState.STARTUP_OVER); - - return startupSchedules; - } - -// private PeerInstallSchedules peerStart(String peerPath, PeerInstallSchedules installSchedules) { -// -// MasterAddr masterAddr = installSchedules.getIdentification().getMasterAddr(); -// -// String ledgerKey = installSchedules.getIdentification().getLedgerKey(); -// -// String ledgerAndNodeKey = installSchedules.getIdentification().getLedgerAndNodeKey(); -// -// saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, -// "Steps to start processing PeerNodeStart !!!", -// ScheduleState.STARTUP_START); -// // 启动Peer -// // 说明初始化成功 -// // 判断是否需要启动Peer -// String peerVerify = ledgerService.peerVerifyKey(peerPath); -// -// try { -// if (!CommandUtils.isActive(peerVerify)) { -// // 不存在,则需要再启动 -// String peerStartCmd = ledgerService.peerStartCommand(peerPath); -// -// LOGGER.info("Execute Peer-Startup's Shell {}", peerStartCmd); -// -// if (!CommandUtils.executeAndVerify(CommandUtils.toCommandList(peerStartCmd), peerVerify)) { -// // Peer节点启动失败 -// throw new IllegalStateException("Peer Node Start UP Fail !!!"); -// } -// saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, -// String.format("Peer's process %s start -> %s", peerVerify, SUCCESS), -// ScheduleState.STARTUP_SUCCESS); -// } else { -// // 命令已经存在 -// saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, -// String.format("Peer's process is exist -> %s", peerVerify), -// ScheduleState.NO_STARTUP); -// } -// } catch (Exception e) { -// saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, -// e.getMessage(), -// ScheduleState.STARTUP_FAIL); -// throw new IllegalStateException(e); -// } -// -// saveInstallSchedule(installSchedules, masterAddr, ledgerKey, ledgerAndNodeKey, -// "Steps to start processing PeerNodeStart over !!!", -// ScheduleState.STARTUP_OVER); -// -// return installSchedules; -// } - - private boolean peerStop(String peerPath) { - - // 判断是否需要停止Peer - String peerVerify = ledgerService.peerVerifyKey(peerPath); - - try { - if (CommandUtils.isActive(peerVerify)) { - - LOGGER.info("We need stop peer {}", peerVerify); - // 需要停止Peer节点 - CommandUtils.killVm(peerVerify); - - // 最多循环5次进行判断 - int maxSize = 5; - - while (maxSize > 0) { - try { - Thread.sleep(3000); - if (!CommandUtils.isActive(peerVerify)) { - return true; - } - } catch (Exception e) { - LOGGER.error("Check Peer Stop State !!!", e); - } finally { - maxSize--; - } - } - } else { - LOGGER.info("We do not need stop peer {}", peerVerify); - return false; - } - } catch (Exception e) { - LOGGER.error("Stop Peer Node", e); - throw new IllegalStateException(e); - } - return false; - } - - private String writeConsensusContent(String consensusContent, File consensusFile) throws IOException { - // 将字符串转换为字节数组 - byte[] consensusBytes = Base58Utils.decode(consensusContent); - forceWrite(consensusBytes, consensusFile); - return consensusFile.getName(); - } - - private void forceWrite(List lines, File file) throws IOException { - if (file.exists()) { - FileUtils.moveFile(file, new File(file.getPath() + "_bak_" + currentDate())); - } - - FileUtils.writeLines(file, StandardCharsets.UTF_8.toString(), lines); - } - - private void forceWrite(byte[] content, File file) throws IOException { - if (file.exists()) { - FileUtils.moveFile(file, new File(file.getPath() + "_bak_" + currentDate())); - } - - FileUtils.writeByteArrayToFile(file, content); - } - - private void verify(PeerSharedConfigs peerSharedConfigs) { - // 校验其中内容 - List sharedConfigs = peerSharedConfigs.getSharedConfigs(); - - // 首先保证其中的数据一致性 - // 1、name不能重复; - // 2、pubKey不能重复; - // 3、ipAddr + initPort不能重复; - - Set nameSet = new HashSet<>(), - pubKeySet = new HashSet<>(), - addrSet = new HashSet<>(); - - for (PeerSharedConfig sharedConfig : sharedConfigs) { - String name = sharedConfig.getName(), - pubKey = sharedConfig.getPubKey(), - addr = sharedConfig.addr(); - if (nameSet.contains(name)) { - throw new IllegalStateException(String.format("Name [%s] is Conflict !!!", name)); - } else { - nameSet.add(name); - } - - if (pubKeySet.contains(pubKey)) { - throw new IllegalStateException(String.format("PubKey [%s] is Conflict !!!", pubKey)); - } else { - pubKeySet.add(pubKey); - } - - if (addrSet.contains(addr)) { - throw new IllegalStateException(String.format("Address [%s] is Conflict !!!", addr)); - } else { - addrSet.add(addr); - } - } - } - - private void saveInstallSchedule(PeerInstallSchedules installSchedules, MasterAddr masterAddr, String ledgerKey, String ledgerAndNodeKey, String content, ScheduleState state) { - - // 日志打印相关内容 - LOGGER.info(content); - - // 生成InstallSchedule对象 - InstallSchedule schedule = installSchedule(ledgerKey, ledgerAndNodeKey, content, state); - - // 加入反馈列表 - installSchedules.addInstallSchedule( - new PeerInstallSchedule(new InstallProcess(content), state)); - - // 将InstallSchedule写入数据库 - umpStateService.save(schedule, masterAddr); - } - - private void saveInstallSchedule(PeerInstallSchedules installSchedules, String content, ScheduleState state) { - - // 日志打印相关内容 - LOGGER.info(content); - - // 加入反馈列表 - installSchedules.addInstallSchedule( - new PeerInstallSchedule(new InstallProcess(content), state)); - } - - private void saveStartupSchedules(PeerStartupSchedules startupSchedules, String content, ScheduleState state) { - - // 日志打印相关内容 - LOGGER.info(content); - - // 加入反馈列表 - startupSchedules.addInstallSchedule( - new PeerInstallSchedule(new InstallProcess(content), state)); - } - - private InstallSchedule installSchedule(String ledgerKey, String ledgerAndNodeKey, String content, ScheduleState state) { - - InstallProcess process = new InstallProcess(content); - - return new InstallSchedule(ledgerKey, ledgerAndNodeKey, process, state); - - } - - private List localConfContents(PeerLocalConfig localConfig, int nodeId) { - /** - * #当前参与方的 id,与ledger.init文件中cons_parti.id一致,默认从0开始 - * local.parti.id=0 - * - * #当前参与方的公钥 - * local.parti.pubkey= - * - * #当前参与方的私钥(密文编码) - * local.parti.privkey= - * - * #当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入 - * local.parti.pwd= - * - * #账本初始化完成后生成的"账本绑定配置文件"的输出目录 - * #推荐使用绝对路径,相对路径以当前文件(local.conf)所在目录为基准 - * ledger.binding.out=../ - * - * #账本数据库的连接字符 - * #rocksdb数据库连接格式:rocksdb://{path},例如:rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - * #redis数据库连接格式:redis://{ip}:{prot}/{db},例如:redis://127.0.0.1:6379/0 - * ledger.db.uri= - * - * #账本数据库的连接口令 - * ledger.db.pwd= - */ - - List localContents = new ArrayList<>(); - - localContents.add(valueToConfig(UmpConstant.LOCAL_PARTI_ID_PREFIX, nodeId)); - - localContents.add(valueToConfig(UmpConstant.LOCAL_PARTI_PUBKEY_PREFIX, localConfig.getPubKey())); - - localContents.add(valueToConfig(UmpConstant.LOCAL_PARTI_PRIVKEY_PREFIX, localConfig.getPrivKey())); - - localContents.add(valueToConfig(UmpConstant.LOCAL_PARTI_PWD_PREFIX, localConfig.getEncodePwd())); - - localContents.add(valueToConfig(UmpConstant.LEDGER_BINDING_OUT_PREFIX, localConfig.bindingOutPath())); - - localContents.add(valueToConfig(UmpConstant.LEDGER_DB_URI_PREFIX, dbUri(localConfig.getDbName(), localConfig.getPeerPath()))); - - localContents.add(valueToConfig(UmpConstant.LEDGER_DB_PWD_PREFIX, "")); - - return localContents; - } - - private String valueToConfig(String prefix, Object value) { - return prefix + "=" + value; - } - - private String currentDate() { - return SDF.format(new Date()); - } - - private String dbUri(final String dbName, final String peerPath) { - - String dbDirectoryPath = peerPath + File.separator + dbName; - - String dbUri = ROCKSDB_PROTOCOL + dbDirectoryPath; - - File dbDirectory = new File(dbDirectoryPath); - - if (!dbDirectory.exists()) { - return dbUri; - } - throw new IllegalStateException(String.format("DB name = %s, path = %s is Exist !!!", dbName, dbDirectoryPath)); - } - - private static class CurrentLedger { - - private String ledgerHash; - - private long lastTime; - - public CurrentLedger() { - } - - public CurrentLedger(long lastTime) { - this.lastTime = lastTime; - } - - public String getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(String ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public long getLastTime() { - return lastTime; - } - - public void setLastTime(long lastTime) { - this.lastTime = lastTime; - } - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpSimulateService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpSimulateService.java deleted file mode 100644 index c6c8ea82..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpSimulateService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.config.PeerSharedConfigVv; -import com.jd.blockchain.ump.model.user.UserKeys; -import com.jd.blockchain.ump.model.user.UserKeysVv; - -public interface UmpSimulateService { - - UserKeysVv userKeysVv(int nodeId); - - UserKeys userKeys(int nodeId); - - PeerLocalConfig nodePeerLocalConfig(int nodeId, boolean isMaster); - - PeerSharedConfigVv peerSharedConfigVv(int nodeId, boolean isMaster); -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpSimulateServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpSimulateServiceHandler.java deleted file mode 100644 index 3bfb20bf..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpSimulateServiceHandler.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.config.PeerSharedConfigVv; -import com.jd.blockchain.ump.model.user.UserKeys; -import com.jd.blockchain.ump.model.user.UserKeysVv; -import com.jd.blockchain.ump.service.consensus.providers.BftsmartConsensusProvider; -import org.apache.commons.codec.binary.Hex; -import org.springframework.stereotype.Service; - -import java.util.Random; - -@Service -public class UmpSimulateServiceHandler implements UmpSimulateService { - - private static final Random RANDOM_ROCKSDB = new Random(); - - private static final String SHARED_KEY = "JDChain"; - - private static final int TOTAL_SIZE = 4; - - private static final String LOCALHOST = "127.0.0.1"; - - private static final String CONSENSUS_PROVIDER = BftsmartConsensusProvider.BFTSMART_PROVIDER; - - private static final String CONSENSUS_CONF = BftsmartConsensusProvider.BFTSMART_CONFIG_FILE; - - private static final int INIT_PORT_START = 9000; - - private static final String[] PUBKEYS = new String[]{ - "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk"}; - - private static final String[] PRIVKEYS = new String[]{ - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns"}; - - private static final String ENCODE_PWD = "DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY"; - - private static final String BINDING_OUT = "../"; - - private static final String[] DB_URIS = new String[]{ - "rocksdb:///Users/shaozhuguang/Documents/simulate/peer0/rocksdb", - "rocksdb:///Users/shaozhuguang/Documents/simulate/peer1/rocksdb", - "rocksdb:///Users/shaozhuguang/Documents/simulate/peer2/rocksdb", - "rocksdb:///Users/shaozhuguang/Documents/simulate/peer3/rocksdb"}; - - private static final String DB_PWD = ""; - - private static final String DB_NAME = "rocksdb_"; - - private static final String[] PEER_PATHS = new String[]{ - "/Users/shaozhuguang/Documents/simulate/peer0", - "/Users/shaozhuguang/Documents/simulate/peer1", - "/Users/shaozhuguang/Documents/simulate/peer2", - "/Users/shaozhuguang/Documents/simulate/peer3"}; - - private static final String[] CONSENSUS_NODES = new String[]{ - "127.0.0.1:6000", - "127.0.0.1:6010", - "127.0.0.1:6020", - "127.0.0.1:6030"}; - - - @Override - public UserKeysVv userKeysVv(int nodeId) { - - UserKeys userKeys = userKeys(nodeId); - - return userKeys.toUserKeysVv(); - } - - @Override - public UserKeys userKeys(int nodeId) { - - return new UserKeys("Peer-" + nodeId, PRIVKEYS[nodeId], PUBKEYS[nodeId], ENCODE_PWD); - } - - @Override - public PeerLocalConfig nodePeerLocalConfig(int nodeId, boolean isMaster) { - - UserKeys userKeys = userKeys(nodeId); - - return peerSharedConfigVv(nodeId, isMaster).toPeerLocalConfig(userKeys); - } - - @Override - public PeerSharedConfigVv peerSharedConfigVv(int nodeId, boolean isMaster) { - - PeerSharedConfigVv sharedConfigVv = new PeerSharedConfigVv(); - - sharedConfigVv.setSharedKey(SHARED_KEY); - sharedConfigVv.setName(SHARED_KEY + "-" + nodeId); - sharedConfigVv.setInitAddr(LOCALHOST); - sharedConfigVv.setInitPort(INIT_PORT_START + nodeId * 10); - sharedConfigVv.setConsensusNode(CONSENSUS_NODES[nodeId]); - sharedConfigVv.setPubKey(PUBKEYS[nodeId]); - sharedConfigVv.setUserId(nodeId); - sharedConfigVv.setPeerPath(PEER_PATHS[nodeId]); - sharedConfigVv.setDbName(dbName()); - - if (isMaster) { - sharedConfigVv.setLedgerName(ledgerName()); - sharedConfigVv.setNodeSize(TOTAL_SIZE); - } else { - sharedConfigVv.setMasterAddr(LOCALHOST); - sharedConfigVv.setMasterPort(8080); - } - - return sharedConfigVv; - } - - private String ledgerName() { - - byte[] nameBytes = new byte[4]; - - RANDOM_ROCKSDB.nextBytes(nameBytes); - - return Hex.encodeHexString(nameBytes); - } - - private String dbName() { - - byte[] nameBytes = new byte[4]; - - RANDOM_ROCKSDB.nextBytes(nameBytes); - - return DB_NAME + Hex.encodeHexString(nameBytes); - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStateService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStateService.java deleted file mode 100644 index 18ae5662..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStateService.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.MasterAddr; -import com.jd.blockchain.ump.model.config.LedgerIdentification; -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.state.*; -import com.jd.blockchain.ump.model.user.UserKeys; -import com.jd.blockchain.ump.model.user.UserKeysVv; - -import java.util.List; -import java.util.Map; - -public interface UmpStateService { - - void save(String ledgerAndNodeKey, PeerLocalConfig localConfig); - - void save(String ledgerKey, List sharedConfigKeys); - - void save(InstallSchedule installSchedule, MasterAddr masterAddr); - - void save(UserKeys userKeys); - - void save(LedgerPeerInstall peerInstall); - - void save(LedgerMasterInstall masterInstall); - - void save(LedgerIdentification identification); - - void saveLedgerHash(String ledgerAndNodeKey, String ledgerHash); - - List readUserKeysList(); - - List readUserKeysVvList(); - - UserKeys readUserKeys(int id); - - PeerLocalConfig readConfig(String ledgerAndNodeKey); - - PeerInstallSchedules loadState(String ledgerAndNodeKey); - - PeerInstallSchedules loadInitState(String ledgerAndNodeKey); - - PeerInstallSchedules readState(String ledgerAndNodeKey); - - PeerInstallSchedules readInitState(String ledgerAndNodeKey); - - Map> readStates(String ledgerKey); - - LedgerIdentification readIdentification(String ledgerAndNodeKey); - - List readLedgerPeerInstalls(); - - List readLedgerMasterInstalls(); - - List readLedgerPeerIniteds(); - - List readLedgerPeerIniteds(String search); - - List readLedgerIniteds(String search); - - String readLedgerHash(String ledgerAndNodeKey); - - int peerPort(String peerPath); - - int peerPort(); -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStateServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStateServiceHandler.java deleted file mode 100644 index 935e3e9e..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStateServiceHandler.java +++ /dev/null @@ -1,905 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.ump.dao.DBConnection; -import com.jd.blockchain.ump.model.*; -import com.jd.blockchain.ump.model.config.LedgerIdentification; -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.state.*; -import com.jd.blockchain.ump.model.user.UserKeys; -import com.jd.blockchain.ump.model.user.UserKeysVv; -import com.jd.blockchain.ump.util.CommandUtils; -import com.jd.blockchain.ump.util.HttpJsonClientUtils; -import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -@Service -public class UmpStateServiceHandler implements UmpStateService, Closeable { - - private final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMM-ddHHmmss"); - - private static final String PEER_IDENTIFICATION_FORMAT = "PEER_IDENTIFICATION_INDEX_%s"; - - private static final String PEER_INSTALL_MAX_KEY = "PEER_INSTALL_MAX_INDEX"; - - private static final String PEER_INSTALL_KEY_FORMAT = "PEER_INSTALL_INDEX_%s"; - - private static final String MASTER_INSTALL_MAX_KEY = "MASTER_INSTALL_MAX_INDEX"; - - private static final String MASTER_INSTALL_KEY_FORMAT = "MASTER_INSTALL_INDEX_%s"; - - private static final String USERS_KEY_MAX_KEY = "USERS_KEY_MAX_INDEX"; - - private static final String USERS_KEY_FORMAT = "USERS_%s_REGISTER"; - - private static final String MAX_SIZE_KEY_SUFFIX = "_MAX_SIZE_KEY"; - - private static final String LEDGER_HASH_KEY_SUFFIX = "_LEDGER_HASH_KEY"; - - private static final String LEDGER_NODE_KEY_CONFIG_SUFFIX = "_LEDGER_NODE_CONFIG_KEY"; - - private static final String LEDGER_NODE_KEY_SUFFIX = "_LEDGER_NODE_KEY"; - - private static final String CURRENT_INDEX_KEY_SUFFIX_FORMAT = "_%s_INDEX_KEY"; - - private static final String PORT_ARG = "-p"; - - private static final String LOCALHOST = "127.0.0.1"; - - private ExecutorService singleHttpThread = Executors.newSingleThreadExecutor(); - - @Autowired - private DBConnection dbConnection; - - @Autowired - private LedgerService ledgerService; - - @Override - public synchronized void save(String ledgerAndNodeKey, PeerLocalConfig localConfig) { - - String ledgerAndNodeConfigKey = ledgerAndNodeConfigKey(ledgerAndNodeKey); - - dbConnection.put(ledgerAndNodeConfigKey, JSON.toJSONString(localConfig)); - } - - @Override - public synchronized void save(String ledgerKey, List sharedConfigKeys) { - - String ledgerAllNodeKey = ledgerAllNodeKey(ledgerKey); - - StringBuilder sBuilder = new StringBuilder(); - - for (String sharedConfigKey : sharedConfigKeys) { - if (sBuilder.length() > 0) { - sBuilder.append(";"); - } - sBuilder.append(sharedConfigKey); - } - - dbConnection.put(ledgerAllNodeKey, sBuilder.toString()); - } - - @Override - public synchronized void save(InstallSchedule installSchedule, MasterAddr masterAddr) { - try { - String ledgerAndNodeKey = installSchedule.getLedgerAndNodeKey(); - // 不使用队列,直接将其写入数据库 - // 需要查询目前该Key对应的最大值是多少 - String maxKey = ledgerAndNodeMaxKey(ledgerAndNodeKey); - String maxIdChars = dbConnection.get(maxKey); - int maxId = 0; - if (maxIdChars != null && maxIdChars.length() > 0) { - maxId = Integer.parseInt(maxIdChars) + 1; - } - - String newKey = ledgerAndNodeCurrentNewKey(ledgerAndNodeKey, maxId); - - // 内容写入数据库 - dbConnection.put(newKey, installSchedule, InstallSchedule.class); - - // 更新最大值 - dbConnection.put(maxKey, String.valueOf(maxId)); - - if (masterAddr != null && masterAddr.legal()) { - singleHttpThread.execute(() -> { - - try { - // 发送HTTP请求 - HttpJsonClientUtils.httpPost(masterAddr, UmpConstant.REQUEST_STATE_URL, installSchedule, String.class, false); - } catch (Exception e) { - // 暂不关注是否发送成功 - LOGGER.error(e.toString()); - } - - }); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - @Override - public synchronized void save(UserKeys userKeys) { - - int maxIndex = maxIndex(USERS_KEY_MAX_KEY); - - String userKey = usersKey(maxIndex); - - // 重置userId - userKeys.setId(maxIndex); - - // 将用户信息写入数据库 - dbConnection.put(userKey, JSON.toJSONString(userKeys)); - - // 更新最大值 - dbConnection.put(USERS_KEY_MAX_KEY, String.valueOf(maxIndex)); - - try { - // 将其放入文件中 - String keysDirPath = UmpConstant.PROJECT_PATH + UmpConstant.PATH_CONFIG_KEYS; - - File keysDir = new File(keysDirPath); - - if (!keysDir.exists()) { - // 创建文件夹 - keysDir.mkdir(); - } - saveKeys2Files(keysDirPath, userKeys); - } catch (Exception e) { - LOGGER.error("Save Keys To File !", e); - } - } - - @Override - public synchronized void save(LedgerPeerInstall peerInstall) { - - int maxIndex = maxIndex(PEER_INSTALL_MAX_KEY); - - // 将用户信息写入数据库 - dbConnection.put(peerInstallKey(maxIndex), JSON.toJSONString(peerInstall)); - - // 更新最大值 - dbConnection.put(PEER_INSTALL_MAX_KEY, String.valueOf(maxIndex)); - - } - - @Override - public synchronized void save(LedgerMasterInstall masterInstall) { - - int maxIndex = maxIndex(MASTER_INSTALL_MAX_KEY); - - // 将用户信息写入数据库 - dbConnection.put(masterInstallKey(maxIndex), JSON.toJSONString(masterInstall)); - - // 更新最大值 - dbConnection.put(MASTER_INSTALL_MAX_KEY, String.valueOf(maxIndex)); - } - - @Override - public synchronized void save(LedgerIdentification identification) { - - String ledgerAndNodeKey = identification.getLedgerAndNodeKey(); - - String idKey = String.format(PEER_IDENTIFICATION_FORMAT, ledgerAndNodeKey); - - dbConnection.put(idKey, JSON.toJSONString(identification)); - } - - @Override - public void saveLedgerHash(String ledgerAndNodeKey, String ledgerHash) { - - String ledgerHashKey = ledgerAndNodeHashKey(ledgerAndNodeKey); - - dbConnection.put(ledgerHashKey, ledgerHash); - } - - @Override - public List readUserKeysList() { - - List userKeysList = new ArrayList<>(); - - String maxIndexChars = dbConnection.get(USERS_KEY_MAX_KEY); - - if (maxIndexChars != null && maxIndexChars.length() > 0) { - - int maxIndex = Integer.parseInt(maxIndexChars); - - for (int i = 0; i <= maxIndex; i++) { - try { - - String json = dbConnection.get(usersKey(i)); - - if (json != null && json.length() > 0) { - userKeysList.add(JSON.parseObject(json, UserKeys.class)); - } - } catch (Exception e) { - LOGGER.error(e.toString()); - } - } - } - - return userKeysList; - } - - @Override - public List readUserKeysVvList() { - - List userKeysVvList = new ArrayList<>(); - - List userKeysList = readUserKeysList(); - - if (!userKeysList.isEmpty()) { - for (UserKeys userKeys : userKeysList) { - - userKeysVvList.add(userKeys.toUserKeysVv()); - } - } - - return userKeysVvList; - } - - @Override - public UserKeys readUserKeys(int id) { - - String userKey = usersKey(id); - - String userKeysJson = dbConnection.get(userKey); - - if (userKeysJson != null && userKeysJson.length() > 0) { - return JSON.parseObject(userKeysJson, UserKeys.class); - } - - return null; - } - - @Override - public PeerLocalConfig readConfig(String ledgerAndNodeKey) { - - String json = dbConnection.get(ledgerAndNodeConfigKey(ledgerAndNodeKey)); - - if (json != null && json.length() > 0) { - - return JSON.parseObject(json, PeerLocalConfig.class); - } - - return null; - } - - @Override - public PeerInstallSchedules loadState(String ledgerAndNodeKey) { - - PeerInstallSchedules installSchedules = loadInitState(ledgerAndNodeKey); - - String ledgerHash = ledgerService.readLedgerHash(ledgerAndNodeKey); - - if (ledgerHash == null || ledgerHash.length() == 0) { - throw new IllegalStateException("Can not find LedgerHash from DataBase !!!"); - } - - return installSchedules.initLedgerHash(ledgerHash); - - } - - @Override - public PeerInstallSchedules loadInitState(String ledgerAndNodeKey) { - // 获取LedgerIdentification - LedgerIdentification identification = readIdentification(ledgerAndNodeKey); - - if (identification == null) { - throw new IllegalStateException("Can not find LedgerIdentification from DataBase !!!"); - } - - return new PeerInstallSchedules(identification); - } - - @Override - public PeerInstallSchedules readState(final String ledgerAndNodeKey) { - - PeerInstallSchedules installSchedules = loadState(ledgerAndNodeKey); - - loadInstallSchedules(installSchedules, ledgerAndNodeKey); - - return installSchedules; - } - - @Override - public PeerInstallSchedules readInitState(String ledgerAndNodeKey) { - - PeerInstallSchedules installSchedules = loadInitState(ledgerAndNodeKey); - - loadInstallSchedules(installSchedules, ledgerAndNodeKey); - - return installSchedules; - } - - @Override - public Map> readStates(String ledgerKey) { - - String ledgerAllNodeKey = ledgerAllNodeKey(ledgerKey); - - String ledgerAllNodeValues = dbConnection.get(ledgerAllNodeKey); - - String[] ledgerAndNodeKeys = ledgerAllNodeValues.split(";"); - - Map> allInstallSchedules = new HashMap<>(); - - // 不存在就返回空值 - if (ledgerAndNodeKeys.length > 0) { - - for (String ledgerAndNodeKey : ledgerAndNodeKeys) { - // 获取每个LedgerAndNodeKey数据 - List installSchedules = readInstallSchedules(ledgerAndNodeKey); - - if (installSchedules != null) { - - allInstallSchedules.put(ledgerAndNodeKey, installSchedules); - } - } - } - - return allInstallSchedules; - } - - @Override - public LedgerIdentification readIdentification(String ledgerAndNodeKey) { - - String idKey = String.format(PEER_IDENTIFICATION_FORMAT, ledgerAndNodeKey); - - String identificationJson = dbConnection.get(idKey); - - if (identificationJson != null && identificationJson.length() > 0) { - - return JSON.parseObject(identificationJson, LedgerIdentification.class); - } - - return null; - } - - @Override - public List readLedgerPeerInstalls() { - - List peerInstallList = new ArrayList<>(); - - String maxIndexChars = dbConnection.get(PEER_INSTALL_MAX_KEY); - - if (maxIndexChars != null && maxIndexChars.length() > 0) { - - int maxIndex = Integer.parseInt(maxIndexChars); - - for (int i = 1; i <= maxIndex; i++) { - try { - String json = dbConnection.get(peerInstallKey(i)); - - if (json != null && json.length() > 0) { - peerInstallList.add(JSON.parseObject(json, LedgerPeerInstall.class)); - } - } catch (Exception e) { - LOGGER.error(e.toString()); - } - } - } - - return peerInstallList; - } - - @Override - public List readLedgerMasterInstalls() { - - List masterInstalls = new ArrayList<>(); - - String maxIndexChars = dbConnection.get(PEER_INSTALL_MAX_KEY); - - if (maxIndexChars != null && maxIndexChars.length() > 0) { - - int maxIndex = Integer.parseInt(maxIndexChars); - - for (int i = 1; i <= maxIndex; i++) { - try { - String json = dbConnection.get(masterInstallKey(i)); - - if (json != null && json.length() > 0) { - masterInstalls.add(JSON.parseObject(json, LedgerMasterInstall.class)); - } - } catch (Exception e) { - LOGGER.error(e.toString()); - } - } - } - - return masterInstalls; - } - - @Override - public List readLedgerPeerIniteds() { - - List peerIniteds = new ArrayList<>(); - - List peerInstalls = readLedgerPeerInstalls(); - - if (!peerInstalls.isEmpty()) { - - LOGGER.info("Read LedgerPeerInstalls, Size = {}", peerInstalls.size()); - for (LedgerPeerInstall peerInstall : peerInstalls) { - - String ledgerAndNodeKey = peerInstall.getLedgerAndNodeKey(); - - // 数据库中读取存放的LedgerHash - String ledgerHash = readLedgerHash(ledgerAndNodeKey); - - if (ledgerHash == null || ledgerHash.length() == 0) { - continue; - } - - LedgerPeerInited peerInited = new LedgerPeerInited(ledgerHash, peerInstall); - - // 检测账本中的Hash是否真正存在 - StartupState startupState = StartupState.UNKNOWN; - try { - startupState = startupState(ledgerHash, peerInstall); - } catch (Exception e) { - LOGGER.error("Check Ledger Hash Exist !!!", e); - } - - // 设置账本状态 - peerInited.setStartupState(startupState); - - // 添加到集合 - peerIniteds.add(peerInited); - } - } else { - LOGGER.error("Read LedgerPeerInstalls is Empty !!!"); - } - return peerIniteds; - } - - @Override - public List readLedgerPeerIniteds(String search) { - - List initedList = readLedgerPeerIniteds(); - - if (search != null && search.length() > 0 && !initedList.isEmpty()) { - - List filterInitedList = new ArrayList<>(); - - for (LedgerPeerInited peerInited : initedList) { - if (isMatch(peerInited, search)) { - filterInitedList.add(peerInited); - } - } - - return filterInitedList; - } - - return initedList; - } - - @Override - public List readLedgerIniteds(String search) { - - List ledgerInitedsFromConf = loadAllLedgerIniteds(UmpConstant.PROJECT_PATH); - - if (!ledgerInitedsFromConf.isEmpty()) { - - List ledgerIniteds = new ArrayList<>(); - - for (LedgerInited ledgerInited : ledgerInitedsFromConf) { - - if (isMatch(ledgerInited, search)) { - ledgerIniteds.add(ledgerInited); - } - } - - return ledgerIniteds; - } - - return ledgerInitedsFromConf; - } - - @Override - public String readLedgerHash(String ledgerAndNodeKey) { - - String ledgerHashKey = ledgerAndNodeHashKey(ledgerAndNodeKey); - - return dbConnection.get(ledgerHashKey); - } - - @Override - public int peerPort(String peerPath) { - - String peerVerify = ledgerService.peerVerifyKey(peerPath); - - try { - if (!CommandUtils.isActive(peerVerify)) { - // 进程不存在 - LOGGER.info("Can not find Peer Process {} !!!", peerVerify); - return 0; - } - return listenPort(peerVerify); - } catch (Exception e) { - // 进程处理错误打印日志即可 - LOGGER.error(String.format("Peer Port Check %s !!!", peerVerify), e); - } - - return 0; - } - - @Override - public int peerPort() { - return peerPort(UmpConstant.PROJECT_PATH); - } - - @Override - public void close() throws IOException { -// writeRunner.close(); - } - - private boolean isMatch(LedgerInited ledgerInited, String search) { - - if (search == null || search.length() == 0) { - return true; - } - - String ledgerHash = ledgerInited.getLedgerHash(); - String ledgerName = ledgerInited.getLedgerName(); - String partiName = ledgerInited.getPartiName(); - String partiAddress = ledgerInited.getPartiAddress(); - String dbUri = ledgerInited.getDbUri(); - StartupState startupState = ledgerInited.getStartupState(); - - if ( - ledgerHash.contains(search) || - startupState.toString().equals(search) || - ledgerName.contains(search) || - partiName.contains(search) || - partiAddress.contains(search) || - dbUri.contains(search) - ) { - return true; - } - return false; - } - - private boolean isMatch(LedgerPeerInited peerInited, String search) { - - if (search == null || search.length() == 0) { - return true; - } - - String ledgerHash = peerInited.getLedgerHash(); - StartupState startupState = peerInited.getStartupState(); - LedgerPeerInstall peerInstall = peerInited.getPeerInstall(); - - if (ledgerHash.contains(search) || - startupState.toString().equals(search) || - peerInstall.getNodeName().contains(search) || - peerInstall.getCreateTime().contains(search) - ) { - return true; - } - return false; - } - - private void loadInstallSchedules(PeerInstallSchedules installSchedules, String ledgerAndNodeKey) { - List schedules = readInstallSchedules(ledgerAndNodeKey); - - for (InstallSchedule installSchedule : schedules) { - installSchedules.addInstallSchedule( - new PeerInstallSchedule(installSchedule.getProcess(), installSchedule.getState())); - } - } - - private List readInstallSchedules(String ledgerAndNodeKey) { - String maxKey = ledgerAndNodeMaxKey(ledgerAndNodeKey); - String maxIdChars = dbConnection.get(maxKey); - if (maxIdChars == null || maxIdChars.length() == 0) { - return null; - } - int maxId = Integer.parseInt(maxIdChars); - - List schedules = new ArrayList<>(); - - for (int i = 0; i <= maxId; i++) { - - try { - String currentKey = ledgerAndNodeCurrentNewKey(ledgerAndNodeKey, i); - - String jsonChars = dbConnection.get(currentKey); - - if (jsonChars != null && jsonChars.length() > 0) { - schedules.add(JSON.parseObject(jsonChars, InstallSchedule.class)); - } - } catch (Exception e) { - // 打印错误,暂不处理其他 - LOGGER.error(e.toString()); - } - } - - return schedules; - } - - private List loadAllLedgerIniteds(String peerPath) { - - List ledgerInitedsFromConf = ledgerService.allLedgerIniteds(peerPath); - - if (!ledgerInitedsFromConf.isEmpty()) { - - // 逐个检查其状态 - for (LedgerInited ledgerInited : ledgerInitedsFromConf) { - // 判断该账本对应的数据库是否存在 - if (!dbConnection.exist(ledgerInited.getDbUri())) { - ledgerInited.setStartupState(StartupState.DB_UNEXIST); - continue; - } - - String peerVerify = ledgerService.peerVerifyKey(peerPath); - - try { - if (!CommandUtils.isActive(peerVerify)) { - // 进程不存在 - LOGGER.info("Can not find Peer Process {} !!!", peerVerify); - ledgerInited.setStartupState(StartupState.UNLOAD); - continue; - } - } catch (Exception e) { - // 进程处理错误打印日志即可 - LOGGER.error(String.format("Command Check %s !!!", peerVerify), e); - } - // 查看该进程对应的监听端口 - try { - int listenPort = listenPort(peerVerify); - - LOGGER.info("Find Listen Port = {} !", listenPort); - - if (listenPort > 0) { - - int maxSize = 3, checkIndex = 1; - - boolean isRead = false; - - while (maxSize > 0) { - - try { - // 发送请求到对应地址 - JSONArray ledgerHashs = HttpJsonClientUtils.httpGet(ledgersUrl(listenPort), JSONArray.class, true); - - if (ledgerHashs != null && !ledgerHashs.isEmpty()) { - for(Object hashObj : ledgerHashs) { - if (hashObj instanceof JSONObject) { - if (ledgerInited.getLedgerHash().equals(((JSONObject) hashObj).getString("value"))) { - // 说明该账本已经被加载 - ledgerInited.setStartupState(StartupState.LOADED); - isRead = true; - break; - } - } - } - if (isRead) { - break; - } - } - - // 6秒休眠 - Thread.sleep(3000); - } catch (Exception e) { - LOGGER.error(String.format("Request LedgerHashs from PeerNode [%s]", checkIndex++), e); - } - - maxSize --; - } - - if (!isRead) { - // 表明等待加载,无须再启动 - ledgerInited.setStartupState(StartupState.LOADING); - } - } - } catch (Exception e) { - LOGGER.error(String.format("Command [%s] 'Listen Port Check !!!", peerVerify), e); - } - } - } - - return ledgerInitedsFromConf; - } - - private StartupState startupState(String ledgerHash, LedgerPeerInstall peerInstall) { - - String peerPath = peerInstall.getPeerPath(); - - // 首先检查文件中是否存在该Hash值 - LedgerBindingConf ledgerBindingConf = ledgerService.allLedgerHashs(peerPath); - - Set allLedgerHashs = ledgerBindingConf.getLedgerHashs(); - - if (!allLedgerHashs.contains(ledgerHash)) { - - // 文件中不存在 - return StartupState.UNEXIST; - } - - // 判断该账本对应的数据库是否存在 - if (!ledgerService.dbExist(peerPath, ledgerHash)) { - - // 该账本对应数据库不存在 - return StartupState.DB_UNEXIST; - } - - // 文件中存在则检查进程是否存在 - // 进程存在标识为LOADED,否则标识为LOADING,暂时用不到LOADING - String peerVerify = ledgerService.peerVerifyKey(peerPath); - - try { - if (!CommandUtils.isActive(peerVerify)) { - // 进程不存在 - return StartupState.UNLOAD; - } - - } catch (Exception e) { - // 进程处理错误打印日志即可 - LOGGER.error(String.format("Command Check %s !!!", peerVerify), e); - } - - // 查看该进程对应的监听端口 - try { - int listenPort = listenPort(peerVerify); - - LOGGER.info("Find Listen Port = {} !", listenPort); - - if (listenPort > 0) { - // 发送请求到对应地址 - JSONArray ledgerHashs = HttpJsonClientUtils.httpGet(ledgersUrl(listenPort), JSONArray.class, true); - - if (ledgerHashs != null && !ledgerHashs.isEmpty()) { - for(Object hashObj : ledgerHashs) { - if (hashObj instanceof JSONObject) { - if (ledgerHash.equals(((JSONObject) hashObj).getString("value"))) { - // 说明该账本已经被加载 - return StartupState.LOADED; - } - } - } - // 表明等待加载,无须再启动 - return StartupState.LOADING; - } - } - } catch (Exception e) { - LOGGER.error(String.format("Command [%s] 'Listen Port Check !!!", peerVerify), e); - } - - return StartupState.UNKNOWN; - } - - private String ledgersUrl(int listenPort) { - return "http://" + LOCALHOST + ":" + listenPort + "/ledgers"; - } - - private int listenPort(String peerVerify) throws Exception { - - String portArg = mainArg(peerVerify, PORT_ARG); - - if (portArg != null && portArg.length() > 0) { - return Integer.parseInt(portArg); - } - - return 0; - } - - private String mainArg(String processName, String argKey) throws Exception { - - String[] cmdLineArray = mainArgs(processName); - - if (cmdLineArray != null && cmdLineArray.length > 0) { - for (int i = 0; i < cmdLineArray.length; i++) { - String currArg = cmdLineArray[i].trim(); - if (currArg.equals(argKey) && (i + 1) < cmdLineArray.length) { - return cmdLineArray[i+1].trim(); - } - } - } - return null; - } - - private String[] mainArgs(String processName) throws Exception { - - String mainArgs = CommandUtils.mainArgs(processName); - - if (mainArgs != null && mainArgs.length() > 0) { - ///Users/shaozhuguang/Documents/newenv/peer4/system/deployment-peer-1.1.0-SNAPSHOT.jar -home=/Users/shaozhuguang/Documents/newenv/peer4 -c /Users/shaozhuguang/Documents/newenv/peer4/config/ledger-binding.conf -p 7080 - return mainArgs.split(" "); - } - - return null; - } - - private synchronized int maxIndex(String key) { - int maxIndex = 1; - String maxIndexChars = dbConnection.get(key); - if (maxIndexChars != null && maxIndexChars.length() > 0) { - maxIndex = Integer.parseInt(maxIndexChars) + 1; - } - return maxIndex; - } - - private String usersKey(int userId) { - return String.format(USERS_KEY_FORMAT, userId); - } - - private String peerInstallKey(int index) { - return String.format(PEER_INSTALL_KEY_FORMAT, index); - } - - private String masterInstallKey(int index) { - return String.format(MASTER_INSTALL_KEY_FORMAT, index); - } - - private String ledgerAndNodeConfigKey(String ledgerAndNodeKey) { - - return ledgerAndNodeKey + LEDGER_NODE_KEY_CONFIG_SUFFIX; - } - - private String ledgerAllNodeKey(String ledgerKey) { - - return ledgerKey + LEDGER_NODE_KEY_SUFFIX; - } - - private String ledgerAndNodeMaxKey(String ledgerAndNodeKey) { - - return ledgerAndNodeKey + MAX_SIZE_KEY_SUFFIX; - } - - private String ledgerAndNodeHashKey(String ledgerAndNodeKey) { - - return ledgerAndNodeKey + LEDGER_HASH_KEY_SUFFIX; - } - - private String ledgerAndNodeCurrentNewKey(String ledgerAndNodeKey, int currentId) { - - return String.format( - ledgerAndNodeKey + CURRENT_INDEX_KEY_SUFFIX_FORMAT, - currentId); - } - - private void saveKeys2Files(String keysDirPath, UserKeys userKeys) throws IOException { - - // 写入私钥 - write(keysDirPath, userKeys.getName(), UmpConstant.PRIVATE_KEY_SUFFIX, userKeys.getPrivKey()); - // 写入公钥 - write(keysDirPath, userKeys.getName(), UmpConstant.PUBLIC_KEY_SUFFIX, userKeys.getPubKey()); - // 写入密钥 - write(keysDirPath, userKeys.getName(), UmpConstant.PWD_SUFFIX, userKeys.getEncodePwd()); - } - - private void write(String keysDirPath, String name, String suffix, String writeContent) throws IOException { - - String keyeFilePath = keysDirPath + File.separator + name + suffix; - - File keysFile = new File(keyeFilePath); - - if (keysFile.exists()) { - // 文件存在,备份文件 - FileUtils.copyFile(keysFile, new File(keyeFilePath + "_bak_" + currentTime())); - } - - // 将Priv文件内容写入 - FileUtils.writeStringToFile(keysFile, writeContent, StandardCharsets.UTF_8); - } - - private String currentTime() { - return SDF.format(new Date()); - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStoreService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStoreService.java deleted file mode 100644 index 658a6017..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStoreService.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.service.DataRetrievalService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/15 下午3:08 - * Description: - */ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.penetrate.LeaderDomain; - -import java.util.List; - -/** - * data store; - */ -public interface UmpStoreService { - /** - * get ledger info by ledgerHash; - * @param ledgerHash - * @return - */ - LeaderDomain findLedgerInfo(String ledgerHash); - - /** - * get all ledgers; - * @return - */ - List findAllLedgers(); - - /** - * get all states by seed; - * @param seed - * @return - */ - List findStates(String seed); - - /** - * get value by key; - * @param key - * @return - */ - Object findRecord(String key); - - void saveLedgerInfo(LeaderDomain leaderDomain); - - void saveRecord(String key, Object obj); - - void saveState4Seed(String key, String state); -} \ No newline at end of file diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStoreServiceImpl.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStoreServiceImpl.java deleted file mode 100644 index a601765f..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UmpStoreServiceImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.gateway.service.DataRetrievalService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/15 下午3:08 - * Description: - */ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.model.penetrate.LeaderDomain; -import com.jd.blockchain.ump.model.penetrate.store.MemStore; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; - -/** - * data store; - */ -@Service -public class UmpStoreServiceImpl implements UmpStoreService{ - @Override - public LeaderDomain findLedgerInfo(String ledgerHash) { - return (LeaderDomain) MemStore.instance.get(ledgerHash); - } - - @Override - public List findAllLedgers() { - return (List)MemStore.instance.get(UmpConstant.ALL_LEDGER); - } - - @Override - public List findStates(String seed) { - return (List)MemStore.instance.get(seed); - } - - @Override - public Object findRecord(String key) { - return MemStore.instance.get(key); - } - - @Override - public void saveLedgerInfo(LeaderDomain leaderDomain) { - MemStore.instance.put(leaderDomain.getLedgerHash(),leaderDomain); - //also put it into ALL_LEDGER; - Object obj = MemStore.instance.get(UmpConstant.ALL_LEDGER); - List leaderDomains = null; - if(obj == null){ - leaderDomains = new ArrayList<>(); - }else { - leaderDomains = (List)obj; - } - leaderDomains.add(leaderDomain); - MemStore.instance.put(UmpConstant.ALL_LEDGER,leaderDomains); - } - - @Override - public void saveRecord(String key, Object obj) { - MemStore.instance.put(key,obj); - } - - @Override - public void saveState4Seed(String key, String state) { - Object obj = MemStore.instance.get(key); - List states = null; - if(obj == null){ - states = new ArrayList<>(); - }else { - states = (List)obj; - } - states.add(state); - MemStore.instance.put(key,states); - } -} \ No newline at end of file diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UtilService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UtilService.java deleted file mode 100644 index a2083d88..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UtilService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.ump.model.user.UserKeyBuilder; -import com.jd.blockchain.ump.model.user.UserKeys; - -public interface UtilService { - - UserKeys create(UserKeyBuilder builder); - - UserKeys create(String name, String seed, String pwd); - - UserKeys read(int id); - - boolean verify(UserKeys userKeys, String pwd); -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UtilServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UtilServiceHandler.java deleted file mode 100644 index 3a2b3eee..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/UtilServiceHandler.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.jd.blockchain.ump.service; - -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.utils.classic.ED25519Utils; -import com.jd.blockchain.ump.model.user.UserKeyBuilder; -import com.jd.blockchain.ump.model.user.UserKeys; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.security.ShaUtils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; -import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; -import org.bouncycastle.crypto.prng.FixedSecureRandom; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.nio.charset.Charset; - -import static com.jd.blockchain.crypto.KeyGenUtils.encodePrivKey; -import static com.jd.blockchain.crypto.KeyGenUtils.encodePubKey; - -@Service -public class UtilServiceHandler implements UtilService { - - private static final String UTF_8 = "UTF-8"; - - @Autowired - private UmpStateService umpStateService; - - @Override - public UserKeys create(UserKeyBuilder builder) { - - return create(builder.getName(), builder.getSeed(), builder.getPwd()); - } - - @Override - public UserKeys create(String name, String seed, String pwd) { - - AsymmetricCipherKeyPair keyPair = ED25519Utils.generateKeyPair( - new FixedSecureRandom(seed.getBytes(Charset.forName(UTF_8)))); - - PubKey pubKey = new PubKey(ClassicAlgorithm.ED25519, - ((Ed25519PublicKeyParameters) keyPair.getPublic()).getEncoded()); - - PrivKey privKey = new PrivKey(ClassicAlgorithm.ED25519, - ((Ed25519PrivateKeyParameters) keyPair.getPrivate()).getEncoded()); - - return create(name, pubKey, privKey, pwd); - } - - @Override - public UserKeys read(int userId) { - - return umpStateService.readUserKeys(userId); - } - - @Override - public boolean verify(UserKeys userKeys, String pwd) { - - String encodePwd = Base58Utils.encode((ShaUtils.hash_256(pwd.getBytes(Charset.forName(UTF_8))))); - - if (encodePwd.equals(userKeys.getEncodePwd())) { - return true; - } - return false; - } - - private UserKeys create(String name, PubKey pubKey, PrivKey privKey, String pwd) { - - byte[] pwdBytes = ShaUtils.hash_256(pwd.getBytes(Charset.forName(UTF_8))); - - return new UserKeys( - name, - encodePrivKey(privKey, pwdBytes), - encodePubKey(pubKey), -// pwd, // 密码不保存到数据库,防止泄露 - Base58Utils.encode(pwdBytes)); - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusProvider.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusProvider.java deleted file mode 100644 index 124b6d10..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusProvider.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ump.service.consensus; - -import com.jd.blockchain.ump.model.config.PeerLocalConfig; - -import java.util.List; -import java.util.Properties; - -public interface ConsensusProvider { - - String NEXT_LINE = "\r\n"; - - String provider(); - - String configFilePath(); - - void setConfig(Properties properties); - - Properties getConfig(); - - byte[] handleSharedConfigs(List sharedConfigs); -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusService.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusService.java deleted file mode 100644 index aeb5fcba..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jd.blockchain.ump.service.consensus; - -import com.jd.blockchain.ump.model.config.PeerLocalConfig; - -import java.util.List; - -public interface ConsensusService { - - String initConsensusConf(String consensusProvider, List sharedConfigs); -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusServiceHandler.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusServiceHandler.java deleted file mode 100644 index 7745eb97..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/ConsensusServiceHandler.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.jd.blockchain.ump.service.consensus; - -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.util.Base58Utils; -import org.reflections.Reflections; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -@Service -public class ConsensusServiceHandler implements ConsensusService { - - private static final String PATH_INNER = "/"; - - private static final Map CONSENSUS_PROVIDERS = new ConcurrentHashMap<>(); - - static { - try { - initProviders(); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - @Override - public String initConsensusConf(String consensusProvider, List sharedConfigs) { - // 首先根据provider获取对应的配置信息 - ConsensusProvider provider = CONSENSUS_PROVIDERS.get(consensusProvider); - - if (provider == null) { - throw new IllegalStateException( - String.format("ConsensusProvider[%s] can not find Manage-Class !!!", consensusProvider)); - } - - byte[] result = provider.handleSharedConfigs(sharedConfigs); - - return Base58Utils.encode(result); - } - - private static void initProviders() { - // 初始化所有实现类 - Reflections reflections = new Reflections("com.jd.blockchain.ump.service.consensus"); - - Set> providerSet = - reflections.getSubTypesOf(ConsensusProvider.class); - - for (Class clazz : providerSet) { - - if (!clazz.isInterface()) { - try { - // 根据class生成对象 - ConsensusProvider provider = clazz.newInstance(); - String providerKey = provider.provider(); - if (providerKey != null && providerKey.length() > 0 && - !CONSENSUS_PROVIDERS.containsKey(providerKey)) { - - // 根据value读取配置文件中的内容 - InputStream currentFileInputStream = ConsensusServiceHandler.class.getResourceAsStream( - PATH_INNER + provider.configFilePath()); - - Properties currentProps = new Properties(); - - currentProps.load(currentFileInputStream); - - provider.setConfig(currentProps); - - CONSENSUS_PROVIDERS.put(providerKey, provider); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - } - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/BftsmartConsensusProvider.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/BftsmartConsensusProvider.java deleted file mode 100644 index e7179501..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/BftsmartConsensusProvider.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.jd.blockchain.ump.service.consensus.providers; - - -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.config.PeerSharedConfig; -import com.jd.blockchain.ump.service.consensus.ConsensusProvider; - -import java.nio.charset.StandardCharsets; -import java.util.*; - -public class BftsmartConsensusProvider implements ConsensusProvider { - - public static final String BFTSMART_PROVIDER = "com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"; - - public static final String BFTSMART_CONFIG_FILE = "bftsmart.default.config"; - - private static final int MIN_PARTI_SIZE = 4; - - private Properties bftsmartProps; - - @Override - public String provider() { - return BFTSMART_PROVIDER; - } - - @Override - public String configFilePath() { - return BFTSMART_CONFIG_FILE; - } - - @Override - public void setConfig(Properties properties) { - bftsmartProps = properties; - } - - @Override - public Properties getConfig() { - return bftsmartProps; - } - - @Override - public byte[] handleSharedConfigs(List sharedConfigs) { - - // 首先校验其中的ConsensusNode是否完全一致,若完全一致则不可以 - verify(sharedConfigs); - - StringBuilder sBuilder = new StringBuilder(); - - // 先加入当前节点信息 - List nodeConfigs = nodeConfigs(sharedConfigs); - - for (String nodeConfig : nodeConfigs) { - sBuilder.append(nodeConfig).append(NEXT_LINE); - } - - int nodeNum = sharedConfigs.size(); - - // 写入之前配置文件中的内容 - for (Map.Entry entry : bftsmartProps.entrySet()) { - - // 获取Key-Value - String key = (String) entry.getKey(), value = (String) entry.getValue(); - - // 对特殊的Key和Value单独处理 - /** - * system.servers.num = 4 - * - * system.servers.f = 1 - * - * system.initial.view = 0,1,2,3 - */ - if (key.startsWith(BftsmartConstant.SERVERS_NUM_PREFIX)) { - - sBuilder.append(BftsmartConstant.SERVERS_NUM_PREFIX + " = " + nodeNum).append(NEXT_LINE); - } else if (key.startsWith(BftsmartConstant.SERVERS_F_PREFIX)) { - - sBuilder.append(BftsmartConstant.SERVERS_F_PREFIX + " = " + nodeFNum(nodeNum)).append(NEXT_LINE); - } else if (key.startsWith(BftsmartConstant.INIT_VIEW_PREFIX)) { - - sBuilder.append(BftsmartConstant.INIT_VIEW_PREFIX + " = " + initView(nodeNum)).append(NEXT_LINE); - } else { - - sBuilder.append(key + " = " + value).append(NEXT_LINE); - } - } - - return sBuilder.toString().getBytes(StandardCharsets.UTF_8); - } - - private String initView(int nodeNum) { - - StringBuilder views = new StringBuilder(); - - for (int i = 0; i < nodeNum; i++) { - if (views.length() > 0) { - views.append(","); - } - views.append(i); - } - return views.toString(); - } - - private void verify(List sharedConfigs) { - - Set consensusInfos = new HashSet<>(); - - if (sharedConfigs == null) { - throw new IllegalStateException("Shared Configs is NULL !!!"); - } - - if (sharedConfigs.size() < MIN_PARTI_SIZE) { - throw new IllegalStateException( - String.format("Shared Configs's size = %s, can not meet minimum %s !!!", - sharedConfigs.size(), MIN_PARTI_SIZE)); - } - - for (PeerLocalConfig sharedConfig : sharedConfigs) { - String consensusInfo = sharedConfig.getConsensusNode(); - if (consensusInfos.contains(consensusInfo)) { - throw new IllegalStateException("Shared Configs's Consensus may be conflict !!!"); - } - consensusInfos.add(consensusInfo); - } - } - - private List nodeConfigs(List sharedConfigs) { - - List nodeConfigs = new ArrayList<>(); - - if (sharedConfigs != null && !sharedConfigs.isEmpty()) { - for (int i = 0; i < sharedConfigs.size(); i++) { - - PeerSharedConfig sharedConfig = sharedConfigs.get(i); - - String consensusNode = sharedConfig.getConsensusNode(); - - String[] hostAndPort = consensusNode.split(":"); - - nodeConfigs.add(String.format(BftsmartConstant.HOST_FORMAT, i, hostAndPort[0])); - - nodeConfigs.add(String.format(BftsmartConstant.PORT_FORMAT, i, hostAndPort[1])); - - nodeConfigs.add(String.format(BftsmartConstant.SECURE_FORMAT, i, false)); - - } - } - - return nodeConfigs; - } - - private int nodeFNum(int nodeNum) { - /** - * 3F+1 - * - * 假设有4个节点,则可有一个,若有N个,则N-1/3 - */ - if (nodeNum < 4) { - return 0; - } - return (nodeNum - 1) / 3; - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/BftsmartConstant.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/BftsmartConstant.java deleted file mode 100644 index 78afdbe4..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/BftsmartConstant.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.ump.service.consensus.providers; - -public class BftsmartConstant { - - public static final String HOST_FORMAT = "system.server.%s.network.host=%s"; - - public static final String PORT_FORMAT = "system.server.%s.network.port=%s"; - - public static final String SECURE_FORMAT = "system.server.%s.network.secure=%s"; - - public static final String SERVERS_NUM_PREFIX = "system.servers.num"; - - public static final String SERVERS_F_PREFIX = "system.servers.f"; - - public static final String INIT_VIEW_PREFIX = "system.initial.view"; - -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/MsgQueueConsensusProvider.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/MsgQueueConsensusProvider.java deleted file mode 100644 index 31ab2f20..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/service/consensus/providers/MsgQueueConsensusProvider.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.ump.service.consensus.providers; - -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.service.consensus.ConsensusProvider; - -import java.util.List; -import java.util.Properties; - -public class MsgQueueConsensusProvider implements ConsensusProvider { - - private static final String MSGQUEUE_PROVIDER = "com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider"; - - private static final String MSGQUEUE_CONFIG_FILE = "mq.default.config"; - - private Properties msgQueueProps; - - @Override - public String provider() { - return MSGQUEUE_PROVIDER; - } - - @Override - public String configFilePath() { - return MSGQUEUE_CONFIG_FILE; - } - - @Override - public void setConfig(Properties properties) { - this.msgQueueProps = properties; - } - - @Override - public Properties getConfig() { - return msgQueueProps; - } - - @Override - public byte[] handleSharedConfigs(List sharedConfigs) { - return new byte[0]; - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/Base58Utils.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/Base58Utils.java deleted file mode 100644 index ff74ba9b..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/Base58Utils.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.jd.blockchain.ump.util; - -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; - -public class Base58Utils { - - public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); - - private static final int[] INDEXES = new int[128]; - - static { - for (int i = 0; i < INDEXES.length; i++) { - INDEXES[i] = -1; - } - for (int i = 0; i < ALPHABET.length; i++) { - INDEXES[ALPHABET[i]] = i; - } - } - - /** - * Encodes the given bytes in base58. No checksum is appended. - */ - public static String encode(byte[] input) { - if (input.length == 0) { - return ""; - } - input = copyOfRange(input, 0, input.length); - // Count leading zeroes. - int zeroCount = 0; - while (zeroCount < input.length && input[zeroCount] == 0) { - ++zeroCount; - } - // The actual encoding. - byte[] temp = new byte[input.length * 2]; - int j = temp.length; - - int startAt = zeroCount; - while (startAt < input.length) { - byte mod = divmod58(input, startAt); - if (input[startAt] == 0) { - ++startAt; - } - temp[--j] = (byte) ALPHABET[mod]; - } - - // Strip extra '1' if there are some after decoding. - while (j < temp.length && temp[j] == ALPHABET[0]) { - ++j; - } - // Add as many leading '1' as there were leading zeros. - while (--zeroCount >= 0) { - temp[--j] = (byte) ALPHABET[0]; - } - - byte[] output = copyOfRange(temp, j, temp.length); - try { - return new String(output, "US-ASCII"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); // Cannot happen. - } - } - - public static byte[] decode(String input) throws IllegalArgumentException { - if (input.length() == 0) { - return new byte[0]; - } - byte[] input58 = new byte[input.length()]; - // Transform the String to a base58 byte sequence - for (int i = 0; i < input.length(); ++i) { - char c = input.charAt(i); - - int digit58 = -1; - if (c >= 0 && c < 128) { - digit58 = INDEXES[c]; - } - if (digit58 < 0) { - throw new IllegalArgumentException("Illegal character " + c + " at " + i); - } - - input58[i] = (byte) digit58; - } - // Count leading zeroes - int zeroCount = 0; - while (zeroCount < input58.length && input58[zeroCount] == 0) { - ++zeroCount; - } - // The encoding - byte[] temp = new byte[input.length()]; - int j = temp.length; - - int startAt = zeroCount; - while (startAt < input58.length) { - byte mod = divmod256(input58, startAt); - if (input58[startAt] == 0) { - ++startAt; - } - - temp[--j] = mod; - } - // Do no add extra leading zeroes, move j to first non null byte. - while (j < temp.length && temp[j] == 0) { - ++j; - } - - return copyOfRange(temp, j - zeroCount, temp.length); - } - - public static BigInteger decodeToBigInteger(String input) throws IllegalArgumentException { - return new BigInteger(1, decode(input)); - } - - // - // number -> number / 58, returns number % 58 - // - private static byte divmod58(byte[] number, int startAt) { - int remainder = 0; - for (int i = startAt; i < number.length; i++) { - int digit256 = (int) number[i] & 0xFF; - int temp = remainder * 256 + digit256; - - number[i] = (byte) (temp / 58); - - remainder = temp % 58; - } - - return (byte) remainder; - } - - // - // number -> number / 256, returns number % 256 - // - private static byte divmod256(byte[] number58, int startAt) { - int remainder = 0; - for (int i = startAt; i < number58.length; i++) { - int digit58 = (int) number58[i] & 0xFF; - int temp = remainder * 58 + digit58; - - number58[i] = (byte) (temp / 256); - - remainder = temp % 256; - } - - return (byte) remainder; - } - - private static byte[] copyOfRange(byte[] source, int from, int to) { - byte[] range = new byte[to - from]; - System.arraycopy(source, from, range, 0, range.length); - - return range; - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/CommandUtils.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/CommandUtils.java deleted file mode 100644 index 3290d2ce..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/CommandUtils.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.jd.blockchain.ump.util; - -import sun.jvmstat.monitor.MonitoredHost; -import sun.jvmstat.monitor.MonitoredVm; -import sun.jvmstat.monitor.MonitoredVmUtil; -import sun.jvmstat.monitor.VmIdentifier; - -import java.util.*; - -public class CommandUtils { - - public static void killVm(String processName) throws Exception { - - MonitoredVm activeVm = activeVm(processName); - - if (activeVm != null) { - killVm(activeVm); - } - } - - public static void killVm(MonitoredVm vm) throws Exception { - if (vm != null) { - int vmId = vm.getVmIdentifier().getLocalVmId(); - List killCmd = killCommand(vmId); - execute(killCmd); - } - } - - public static List toCommandList(String cmd) { - // 要求使用空格 - String[] cmdArray = cmd.split(" "); - - if (cmdArray.length > 0) { - return Arrays.asList(cmdArray); - } - - return null; - - } - - public static Process execute(List cmds) throws Exception { - - if (cmds == null || cmds.isEmpty()) { - throw new IllegalStateException("Command's List is NULL !!!"); - } - - ProcessBuilder pBuilder = new ProcessBuilder(cmds); - - Process process = pBuilder.start(); - - return process; - - } - - public static boolean executeAndVerify(List cmds, String verify) throws Exception { - - if (cmds == null || cmds.isEmpty()) { - throw new IllegalStateException("Command's List is NULL !!!"); - } - - ProcessBuilder pBuilder = new ProcessBuilder(cmds); - - pBuilder.start(); - - // 时延5s,再进行判断 - Thread.sleep(5000); - - return isActive(verify); - - } - - public static MonitoredVm activeVm(String processName) throws Exception { - - MonitoredHost localMonitored = MonitoredHost.getMonitoredHost("localhost"); - - Set activeVms = new HashSet<>(localMonitored.activeVms()); - - for (Integer vmId : activeVms) { - - try { - MonitoredVm vm = localMonitored.getMonitoredVm(new VmIdentifier("//" + vmId)); - - String vmProcessName = MonitoredVmUtil.mainClass(vm, true); - - if (vmProcessName.contains(processName)) { - return vm; - } - } catch (Exception e) { - // 此处异常打印即可,不需要处理 - System.err.println(e); - } - } - - return null; - } - - public static boolean isActive(String processName) throws Exception { - - MonitoredVm activeVm = activeVm(processName); - - return activeVm != null; - } - - public static String mainArgs(MonitoredVm vm) { - if (vm != null) { - try { - return MonitoredVmUtil.mainArgs(vm); - } catch (Exception e) { - // 打印日志即可 - System.err.println(e); - } - } - return null; - } - - public static String mainArgs(String processName) throws Exception { - - return mainArgs(activeVm(processName)); - } - - public static List killCommand(int vmId) { - if (vmId > 1) { - List killCmd = new ArrayList<>(); - killCmd.add("kill"); - killCmd.add("-9"); - killCmd.add(String.valueOf(vmId)); - - return killCmd; - } - - throw new IllegalStateException(String.format("Can not kill Process ID = [%s]", vmId)); - } -} diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/HttpClientPool.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/HttpClientPool.java deleted file mode 100644 index d3ee0541..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/HttpClientPool.java +++ /dev/null @@ -1,303 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.utils.http.agent.HttpClientPool - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/14 下午3:20 - * Description: - */ -package com.jd.blockchain.ump.util; - -import com.alibaba.fastjson.JSONObject; -import org.apache.http.*; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.*; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.LayeredConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -import java.io.*; -import java.net.UnknownHostException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * - * @author shaozhuguang - * @create 2019/1/14 - * @since 1.0.0 - */ - -public class HttpClientPool { - - private static final int TEN_MINUTE = 600 * 1000; - - private static final int TIME_OUT = TEN_MINUTE; - - private static final int CONNECT_TIME_OUT = TEN_MINUTE; - - private static final int SOCKET_TIME_OUT = TEN_MINUTE; - - private static final int MAX_TOTAL = 200; - - private static final int MAX_PER_ROUTE = 40; - - private static final int MAX_ROUTE = 100; - - private static final int RETRY_COUNT = 5; - - private static final String DEFAULT_CHARSET = "UTF-8"; - - private static final Map httpClients = new ConcurrentHashMap<>(); - - private final static Lock lock = new ReentrantLock(); - - private static void config(HttpRequestBase httpRequestBase) { - // 配置请求的超时设置 - RequestConfig requestConfig = RequestConfig.custom() - .setConnectionRequestTimeout(TIME_OUT) - .setConnectTimeout(CONNECT_TIME_OUT) - .setSocketTimeout(SOCKET_TIME_OUT) - .build(); - httpRequestBase.setConfig(requestConfig); - } - - /** - * 获取HttpClient对象 - * - * @param url - * @return - */ - public static CloseableHttpClient getHttpClient(String url) { - String hostName = url.split("/")[2]; - int port = 80; - if (hostName.contains(":")) { - String[] arr = hostName.split(":"); - hostName = arr[0]; - port = Integer.parseInt(arr[1]); - } - return getHttpClient(hostName, port); - } - - /** - * 获取HttpClient对象 - * - * @param hostName - * @param port - * @return - */ - public static CloseableHttpClient getHttpClient(String hostName, int port) { - String key = hostName + ":" + port; - CloseableHttpClient httpClient = httpClients.get(key); - if (httpClient == null) { - try { - lock.lock(); - if (httpClient == null) { - httpClient = createHttpClient(MAX_TOTAL, MAX_PER_ROUTE, MAX_ROUTE, hostName, port); - httpClients.put(key, httpClient); - } - } finally { - lock.unlock(); - } - } - return httpClient; - } - - /** - * 创建HttpClient - * - * @param maxTotal - * @param maxPerRoute - * @param maxRoute - * @param hostname - * @param port - * @return - */ - public static CloseableHttpClient createHttpClient(int maxTotal, - int maxPerRoute, int maxRoute, String hostname, int port) { - ConnectionSocketFactory plainsf = PlainConnectionSocketFactory - .getSocketFactory(); - LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory - .getSocketFactory(); - Registry registry = RegistryBuilder - . create().register("http", plainsf) - .register("https", sslsf).build(); - PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( - registry); - cm.setMaxTotal(maxTotal); - cm.setDefaultMaxPerRoute(maxPerRoute); - HttpHost httpHost = new HttpHost(hostname, port); - cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); - HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> { - if (executionCount >= RETRY_COUNT) {// 最多重试5次 - return false; - }else if (exception instanceof NoHttpResponseException) { - return true; - }else if (exception instanceof SSLException) { - return false; - }else if (exception instanceof InterruptedIOException) { - return false; - }else if (exception instanceof SSLHandshakeException) { - return false; - }else if (exception instanceof UnknownHostException) { - return false; - }else if (exception instanceof ConnectTimeoutException) { - return false; - } - - HttpClientContext clientContext = HttpClientContext - .adapt(context); - HttpRequest request = clientContext.getRequest(); - if (!(request instanceof HttpEntityEnclosingRequest)) { - return true; - } - return false; - }; - - CloseableHttpClient httpClient = HttpClients.custom() - .setConnectionManager(cm) - .setRetryHandler(httpRequestRetryHandler).build(); - - return httpClient; - } - - private static void setPostParams(HttpPost httpPost, - Map params) { - List nameValuePairs = new ArrayList<>(); - Set keySet = params.keySet(); - for (String key : keySet) { - nameValuePairs.add(new BasicNameValuePair(key, params.get(key).toString())); - } - try { - httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET)); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - - private static void setJsonPostParams(HttpPost httpPost, String json) { - httpPost.addHeader("Content-type","application/json; charset=utf-8"); - httpPost.setHeader("Accept", "application/json"); - httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8"))); - } - - /** - * POST请求 - * - * @param url - * @param params - * @return String - * @throws IOException - */ - public static String post(String url, Map params) throws IOException { - HttpPost httpPost = new HttpPost(url); - config(httpPost); - setPostParams(httpPost, params); - try (CloseableHttpResponse response = httpPost(url, httpPost)) { - return parseResponse(response); - } - } - - public static String jsonPost(String url, String json) throws IOException { - HttpPost httpPost = new HttpPost(url); - config(httpPost); - setJsonPostParams(httpPost, json); - try (CloseableHttpResponse response = httpPost(url, httpPost)) { - return parseResponse(response); - } - } - - /** - * GET请求 - * - * @param url - * @return String - */ - public static String get(String url) throws IOException { - HttpGet httpGet = new HttpGet(url); - config(httpGet); - try (CloseableHttpResponse response = httpGet(url, httpGet)) { - return parseResponse(response); - } - } - - /** - * Get请求的真实执行 - * - * @param url - * @param httpGet - * @return - * @throws IOException - */ - private static CloseableHttpResponse httpGet(String url, HttpGet httpGet) throws IOException { - return getHttpClient(url) - .execute(httpGet, HttpClientContext.create()); - } - - /** - * POST请求的真实执行 - * - * @param url - * @param httpPost - * @return - * @throws IOException - */ - private static CloseableHttpResponse httpPost(String url, HttpPost httpPost) throws IOException { - return getHttpClient(url) - .execute(httpPost, HttpClientContext.create()); - } - - /** - * 解析response - * - * @param response - * @return - * @throws IOException - */ - private static String parseResponse(CloseableHttpResponse response) throws IOException { - HttpEntity entity = response.getEntity(); - String result = EntityUtils.toString(entity, DEFAULT_CHARSET); - EntityUtils.consume(entity); - return result; - } - - public static String delete(String url) throws IOException { - HttpDelete httpDelete = new HttpDelete(url); - config(httpDelete); - try (CloseableHttpResponse response = httpDelete(url, httpDelete)) { - return parseResponse(response); - } - } - - private static CloseableHttpResponse httpDelete(String url, HttpDelete httpDelete) throws IOException { - return getHttpClient(url) - .execute(httpDelete, HttpClientContext.create()); - } - - -} \ No newline at end of file diff --git a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/HttpJsonClientUtils.java b/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/HttpJsonClientUtils.java deleted file mode 100644 index 04c8c927..00000000 --- a/source/manager/manager-service/src/main/java/com/jd/blockchain/ump/util/HttpJsonClientUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jd.blockchain.ump.util; - -import com.alibaba.fastjson.JSON; -import com.jd.blockchain.ump.model.MasterAddr; -import com.jd.blockchain.ump.model.web.WebResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HttpJsonClientUtils { - - private static final Logger LOGGER = LoggerFactory.getLogger(HttpJsonClientUtils.class); - - public static T httpPost(MasterAddr masterAddr, String url, Object body, Class returnType, boolean isWrapper) { - - try { - String responseJson = HttpClientPool.jsonPost(masterAddr.toHttpUrl() + url, JSON.toJSONString(body)); - - LOGGER.info("Http Post Receive info =[ {} ] from {} ", responseJson, masterAddr.toHttpUrl() + url); - - return response(responseJson, returnType, isWrapper); - } catch (Exception e) { - - LOGGER.error("HttpPostRequestException {}", e.getMessage()); - - throw new IllegalStateException(e); - } - } - - public static T httpGet(String url, Class returnType, boolean isWrapper) { - try { - String responseJson = HttpClientPool.get(url); - - LOGGER.info("Http Get Receive info =[ {} ] from {} ", responseJson, url); - - return response(responseJson, returnType, isWrapper); - - } catch (Exception e) { - - LOGGER.error("HttpGetRequestException {}", e.toString()); - - throw new IllegalStateException(e); - } - } - - private static T response(String responseJson, Class returnType, boolean isWrapper) { - if (isWrapper) { - // 封装类型的情况下使用的是WebResponse - WebResponse webResponse = JSON.parseObject(responseJson, WebResponse.class); - LOGGER.info("Wrapper JSON Data = {}", JSON.toJSONString(webResponse)); - return webResponse.getData(); - } - - if (!JSON.isValid(responseJson)) { - return (T)responseJson; - } - // 对responseJson进行转换 - T data = JSON.parseObject(responseJson, returnType); - LOGGER.info("UnWrapper JSON Data = {}", JSON.toJSONString(data)); - return data; - } -} diff --git a/source/manager/manager-service/src/main/resources/bftsmart.default.config b/source/manager/manager-service/src/main/resources/bftsmart.default.config deleted file mode 100644 index 5ec6e530..00000000 --- a/source/manager/manager-service/src/main/resources/bftsmart.default.config +++ /dev/null @@ -1,122 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage \ No newline at end of file diff --git a/source/manager/manager-service/src/main/resources/mq.default.config b/source/manager/manager-service/src/main/resources/mq.default.config deleted file mode 100644 index e69de29b..00000000 diff --git a/source/manager/manager-service/src/main/resources/security.default.config b/source/manager/manager-service/src/main/resources/security.default.config deleted file mode 100644 index c90e730c..00000000 --- a/source/manager/manager-service/src/main/resources/security.default.config +++ /dev/null @@ -1,21 +0,0 @@ -#security.roles=DEFAULT, ADMIN, MANAGER, GUEST - -security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT - -security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER - -security.role.ADMIN.tx-privileges=DIRECT_OPERATION - -security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT - -security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -security.role.GUEST.ledger-privileges= - -security.role.GUEST.tx-privileges=CONTRACT_OPERATION - -participant.default.roles=ADMIN, MANAGER - -participant.default.roles-policy=UNION \ No newline at end of file diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/UmpApplicationStarter.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/UmpApplicationStarter.java deleted file mode 100644 index fedb5ec7..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/UmpApplicationStarter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.ump; - -import com.jd.blockchain.ump.web.RetrievalConfigListener; -import org.springframework.boot.SpringApplication; - -import java.util.Properties; - -/** - * JDChain Manager 应用启动器 - * - * @author shaozhuguang - * @date 2019-09-20 - * - */ -public class UmpApplicationStarter { - - /** - * 启动SpringBoot - * 使用自定义ClassLoader加载该类及方法调用 - * - * @param args - * @param props - */ - public static void start(String[] args, Properties props) { - SpringApplication springApplication = new SpringApplication(UmpConfiguration.class); - springApplication.addListeners(new RetrievalConfigListener(props)); - springApplication.run(args); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/UmpConfiguration.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/UmpConfiguration.java deleted file mode 100644 index e25fde13..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/UmpConfiguration.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.ump; - - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@EnableAutoConfiguration -@EnableConfigurationProperties -@ComponentScan -public class UmpConfiguration { -} \ No newline at end of file diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/RetrievalController.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/RetrievalController.java deleted file mode 100644 index cde46f20..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/RetrievalController.java +++ /dev/null @@ -1,297 +0,0 @@ -package com.jd.blockchain.ump.controller; - -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.ump.model.ApiResult; -import com.jd.blockchain.ump.model.ErrorCode; -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.model.penetrate.DataAccountSchema; -import com.jd.blockchain.ump.model.penetrate.SchemaDomain; -import com.jd.blockchain.ump.service.DataAccountUmpService; -import com.jd.blockchain.ump.service.DataRetrievalService; -import com.jd.blockchain.ump.service.UmpStateService; -import com.jd.blockchain.ump.web.RetrievalConfig; -import com.jd.blockchain.utils.ConsoleUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; - -/** - * @Author zhaogw - * date 2019/07/18 17:01 - */ -@RestController -@RequestMapping(path = "/schema") -public class RetrievalController { - private static final Log log = LogFactory.getLog(RetrievalController.class); - - @Autowired - private DataRetrievalService dataRetrievalService; - - @Autowired - private DataAccountUmpService dataAccountUmpService; - - @Autowired - private UmpStateService umpStateService; - - /** - * add schema by web; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.POST, value = "") - public Object addSchema4Web(HttpServletRequest request, @RequestBody SchemaDomain schemaDomain) { - String result; - if (RetrievalConfig.getSchemaUrl() == null || RetrievalConfig.getSchemaUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getSchemaUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - - result = dataRetrievalService.retrievalPost(fullQueryUrl,JSONObject.toJSONString(schemaDomain)); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - - /** - * add schema; - * @param request - * @return - */ -// @RequestMapping(method = RequestMethod.POST, value = "") - @Deprecated - public Object addSchema(HttpServletRequest request,@RequestBody JSONObject jsonObject) { - String result; - if (RetrievalConfig.getSchemaUrl() == null || RetrievalConfig.getSchemaUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getSchemaUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrievalPost(fullQueryUrl,jsonObject); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - - /** - * list schema; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.GET, value = "/list") - public Object listSchema(HttpServletRequest request) { - String result; - if (RetrievalConfig.getSchemaUrl() == null || RetrievalConfig.getSchemaUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getSchemaUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrieval(fullQueryUrl); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - - /** - * delete schema; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.DELETE, value = "/{schemaId}") - public Object deleteSchema(HttpServletRequest request) { - String result; - if (RetrievalConfig.getSchemaUrl() == null || RetrievalConfig.getSchemaUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getSchemaUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.delete(fullQueryUrl); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - - /** - * start schema; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.GET, value = "/start/{schemaId}") - public Object startSchema(HttpServletRequest request) { - String result; - if (RetrievalConfig.getSchemaUrl()==null || RetrievalConfig.getSchemaUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getSchemaUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrieval(fullQueryUrl); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - - /** - * stop schema; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.GET, value = "/stop/{schemaId}") - public Object stopSchema(HttpServletRequest request) { - String result; - if (RetrievalConfig.getSchemaUrl() == null || RetrievalConfig.getSchemaUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getSchemaUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrieval(fullQueryUrl); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - - /** - * querysql; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.POST, value = "/querysql") - public Object queryBySql(HttpServletRequest request,@RequestBody String queryString) { - String result; - if (RetrievalConfig.getSchemaUrl() == null || RetrievalConfig.getSchemaUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getSchemaUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrievalPost(fullQueryUrl,queryString); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - - /** - * add dataAccountSchema; - * @return - */ - @RequestMapping(method = RequestMethod.POST, value = "/addDataAccountSchema") - public ApiResult addDataAccountSchema( @RequestBody DataAccountSchema dataAccountSchema) { - try { - dataAccountUmpService.addDataAccountSchema(dataAccountSchema); - return new ApiResult(ErrorCode.SUCCESS); - } catch (Exception e) { - return new ApiResult(ErrorCode.SERVER_ERROR,e.getMessage()); - } - } - - /** - * delete dataAccountSchema; - * @return - */ - @RequestMapping(method = RequestMethod.GET, value = "/delDataAccountSchema/ledger/{ledgerHash}/account/{dataAccount}") - public ApiResult deleteDataAccountSchema(@PathVariable(name = "ledgerHash") String ledgerHash, - @PathVariable(name = "dataAccount") String dataAccount) { - try { - dataAccountUmpService.deleteDataAcccountSchema(ledgerHash, dataAccount); - return new ApiResult(ErrorCode.SUCCESS); - } catch (Exception e) { - return new ApiResult(ErrorCode.SERVER_ERROR,e.getMessage()); - } - } - - /** - * find dataAccountSchema; - * @return - */ - @RequestMapping(method = RequestMethod.GET, value = "/findDataAccountSchema/ledger/{ledgerHash}/account/{dataAccount}") - public ApiResult findDataAccountSchema(@PathVariable(name = "ledgerHash") String ledgerHash, - @PathVariable(name = "dataAccount") String dataAccount) { - try { - DataAccountSchema dataAccountSchema = dataAccountUmpService.findDataAccountSchema(ledgerHash, dataAccount); - return new ApiResult(ErrorCode.SUCCESS,dataAccountSchema); - } catch (Exception e) { - return new ApiResult(ErrorCode.SERVER_ERROR,e.getMessage()); - } - } - - @RequestMapping(method = RequestMethod.GET, value = "/ledgers") - public String getAllLedgers() { - //generate the url; - int peerPort = umpStateService.peerPort(); - String url = "http://localhost:"+peerPort+"/ledgers"; - try { - return dataRetrievalService.retrieval(url); - } catch (Exception e) { - return "{'success':false,'data':'" + e.getMessage() + "'}"; - } - } - - @RequestMapping(method = RequestMethod.GET, value = "/ledger/{ledgerHash}") - public String getAllDataAccounts(@PathVariable(name = "ledgerHash") String ledgerHash) { - //generate the url; - int peerPort = umpStateService.peerPort(); - String url = "http://localhost:"+peerPort+"/ledgers/"+ledgerHash+"/accounts"; - try { - return dataRetrievalService.retrieval(url); - } catch (Exception e) { - return "{'success':false,'data':'" + e.getMessage() + "'}"; - } - } -} \ No newline at end of file diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/TaskRetrievalController.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/TaskRetrievalController.java deleted file mode 100644 index d1262c0b..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/TaskRetrievalController.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jd.blockchain.ump.controller; - -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.service.DataRetrievalService; -import com.jd.blockchain.ump.web.RetrievalConfig; -import com.jd.blockchain.utils.ConsoleUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -/** - * @Author zhaogw - * date 2019/07/18 17:01 - */ -@RestController -@RequestMapping(path = "/tasks") -public class TaskRetrievalController { - private static final Log log = LogFactory.getLog(TaskRetrievalController.class); - -// @Value("${task.retrieval.url}") -// private String taskRetrievalUrl; - - @Autowired - private DataRetrievalService dataRetrievalService; - - /** - * get the nums of all tasks; - * @param request - * @return - */ - @RequestMapping(method = RequestMethod.GET, value = "") - public Object listSchema(HttpServletRequest request) { - String result; - if (RetrievalConfig.getTaskUrl() == null || RetrievalConfig.getTaskUrl().length() <= 0) { - result = "{'message':'OK','data':'" + "schema.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(RetrievalConfig.getTaskUrl()) - .append(request.getRequestURI()) - .append(UmpConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrieval(fullQueryUrl); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'error','data':'" + e.getMessage() + "'}"; - } - } - return JSONObject.parse(result); - } - -} \ No newline at end of file diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpDBController.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpDBController.java deleted file mode 100644 index be55fa34..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpDBController.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.ump.controller; - -import com.jd.blockchain.ump.dao.DBConnection; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping(path = "/db/") -public class UmpDBController { - - @Autowired - private DBConnection dbConnection; - - @RequestMapping(method = RequestMethod.GET, path = "read/{key}") - public String read(@PathVariable(name = "key") String key) { - - return dbConnection.get(key); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpKeyController.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpKeyController.java deleted file mode 100644 index a7d2aed3..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpKeyController.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jd.blockchain.ump.controller; - -import com.jd.blockchain.ump.model.user.UserKeyBuilder; -import com.jd.blockchain.ump.model.user.UserKeys; -import com.jd.blockchain.ump.model.user.UserKeysVv; -import com.jd.blockchain.ump.service.UmpStateService; -import com.jd.blockchain.ump.service.UtilService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@RequestMapping(path = "/keys/") -public class UmpKeyController { - - @Autowired - private UtilService utilService; - - @Autowired - private UmpStateService umpStateService; - - - /** - * 创建用户 - * - * @param builder - * @return - */ - @RequestMapping(method = RequestMethod.POST, path = "create") - public UserKeysVv create(@RequestBody final UserKeyBuilder builder) { - - // 使用种子生成公私钥 - UserKeys userKeys = utilService.create(builder); - - // 将userKeys保存至数据库 - umpStateService.save(userKeys); - - return userKeys.toUserKeysVv(); - } - - @RequestMapping(method = RequestMethod.GET, path = "list") - public List list() { - - // 从数据库中读取,返回 - return umpStateService.readUserKeysVvList(); - } - - @RequestMapping(method = RequestMethod.GET, path = "read/{user}/{pubKey}") - public UserKeysVv read(@PathVariable(name = "user") int userId, - @PathVariable(name = "pubKey") String pubKey) { - - UserKeys userKeys = utilService.read(userId); - - if (userKeys != null) { - if (userKeys.getPubKey().equals(pubKey)) { - - return userKeys.toUserKeysVv(); - } - } - throw new IllegalStateException(String.format("Can not find UserKeys by %s", pubKey)); - } - - /** - * 解析UserKeys - * - * @param userId - * 用户ID - * @param pwd - * 密码(非编码后密码) - * @return - */ - @RequestMapping(method = RequestMethod.GET, path = "resolve/{user}/{pwd}") - public UserKeys resolve(@PathVariable(name = "user") int userId, - @PathVariable(name = "pwd") String pwd) { - - UserKeys userKeys = utilService.read(userId); - - if (utilService.verify(userKeys, pwd)) { - - return userKeys; - } - throw new IllegalStateException(String.format("Can not resolve UserKeys by %s", pwd)); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpMasterController.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpMasterController.java deleted file mode 100644 index 7caa0584..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpMasterController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jd.blockchain.ump.controller; - -import com.jd.blockchain.ump.model.PeerSharedConfigs; -import com.jd.blockchain.ump.model.config.LedgerConfig; -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.state.InstallSchedule; -import com.jd.blockchain.ump.model.state.LedgerMasterInstall; -import com.jd.blockchain.ump.service.UmpService; -import com.jd.blockchain.ump.service.UmpStateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping(path = "/master/") -public class UmpMasterController { - - @Autowired - private UmpService umpService; - - @Autowired - private UmpStateService umpStateService; - - /** - * 需要支持的接口 - * 1、接收节点Share的信息 - * 2、接收节点发送来的状态信息 - * 3、接收前端查看某些节点状态的请求 - */ - @RequestMapping(method = RequestMethod.POST, path = "share") - public LedgerConfig share(@RequestBody final PeerLocalConfig sharedConfig) { - - PeerSharedConfigs sharedConfigs = umpService.loadPeerSharedConfigs(sharedConfig); - - if (sharedConfigs == null) { - throw new IllegalStateException("PeerSharedConfig may be exits Conflict !!!"); - } - - return umpService.response(sharedConfigs, sharedConfig); - } - - /** - * 接收其他Peer节点发送的安装信息 - * - * @param installSchedule - * 安装信息 - * - * @return - */ - @RequestMapping(method = RequestMethod.POST, path = "receive") - public String receive(@RequestBody final InstallSchedule installSchedule) { - - try { - umpStateService.save(installSchedule, null); - } catch (Exception e) { - return "FAIL"; - } - - return "SUCCESS"; - } - - @RequestMapping(method = RequestMethod.GET, path = "read/{ledgerKey}") - public Map> readState(@PathVariable(name = "ledgerKey") String ledgerKey) { - - return umpStateService.readStates(ledgerKey); - } - - @RequestMapping(method = RequestMethod.GET, path = "list") - public List ledgerInstallList() { - - // 返回当前Master收到的所有节点所有的安装信息 - return umpStateService.readLedgerMasterInstalls(); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpPeerController.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpPeerController.java deleted file mode 100644 index 9222b14c..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpPeerController.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.jd.blockchain.ump.controller; - -import com.jd.blockchain.ump.model.MasterAddr; -import com.jd.blockchain.ump.model.UmpConstant; -import com.jd.blockchain.ump.model.config.LedgerConfig; -import com.jd.blockchain.ump.model.config.LedgerIdentification; -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.config.PeerSharedConfigVv; -import com.jd.blockchain.ump.model.state.*; -import com.jd.blockchain.ump.model.user.UserKeys; -import com.jd.blockchain.ump.service.UmpService; -import com.jd.blockchain.ump.service.UmpStateService; -import com.jd.blockchain.ump.service.UtilService; -import com.jd.blockchain.ump.util.HttpJsonClientUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@RequestMapping(path = "/peer/") -public class UmpPeerController { - - @Autowired - private UmpService umpService; - - @Autowired - private UmpStateService umpStateService; - - @Autowired - private UmpMasterController masterController; - - @Autowired - private UtilService utilService; - -// @RequestMapping(method = RequestMethod.POST, path = "share") - public LedgerIdentification share(@RequestBody PeerLocalConfig localConfig) { - - //首先校验配置信息 - localConfig.verify(); - - MasterAddr masterAddr = localConfig.masterAddr(); - - LedgerConfig ledgerConfig; - - if (localConfig.master()) { - // 当前节点本身是master,直接调用Controller方法 - ledgerConfig = masterController.share(localConfig); - } else { - ledgerConfig = HttpJsonClientUtils.httpPost(masterAddr, UmpConstant.REQUEST_SHARED_URL, localConfig, LedgerConfig.class, false); - } - - if (ledgerConfig == null) { - // 未加载成功 - throw new IllegalStateException("Can not load Ledger-Config's Data from Master Node !!!"); - } - - String ledgerAndNodeKey = umpService.save(masterAddr, ledgerConfig, localConfig); - - int nodeId = ledgerConfig.getInitConfig().nodeId(localConfig.getPubKey()); - - LedgerIdentification identification = new LedgerIdentification(nodeId, localConfig, - masterAddr, ledgerAndNodeKey, ledgerConfig.getInitConfig()); - - // 将数据写入数据库 - umpStateService.save(identification); - - return identification; - } - - @RequestMapping(method = RequestMethod.POST, path = "share") - public LedgerIdentification share(@RequestBody PeerSharedConfigVv sharedConfigVv) { - - String pubKey = sharedConfigVv.getPubKey(); - - if (pubKey == null || pubKey.length() == 0) { - throw new IllegalStateException("Public Key can not be empty !!!"); - } - - // 获取对应的UsersKey,转换为LocalConfig - UserKeys userKeys = utilService.read(sharedConfigVv.getUserId()); - - if (userKeys == null || !pubKey.equals(userKeys.getPubKey())) { - throw new IllegalStateException(String.format("Can not find UserKeys by %s", pubKey)); - } - - PeerLocalConfig localConfig = sharedConfigVv.toPeerLocalConfig(userKeys); - - return share(localConfig); - } - - @RequestMapping(method = RequestMethod.POST, path = "install/{ledgerAndNodeKey}") - public PeerInstallSchedules install(@PathVariable(name = "ledgerAndNodeKey") String ledgerAndNodeKey) { - - return umpService.install(ledgerAndNodeKey); - } - - @RequestMapping(method = RequestMethod.POST, path = "init/{ledgerAndNodeKey}") - public PeerInstallSchedules init(@PathVariable(name = "ledgerAndNodeKey") String ledgerAndNodeKey) { - - return umpService.init(ledgerAndNodeKey); - } - - @RequestMapping(method = RequestMethod.POST, path = "startup") - public PeerStartupSchedules startup() { - - return umpService.startup(); - } - -// @RequestMapping(method = RequestMethod.POST, path = "stop/{ledgerAndNodeKey}") - public boolean stop(@PathVariable(name = "ledgerAndNodeKey") String ledgerAndNodeKey) { - - return umpService.stop(ledgerAndNodeKey); - } - - @RequestMapping(method = RequestMethod.POST, path = "stop") - public boolean stop() { - - return umpService.stop(); - } - - @RequestMapping(method = RequestMethod.GET, path = "init/read/{ledgerAndNodeKey}") - public PeerInstallSchedules readInitState(@PathVariable(name = "ledgerAndNodeKey") String ledgerAndNodeKey) { - - return umpStateService.readInitState(ledgerAndNodeKey); - } - - @RequestMapping(method = RequestMethod.GET, path = "list") - public List ledgerInstallList() { - - // 返回当前Peer节点所有的安装信息 - return umpStateService.readLedgerPeerInstalls(); - } - - public List ledgerInitedList(@RequestParam(name = "search", required = false) String search) { - - // 返回当前Peer节点所有的初始化后信息 - return umpStateService.readLedgerPeerIniteds(search); - } - - @RequestMapping(method = RequestMethod.GET, path = "initeds") - public List ledgerIniteds(@RequestParam(name = "search", required = false) String search) { - - // 返回当前Peer节点所有的初始化后信息 - return umpStateService.readLedgerIniteds(search); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpPeerSimulateController.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpPeerSimulateController.java deleted file mode 100644 index 35f0e8af..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/controller/UmpPeerSimulateController.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jd.blockchain.ump.controller; - -import com.jd.blockchain.ump.model.config.LedgerIdentification; -import com.jd.blockchain.ump.model.config.PeerLocalConfig; -import com.jd.blockchain.ump.model.state.PeerInstallSchedules; -import com.jd.blockchain.ump.service.UmpService; -import com.jd.blockchain.ump.service.UmpSimulateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -@RestController -@RequestMapping(path = "/peer/") -public class UmpPeerSimulateController { - - private final Map ledgerAndNodeKeys = new ConcurrentHashMap<>(); - - @Autowired - private UmpService umpService; - - @Autowired - private UmpSimulateService simulateService; - - @Autowired - private UmpPeerController peerController; - - @RequestMapping(method = RequestMethod.GET, path = "share/simulate/{node}") - public LedgerIdentification share(@PathVariable(name = "node") int nodeId) { - - boolean isMaster = false; - if (nodeId == 0) { - isMaster = true; - } - - PeerLocalConfig localConfig = simulateService.nodePeerLocalConfig(nodeId, isMaster); - - LedgerIdentification identification = peerController.share(localConfig); - - // 作为缓存使用 - ledgerAndNodeKeys.put(nodeId, identification.getLedgerAndNodeKey()); - - return identification; - } - - - @RequestMapping(method = RequestMethod.GET, path = "install/simulate/{node}") - public PeerInstallSchedules install(@PathVariable(name = "node") int nodeId) { - - String ledgerAndNodeKey = ledgerAndNodeKeys.get(nodeId); - - return umpService.install(ledgerAndNodeKey); - } - - @RequestMapping(method = RequestMethod.GET, path = "init/simulate/{node}") - public PeerInstallSchedules init(@PathVariable(name = "node") int nodeId) { - - return umpService.init(ledgerAndNodeKeys.get(nodeId)); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/ControllerConfigurer.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/ControllerConfigurer.java deleted file mode 100644 index 6c5be2f3..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/ControllerConfigurer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.ump.web; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class ControllerConfigurer implements WebMvcConfigurer { - - @Override - public void addInterceptors(InterceptorRegistry registry) { - - // 添加打印日志的拦截器 - registry.addInterceptor(new LogPrintInterceptor()).addPathPatterns("/**"); - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources"); - } - - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("web/index.html"); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/ExceptionResponseAdvice.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/ExceptionResponseAdvice.java deleted file mode 100644 index c079fccc..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/ExceptionResponseAdvice.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jd.blockchain.ump.web; - -import com.jd.blockchain.ump.model.web.ErrorCode; -import com.jd.blockchain.ump.model.web.WebResponse; -import com.jd.blockchain.utils.BusinessException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -import javax.servlet.http.HttpServletRequest; - -@RestControllerAdvice -public class ExceptionResponseAdvice { - - private final Logger logger = LoggerFactory.getLogger(getClass()); - - @ExceptionHandler(value = Exception.class) - @ResponseBody - public WebResponse json(HttpServletRequest req, Exception ex) { - - WebResponse.ErrorMessage message; - - String reqURL = "[" + req.getMethod() + "] " + req.getRequestURL().toString(); - - if (ex instanceof BusinessException) { - BusinessException businessException = (BusinessException) ex; - message = new WebResponse.ErrorMessage(businessException.getErrorCode(), businessException.getMessage()); - } else { - logger.error("Exception occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() - + "]" + ex.getMessage(), ex); - - message = new WebResponse.ErrorMessage(ErrorCode.UNEXPECTED.getValue(), ex.toString()); - } - return WebResponse.createFailureResult(message); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/JsonResponseAdvice.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/JsonResponseAdvice.java deleted file mode 100644 index 9c9505e1..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/JsonResponseAdvice.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jd.blockchain.ump.web; - -import com.jd.blockchain.ump.controller.RetrievalController; -import com.jd.blockchain.ump.controller.TaskRetrievalController; -import com.jd.blockchain.ump.model.config.LedgerConfig; -import com.jd.blockchain.ump.model.web.WebResponse; -import org.springframework.core.MethodParameter; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.server.ServerHttpRequest; -import org.springframework.http.server.ServerHttpResponse; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; - -@RestControllerAdvice -public class JsonResponseAdvice implements ResponseBodyAdvice { - - @Override - public boolean supports(MethodParameter returnType, Class> converterType) { - if (MappingJackson2HttpMessageConverter.class == converterType - && (returnType.getContainingClass().getName().startsWith("com.jd.blockchain.ump") - || returnType.getDeclaringClass().getName().startsWith("com.jd.blockchain.ump"))) { - - if (returnType.getContainingClass() == RetrievalController.class || returnType.getContainingClass() == TaskRetrievalController.class) { - return false; - } - - return true; - } - return false; - } - - @Override - public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, - Class> selectedConverterType, ServerHttpRequest request, - ServerHttpResponse response) { - if (body == null) { - return WebResponse.createSuccessResult(null); - } - - if (body instanceof ResponseEntity) { - return body; - } - - // LedgerConfig单独处理 - if (body instanceof LedgerConfig) { - return body; - } - - // 把返回结果自动转换为 WebResponse; - if (body instanceof WebResponse) { - return body; - } - return WebResponse.createSuccessResult(body); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/LogPrintInterceptor.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/LogPrintInterceptor.java deleted file mode 100644 index c68ef5e8..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/LogPrintInterceptor.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.ump.web; - -import com.alibaba.fastjson.JSON; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.servlet.HandlerInterceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.Map; - -public class LogPrintInterceptor implements HandlerInterceptor { - - private final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - // 记录日志 - // 请求的参数: - String parameters = ""; - Map requestParameters = request.getParameterMap(); - if (requestParameters != null && !requestParameters.isEmpty()) { - parameters = JSON.toJSONString(requestParameters); - } - LOGGER.info("Request[{}][{}], parameters=[{}]", - request.getRequestURL().toString(), // 请求URL - request.getMethod(), // 请求的方法 - parameters); // 请求的参数 - - return true; - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/RetrievalConfig.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/RetrievalConfig.java deleted file mode 100644 index 8c254f02..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/RetrievalConfig.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jd.blockchain.ump.web; - -import org.springframework.beans.BeansException; -import org.springframework.core.io.support.PropertiesLoaderUtils; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import static com.jd.blockchain.ump.model.UmpConstant.SCHEMA_RETRIEVAL_URL; -import static com.jd.blockchain.ump.model.UmpConstant.TASK_RETRIEVAL_URL; - -public class RetrievalConfig { - - private static Map propertiesMap = new HashMap<>(); - - private String schemaUrl; - private String taskUrl; - - public static void processProperties(Properties props) throws BeansException { - propertiesMap = new HashMap(); - for (Object key : props.keySet()) { - String keyStr = key.toString(); - try { - // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下 - propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (java.lang.Exception e) { - e.printStackTrace(); - } - } - } - - public static void loadAllProperties(String propertyFileName) { - try { - Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName); - processProperties(properties); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getProperty(String name) { - return propertiesMap.get(name).toString(); - } - - public static Map getAllProperty() { - return propertiesMap; - } - - public static String getSchemaUrl() { - return propertiesMap.get(SCHEMA_RETRIEVAL_URL); - } - - public static String getTaskUrl() { - return propertiesMap.get(TASK_RETRIEVAL_URL); - } - -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/RetrievalConfigListener.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/RetrievalConfigListener.java deleted file mode 100644 index 7ab9a75e..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/RetrievalConfigListener.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.ump.web; - - -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; - -import java.util.Properties; - -public class RetrievalConfigListener implements ApplicationListener { - private Properties props; - - public RetrievalConfigListener(Properties props){ - this.props = props; - } - - @Override - public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { - RetrievalConfig.processProperties(props); - } -} diff --git a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/UmpSecurityConfiguration.java b/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/UmpSecurityConfiguration.java deleted file mode 100644 index 5a50b7e4..00000000 --- a/source/manager/manager-web/src/main/java/com/jd/blockchain/ump/web/UmpSecurityConfiguration.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jd.blockchain.ump.web; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -@EnableWebSecurity -public class UmpSecurityConfiguration extends WebSecurityConfigurerAdapter { - - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().permitAll(); - http.csrf().disable(); - } -} diff --git a/source/peer/.gitignore b/source/peer/.gitignore deleted file mode 100644 index 4f496dc3..00000000 --- a/source/peer/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/target/ -/.apt_generated_tests/ diff --git a/source/peer/shell/start.bat b/source/peer/shell/start.bat deleted file mode 100644 index ce8a26c8..00000000 --- a/source/peer/shell/start.bat +++ /dev/null @@ -1 +0,0 @@ -java -jar peer-0.0.1-SNAPSHOT.jar --spring.config.location=file:config/application.properties diff --git a/source/peer/shell/start.sh b/source/peer/shell/start.sh deleted file mode 100644 index 6c015ea4..00000000 --- a/source/peer/shell/start.sh +++ /dev/null @@ -1 +0,0 @@ -nohup java -jar peer-0.0.1-SNAPSHOT.jar --spring.config.location=file:config/application.properties & diff --git a/source/peer/shell/stop.sh b/source/peer/shell/stop.sh deleted file mode 100644 index 5657192c..00000000 --- a/source/peer/shell/stop.sh +++ /dev/null @@ -1,6 +0,0 @@ -PID=`ps -ef | grep "java -jar peer-" | grep -v grep | awk '{print $2}'` -PROC_PATH=`ps -ef | grep "java -jar peer-" | grep -v grep | awk '{print $8}'` -echo "Stopping peer[$PID][$PROC_PATH] ......" -kill 9 $PID - -echo "Peer stopped!" diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/ConsensusManage.java b/source/peer/src/main/java/com/jd/blockchain/peer/ConsensusManage.java deleted file mode 100644 index 55da341c..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/ConsensusManage.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.peer; - -import com.jd.blockchain.consensus.service.NodeServer; - -/** - * 共识服务管理; - * @author huanghaiquan - * - */ -public interface ConsensusManage { - - /** - * @return - */ - ConsensusRealm[] getRealms(); - - /** - * 启动参与的全部共识域的共识服务; - */ - void runAllRealms(); - - /** - * 启动某个共识服务 - * @param nodeServer - */ - void runRealm(NodeServer nodeServer); - - /** - * 停止共识服务; - */ - void closeAllRealms(); - -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/ConsensusRealm.java b/source/peer/src/main/java/com/jd/blockchain/peer/ConsensusRealm.java deleted file mode 100644 index 2beb0b49..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/ConsensusRealm.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.peer; - -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.utils.Bytes; - -/** - * 共识域; - * - * @author huanghaiquan - * - */ -public interface ConsensusRealm { - - /** - * 共识节点列表; - * - * @return - */ - ParticipantNode[] getNodes(); - - /** - * 共识系统配置; - * @return - */ - Bytes getSetting(); - - /** - * 与指定的共识域是否有交集; - * - * @param other - * @return - */ - boolean hasIntersection(ConsensusRealm other); - -} \ No newline at end of file diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/LedgerBindingConfigAware.java b/source/peer/src/main/java/com/jd/blockchain/peer/LedgerBindingConfigAware.java deleted file mode 100644 index e8b244c6..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/LedgerBindingConfigAware.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jd.blockchain.peer; - -import com.jd.blockchain.consensus.service.NodeServer; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; - -public interface LedgerBindingConfigAware { - - void setConfig(LedgerBindingConfig config); - - NodeServer setConfig(LedgerBindingConfig config, HashDigest ledgerHash); -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/PeerManage.java b/source/peer/src/main/java/com/jd/blockchain/peer/PeerManage.java deleted file mode 100644 index 300bca6c..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/PeerManage.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jd.blockchain.peer; - -public interface PeerManage extends LedgerBindingConfigAware, ConsensusManage{ - -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/PeerServerBooter.java b/source/peer/src/main/java/com/jd/blockchain/peer/PeerServerBooter.java deleted file mode 100644 index b7892879..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/PeerServerBooter.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.jd.blockchain.peer; - -import com.jd.blockchain.consts.Global; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.ArgumentSet; -import com.jd.blockchain.utils.ConsoleUtils; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.io.ClassPathResource; - -import java.io.File; -import java.io.InputStream; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * 节点服务器; - * - * @author huanghaiquan - * - */ -public class PeerServerBooter { - - private static final Log log = LogFactory.getLog(PeerServerBooter.class); - - // 初始化账本绑定配置文件的路径; - public static final String LEDGERBIND_ARG = "-c"; - // 服务地址; - private static final String HOST_ARG = "-h"; - // 服务端口; - private static final String PORT_ARG = "-p"; - // 是否输出调试信息; - private static final String DEBUG_OPT = "-debug"; - - public static String ledgerBindConfigFile; - - static { - // 加载 Global ,初始化全局设置; - Global.initialize(); - } - - public static void main(String[] args) { - PeerServerBooter peerServerBooter = new PeerServerBooter(); - peerServerBooter.handle(args); - } - - public void handle(String[] args){ - LedgerBindingConfig ledgerBindingConfig = null; - ArgumentSet arguments = ArgumentSet.resolve(args, - ArgumentSet.setting().prefix(LEDGERBIND_ARG, HOST_ARG, PORT_ARG).option(DEBUG_OPT)); - boolean debug = false; - try { - ArgumentSet.ArgEntry argLedgerBindConf = arguments.getArg(LEDGERBIND_ARG); - ledgerBindConfigFile = argLedgerBindConf == null ? null : argLedgerBindConf.getValue(); - if (ledgerBindConfigFile == null) { - ConsoleUtils.info("Load build-in default configuration ..."); - ClassPathResource configResource = new ClassPathResource("ledger-binding.conf"); - - try (InputStream in = configResource.getInputStream()) { - ledgerBindingConfig = LedgerBindingConfig.resolve(in); - } catch (Exception e) { - throw e; - } - } else { - ConsoleUtils.info("Load configuration,ledgerBindConfigFile position="+ledgerBindConfigFile); - File file = new File(ledgerBindConfigFile); - ledgerBindingConfig = LedgerBindingConfig.resolve(file); - } - String host = null; - ArgumentSet.ArgEntry hostArg = arguments.getArg(HOST_ARG); - if (hostArg != null) { - host = hostArg.getValue(); - } - int port = 0; - ArgumentSet.ArgEntry portArg = arguments.getArg(PORT_ARG); - if (portArg != null) { - try { - port = Integer.parseInt(portArg.getValue()); - } catch (NumberFormatException e) { - // ignore NumberFormatException of port argument; - } - } - - debug = arguments.hasOption(DEBUG_OPT); - - PeerServerBooter booter = new PeerServerBooter(ledgerBindingConfig, host, port); - if(log.isDebugEnabled()){ - log.debug("PeerServerBooter's urls="+ Arrays.toString(((URLClassLoader) booter.getClass().getClassLoader()).getURLs())); - } - booter.start(); - } catch (Exception e) { - ConsoleUtils.error("Error occurred on startup! --%s", e.getMessage()); - if (debug) { - e.printStackTrace(); - } - } - } - - private LedgerBindingConfig ledgerBindingConfig; - private String hostAddress; - private int port; - private Object[] externalBeans; - private volatile ConfigurableApplicationContext appContext; - - public PeerServerBooter(){} - - public PeerServerBooter(LedgerBindingConfig ledgerBindingConfig, String hostAddress, int port, - Object... externalBeans) { - this.ledgerBindingConfig = ledgerBindingConfig; - this.hostAddress = hostAddress; - this.port = port; - this.externalBeans = externalBeans; - } - - public synchronized void start() { - if (appContext != null) { - throw new IllegalStateException("Peer server is running already!"); - } - appContext = startServer(ledgerBindingConfig, hostAddress, port, externalBeans); - } - - public synchronized void close() { - if (appContext == null) { - return; - } - ConfigurableApplicationContext ctx = appContext; - appContext = null; - ctx.close(); - } - - /** - * 启动服务; - * - * @param ledgerBindingConfig - * 账本绑定配置; - * @param hostAddress - * 服务地址;如果为空,则采用默认配置; - * @param port - * 端口地址;如果小于等于 0 ,则采用默认配置; - * @return - */ - private static ConfigurableApplicationContext startServer(LedgerBindingConfig ledgerBindingConfig, - String hostAddress, int port, Object... externalBeans) { - List argList = new ArrayList(); - String argServerAddress = String.format("--server.address=%s", "0.0.0.0"); - argList.add(argServerAddress); -// if (hostAddress != null && hostAddress.length() > 0) { -// String argServerAddress = String.format("--server.address=%s", hostAddress); -// argList.add(argServerAddress); -// } - if (port > 0) { - String argServerPort = String.format("--server.port=%s", port); - argList.add(argServerPort); - } - - String[] args = argList.toArray(new String[argList.size()]); - - SpringApplication app = new SpringApplication(PeerConfiguration.class); - if (externalBeans != null && externalBeans.length > 0) { - app.addInitializers((ApplicationContextInitializer) applicationContext -> { - ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); - for (Object bean : externalBeans) { - if (bean != null) { - beanFactory.registerSingleton(bean.toString(), bean); - } - } - }); - } - // 启动 web 服务; - ConfigurableApplicationContext ctx = app.run(args); - - // 建立共识网络; - Map bindingConfigAwares = ctx.getBeansOfType(LedgerBindingConfigAware.class); - for (LedgerBindingConfigAware aware : bindingConfigAwares.values()) { - aware.setConfig(ledgerBindingConfig); - } - ConsensusManage consensusManage = ctx.getBean(ConsensusManage.class); - consensusManage.runAllRealms(); - - return ctx; - } - - public DbConnectionFactory getDBConnectionFactory() { - return appContext.getBean(DbConnectionFactory.class); - } -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusMessageDispatcher.java b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusMessageDispatcher.java deleted file mode 100644 index 6b8967f6..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusMessageDispatcher.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.jd.blockchain.peer.consensus; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.OperationResult; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.core.TransactionBatchProcessor; -import com.jd.blockchain.ledger.core.TransactionEngineImpl; -import com.jd.blockchain.service.TransactionBatchProcess; -import com.jd.blockchain.service.TransactionBatchResultHandle; -import com.jd.blockchain.service.TransactionEngine; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.concurrent.AsyncFuture; -import com.jd.blockchain.utils.concurrent.CompletableAsyncFuture; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.jd.blockchain.consensus.service.MessageHandle; -import com.jd.blockchain.consensus.service.StateSnapshot; -import com.jd.blockchain.crypto.HashDigest; - -import javax.swing.plaf.nimbus.State; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * @author huanghaiquan - * - */ -@Component -public class ConsensusMessageDispatcher implements MessageHandle { - - @Autowired - private TransactionEngine txEngine; - - // todo 可能存在内存溢出的问题 - private final Map realmProcessorMap = new ConcurrentHashMap<>(); - - private final ReentrantLock beginLock = new ReentrantLock(); - - @Override - public String beginBatch(String realmName) { - RealmProcessor realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - beginLock.lock(); - try { - realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - realmProcessor = initRealmProcessor(realmName); - realmProcessorMap.put(realmName, realmProcessor); - } - } finally { - beginLock.unlock(); - } - } - return realmProcessor.newBatchId(); - } - - @Override - public StateSnapshot getStateSnapshot(String realmName) { - RealmProcessor realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - throw new IllegalArgumentException("RealmName is not init!"); - } - - return realmProcessor.getStateSnapshot(); - - } - - @Override - public StateSnapshot getGenisStateSnapshot(String realmName) { - RealmProcessor realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - throw new IllegalArgumentException("RealmName is not init!"); - } - return realmProcessor.getGenisStateSnapshot(); - } - - @Override - public AsyncFuture processOrdered(int messageId, byte[] message, String realmName, String batchId) { - // TODO 要求messageId在同一个批次不重复,但目前暂不验证 - RealmProcessor realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - throw new IllegalArgumentException("RealmName is not init!"); - } - if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { - throw new IllegalArgumentException("BatchId is not begin!"); - } - TransactionRequest txRequest = BinaryProtocol.decode(message); - return realmProcessor.schedule(txRequest); - } - - @Override - public StateSnapshot completeBatch(String realmName, String batchId) { - RealmProcessor realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - throw new IllegalArgumentException("RealmName is not init!"); - } - if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { - throw new IllegalArgumentException("BatchId is not begin!"); - } - return realmProcessor.complete(); - } - - @Override - public void commitBatch(String realmName, String batchId) { - RealmProcessor realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - throw new IllegalArgumentException("RealmName is not init!"); - } - if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { - throw new IllegalArgumentException("BatchId is not begin!"); - } - realmProcessor.commit(); -// realmProcessorMap.remove(realmName); - } - - @Override - public void rollbackBatch(String realmName, String batchId, int reasonCode) { - RealmProcessor realmProcessor = realmProcessorMap.get(realmName); - if (realmProcessor == null) { - throw new IllegalArgumentException("RealmName is not init!"); - } - if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { - throw new IllegalArgumentException("BatchId is not begin!"); - } - realmProcessor.rollback(reasonCode); -// realmProcessorMap.remove(realmName); - } - - @Override - public AsyncFuture processUnordered(byte[] message) { - // TODO Auto-generated method stub - throw new IllegalArgumentException("Not implemented!"); - } - - private RealmProcessor initRealmProcessor(String realmName) { - RealmProcessor realmProcessor = new RealmProcessor(); - byte[] hashBytes = Base58Utils.decode(realmName); - HashDigest ledgerHash = new HashDigest(hashBytes); - realmProcessor.realmName = realmName; - realmProcessor.ledgerHash = ledgerHash; - return realmProcessor; - } - - private final class RealmProcessor { - - private final Lock realmLock = new ReentrantLock(); - - private String currBatchId; - - private final ExecutorService txExecutor = Executors.newSingleThreadExecutor(); - - // todo 暂不处理队列溢出导致的OOM问题 - private final ExecutorService asyncBlExecutor = Executors.newSingleThreadExecutor(); - - private Map> txResponseMap; - - private TransactionBatchResultHandle batchResultHandle; - - private final AtomicLong batchIdIndex = new AtomicLong(); - - private LedgerBlock currBlock; - - private TransactionBatchProcess txBatchProcess; - - HashDigest ledgerHash; - - String realmName; - - public String getRealmName() { - return realmName; - } - - public TransactionBatchProcess getTxBatchProcess() { - return txBatchProcess; - } - - public AtomicLong getBatchIdIndex() { - return batchIdIndex; - } - - public HashDigest getLedgerHash() { - return ledgerHash; - } - - public String getCurrBatchId() { - return currBatchId; - } - - public String newBatchId() { - realmLock.lock(); - try { - if (currBatchId == null) { - currBatchId = getRealmName() + "-" + getBatchIdIndex().getAndIncrement(); - } - if (txResponseMap == null) { - txResponseMap = new ConcurrentHashMap<>(); - } - if (txBatchProcess == null) { - txBatchProcess = txEngine.createNextBatch(ledgerHash); - } - } finally { - realmLock.unlock(); - } - return currBatchId; - } - - public StateSnapshot getStateSnapshot() { - return new BlockStateSnapshot(((TransactionBatchProcessor)getTxBatchProcess()).getPreLatestBlockHeight(), ((TransactionBatchProcessor)getTxBatchProcess()).getPrevLatestBlockHash()); - } - - public StateSnapshot getGenisStateSnapshot() { - return new BlockStateSnapshot(0, ((TransactionBatchProcessor)getTxBatchProcess()).getGenisBlockHash()); - } - - public AsyncFuture schedule(TransactionRequest txRequest) { - CompletableAsyncFuture asyncTxResult = new CompletableAsyncFuture<>(); - TransactionResponse resp = getTxBatchProcess().schedule(txRequest); - txResponseMap.put(resp, asyncTxResult); -// txExecutor.execute(() -> { -// TransactionResponse resp = getTxBatchProcess().schedule(txRequest); -// txResponseMap.put(resp, asyncTxResult); -// }); - return asyncTxResult; - } - - public StateSnapshot complete() { - batchResultHandle = getTxBatchProcess().prepare(); - currBlock = batchResultHandle.getBlock(); - long blockHeight = currBlock.getHeight(); - HashDigest blockHash = currBlock.getHash(); - asyncBlExecute(new HashMap<>(txResponseMap), blockHeight, blockHash); - BlockStateSnapshot blockStateSnapshot = new BlockStateSnapshot(blockHeight, blockHash); - return blockStateSnapshot; - -// -// -// CompletableAsyncFuture asyncStateSnapshot = new CompletableAsyncFuture<>(); -// txExecutor.execute(() -> { -// batchResultHandle = getTxBatchProcess().prepare(); -// currBlock = batchResultHandle.getBlock(); -// long blockHeight = currBlock.getHeight(); -// HashDigest blockHash = currBlock.getHash(); -// asyncBlExecute(new HashMap<>(txResponseMap), blockHeight, blockHash); -// BlockStateSnapshot blockStateSnapshot = new BlockStateSnapshot(blockHeight, blockHash); -// asyncStateSnapshot.complete(blockStateSnapshot); -// }); -// return asyncStateSnapshot.get(); - } - - public void commit() { - realmLock.lock(); - try { - if (batchResultHandle == null) { - throw new IllegalArgumentException("BatchResultHandle is null, complete() is not execute !"); - } - batchResultHandle.commit(); - currBatchId = null; - txResponseMap = null; - txBatchProcess = null; - batchResultHandle =null; - } finally { - realmLock.unlock(); - } - } - - public void rollback(int reasonCode) { - realmLock.lock(); - try { - if (batchResultHandle != null) { - batchResultHandle.cancel(TransactionState.valueOf((byte)reasonCode)); - } - currBatchId = null; - txResponseMap = null; - txBatchProcess = null; - batchResultHandle = null; - ((TransactionEngineImpl) (txEngine)).freeBatch(ledgerHash); - ((TransactionEngineImpl) (txEngine)).resetNewBlockEditor(ledgerHash); - } finally { - realmLock.unlock(); - } - } - - private void asyncBlExecute(Map> asyncMap, - long blockHeight, HashDigest blockHash) { - asyncBlExecutor.execute(() -> { - // 填充应答结果 - for (Map.Entry> entry : asyncMap.entrySet()) { - CompletableAsyncFuture asyncResult = entry.getValue(); - TxResponse txResponse = new TxResponse(entry.getKey()); - txResponse.setBlockHeight(blockHeight); - txResponse.setBlockHash(blockHash); - asyncResult.complete(BinaryProtocol.encode(txResponse, TransactionResponse.class)); - } - }); - } - - private final class TxResponse implements TransactionResponse { - - private long blockHeight; - - private HashDigest blockHash; - - private TransactionResponse txResp; - - public TxResponse(TransactionResponse txResp) { - this.txResp = txResp; - } - - public void setBlockHeight(long blockHeight) { - this.blockHeight = blockHeight; - } - - public void setBlockHash(HashDigest blockHash) { - this.blockHash = blockHash; - } - - @Override - public HashDigest getContentHash() { - return this.txResp.getContentHash(); - } - - @Override - public TransactionState getExecutionState() { - return this.txResp.getExecutionState(); - } - - @Override - public HashDigest getBlockHash() { - return this.blockHash; - } - - @Override - public long getBlockHeight() { - return this.blockHeight; - } - - @Override - public boolean isSuccess() { - return this.txResp.isSuccess(); - } - - @Override - public OperationResult[] getOperationResults() { - return txResp.getOperationResults(); - } - } - - private final class BlockStateSnapshot implements StateSnapshot { - - private long id; - - private byte[] snapshotBytes; - - public BlockStateSnapshot(long id, byte[] snapshotBytes) { - this.id = id; - this.snapshotBytes = snapshotBytes; - } - - public BlockStateSnapshot(long id, HashDigest hash) { - this(id, hash.toBytes()); - } - - @Override - public long getId() { - return id; - } - - @Override - public byte[] getSnapshot() { - return snapshotBytes; - } - } - } -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusMessageDispatcher2.java b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusMessageDispatcher2.java deleted file mode 100644 index 7cf37806..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusMessageDispatcher2.java +++ /dev/null @@ -1,474 +0,0 @@ -//package com.jd.blockchain.peer.consensus; -// -//import com.jd.blockchain.binaryproto.BinaryEncodingUtils; -//import com.jd.blockchain.consensus.event.EventEntity; -//import com.jd.blockchain.consensus.event.EventProducer; -//import com.jd.blockchain.consensus.service.MessageHandle; -//import com.jd.blockchain.consensus.service.StateSnapshot; -//import com.jd.blockchain.crypto.hash.HashDigest; -//import com.jd.blockchain.ledger.LedgerBlock; -//import com.jd.blockchain.ledger.TransactionRequest; -//import com.jd.blockchain.ledger.TransactionResponse; -//import com.jd.blockchain.ledger.TransactionState; -//import com.jd.blockchain.ledger.service.TransactionBatchProcess; -//import com.jd.blockchain.ledger.service.TransactionBatchResultHandle; -//import com.jd.blockchain.ledger.service.TransactionEngine; -//import com.lmax.disruptor.BlockingWaitStrategy; -//import com.lmax.disruptor.EventFactory; -//import com.lmax.disruptor.EventHandler; -//import com.lmax.disruptor.RingBuffer; -//import com.lmax.disruptor.dsl.Disruptor; -//import com.lmax.disruptor.dsl.ProducerType; -//import my.utils.codec.Base58Utils; -//import my.utils.concurrent.AsyncFuture; -//import my.utils.concurrent.CompletableAsyncFuture; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Component; -// -//import java.util.Iterator; -//import java.util.LinkedList; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ConcurrentHashMap; -//import java.util.concurrent.atomic.AtomicLong; -//import java.util.concurrent.locks.ReentrantLock; -// -///** -// * @author huanghaiquan -// * -// */ -//@Component -//public class ConsensusMessageDispatcher2 implements MessageHandle { -// -// @Autowired -// private TransactionEngine txEngine; -// -// private Map realmProcessorMap = new ConcurrentHashMap<>(); -// -// private ReentrantLock beginLock = new ReentrantLock(); -// -// @Override -// public String beginBatch(String realmName) { -// RealmProcessor realmProcessor = realmProcessorMap.get(realmName); -// if (realmProcessor == null) { -// try { -// beginLock.lock(); -// realmProcessor = realmProcessorMap.get(realmName); -// if (realmProcessor == null) { -// realmProcessor = initRealmProcessor(realmName); -// realmProcessorMap.put(realmName, realmProcessor); -// } -// } finally { -// beginLock.unlock(); -// } -// } -// return realmProcessor.newBatchId(); -// } -// -// @Override -// public AsyncFuture processOrdered(int messageId, byte[] message, String realmName, String batchId) { -// // TODO 要求messageId在同一个批次不重复,但目前暂不验证 -// RealmProcessor realmProcessor = realmProcessorMap.get(realmName); -// if (realmProcessor == null) { -// throw new IllegalArgumentException("RealmName is not init!"); -// } -// if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { -// throw new IllegalArgumentException("BatchId is not begin!"); -// } -// TransactionRequest txRequest = BinaryEncodingUtils.decode(message); -// return realmProcessor.schedule(txRequest); -// } -// -// @Override -// public StateSnapshot completeBatch(String realmName, String batchId) { -// RealmProcessor realmProcessor = realmProcessorMap.get(realmName); -// if (realmProcessor == null) { -// throw new IllegalArgumentException("RealmName is not init!"); -// } -// if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { -// throw new IllegalArgumentException("BatchId is not begin!"); -// } -// return realmProcessor.complete(); -// } -// -// @Override -// public void commitBatch(String realmName, String batchId) { -// RealmProcessor realmProcessor = realmProcessorMap.get(realmName); -// if (realmProcessor == null) { -// throw new IllegalArgumentException("RealmName is not init!"); -// } -// if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { -// throw new IllegalArgumentException("BatchId is not begin!"); -// } -// realmProcessor.commit(); -// } -// -// @Override -// public void rollbackBatch(String realmName, String batchId, int reasonCode) { -// RealmProcessor realmProcessor = realmProcessorMap.get(realmName); -// if (realmProcessor == null) { -// throw new IllegalArgumentException("RealmName is not init!"); -// } -// if (!realmProcessor.getCurrBatchId().equalsIgnoreCase(batchId)) { -// throw new IllegalArgumentException("BatchId is not begin!"); -// } -// realmProcessor.rollback(reasonCode); -// } -// -// @Override -// public AsyncFuture processUnordered(byte[] message) { -// // TODO Auto-generated method stub -// throw new IllegalArgumentException("Not implemented!"); -// } -// -// private RealmProcessor initRealmProcessor(String realmName) { -// RealmProcessor realmProcessor = new RealmProcessor(); -// byte[] hashBytes = Base58Utils.decode(realmName); -// HashDigest ledgerHash = new HashDigest(hashBytes); -// realmProcessor.realmName = realmName; -// realmProcessor.ledgerHash = ledgerHash; -// return realmProcessor; -// } -// -// private final class RealmProcessor { -// -// private String currBatchId; -// -//// private final ExecutorService txExecutor = Executors.newFixedThreadPool(4); -// -//// private Map> txResponseMap; -// -// private LinkedList txResponseExtensions; -// -// private TransactionBatchResultHandle batchResultHandle; -// -// private final AtomicLong batchIdIndex = new AtomicLong(); -// -//// private LedgerBlock currBlock; -// -// private TransactionBatchProcess txBatchProcess; -// -// private EventProducer eventProducer; -// -// HashDigest ledgerHash; -// -// String realmName; -// -// public RealmProcessor() { -// BlockEventHandler eventHandler = new BlockEventHandler(); -// Disruptor> disruptor = -// new Disruptor<>(new BlockEventFactory(), -// BlockEventFactory.BUFFER_SIZE, r -> { -// return new Thread(r); -// }, ProducerType.SINGLE, new BlockingWaitStrategy()); -// -// disruptor.handleEventsWith(eventHandler); -// disruptor.start(); -// RingBuffer> ringBuffer = disruptor.getRingBuffer(); -// this.eventProducer = new BlockEventProducer(ringBuffer); -// } -// -// public String getRealmName() { -// return realmName; -// } -// -// public TransactionBatchProcess getTxBatchProcess() { -// return txBatchProcess; -// } -// -// public AtomicLong getBatchIdIndex() { -// return batchIdIndex; -// } -// -// public HashDigest getLedgerHash() { -// return ledgerHash; -// } -// -// public String getCurrBatchId() { -// return currBatchId; -// } -// -// public synchronized String newBatchId() { -// if (currBatchId == null) { -// currBatchId = getRealmName() + "-" + getBatchIdIndex().getAndIncrement(); -// } -// if (txBatchProcess == null) { -// txBatchProcess = txEngine.createNextBatch(ledgerHash); -// } -//// if (txResponseMap == null) { -//// txResponseMap = new ConcurrentHashMap<>(); -//// } -// if (txResponseExtensions == null) { -// txResponseExtensions = new LinkedList<>(); -// } -// return currBatchId; -// } -// -// public AsyncFuture schedule(TransactionRequest txRequest) { -// CompletableAsyncFuture asyncTxResult = new CompletableAsyncFuture<>(); -// TransactionResponse resp = getTxBatchProcess().schedule(txRequest); -// TxResponseExtension extension = new TxResponseExtension(resp, asyncTxResult); -// txResponseExtensions.addFirst(extension); -//// txResponseMap.put(resp, asyncTxResult); -//// txExecutor.execute(() -> { -//// if (txBatchProcess == null) { -//// txBatchProcess = txEngine.createNextBatch(ledgerHash); -//// } -//// TransactionResponse resp = getTxBatchProcess().schedule(txRequest); -//// if (txResponseMap == null) { -//// txResponseMap = new ConcurrentHashMap<>(); -//// } -//// txResponseMap.put(resp, asyncTxResult); -//// }); -// return asyncTxResult; -// } -// -// public StateSnapshot complete() { -//// CompletableAsyncFuture asyncStateSnapshot = new CompletableAsyncFuture<>(); -// batchResultHandle = getTxBatchProcess().prepare(); -// LedgerBlock currBlock = batchResultHandle.getBlock(); -//// List extensions = new ArrayList<>(); -//// Collections.copy(extensions, new ArrayList<>(txResponseExtensions)); -// BlockResponse blockResponse = new BlockResponse(currBlock, new LinkedList<>(txResponseExtensions)); -// this.eventProducer.publish(blockResponse); -//// handleResponse(currBlock, new LinkedList<>(txResponseExtensions)); -// txResponseExtensions = null; -// -//// -//// -//// // 填充应答结果 -//// for (Map.Entry> entry : txResponseMap.entrySet()) { -//// CompletableAsyncFuture asyncResult = entry.getValue(); -//// TxResponse txResponse = new TxResponse(entry.getKey()); -//// txResponse.setBlockHeight(currBlock.getHeight()); -//// txResponse.setBlockHash(currBlock.getHash()); -//// asyncResult.complete(BinaryEncodingUtils.encode(txResponse, TransactionResponse.class)); -//// } -// BlockStateSnapshot blockStateSnapshot = new BlockStateSnapshot(currBlock.getHeight(), currBlock.getHash()); -//// asyncStateSnapshot.complete(blockStateSnapshot); -// -//// txExecutor.execute(() -> { -//// batchResultHandle = getTxBatchProcess().prepare(); -//// currBlock = batchResultHandle.getBlock(); -//// // 填充应答结果 -//// for (Map.Entry> entry : txResponseMap.entrySet()) { -//// CompletableAsyncFuture asyncResult = entry.getValue(); -//// TxResponse txResponse = new TxResponse(entry.getKey()); -//// txResponse.setBlockHeight(currBlock.getHeight()); -//// txResponse.setBlockHash(currBlock.getHash()); -//// asyncResult.complete(BinaryEncodingUtils.encode(txResponse, TransactionResponse.class)); -//// } -//// BlockStateSnapshot blockStateSnapshot = new BlockStateSnapshot(currBlock.getHeight(), currBlock.getHash()); -//// asyncStateSnapshot.complete(blockStateSnapshot); -//// }); -//// return asyncStateSnapshot.get(); -// return blockStateSnapshot; -// } -// -// public void commit() { -// if (batchResultHandle == null) { -// throw new IllegalArgumentException("BatchResultHandle is null, complete() is not execute !"); -// } -// batchResultHandle.commit(); -//// txResponseMap = null; -// currBatchId = null; -// txBatchProcess = null; -// } -// -// public void rollback(int reasonCode) { -// batchResultHandle.cancel(TransactionState.valueOf((byte)reasonCode)); -// } -// -//// private void handleResponse(final LedgerBlock block, final List txResponseExtensions) { -//// txExecutor.execute(() -> { -//// Iterator iterator = txResponseExtensions.iterator(); -//// while(iterator.hasNext()){ -//// TxResponseExtension data = iterator.next(); -//// CompletableAsyncFuture asyncResult = data.getAsyncTxResult(); -//// TxResponse txResponse = new TxResponse(data.getResponse()); -//// txResponse.setBlockHeight(block.getHeight()); -//// txResponse.setBlockHash(block.getHash()); -//// asyncResult.complete(BinaryEncodingUtils.encode(txResponse, TransactionResponse.class)); -//// } -//// }); -//// } -// -// private final class TxResponse implements TransactionResponse { -// -// private long blockHeight; -// -// private HashDigest blockHash; -// -// private TransactionResponse txResp; -// -// public TxResponse(TransactionResponse txResp) { -// this.txResp = txResp; -// } -// -// public void setBlockHeight(long blockHeight) { -// this.blockHeight = blockHeight; -// } -// -// public void setBlockHash(HashDigest blockHash) { -// this.blockHash = blockHash; -// } -// -// @Override -// public HashDigest getContentHash() { -// return this.txResp.getContentHash(); -// } -// -// @Override -// public TransactionState getExecutionState() { -// return this.txResp.getExecutionState(); -// } -// -// @Override -// public HashDigest getBlockHash() { -// return this.blockHash; -// } -// -// @Override -// public long getBlockHeight() { -// return this.blockHeight; -// } -// -// @Override -// public boolean isSuccess() { -// return this.txResp.isSuccess(); -// } -// } -// -// private final class TxResponseExtension { -// -// private TransactionResponse response; -// -// private CompletableAsyncFuture asyncTxResult; -// -// public TxResponseExtension(TransactionResponse response, CompletableAsyncFuture asyncTxResult) { -// this.response = response; -// this.asyncTxResult = asyncTxResult; -// } -// -// public TransactionResponse getResponse() { -// return response; -// } -// -// public void setResponse(TransactionResponse response) { -// this.response = response; -// } -// -// public CompletableAsyncFuture getAsyncTxResult() { -// return asyncTxResult; -// } -// -// public void setAsyncTxResult(CompletableAsyncFuture asyncTxResult) { -// this.asyncTxResult = asyncTxResult; -// } -// } -// -// private final class BlockResponse { -// -// private LedgerBlock block; -// -// private LinkedList txResponseExtensions; -// -// public BlockResponse(LedgerBlock block, LinkedList txResponseExtensions) { -// this.block = block; -// this.txResponseExtensions = txResponseExtensions; -// } -// -// public LedgerBlock getBlock() { -// return block; -// } -// -// public void setBlock(LedgerBlock block) { -// this.block = block; -// } -// -// public LinkedList getTxResponseExtensions() { -// return txResponseExtensions; -// } -// -// public void setTxResponseExtensions(LinkedList txResponseExtensions) { -// this.txResponseExtensions = txResponseExtensions; -// } -// } -// -// private final class BlockStateSnapshot implements StateSnapshot { -// -// private long id; -// -// private byte[] snapshotBytes; -// -// public BlockStateSnapshot(long id, byte[] snapshotBytes) { -// this.id = id; -// this.snapshotBytes = snapshotBytes; -// } -// -// public BlockStateSnapshot(long id, HashDigest hash) { -// this(id, hash.toBytes()); -// } -// -// @Override -// public long getId() { -// return id; -// } -// -// @Override -// public byte[] getSnapshot() { -// return snapshotBytes; -// } -// } -// -// private final class BlockEventHandler implements EventHandler> { -// -// @Override -// public void onEvent(EventEntity event, long sequence, boolean endOfBatch) throws Exception { -// BlockResponse blockResponse = event.getEntity(); -// final LedgerBlock block = blockResponse.getBlock(); -// -// final List txResponseExtensions = blockResponse.getTxResponseExtensions(); -// Iterator iterator = txResponseExtensions.iterator(); -// while(iterator.hasNext()){ -// TxResponseExtension data = iterator.next(); -// CompletableAsyncFuture asyncResult = data.getAsyncTxResult(); -// TxResponse txResponse = new TxResponse(data.getResponse()); -// txResponse.setBlockHeight(block.getHeight()); -// txResponse.setBlockHash(block.getHash()); -// asyncResult.complete(BinaryEncodingUtils.encode(txResponse, TransactionResponse.class)); -// } -// } -// } -// -// private class BlockEventFactory implements EventFactory> { -// -// public static final int BUFFER_SIZE = 64 * 1024; -// -// @Override -// public EventEntity newInstance() { -// return new EventEntity<>(); -// } -// } -// -// private class BlockEventProducer implements EventProducer { -// -// private final RingBuffer> ringBuffer; -// -// public BlockEventProducer(RingBuffer> ringBuffer) { -// this.ringBuffer = ringBuffer; -// } -// -// @Override -// public void publish(BlockResponse entity) { -// long sequence = ringBuffer.next(); -// try { -// EventEntity event = ringBuffer.get(sequence); -// event.setEntity(entity); -// } finally { -// this.ringBuffer.publish(sequence); -// } -// } -// } -// } -//} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusRealmImpl.java b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusRealmImpl.java deleted file mode 100644 index d5d5fca9..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusRealmImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.jd.blockchain.peer.consensus; - -import java.util.Arrays; - -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.peer.ConsensusRealm; -import com.jd.blockchain.utils.Bytes; - -public class ConsensusRealmImpl implements ConsensusRealm { - - private ParticipantNode[] nodes; - - private Bytes setting; - - private int hashCode; - - public ConsensusRealmImpl(ParticipantNode[] nodeList) { - this.nodes = nodeList; - Bytes[] addrs = new Bytes[nodes.length]; - int i = 0; - for (ParticipantNode n : nodes) { - addrs[i++] = n.getAddress(); - } - this.hashCode = Arrays.hashCode(addrs); - } - - /* - * (non-Javadoc) - * - * @see - * com.jd.blockchain.peer.consensus.ConsensusRealm#getConsensusParticipants() - */ - @Override - public ParticipantNode[] getNodes() { - return Arrays.copyOf(nodes, nodes.length); - // return participantNodes.toArray(new - // ConsensusParticipant[participantNodes.size()]); - } - - // public void addNode(ConsensusNode participantNode) { - // participantNodes.add(participantNode); - // } - - @Override - public Bytes getSetting() { - return setting; - } - - public void setSetting(Bytes setting) { - this.setting = setting; - } - - /* - * (non-Javadoc) - * - * @see - * com.jd.blockchain.peer.consensus.ConsensusRealm#hasCommon(com.jd.blockchain. - * peer.consensus.ConsensusRealm) - */ - @Override - public boolean hasIntersection(ConsensusRealm otherRealm) { - // in case: different ledger ,same consensus realm - if (this.equals(otherRealm)) { - return true; - } - // in case: consensus realm has intersection - ParticipantNode[] otherNodes = otherRealm.getNodes(); - for (ParticipantNode node : nodes) { - for (ParticipantNode other : otherNodes) { - if (node.getAddress().equals(other.getAddress())) { - return true; - } - } - } - return false; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (obj instanceof ConsensusRealmImpl) { - ConsensusRealmImpl realm = (ConsensusRealmImpl) obj; - return this.hashCode() == realm.hashCode(); - } - return false; - } -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/LedgerStateManager.java b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/LedgerStateManager.java deleted file mode 100644 index b88fc49d..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/LedgerStateManager.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jd.blockchain.peer.consensus; - -import java.io.InputStream; -import java.util.Iterator; - -import com.jd.blockchain.consensus.service.StateMachineReplicate; -import com.jd.blockchain.consensus.service.StateSnapshot; -import org.springframework.stereotype.Component; - -@Component -public class LedgerStateManager implements StateMachineReplicate{ - - @Override - public long getLatestStateID(String realmName) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public StateSnapshot getSnapshot(String realmName, long stateId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Iterator getSnapshots(String realmName, long fromStateId, long toStateId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public InputStream readState(String realmName, long stateId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setupState(String realmName, StateSnapshot snapshot, InputStream state) { - // TODO Auto-generated method stub - - } - -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/ledger/LedgerConfigurer.java b/source/peer/src/main/java/com/jd/blockchain/peer/ledger/LedgerConfigurer.java deleted file mode 100644 index 5c5c8b7e..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/ledger/LedgerConfigurer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.peer.ledger; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.TransactionEngineImpl; -import com.jd.blockchain.service.TransactionEngine; - -@Configuration -public class LedgerConfigurer { - - @ConditionalOnMissingBean - @Bean - public LedgerManager ledgerManager() { - return new LedgerManager(); - } - - @Bean - public TransactionEngine transactionEngine() { - return new TransactionEngineImpl(); - } - - @Bean - public OperationHandleRegisteration operationHandleRegisteration() { - return new DefaultOperationHandleRegisteration(); - } -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/statetransfer/DataSequenceReaderImpl.java b/source/peer/src/main/java/com/jd/blockchain/peer/statetransfer/DataSequenceReaderImpl.java deleted file mode 100644 index 71161411..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/statetransfer/DataSequenceReaderImpl.java +++ /dev/null @@ -1,132 +0,0 @@ -//package com.jd.blockchain.peer.statetransfer; -// -//import com.jd.blockchain.binaryproto.BinaryEncodingUtils; -//import com.jd.blockchain.crypto.hash.HashDigest; -//import com.jd.blockchain.ledger.LedgerBlock; -//import com.jd.blockchain.ledger.LedgerTransaction; -//import com.jd.blockchain.ledger.core.LedgerManage; -//import com.jd.blockchain.ledger.core.LedgerRepository; -//import com.jd.blockchain.ledger.core.TransactionSet; -//import com.jd.blockchain.statetransfer.DataSequenceElement; -//import com.jd.blockchain.statetransfer.DataSequenceInfo; -//import com.jd.blockchain.statetransfer.callback.DataSequenceReader; -//import com.jd.blockchain.storage.service.DbConnection; -//import com.jd.blockchain.storage.service.DbConnectionFactory; -//import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -//import com.jd.blockchain.utils.codec.Base58Utils; -//import com.jd.blockchain.utils.codec.HexUtils; -//import org.springframework.beans.factory.annotation.Autowired; -// -///** -// *数据序列差异的提供者需要使用的回调接口实现类 -// * @author zhangshuang -// * @create 2019/4/11 -// * @since 1.0.0 -// */ -//public class DataSequenceReaderImpl implements DataSequenceReader { -// -// private LedgerManage ledgerManager; -// -// private DbConnectionFactory connFactory; -// -// private LedgerBindingConfig config; -// -// public DataSequenceReaderImpl(LedgerBindingConfig config, LedgerManage ledgerManager, DbConnectionFactory connFactory) { -// this.config = config; -// this.ledgerManager = ledgerManager; -// this.connFactory = connFactory; -// } -// -// -// /** -// * @param id 账本哈希的Base58编码 -// * @return DataSequenceInfo 数据序列信息 -// */ -// @Override -// public DataSequenceInfo getDSInfo(String id) { -// -// byte[] hashBytes = Base58Utils.decode(id); -// -// HashDigest ledgerHash = new HashDigest(hashBytes); -// -// LedgerBindingConfig.BindingConfig bindingConfig = config.getLedger(ledgerHash); -// DbConnection dbConnNew = connFactory.connect(bindingConfig.getDbConnection().getUri(), -// bindingConfig.getDbConnection().getPassword()); -// LedgerRepository ledgerRepository = ledgerManager.register(ledgerHash, dbConnNew.getStorageService()); -// -// return new DataSequenceInfo(id, ledgerRepository.getLatestBlockHeight()); -// } -// -// /** -// * -// * @param id 账本哈希的Base58编码 -// * @param from 数据序列复制的起始高度 -// * @param to 数据序列复制的结束高度 -// * @return DataSequenceElement【】数据序列差异数据元素的数组 -// */ -// @Override -// public DataSequenceElement[] getDSDiffContent(String id, long from, long to) { -// -// DataSequenceElement[] dataSequenceElements = new DataSequenceElement[(int)(to - from + 1)]; -// for (long i = from; i < to + 1; i++) { -// dataSequenceElements[(int)(i - from)] = getDSDiffContent(id, i); -// } -// -// return dataSequenceElements; -// } -// -// /** -// * 账本交易序列化 -// * @param transaction 账本交易 -// * @return byte[] 对账本交易进行序列化的结果 -// */ -// private byte[] serialize(LedgerTransaction transaction) { -// return BinaryEncodingUtils.encode(transaction, LedgerTransaction.class); -// } -// -// /** -// * 获得账本某一高度区块上的所有交易 -// * @param id 账本哈希的Base58编码 -// * @param height 账本的某个区块高度 -// * @return DataSequenceElement 数据序列差异数据元素 -// */ -// @Override -// public DataSequenceElement getDSDiffContent(String id, long height) { -// -// int lastHeightTxTotalNums = 0; -// -// byte[][] transacionDatas = null; -// -// byte[] hashBytes = Base58Utils.decode(id); -// -// HashDigest ledgerHash = new HashDigest(hashBytes); -// -// LedgerBindingConfig.BindingConfig bindingConfig = config.getLedger(ledgerHash); -// DbConnection dbConnNew = connFactory.connect(bindingConfig.getDbConnection().getUri(), -// bindingConfig.getDbConnection().getPassword()); -// LedgerRepository ledgerRepository = ledgerManager.register(ledgerHash, dbConnNew.getStorageService()); -// -// LedgerBlock ledgerBlock = ledgerRepository.getBlock(height); -// TransactionSet transactionSet = ledgerRepository.getTransactionSet(ledgerBlock); -// -// if (height > 0) { -// lastHeightTxTotalNums = (int) ledgerRepository.getTransactionSet(ledgerRepository.getBlock(height - 1)).getTotalCount(); -// } -// -// int currentHeightTxTotalNums = (int)ledgerRepository.getTransactionSet(ledgerRepository.getBlock(height)).getTotalCount(); -// -// // get all transactions from current height block -// int currentHeightTxNums = currentHeightTxTotalNums - lastHeightTxTotalNums; -// -// LedgerTransaction[] transactions = transactionSet.getTxs(lastHeightTxTotalNums , currentHeightTxNums); -// -// for (int i = 0; i < transactions.length; i++) { -// byte[] transactionData = serialize(transactions[i]); -// transacionDatas[i] = transactionData; -// } -// -// return new DataSequenceElement(id, height, transacionDatas); -// } -// -// -//} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/statetransfer/DataSequenceWriterImpl.java b/source/peer/src/main/java/com/jd/blockchain/peer/statetransfer/DataSequenceWriterImpl.java deleted file mode 100644 index 774e69b5..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/statetransfer/DataSequenceWriterImpl.java +++ /dev/null @@ -1,170 +0,0 @@ -//package com.jd.blockchain.peer.statetransfer; -// -//import com.jd.blockchain.consensus.service.MessageHandle; -//import com.jd.blockchain.ledger.TransactionState; -//import com.jd.blockchain.statetransfer.DataSequenceElement; -//import com.jd.blockchain.statetransfer.DataSequenceInfo; -//import com.jd.blockchain.statetransfer.callback.DataSequenceWriter; -//import com.jd.blockchain.statetransfer.comparator.DataSequenceComparator; -// -//import java.util.ArrayList; -//import java.util.Collections; -// -///** -// *数据序列差异的请求者需要使用的回调接口实现类 -// * @author zhangshuang -// * @create 2019/4/11 -// * @since 1.0.0 -// */ -//public class DataSequenceWriterImpl implements DataSequenceWriter { -// -// private long currHeight; -// private ArrayList deceidedElements = new ArrayList(); -// -// private MessageHandle batchMessageHandle; -// -// -// public DataSequenceWriterImpl(MessageHandle batchMessageHandle) { -// this.batchMessageHandle = batchMessageHandle; -// } -// -// /** -// * 检查数据序列差异元素中的高度是否合理; -// * @param currHeight 当前结点的账本高度 -// * @param dsUpdateElements 需要更新到本地结点的数据序列元素List -// * @return -// */ -// private int checkElementsHeight(long currHeight, ArrayList dsUpdateElements) { -// boolean lossMiddleElements = false; -// -// // lose first element -// if (currHeight + 1 < dsUpdateElements.get(0).getHeight()){ -// System.out.println("Diff response loss first element error!"); -// return DataSequenceErrorType.DATA_SEQUENCE_LOSS_FIRST_ELEMENT.CODE; -// } -// else { -// for (int i = 0; i < dsUpdateElements.size(); i++) { -// if (dsUpdateElements.get(i).getHeight() == currHeight + 1 + i) { -// deceidedElements.add(dsUpdateElements.get(i)); -// } -// // lose middle elements -// else { -// lossMiddleElements = true; -// break; -// } -// } -// -// if (lossMiddleElements) { -// System.out.println("Diff response loss middle elements error!"); -// return DataSequenceErrorType.DATA_SEQUENCE_LOSS_MIDDLE_ELEMENT.CODE; -// } -// -// System.out.println("Diff response elements height normal!"); -// return DataSequenceErrorType.DATA_SEQUENCE_ELEMENT_HEIGHT_NORMAL.CODE; -// } -// -// } -// -// /** -// * 对本地结点执行账本更新 -// * @param realmName 账本哈希的Base58编码 -// * @return void -// */ -// private void exeUpdate(String realmName) { -// -// for (int i = 0; i < deceidedElements.size(); i++) { -// byte[][] element = deceidedElements.get(i).getData(); -// -// String batchId = batchMessageHandle.beginBatch(realmName); -// try { -// int msgId = 0; -// for (byte[] txContent : element) { -// batchMessageHandle.processOrdered(msgId++, txContent, realmName, batchId); -// } -// // 结块 -// batchMessageHandle.completeBatch(realmName, batchId); -// batchMessageHandle.commitBatch(realmName, batchId); -// } catch (Exception e) { -// // todo 需要处理应答码 404 -// batchMessageHandle.rollbackBatch(realmName, batchId, TransactionState.DATA_SEQUENCE_UPDATE_ERROR.CODE); -// } -// } -// -// } -// -// /** -// * @param dsInfo 当前结点的数据序列信息 -// * @param diffContents 数据序列差异的数据元素数组 -// * @return int 更新结果码 -// */ -// @Override -// public int updateDSInfo(DataSequenceInfo dsInfo, DataSequenceElement[] diffContents) { -// int result = 0; -// -// try { -// ArrayList dsUpdateElements = new ArrayList(); -// //remove unexpected elements -// for (int i = 0 ; i < diffContents.length; i++) { -// if (diffContents[i].getId().equals(dsInfo.getId())) { -// dsUpdateElements.add(diffContents[i]); -// } -// } -// -// // sort elements by height -// Collections.sort(dsUpdateElements, new DataSequenceComparator()); -// -// currHeight = dsInfo.getHeight(); -// -// // check element's height -// result = checkElementsHeight(currHeight, dsUpdateElements); -// -// // cann't exe update -// if (result == DataSequenceErrorType.DATA_SEQUENCE_LOSS_FIRST_ELEMENT.CODE) { -// return result; -// } -// // exe elements update -// else { -// exeUpdate(dsInfo.getId()); -// return result; -// } -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// -// return result; -// } -// -// @Override -// public int updateDSInfo(DataSequenceInfo dsInfo, DataSequenceElement diffContents) { -// return 0; -// } -// -// -// /** -// * 数据序列更新错误码 -// * @param -// * @return -// */ -// public enum DataSequenceErrorType { -// DATA_SEQUENCE_LOSS_FIRST_ELEMENT((byte) 0x1), -// DATA_SEQUENCE_LOSS_MIDDLE_ELEMENT((byte) 0x2), -// DATA_SEQUENCE_ELEMENT_HEIGHT_NORMAL((byte) 0x3), -// ; -// public final int CODE; -// -// private DataSequenceErrorType(byte code) { -// this.CODE = code; -// } -// -// public static DataSequenceErrorType valueOf(byte code) { -// for (DataSequenceErrorType errorType : DataSequenceErrorType.values()) { -// if (errorType.CODE == code) { -// return errorType; -// } -// } -// throw new IllegalArgumentException("Unsupported code[" + code + "] of errorType!"); -// } -// } -// -//} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/ManagementController.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/ManagementController.java deleted file mode 100644 index b21ba8da..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/web/ManagementController.java +++ /dev/null @@ -1,281 +0,0 @@ -package com.jd.blockchain.peer.web; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.ledger.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.ClientIdentifications; -import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.consensus.action.ActionResponse; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; -import com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings; -import com.jd.blockchain.consensus.mq.server.MsgQueueMessageDispatcher; -import com.jd.blockchain.consensus.service.MessageHandle; -import com.jd.blockchain.consensus.service.NodeServer; -import com.jd.blockchain.consensus.service.ServerSettings; -import com.jd.blockchain.consensus.service.StateMachineReplicate; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerAdminInfo; -import com.jd.blockchain.ledger.core.LedgerAdminDataQuery; -import com.jd.blockchain.ledger.core.LedgerManage; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.peer.ConsensusRealm; -import com.jd.blockchain.peer.LedgerBindingConfigAware; -import com.jd.blockchain.peer.PeerManage; -import com.jd.blockchain.setting.GatewayIncomingSetting; -import com.jd.blockchain.setting.LedgerIncomingSetting; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.ByteArray; -import com.jd.blockchain.web.converters.BinaryMessageConverter; - -/** - * 网关管理服务; - * - * 提供 - * - * @author huanghaiquan - * - */ -@RestController -@RequestMapping(path = "/management") -public class ManagementController implements LedgerBindingConfigAware, PeerManage { - - private static Logger LOGGER = LoggerFactory.getLogger(ManagementController.class); - - public static final String GATEWAY_PUB_EXT_NAME = ".gw.pub"; - - public static final int MIN_GATEWAY_ID = 10000; - - @Autowired - private LedgerManage ledgerManager; - - @Autowired - private DbConnectionFactory connFactory; - - private Map ledgerTxConverters = new ConcurrentHashMap<>(); - - private Map ledgerPeers = new ConcurrentHashMap<>(); - private Map ledgerCryptoSettings = new ConcurrentHashMap<>(); - - - private LedgerBindingConfig config; - - @Autowired - private MessageHandle consensusMessageHandler; - - @Autowired - private StateMachineReplicate consensusStateManager; - - static { - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(LedgerBlock.class); - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class); - - DataContractRegistry.register(Operation.class); - DataContractRegistry.register(ContractCodeDeployOperation.class); - DataContractRegistry.register(ContractEventSendOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - - DataContractRegistry.register(ActionResponse.class); - - DataContractRegistry.register(BftsmartConsensusSettings.class); - DataContractRegistry.register(BftsmartNodeSettings.class); - - DataContractRegistry.register(LedgerAdminInfo.class); - DataContractRegistry.register(LedgerSettings.class); - - // 注册角色/权限相关接口 - DataContractRegistry.register(RolesConfigureOperation.class); - DataContractRegistry.register(RolesConfigureOperation.RolePrivilegeEntry.class); - DataContractRegistry.register(UserAuthorizeOperation.class); - DataContractRegistry.register(UserAuthorizeOperation.UserRolesEntry.class); - DataContractRegistry.register(PrivilegeSet.class); - DataContractRegistry.register(RoleSet.class); - DataContractRegistry.register(SecurityInitSettings.class); - DataContractRegistry.register(RoleInitSettings.class); - DataContractRegistry.register(UserAuthInitSettings.class); - DataContractRegistry.register(LedgerMetadata_V2.class); - } - - /** - * 接入认证; - * - * @param clientIdentifications - * @return - */ - @RequestMapping(path = "/gateway/auth", method = RequestMethod.POST, consumes = BinaryMessageConverter.CONTENT_TYPE_VALUE) - public GatewayIncomingSetting authenticateGateway(@RequestBody ClientIdentifications clientIdentifications) { - // 去掉不严谨的网关注册和认证逻辑;暂时先放开,不做认证,后续应该在链上注册网关信息,并基于链上的网关信息进行认证; - // by: huanghaiquan; at 2018-09-11 18:34; - // TODO: 实现网关的链上注册与认证机制; - // TODO: 暂时先返回全部账本对应的共识网络配置信息;以账本哈希为 key 标识每一个账本对应的共识域、以及共识配置参数; - if (ledgerPeers.size() == 0 || clientIdentifications == null) { - return null; - } - - ClientIdentification[] identificationArray = clientIdentifications.getClientIdentifications(); - if (identificationArray == null || identificationArray.length <= 0) { - return null; - } - - GatewayIncomingSetting setting = new GatewayIncomingSetting(); - List ledgerIncomingList = new ArrayList(); - - for (HashDigest ledgerHash : ledgerPeers.keySet()) { - - NodeServer peer = ledgerPeers.get(ledgerHash); - - String peerProviderName = peer.getProviderName(); - - ConsensusProvider provider = ConsensusProviders.getProvider(peer.getProviderName()); - - ClientIncomingSettings clientIncomingSettings = null; - for (ClientIdentification authId : identificationArray) { - if (authId.getProviderName() == null || - authId.getProviderName().length() <= 0 || - !authId.getProviderName().equalsIgnoreCase(peerProviderName)) { - continue; - } - try { - clientIncomingSettings = peer.getManageService().authClientIncoming(authId); - break; - } catch (Exception e) { - throw new AuthenticationServiceException(e.getMessage(), e); - } - } - if (clientIncomingSettings == null) { - continue; - } - - byte[] clientIncomingBytes = provider.getSettingsFactory().getIncomingSettingsEncoder() - .encode(clientIncomingSettings); - String base64ClientIncomingSettings = ByteArray.toBase64(clientIncomingBytes); - - LedgerIncomingSetting ledgerIncomingSetting = new LedgerIncomingSetting(); - ledgerIncomingSetting.setLedgerHash(ledgerHash); - ledgerIncomingSetting.setCryptoSetting(ledgerCryptoSettings.get(ledgerHash)); - ledgerIncomingSetting.setClientSetting(base64ClientIncomingSettings); - ledgerIncomingSetting.setProviderName(peerProviderName); - - ledgerIncomingList.add(ledgerIncomingSetting); - - } - setting.setLedgers(ledgerIncomingList.toArray(new LedgerIncomingSetting[ledgerIncomingList.size()])); - return setting; - } - - @Override - public void setConfig(LedgerBindingConfig config) { - // TODO 更新配置;暂时不考虑变化过程的平滑切换问题,后续完善该流程; - // 1、检查账本的数据库配置;a、配置发生变化的账本,建立新的账本库(LedgerRepository)替换旧的实例;b、加入新增加的账本库实例;c、移除已经废弃的账本库; - // 2、完成账本库更改后,读取最新的共识配置信息,更新共识域; - // 3、基于当前共识地址检查共识域;a、启动新增加的共识地址,以及更新相应的共识域关系;c、已经废弃的共识域直接停止; - try { - // remove all existing ledger repositories; - HashDigest[] existingLedgerHashs = ledgerManager.getLedgerHashs(); - for (HashDigest lh : existingLedgerHashs) { - ledgerManager.unregister(lh); - } - HashDigest[] ledgerHashs = config.getLedgerHashs(); - for (HashDigest ledgerHash : ledgerHashs) { - setConfig(config,ledgerHash); - } - - this.config = config; - - } catch (Exception e) { - LOGGER.error("Error occurred on configing LedgerBindingConfig! --" + e.getMessage(), e); - throw new IllegalStateException(e); - } - } - - @Override - public NodeServer setConfig(LedgerBindingConfig config, HashDigest ledgerHash) { - LedgerBindingConfig.BindingConfig bindingConfig = config.getLedger(ledgerHash); - DbConnection dbConnNew = connFactory.connect(bindingConfig.getDbConnection().getUri(), - bindingConfig.getDbConnection().getPassword()); - LedgerQuery ledgerRepository = ledgerManager.register(ledgerHash, dbConnNew.getStorageService()); - - // load provider; - LedgerAdminInfo ledgerAdminAccount = ledgerRepository.getAdminInfo(); - String consensusProvider = ledgerAdminAccount.getSettings().getConsensusProvider(); - ConsensusProvider provider = ConsensusProviders.getProvider(consensusProvider); - // find current node; - Bytes csSettingBytes = ledgerAdminAccount.getSettings().getConsensusSetting(); - ConsensusSettings csSettings = provider.getSettingsFactory().getConsensusSettingsEncoder() - .decode(csSettingBytes.toBytes()); - NodeSettings currentNode = null; - for (NodeSettings nodeSettings : csSettings.getNodes()) { - if (nodeSettings.getAddress().equals(bindingConfig.getParticipant().getAddress())) { - currentNode = nodeSettings; - } - } - if (currentNode == null) { - throw new IllegalArgumentException( - "Current node is not found from the consensus settings of ledger[" + ledgerHash.toBase58() - + "]!"); - } - ServerSettings serverSettings = provider.getServerFactory().buildServerSettings(ledgerHash.toBase58(), csSettings, currentNode.getAddress()); - - NodeServer server = provider.getServerFactory().setupServer(serverSettings, consensusMessageHandler, - consensusStateManager); - ledgerPeers.put(ledgerHash, server); - ledgerCryptoSettings.put(ledgerHash, ledgerAdminAccount.getSettings().getCryptoSetting()); - - return server; - } - - @Override - public ConsensusRealm[] getRealms() { - throw new IllegalStateException("Not implemented!"); - } - - @Override - public void runAllRealms() { - for (NodeServer peer : ledgerPeers.values()) { - runRealm(peer); - } - } - - @Override - public void runRealm(NodeServer nodeServer) { - nodeServer.start(); - } - - @Override - public void closeAllRealms() { - for (NodeServer peer : ledgerPeers.values()) { - peer.stop(); - } - } -} diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerGlobalExceptionHandler.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerGlobalExceptionHandler.java deleted file mode 100644 index eaad2b55..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerGlobalExceptionHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jd.blockchain.peer.web; - -import javax.servlet.http.HttpServletRequest; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.alibaba.fastjson.JSONException; -import com.jd.blockchain.utils.BusinessException; -import com.jd.blockchain.utils.web.model.ErrorCode; -import com.jd.blockchain.utils.web.model.WebResponse; -import com.jd.blockchain.utils.web.model.WebResponse.ErrorMessage; - -/** - * 全局异常处理类 - */ -@ControllerAdvice -public class PeerGlobalExceptionHandler { - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - @ExceptionHandler(value = Exception.class) - @ResponseBody - public WebResponse json(HttpServletRequest req, Exception ex) { - String reqURL = req.getRequestURL().insert(0, "[" + req.getMethod() + "] ").toString(); - ErrorMessage message = null; - if (ex instanceof BusinessException) { - logger.error("BusinessException occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "] " - + ex.getMessage(), ex); - BusinessException businessException = (BusinessException) ex; - message = new ErrorMessage(businessException.getErrorCode(), businessException.getMessage()); - } else if (ex instanceof JSONException) { - logger.error("JSONException occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "] " - + ex.getMessage(), ex); - message = new ErrorMessage(ErrorCode.REQUEST_PARAM_FORMAT_ILLEGAL.getValue(), - ErrorCode.REQUEST_PARAM_FORMAT_ILLEGAL.getDescription()); - } else { - logger.error("Unexpected exception occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() - + "]" + ex.getMessage(), ex); - message = new ErrorMessage(ErrorCode.UNEXPECTED.getValue(), ErrorCode.UNEXPECTED.getDescription(ex.getMessage())); - } - WebResponse responseResult = WebResponse.createFailureResult(message); - return responseResult; - } - -} \ No newline at end of file diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerJsonResponseAdvice.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerJsonResponseAdvice.java deleted file mode 100644 index cc663aa1..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerJsonResponseAdvice.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jd.blockchain.peer.web; - -import org.springframework.core.MethodParameter; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.server.ServerHttpRequest; -import org.springframework.http.server.ServerHttpResponse; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; - -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; -import com.jd.blockchain.utils.web.model.JsonWebResponseMessageConverter; -import com.jd.blockchain.utils.web.model.WebResponse; - -@RestControllerAdvice -public class PeerJsonResponseAdvice implements ResponseBodyAdvice { - - @Override - public boolean supports(MethodParameter returnType, Class> converterType) { - if (StringHttpMessageConverter.class == converterType && returnType.getDeclaringClass().getName().startsWith("com.jd")) { - return true; - } - if (JsonWebResponseMessageConverter.class == converterType && returnType.getDeclaringClass().getName().startsWith("com.jd")) { - return true; - } - if (JsonWebResponseMessageConverter.class == converterType && returnType.getDeclaringClass().getName().startsWith("com.jd")) { - return true; - } - if (MappingJackson2HttpMessageConverter.class == converterType - && returnType.getDeclaringClass().getName().startsWith("com.jd")) { - return true; - } - return false; - } - - @Override - public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, - Class> selectedConverterType, ServerHttpRequest request, - ServerHttpResponse response) { - WebResponse result = null; - if (body == null) { - result = WebResponse.createSuccessResult(null); - } - if (body instanceof ResponseEntity) { - return body; - } - // 把返回结果自动转换为 WebResponse; - if (body instanceof WebResponse) { - return body; - } - result = WebResponse.createSuccessResult(body); - if (String.class == returnType.getMethod().getReturnType()) { - return JSONSerializeUtils.serializeToJSON(result); - } - return result; - } - -} \ No newline at end of file diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerTimeTasks.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerTimeTasks.java deleted file mode 100644 index dc5c77ec..00000000 --- a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerTimeTasks.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.peer.web.ScheduledTasks - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/7 上午11:12 - * Description: - */ -package com.jd.blockchain.peer.web; - -import com.jd.blockchain.consensus.service.NodeServer; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.core.LedgerManage; -import com.jd.blockchain.peer.ConsensusManage; -import com.jd.blockchain.peer.LedgerBindingConfigAware; -import com.jd.blockchain.peer.PeerServerBooter; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.core.io.ClassPathResource; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.io.File; -import java.io.InputStream; -import java.util.*; - -/** - * - * @author shaozhuguang - * @create 2019/1/7 - * @since 1.0.0 - */ -@Component -@EnableScheduling -public class PeerTimeTasks implements ApplicationContextAware { - - private static Logger LOGGER = LoggerFactory.getLogger(PeerTimeTasks.class); - - private ApplicationContext applicationContext; - - @Autowired - private LedgerManage ledgerManager; - - private String ledgerBindConfigFile; - - //每1分钟执行一次 - @Scheduled(cron = "0 */5 * * * * ") - public void updateLedger(){ - - LOGGER.debug("Time Task Update Ledger Tasks Start {}", new Date()); - - try { - LedgerBindingConfig ledgerBindingConfig = loadLedgerBindingConfig(); - - HashDigest[] totalLedgerHashs = ledgerBindingConfig.getLedgerHashs(); - - HashDigest[] existingLedgerHashs = ledgerManager.getLedgerHashs(); - - Set newAddHashs = new HashSet<>(); - - for (HashDigest ledgerHash : totalLedgerHashs) { - boolean isExist = false; - for (HashDigest exist : existingLedgerHashs) { - if (ledgerHash.equals(exist)) { - isExist = true; - break; - } - } - if (!isExist) { - newAddHashs.add(ledgerHash); - } - } - if (!newAddHashs.isEmpty()) { - // 建立共识网络; - Map bindingConfigAwares = applicationContext.getBeansOfType(LedgerBindingConfigAware.class); - List nodeServers = new ArrayList<>(); - for (HashDigest ledgerHash : newAddHashs) { - - LOGGER.info("New Ledger [{}] Need To Be Init !!!", ledgerHash.toBase58()); - for (LedgerBindingConfigAware aware : bindingConfigAwares.values()) { - nodeServers.add(aware.setConfig(ledgerBindingConfig, ledgerHash)); - } - } - // 启动指定NodeServer节点 - ConsensusManage consensusManage = applicationContext.getBean(ConsensusManage.class); - for (NodeServer nodeServer : nodeServers) { - consensusManage.runRealm(nodeServer); - } - } else { - LOGGER.debug("All Ledgers is newest!!!"); - } - } catch (Exception e) { - LOGGER.error(e.getMessage()); - } - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - private LedgerBindingConfig loadLedgerBindingConfig() throws Exception { - LedgerBindingConfig ledgerBindingConfig = null; - ledgerBindConfigFile = PeerServerBooter.ledgerBindConfigFile; - LOGGER.debug("Load LedgerBindConfigFile path = {}", - ledgerBindConfigFile == null ? "Default" : ledgerBindConfigFile); - if (ledgerBindConfigFile == null) { - ClassPathResource configResource = new ClassPathResource("ledger-binding.conf"); - try (InputStream in = configResource.getInputStream()) { - ledgerBindingConfig = LedgerBindingConfig.resolve(in); - } catch (Exception e) { - throw e; - } - } else { - File file = new File(ledgerBindConfigFile); - ledgerBindingConfig = LedgerBindingConfig.resolve(file); - } - return ledgerBindingConfig; - } -} \ No newline at end of file diff --git a/source/peer/src/main/resources/banner.txt b/source/peer/src/main/resources/banner.txt deleted file mode 100644 index c39618bd..00000000 --- a/source/peer/src/main/resources/banner.txt +++ /dev/null @@ -1,13 +0,0 @@ - - ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄ -▐░░░░░░░░░░░▌▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░▌ ▐░▌ - ▀▀▀▀▀█░█▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░▌░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ - ▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▐░▌ -▐░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░░▌ - ▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀ - diff --git a/source/peer/src/main/resources/log4j2.xml b/source/peer/src/main/resources/log4j2.xml deleted file mode 100644 index 2ee82e89..00000000 --- a/source/peer/src/main/resources/log4j2.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/AbstractModule.java b/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/AbstractModule.java deleted file mode 100644 index e7045d68..00000000 --- a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/AbstractModule.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.jd.blockchain.runtime; - -import java.io.InputStream; -import java.util.concurrent.Callable; - -import com.jd.blockchain.utils.concurrent.AsyncFuture; -import com.jd.blockchain.utils.concurrent.CompletableAsyncFuture; - -public abstract class AbstractModule implements Module { - - - protected abstract ClassLoader getModuleClassLoader(); - - @Override - public String getMainClass(){return null;} - - @Override - public Class loadClass(String className) { - try { - return getModuleClassLoader().loadClass(className); - } catch (ClassNotFoundException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public InputStream loadResourceAsStream(String name) { - return getModuleClassLoader().getResourceAsStream(name); - } - - @Override - public void execute(Runnable runnable) { - ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); - ClassLoader moduleClassLoader = getModuleClassLoader(); - if (origClassLoader != moduleClassLoader) { - Thread.currentThread().setContextClassLoader(moduleClassLoader); - } - try { - runnable.run(); - } finally { - if (origClassLoader != Thread.currentThread().getContextClassLoader()) { - Thread.currentThread().setContextClassLoader(origClassLoader); - } - } - } - - @Override - public AsyncFuture executeAsync(Runnable runnable) { - ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); - ClassLoader moduleClassLoader = getModuleClassLoader(); - if (origClassLoader != moduleClassLoader) { - Thread.currentThread().setContextClassLoader(moduleClassLoader); - } - return CompletableAsyncFuture.runAsync(() -> { - try { - runnable.run(); - } finally { - if (origClassLoader != Thread.currentThread().getContextClassLoader()) { - Thread.currentThread().setContextClassLoader(origClassLoader); - } - } - }); - - } - - @Override - public AsyncFuture callAsync(Callable callable) { - ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); - ClassLoader moduleClassLoader = getModuleClassLoader(); - if (origClassLoader != moduleClassLoader) { - Thread.currentThread().setContextClassLoader(moduleClassLoader); - } - return CompletableAsyncFuture.callAsync(new Callable() { - @Override - public V call() throws Exception { - try { - return callable.call(); - } finally { - if (origClassLoader != Thread.currentThread().getContextClassLoader()) { - Thread.currentThread().setContextClassLoader(origClassLoader); - } - } - } - }); - } - - @Override - public V call(Callable callable) { - ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); - ClassLoader moduleClassLoader = getModuleClassLoader(); - if (origClassLoader != moduleClassLoader) { - Thread.currentThread().setContextClassLoader(moduleClassLoader); - } - try { - return callable.call(); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } finally { - if (origClassLoader != Thread.currentThread().getContextClassLoader()) { - Thread.currentThread().setContextClassLoader(origClassLoader); - } - } - } - -} \ No newline at end of file diff --git a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/Module.java b/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/Module.java deleted file mode 100644 index 885d9aac..00000000 --- a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/Module.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jd.blockchain.runtime; - -import java.io.InputStream; -import java.util.concurrent.Callable; - -import com.jd.blockchain.utils.concurrent.AsyncFuture; - -public interface Module { - - String getName(); - - Class loadClass(String className); - - InputStream loadResourceAsStream(String name); - - String getMainClass(); - -// Module getParent(); - - /** - * Run in this module's ClassLoader context; - * - * @param runnable - */ - void execute(Runnable runnable); - - /** - * Run asynchronize in this module's ClassLoader context; - * - * @param runnable - * @return - */ - AsyncFuture executeAsync(Runnable runnable); - - V call(Callable callable); - - AsyncFuture callAsync(Callable callable); - -} \ No newline at end of file diff --git a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/RuntimeContext.java b/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/RuntimeContext.java deleted file mode 100644 index e16097c2..00000000 --- a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/RuntimeContext.java +++ /dev/null @@ -1,279 +0,0 @@ -package com.jd.blockchain.runtime; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.jar.Attributes; -import java.util.jar.JarFile; - -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.io.RuntimeIOException; - -public abstract class RuntimeContext { - - public static interface Environment { - - boolean isProductMode(); - - } - - - private static final Object mutex = new Object(); - - private static volatile RuntimeContext runtimeContext; - - public static RuntimeContext get() { - if (runtimeContext == null) { - synchronized (mutex) { - if (runtimeContext == null) { - runtimeContext = new DefaultRuntimeContext(); - } - } - } - return runtimeContext; - } - - protected static void set(RuntimeContext runtimeContext) { - if (RuntimeContext.runtimeContext != null) { - throw new IllegalStateException("RuntimeContext has been setted!"); - } - RuntimeContext.runtimeContext = runtimeContext; - } - - private Map modules = new ConcurrentHashMap<>(); - - public RuntimeContext() { - } - - private File getDynamicModuleJarFile(String name) { - name = name + ".mdl"; - return new File(getRuntimeDir(), name); - } - - public Module getDynamicModule(String name) { - return modules.get(name); - - } - - public List getDynamicModules() { - return new ArrayList<>(modules.values()); - } - - public Module createDynamicModule(String name, byte[] jarBytes) { - Module module = modules.get(name); - if (module != null) { - return module; - } - synchronized (DefaultRuntimeContext.class) { - module = modules.get(name); - if (module != null) { - return module; - } - } - - // Save File to Disk; - File jarFile = getDynamicModuleJarFile(name); - if (jarFile.exists()) { - if (jarFile.isFile()) { - FileUtils.deleteFile(jarFile); - } else { - throw new IllegalStateException("Code storage conflict! --" + jarFile.getAbsolutePath()); - } - } - FileUtils.writeBytes(jarBytes, jarFile); - - try { - URL jarURL = jarFile.toURI().toURL(); - ClassLoader moduleClassLoader = createDynamicModuleClassLoader(jarURL); - - Attributes m = new JarFile(jarFile).getManifest().getMainAttributes(); - String contractMainClass = m.getValue(Attributes.Name.MAIN_CLASS); - module = new DefaultModule(name, moduleClassLoader, contractMainClass); - modules.put(name, module); - - return module; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - - public abstract Environment getEnvironment(); - - protected abstract String getRuntimeDir(); - - protected abstract URLClassLoader createDynamicModuleClassLoader(URL jarURL); - - // ------------------------- inner types -------------------------- - - private static class EnvSettings implements Environment{ - - private boolean productMode; - - @Override - public boolean isProductMode() { - return productMode; - } - - public void setProductMode(boolean productMode) { - this.productMode = productMode; - } - - } - - private static class DefaultModule extends AbstractModule { - - private String name; - - private ClassLoader moduleClassLoader; - - private String mainClass; - - public DefaultModule(String name, ClassLoader cl, String mainClass) { - this.name = name; - this.moduleClassLoader = cl; - this.mainClass = mainClass; - } - - @Override - public String getMainClass() { - return mainClass; - } - - - @Override - public String getName() { - return name; - } - -// @Override -// public Module getParent() { -// return null; -// } - - @Override - protected ClassLoader getModuleClassLoader() { - return moduleClassLoader; - } - - } - - /** - * Default RuntimeContext is a context of that:
- * all modules are running in a single class loader; - * - * @author huanghaiquan - * - */ - static class DefaultRuntimeContext extends RuntimeContext { - - protected String homeDir; - - protected String runtimeDir; - - protected EnvSettings environment; - - public DefaultRuntimeContext() { - - this.environment = new EnvSettings(); - this.environment.setProductMode(true); - - try { - this.homeDir = new File("./").getCanonicalPath(); - this.runtimeDir = new File(homeDir, "runtime").getAbsolutePath(); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - @Override - public Environment getEnvironment() { - return environment; - } - - @Override - protected String getRuntimeDir() { - return runtimeDir; - } - - @Override - protected URLClassLoader createDynamicModuleClassLoader(URL jarURL) { - return new ContractURLClassLoader(jarURL, RuntimeContext.class.getClassLoader()); - } - - } - - static class ContractURLClassLoader extends URLClassLoader { - - private static final String BLACK_CONFIG = "black.config"; - - private static final Set BLACK_CLASSES = new HashSet<>(); - - private static final Set BLACK_PACKAGES = new HashSet<>(); - - static { - initBlacks(); - } - - public ContractURLClassLoader(URL contractJarURL, ClassLoader parent) { - super(new URL[] { contractJarURL }, parent); - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if (BLACK_CLASSES.contains(name)) { - throw new IllegalStateException(String.format("Contract cannot use Class [%s]", name)); - } else { - // 判断该包是否是黑名单 - String trimName = name.trim(); - String packageName = trimName.substring(0, trimName.length() - 2); - if (BLACK_PACKAGES.contains(packageName)) { - throw new IllegalStateException(String.format("Contract cannot use Class [%s]", name)); - } - } - return super.loadClass(name); - } - - private static void initBlacks() { - try { - InputStream inputStream = ContractURLClassLoader.class.getResourceAsStream("/"+ BLACK_CONFIG); - String text = FileUtils.readText(inputStream); - String[] textArray = text.split("\n"); - for (String setting : textArray) { - // 支持按照逗号分隔 - if (setting == null || setting.length() == 0) { - continue; - } - String[] settingArray = setting.split(","); - for (String set : settingArray) { - String totalClass = set.trim(); - if (totalClass.endsWith("*")) { - // 说明是包,获取具体包名 - String packageName = totalClass.substring(0, totalClass.length() - 2); - BLACK_PACKAGES.add(packageName); - } else { - // 具体的类名,直接放入集合 - BLACK_CLASSES.add(totalClass); - } - } - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - public static void main(String[] args) { - for (String s : BLACK_CLASSES) { - System.out.println(s); - } - - for (String s : BLACK_PACKAGES) { - System.out.println(s); - } - } - } -} diff --git a/source/runtime/runtime-context/src/main/resources/black.config b/source/runtime/runtime-context/src/main/resources/black.config deleted file mode 100644 index d3353498..00000000 --- a/source/runtime/runtime-context/src/main/resources/black.config +++ /dev/null @@ -1,2 +0,0 @@ -java.util.Random, com.jd.blockchain.ledger.BlockchainKeyGenerator -java.io.*, java.nio.*, java.net.*, org.apache.commons.io.* \ No newline at end of file diff --git a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/ArgumentSet.java b/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/ArgumentSet.java deleted file mode 100644 index cc2a5102..00000000 --- a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/ArgumentSet.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.jd.blockchain.runtime.boot; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class ArgumentSet { - -// private static Pattern ARG_PATTERN = Pattern.compile("\\-.+\\={1}.*"); - - private ArgEntry[] args; - - private Map prefixArgs = new HashMap<>(); - - private Set options = new HashSet<>(); - - private ArgumentSet(ArgEntry[] args) { - this.args = args; - for (ArgEntry arg : args) { - if (arg.prefix != null) { - prefixArgs.put(arg.prefix, arg); - } - if (arg.option != null) { - options.add(arg.option); - } - } - } - - public static boolean hasOption(String[] args, String option) { - boolean contains = false; - if (args != null) { - for (String a : args) { - if (option.equalsIgnoreCase(a)) { - contains = true; - break; - } - } - } - return contains; - } - - public static Setting setting() { - return new Setting(); - } - - public static ArgumentSet resolve(String[] args, Setting setting) { - List argEntries = new ArrayList<>(); - for (int i = 0; i < args.length; i++) { - if (setting.prefixes.contains(args[i])) { - ArgEntry ae = new ArgEntry(); - ae.prefix = args[i]; - if (i+1 >= args.length) { - throw new IllegalArgumentException(String.format("缺少 %s 参数!", args[i])); - } - i++; - ae.value = args[i]; - argEntries.add(ae); - continue; - } - - if(setting.options.contains(args[i])){ - ArgEntry ae = new ArgEntry(); - ae.option = args[i]; - argEntries.add(ae); - continue; - } - } - return new ArgumentSet(argEntries.toArray(new ArgEntry[argEntries.size()])); - } - - /** - * 按照原始顺序排列的参数列表; - * - * @return - */ - public ArgEntry[] getArgs() { - return args; - } - - public ArgEntry getArg(String prefix) { - return prefixArgs.get(prefix); - } - - public boolean hasOption(String option) { - return options.contains(option); - } - - /** - * @author huanghaiquan - * - */ - public static class ArgEntry { - - private String prefix; - - private String value; - - private String option; - - /** - * 前缀;
- * 如果不是前缀参数,则为 null; - * - * @return - */ - public String getPrefix() { - return prefix; - } - - /** - * 参数值;
- * - * 如果只是选项参数,则返回 null; - * - * @return - */ - public String getValue() { - return value; - } - - /** - * 选项; - * - * @return - */ - public String getOption() { - return option; - } - - } - - public static class Setting { - - private Set prefixes = new HashSet<>(); - - private Set options = new HashSet<>(); - - private Setting() { - } - - - public Setting prefix(String... prefixes) { - this.prefixes.addAll(Arrays.asList(prefixes)); - return this; - } - - public Setting option(String... options) { - this.options.addAll(Arrays.asList(options)); - return this; - } - - } - -} diff --git a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/ClassPathUtils.java b/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/ClassPathUtils.java deleted file mode 100644 index 2d8d6051..00000000 --- a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/ClassPathUtils.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.runtime.boot; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; - -public class ClassPathUtils { - public static URL[] loadClassPaths(File dir) { - try { - File[] jars = dir.listFiles(f -> f.getName().endsWith(".jar") && f.isFile()); - URL[] classpaths = new URL[jars.length]; - for (int i = 0; i < classpaths.length; i++) { - classpaths[i] = jars[i].toURI().toURL(); - } - return classpaths; - } catch (MalformedURLException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } -} diff --git a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/HomeBooter.java b/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/HomeBooter.java deleted file mode 100644 index 1e8329b2..00000000 --- a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/HomeBooter.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.jd.blockchain.runtime.boot; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.regex.Pattern; - -/** - * 一个模块化代码加载的启动器; - * - * @author huanghaiquan - * - */ -public class HomeBooter { - - public static final String LIBS = "libs"; - public static final String SYSTEM = "system"; - public static final String RUNTIME = "runtime"; - - private static final Pattern ARG_PATTERN = Pattern.compile("^[\\-]\\w+[ ]*(=).*$"); - - private static final String HOME = "-home"; - - private static final String MODE = "-mode"; - private static final String MODE_DEBUG = "debug"; - private static final String MODE_PRODUCT = "product"; - - public static final Pattern MODE_PATTERN = Pattern.compile("^(" + MODE + ")[ ]*(=).*$"); - - /** - * 以多 ClassLoader 方式启动系统; - *

- * - * 以参数 -home 方式指定系统的 home 目录;
- * 以参数 -mode=product 指定以生产模式启动,否则以 debug 模式启动; - *

- * - * 系统 home 目录下,以 libs、systems、runtime 区分3个模块:
- * libs: 公共库模块;
- * system: 系统运行模块;
- * runtime: 运行时动态模块; - * - * @param args - */ - public static HomeContext createHomeContext(String[] args) throws IOException { - Properties settings = resolveSettings(args); - - String mode = settings.getProperty(MODE); - boolean productMode = mode != null && MODE_PRODUCT.equalsIgnoreCase(mode); - - String home = settings.getProperty(HOME); - if (home == null) { - throw new IllegalArgumentException("Miss home dir!"); - } - - List peerArgList = new ArrayList<>(); - for (String a : args) { - if (a.startsWith(HOME) || a.startsWith(MODE)) { - continue; - } - peerArgList.add(a); - } - String[] peerArgs = peerArgList.size() > 0 ? peerArgList.toArray(new String[peerArgList.size()]) : new String[0]; - - File homeDir = new File(home); - if (!homeDir.isDirectory()) { - throw new IllegalArgumentException( - "Home directory don't exist or the path is a file! --" + homeDir.getCanonicalPath()); - } - String homeAbsPath = homeDir.getCanonicalPath(); - File libDir = new File(homeAbsPath, LIBS); - if (!libDir.isDirectory()) { - throw new IllegalArgumentException( - "Libs directory don't exist or the path is a file! --" + libDir.getAbsolutePath()); - } - File systemDir = new File(homeAbsPath, SYSTEM); - if (!systemDir.isDirectory()) { - throw new IllegalArgumentException( - "System directory don't exist or the path is a file! --" + systemDir.getAbsolutePath()); - } - File runtimeDir = new File(homeAbsPath, RUNTIME); - if (runtimeDir.isFile()) { - throw new IllegalArgumentException("Runtime dir path is a file! --" + runtimeDir.getAbsolutePath()); - } - if (!runtimeDir.exists()) { - runtimeDir.mkdirs(); - } - - // 以 ExtClassLoader 作为所有创建的ClassLoader的 Parent; - ClassLoader extClassLoader = HomeBooter.class.getClassLoader().getParent(); - - URL[] libJars = loadClassPaths(libDir); - showJars("-------- lib jars --------", libJars); - URLClassLoader libClassLoader = new URLClassLoader(libJars, extClassLoader); - - URL[] systemJars = loadClassPaths(systemDir); - showJars("-------- system jars --------", systemJars); - URLClassLoader systemClassLoader = new URLClassLoader(systemJars, libClassLoader); - - return new HomeContext(libClassLoader, systemClassLoader, homeAbsPath, runtimeDir.getAbsolutePath(), - productMode, peerArgs); - } - - private static void showJars(String msg, URL[] jars) { - System.out.println(msg); - int i = 0; - for (URL url : jars) { - System.out.println(i + ": " + url.toString()); - } - System.out.println("-----------------"); - } - - public static URL[] loadClassPaths(File dir) { - try { - File[] jars = dir.listFiles(f -> f.getName().endsWith(".jar") && f.isFile()); - URL[] classpaths = new URL[jars.length]; - for (int i = 0; i < classpaths.length; i++) { - classpaths[i] = jars[i].toURI().toURL(); - } - return classpaths; - } catch (MalformedURLException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - /** - * 解析参数中以 “-”或者“--”开头的以“=”分隔的键值参数; - * - * @param args - * @return - */ - private static Properties resolveSettings(String[] args) { - Properties prop = new Properties(); - if (args == null || args.length == 0) { - return prop; - } - - for (String arg : args) { - if (ARG_PATTERN.matcher(arg).matches()) { - int i = arg.indexOf("="); - String argName = arg.substring(0, i).trim(); - String argValue = arg.substring(i + 1, arg.length()).trim(); - prop.setProperty(argName, argValue); - } - } - - return prop; - } - -} diff --git a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/HomeContext.java b/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/HomeContext.java deleted file mode 100644 index beae6545..00000000 --- a/source/runtime/runtime-modular-booter/src/main/java/com/jd/blockchain/runtime/boot/HomeContext.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.jd.blockchain.runtime.boot; - -public class HomeContext { - - private String homeDir; - - private String runtimeDir; - - private boolean productMode; - - private ClassLoader libsClassLoader; - - private ClassLoader systemClassLoader; - - private String[] startingArgs; - - public HomeContext(ClassLoader libsClassLoader, ClassLoader systemClassLoader, String homeDir, String runtimeDir, - boolean productMode, String[] startingArgs) { - this.libsClassLoader = libsClassLoader; - this.systemClassLoader = systemClassLoader; - this.homeDir = homeDir; - this.runtimeDir = runtimeDir; - this.productMode = productMode; - this.startingArgs = startingArgs; - } - - public String getHomeDir() { - return homeDir; - } - - public String getRuntimeDir() { - return runtimeDir; - } - - public ClassLoader getLibsClassLoader() { - return libsClassLoader; - } - - public ClassLoader getSystemClassLoader() { - return systemClassLoader; - } - - public boolean isProductMode() { - return productMode; - } - - public String[] getStartingArgs() { - return startingArgs; - } - -} diff --git a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/JarsModule.java b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/JarsModule.java deleted file mode 100644 index 94b64041..00000000 --- a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/JarsModule.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jd.blockchain.runtime.modular; - -import com.jd.blockchain.runtime.AbstractModule; - -public class JarsModule extends AbstractModule { - - private String name; - - private ClassLoader classLoader; - - public JarsModule(String name, ClassLoader classLoader) { - this.name = name; - this.classLoader = classLoader; - } - - - @Override - public String getName() { - return name; - } - - @Override - protected ClassLoader getModuleClassLoader() { - return classLoader; - } - - -} diff --git a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularFactory.java b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularFactory.java deleted file mode 100644 index b23dbfe8..00000000 --- a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.runtime.modular; - -public class ModularFactory { - - /** - * 启动系统; - */ - public static void startSystem(String runtimeDir, boolean productMode, - ClassLoader libClassLoader, String mainClassName, ClassLoader systemClassLoader, String[] args) { - - JarsModule libModule = new JarsModule("LibModule", libClassLoader); - - ModularRuntimeContext runtimeContext = new ModularRuntimeContext(runtimeDir, libModule, productMode); - runtimeContext.register(); - - SystemModule systemModule = new SystemModule(mainClassName, systemClassLoader, runtimeContext); - systemModule.start(args); - } - -} diff --git a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularRuntimeContext.java b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularRuntimeContext.java deleted file mode 100644 index 5b1bc5dc..00000000 --- a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularRuntimeContext.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jd.blockchain.runtime.modular; - -import java.net.URL; -import java.net.URLClassLoader; - -import com.jd.blockchain.runtime.RuntimeContext; - -public class ModularRuntimeContext extends RuntimeContext { - - private String runtimeDir; - - private JarsModule libModule; - - private EnvSettings environment; - - public ModularRuntimeContext(String runtimeDir, JarsModule libModule, - boolean productMode) { - this.environment = new EnvSettings(); - this.environment.setProductMode(productMode); - - this.runtimeDir = runtimeDir; - this.libModule = libModule; - } - - void register() { - RuntimeContext.set(this); - } - - @Override - public Environment getEnvironment() { - return environment; - } - - @Override - protected String getRuntimeDir() { - return runtimeDir; - } - - @Override - protected URLClassLoader createDynamicModuleClassLoader(URL jarURL) { - return new URLClassLoader(new URL[] {jarURL}, libModule.getModuleClassLoader()); - } - - // --------------------------- inner types ----------------------------- - - private static class EnvSettings implements Environment { - - private boolean productMode; - - @Override - public boolean isProductMode() { - return productMode; - } - - public void setProductMode(boolean productMode) { - this.productMode = productMode; - } - - } -} diff --git a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/MuduleClassLoader.java b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/MuduleClassLoader.java deleted file mode 100644 index 732ba9a8..00000000 --- a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/MuduleClassLoader.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jd.blockchain.runtime.modular; - -import java.net.URL; -import java.net.URLClassLoader; - -public class MuduleClassLoader extends URLClassLoader { - private ClassLoader parent; - public MuduleClassLoader(URL[] urls, ClassLoader parent){ - super(urls, parent); - this.parent = parent; - } - - - public Class loadClass(String name) - throws ClassNotFoundException{ - if (name.equals("com.jd.blockchain.contract.model.ContractEventContext") ){ - return this.parent.loadClass(name); - } - return super.loadClass(name); - - } - -} diff --git a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/SystemModule.java b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/SystemModule.java deleted file mode 100644 index 10aa7edc..00000000 --- a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/SystemModule.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jd.blockchain.runtime.modular; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -import com.jd.blockchain.runtime.AbstractModule; - -public class SystemModule extends AbstractModule { - - private ClassLoader classloader; - - private String mainClassName; - - private ModularRuntimeContext modularRuntimeContext; - - public SystemModule(String mainClassName, ClassLoader classloader, ModularRuntimeContext modularRuntimeContext) { - this.mainClassName = mainClassName; - this.classloader = classloader; - this.modularRuntimeContext = modularRuntimeContext; - } - - @Override - public String getName() { - return "SystemModule"; - } - - public ModularRuntimeContext getModularRuntimeContext() { - return modularRuntimeContext; - } - - @Override - protected ClassLoader getModuleClassLoader() { - return classloader; - } - - public void start(String[] args) { - execute(new Runnable() { - @Override - public void run() { - runMainClass(args); - } - }); - } - - private void runMainClass(String[] args) { - try { - Class mainClass = loadClass(mainClassName); - Method mainMethod = mainClass.getMethod("main", String[].class); - if (!Modifier.isStatic(mainMethod.getModifiers())) { - throw new IllegalArgumentException("Miss static main method in class[" + mainClassName + "]!"); - } - mainMethod.invoke(null, (Object) args); - } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - throw new IllegalStateException( - String.format("Error occurred on running %s! --%s", mainClassName, e.getMessage()), e); - } - } - - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainException.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainException.java deleted file mode 100644 index cb89c49e..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.sdk; - -public class BlockchainException extends RuntimeException { - - private static final long serialVersionUID = 8228291068740022658L; - - public BlockchainException() { - } - - public BlockchainException(String message) { - super(message); - } - - public BlockchainException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainExtendQueryService.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainExtendQueryService.java deleted file mode 100644 index 66c8b604..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainExtendQueryService.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.BlockchainExtendQueryService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/10/19 上午9:34 - * Description: - */ -package com.jd.blockchain.sdk; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.transaction.BlockchainQueryService; - -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -/** - * - * @author shaozhuguang - * @create 2018/10/19 - * @since 1.0.0 - */ - -public interface BlockchainExtendQueryService extends BlockchainQueryService { - - /** - * 获取最新区块 - * - * @param ledgerHash - * 账本Hash - * @return - */ - LedgerBlock getLatestBlock(HashDigest ledgerHash); - - /** - * 获取指定区块高度中新增的交易总数(即该区块中交易集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - long getAdditionalTransactionCount(HashDigest ledgerHash, long blockHeight); - - /** - * 获取指定区块Hash中新增的交易总数(即该区块中交易集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - long getAdditionalTransactionCount(HashDigest ledgerHash, HashDigest blockHash); - - /** - * 获取指定账本最新区块附加的交易数量 - * - * @param ledgerHash - * 账本Hash - * @return - */ - long getAdditionalTransactionCount(HashDigest ledgerHash); - - /** - * 获取指定区块高度中新增的数据账户总数(即该区块中数据账户集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - long getAdditionalDataAccountCount(HashDigest ledgerHash, long blockHeight); - - /** - * 获取指定区块Hash中新增的数据账户总数(即该区块中数据账户集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - long getAdditionalDataAccountCount(HashDigest ledgerHash, HashDigest blockHash); - - /** - * 获取指定账本中附加的数据账户数量 - * - * @param ledgerHash - * 账本Hash - * @return - */ - long getAdditionalDataAccountCount(HashDigest ledgerHash); - - /** - * 获取指定区块高度中新增的用户总数(即该区块中用户集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - long getAdditionalUserCount(HashDigest ledgerHash, long blockHeight); - - /** - * 获取指定区块Hash中新增的用户总数(即该区块中用户集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - long getAdditionalUserCount(HashDigest ledgerHash, HashDigest blockHash); - - /** - * 获取指定账本中新增的用户数量 - * - * @param ledgerHash - * 账本Hash - * @return - */ - long getAdditionalUserCount(HashDigest ledgerHash); - - /** - * 获取指定区块高度中新增的合约总数(即该区块中合约集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - long getAdditionalContractCount(HashDigest ledgerHash, long blockHeight); - - /** - * 获取指定区块Hash中新增的合约总数(即该区块中合约集合的数量) - * - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - long getAdditionalContractCount(HashDigest ledgerHash, HashDigest blockHash); - - /** - * 获取指定账本中新增的合约数量 - * - * @param ledgerHash - * 账本Hash - * @return - */ - long getAdditionalContractCount(HashDigest ledgerHash); - - /** - * get all ledgers count; - */ - int getLedgersCount(); -} \ No newline at end of file diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainServiceFactory.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainServiceFactory.java deleted file mode 100644 index cf605b05..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainServiceFactory.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jd.blockchain.sdk; - -public interface BlockchainServiceFactory { - - BlockchainService getBlockchainService(); - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ContractSettings.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ContractSettings.java deleted file mode 100644 index 4a004b2b..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ContractSettings.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jd.blockchain.sdk; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.Bytes; - -public class ContractSettings { - - private Bytes address; - - private PubKey pubKey; - - private HashDigest rootHash; - - private String chainCode; - - public ContractSettings() { - } - - public ContractSettings(Bytes address, PubKey pubKey, HashDigest rootHash) { - this.address = address; - this.pubKey = pubKey; - this.rootHash = rootHash; - } - - public ContractSettings(Bytes address, PubKey pubKey, HashDigest rootHash, String chainCode) { - this.address = address; - this.pubKey = pubKey; - this.rootHash = rootHash; - this.chainCode = chainCode; - } - - public Bytes getAddress() { - return address; - } - - public void setAddress(Bytes address) { - this.address = address; - } - - public PubKey getPubKey() { - return pubKey; - } - - public void setPubKey(PubKey pubKey) { - this.pubKey = pubKey; - } - - public HashDigest getRootHash() { - return rootHash; - } - - public void setRootHash(HashDigest rootHash) { - this.rootHash = rootHash; - } - - public String getChainCode() { - return chainCode; - } - - public void setChainCode(String chainCode) { - this.chainCode = chainCode; - } -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/DefaultServiceSetting.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/DefaultServiceSetting.java deleted file mode 100644 index 59f0b91a..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/DefaultServiceSetting.java +++ /dev/null @@ -1,17 +0,0 @@ -//package com.jd.blockchain.sdk; -// -//import com.jd.blockchain.crypto.CryptoAlgorithm; -// -//public class DefaultServiceSetting implements ServiceSetting { -// -// public static final DefaultServiceSetting INSTANCE = new DefaultServiceSetting(); -// -// private DefaultServiceSetting() { -// } -// -// @Override -// public CryptoAlgorithm getHashAlgorithm() { -// return CryptoAlgorithm.SHA256; -// } -// -//} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerAccessContext.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerAccessContext.java deleted file mode 100644 index df1d2689..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerAccessContext.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jd.blockchain.sdk; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.TransactionService; - -public interface LedgerAccessContext { - - HashDigest getLedgerHash(); - - CryptoSetting getCryptoSetting(); - - TransactionService getTransactionService(); - - BlockchainQueryService getQueryService(); - - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerBaseSettings.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerBaseSettings.java deleted file mode 100644 index 7cc58594..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerBaseSettings.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jd.blockchain.sdk; - - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.ParticipantNode; - -/** - * 账本初始化配置 - * - * @author shaozhuguang - * @date 2019-04-23 - * @since 1.0.0 - * - */ -public class LedgerBaseSettings { - - /** - * 账本初始化种子 - */ - private String seed; - - /** - * 共识参与方的默克尔树的根; - */ - private HashDigest participantsHash; - - /** - * 算法配置 - */ - private CryptoSetting cryptoSetting; - - /** - * 共识协议 - */ - private String consensusProtocol; - - /** - * 共识配置 - */ - private ConsensusSettings consensusSettings; - - /** - * 共识参与方 - */ - private ParticipantNode[] participantNodes; - - public void setSeed(String seed) { - this.seed = seed; - } - - public String getSeed() { - return seed; - } - - public HashDigest getParticipantsHash() { - return participantsHash; - } - - public void setParticipantsHash(HashDigest participantsHash) { - this.participantsHash = participantsHash; - } - - public CryptoSetting getCryptoSetting() { - return cryptoSetting; - } - - public void setCryptoSetting(CryptoSetting cryptoSetting) { - this.cryptoSetting = cryptoSetting; - } - - public String getConsensusProtocol() { - return consensusProtocol; - } - - public void setConsensusProtocol(String consensusProtocol) { - this.consensusProtocol = consensusProtocol; - } - - public ConsensusSettings getConsensusSettings() { - return consensusSettings; - } - - public void setConsensusSettings(ConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - } - - public ParticipantNode[] getParticipantNodes() { - return participantNodes; - } - - public void setParticipantNodes(ParticipantNode[] participantNodes) { - this.participantNodes = participantNodes; - } -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ServiceSetting.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ServiceSetting.java deleted file mode 100644 index 4f85a2c4..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ServiceSetting.java +++ /dev/null @@ -1,9 +0,0 @@ -//package com.jd.blockchain.sdk; -// -//import com.jd.blockchain.crypto.CryptoAlgorithm; -// -//public interface ServiceSetting { -// -// CryptoAlgorithm getHashAlgorithm(); -// -//} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/TransactionalScope.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/TransactionalScope.java deleted file mode 100644 index af51d0c7..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/TransactionalScope.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jd.blockchain.sdk; - -public interface TransactionalScope { - - void startNewTransaction(Runnable runnable); - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/BinarySerializeRequestConverter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/BinarySerializeRequestConverter.java deleted file mode 100644 index 317bd6e6..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/BinarySerializeRequestConverter.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.converters.BinarySerializeRequestConverter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/5 下午5:09 - * Description: 序列化请求体 - */ -package com.jd.blockchain.sdk.converters; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.consensus.ClientIdentifications; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.transaction.TxRequestMessage; -import com.jd.blockchain.utils.http.RequestBodyConverter; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * 序列化请求体 - * @author shaozhuguang - * @create 2018/9/5 - * @since 1.0.0 - */ - -public class BinarySerializeRequestConverter implements RequestBodyConverter { - - public static final String CONTENT_TYPE_VALUE = "application/bin-obj"; - - @Override - public void write(Object param, OutputStream out) throws IOException { - // 使用自定义的序列化方式 - if (param instanceof TransactionRequest) { - byte[] serializeBytes = BinaryProtocol.encode(param, TransactionRequest.class); - out.write(serializeBytes); - out.flush(); - } else if (param instanceof ClientIdentifications) { - byte[] serializeBytes = BinaryProtocol.encode(param, ClientIdentifications.class); - out.write(serializeBytes); - out.flush(); - } - } -} \ No newline at end of file diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/BinarySerializeResponseConverter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/BinarySerializeResponseConverter.java deleted file mode 100644 index 32664abc..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/BinarySerializeResponseConverter.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.converters.BinarySerializeResponseConverter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/5 下午5:22 - * Description: - */ -package com.jd.blockchain.sdk.converters; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.transaction.TxResponseMessage; -import com.jd.blockchain.utils.http.HttpServiceContext; -import com.jd.blockchain.utils.http.ResponseConverter; -import com.jd.blockchain.utils.http.agent.ServiceRequest; -import com.jd.blockchain.utils.io.BytesUtils; - -import java.io.InputStream; - -/** - * - * @author shaozhuguang - * @create 2018/9/5 - * @since 1.0.0 - */ - -public class BinarySerializeResponseConverter implements ResponseConverter { - - @Override - public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext) - throws Exception { - byte[] serializeBytes = BytesUtils.readBytes(responseStream); - Object resolvedObj = BinaryProtocol.decode(serializeBytes); - return resolvedObj; - } - -} \ No newline at end of file diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/ClientResolveUtil.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/ClientResolveUtil.java deleted file mode 100644 index 46bb8d12..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/ClientResolveUtil.java +++ /dev/null @@ -1,393 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.client.ClientResolveUtil - * Author: shaozhuguang - * Department: Y事业部 - * Date: 2019/3/27 下午4:12 - * Description: - */ -package com.jd.blockchain.sdk.converters; - -import java.lang.reflect.Field; - -import com.jd.blockchain.ledger.*; -import org.apache.commons.codec.binary.Base64; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.transaction.ContractCodeDeployOpTemplate; -import com.jd.blockchain.transaction.ContractEventSendOpTemplate; -import com.jd.blockchain.transaction.DataAccountKVSetOpTemplate; -import com.jd.blockchain.transaction.DataAccountRegisterOpTemplate; -import com.jd.blockchain.transaction.KVData; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.transaction.LedgerInitOpTemplate; -import com.jd.blockchain.transaction.UserRegisterOpTemplate; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.codec.HexUtils; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * - * @author shaozhuguang - * @create 2019/3/27 - * @since 1.0.0 - */ - -public class ClientResolveUtil { - - public static TypedKVEntry[] read(TypedKVEntry[] kvDataEntries) { - if (kvDataEntries == null || kvDataEntries.length == 0) { - return kvDataEntries; - } - TypedKVEntry[] resolveKvDataEntries = new TypedKVEntry[kvDataEntries.length]; - // kvDataEntries是代理对象,需要处理 - for (int i = 0; i < kvDataEntries.length; i++) { - TypedKVEntry kvDataEntry = kvDataEntries[i]; - String key = kvDataEntry.getKey(); - long version = kvDataEntry.getVersion(); - DataType dataType = kvDataEntry.getType(); - KvData innerKvData = new KvData(key, version, dataType); - Object valueObj = kvDataEntry.getValue(); - switch (dataType) { - case NIL: - break; - case BYTES: - case TEXT: - case JSON: - case XML: - innerKvData.setValue(valueObj.toString()); - break; - case INT32: - innerKvData.setValue(Integer.parseInt(valueObj.toString())); - break; - case INT64: - innerKvData.setValue(Long.parseLong(valueObj.toString())); - break; - default: - throw new IllegalStateException("Unsupported value type[" + dataType + "] to resolve!"); - } - resolveKvDataEntries[i] = innerKvData; - } - return resolveKvDataEntries; - } - - public static Operation read(Operation operation) { - - try { - // Class - Class clazz = operation.getClass(); - Field field = clazz.getSuperclass().getDeclaredField("h"); - field.setAccessible(true); - Object object = field.get(operation); - if (object instanceof JSONObject) { - JSONObject jsonObject = (JSONObject) object; - if (jsonObject.containsKey("accountID")) { - return convertDataAccountRegisterOperation(jsonObject); - } else if (jsonObject.containsKey("userID")) { - return convertUserRegisterOperation(jsonObject); - } else if (jsonObject.containsKey("contractID")) { - return convertContractCodeDeployOperation(jsonObject); - } else if (jsonObject.containsKey("writeSet")) { - return convertDataAccountKVSetOperation(jsonObject); - } else if (jsonObject.containsKey("initSetting")) { - return convertLedgerInitOperation(jsonObject); - } else if (jsonObject.containsKey("contractAddress")) { - return convertContractEventSendOperation(jsonObject); - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - return null; - } - - public static Object readValueByBytesValue(BytesValue bytesValue) { - DataType dataType = bytesValue.getType(); - Bytes saveVal = bytesValue.getBytes(); - Object showVal; - switch (dataType) { - case BYTES: - // return hex - showVal = HexUtils.encode(saveVal.toBytes()); - break; - case TEXT: - case JSON: - showVal = saveVal.toUTF8String(); - break; - case INT64: - showVal = BytesUtils.toLong(saveVal.toBytes()); - break; - default: - showVal = HexUtils.encode(saveVal.toBytes()); - break; - } - return showVal; - } - - public static DataAccountRegisterOperation convertDataAccountRegisterOperation(JSONObject jsonObject) { - JSONObject account = jsonObject.getJSONObject("accountID"); - return new DataAccountRegisterOpTemplate(blockchainIdentity(account)); - } - - public static DataAccountKVSetOperation convertDataAccountKVSetOperation(JSONObject jsonObject) { - // 写入集合处理 - JSONArray writeSetObj = jsonObject.getJSONArray("writeSet"); - JSONObject accountAddrObj = jsonObject.getJSONObject("accountAddress"); - String addressBase58 = accountAddrObj.getString("value"); - Bytes address = Bytes.fromBase58(addressBase58); - - DataAccountKVSetOpTemplate kvOperation = new DataAccountKVSetOpTemplate(address); - for (int i = 0; i < writeSetObj.size(); i++) { - JSONObject currWriteSetObj = writeSetObj.getJSONObject(i); - long expectedVersion = currWriteSetObj.getLong("expectedVersion"); - JSONObject valueObj = currWriteSetObj.getJSONObject("value"); - String typeStr = valueObj.getString("type"); - // Base58Utils.decode(valueObj.getJSONObject("bytes").getString("value")) - String realValBase58 = valueObj.getJSONObject("bytes").getString("value"); - String key = currWriteSetObj.getString("key"); - DataType dataType = DataType.valueOf(typeStr); - BytesValue bytesValue = TypedValue.fromType(dataType, Base58Utils.decode(realValBase58)); - KVData kvData = new KVData(key, bytesValue, expectedVersion); - kvOperation.set(kvData); - } - - return kvOperation; - } - - public static LedgerInitOperation convertLedgerInitOperation(JSONObject jsonObject) { - JSONObject legerInitObj = jsonObject.getJSONObject("initSetting"); - LedgerInitData ledgerInitSettingData = new LedgerInitData(); - String ledgerSeedStr = legerInitObj.getString("ledgerSeed"); - - // 种子需要做Base64转换 - ledgerInitSettingData.setLedgerSeed(Base64.decodeBase64(BytesUtils.toBytes(ledgerSeedStr))); - - String consensusProvider = legerInitObj.getString("consensusProvider"); - - ledgerInitSettingData.setConsensusProvider(consensusProvider); - - JSONObject cryptoSettingObj = legerInitObj.getJSONObject("cryptoSetting"); - boolean autoVerifyHash = cryptoSettingObj.getBoolean("autoVerifyHash"); - short hashAlgorithm = cryptoSettingObj.getShort("hashAlgorithm"); - - CryptoConfig cryptoConfig = new CryptoConfig(); - - cryptoConfig.setAutoVerifyHash(autoVerifyHash); - - cryptoConfig.setHashAlgorithm(hashAlgorithm); - - ledgerInitSettingData.setCryptoSetting(cryptoConfig); - - JSONObject consensusSettingsObj = legerInitObj.getJSONObject("consensusSettings"); - Bytes consensusSettings = Bytes.fromBase58(consensusSettingsObj.getString("value")); - - ledgerInitSettingData.setConsensusSettings(consensusSettings); - - JSONArray consensusParticipantsArray = legerInitObj.getJSONArray("consensusParticipants"); - - if (!consensusParticipantsArray.isEmpty()) { - ParticipantNode[] participantNodes = new ParticipantNode[consensusParticipantsArray.size()]; - for (int i = 0; i < consensusParticipantsArray.size(); i++) { - JSONObject currConsensusParticipant = consensusParticipantsArray.getJSONObject(i); - Bytes address = Bytes.fromBase58(currConsensusParticipant.getString("address")); - String name = currConsensusParticipant.getString("name"); - int id = currConsensusParticipant.getInteger("id"); - JSONObject pubKeyObj = currConsensusParticipant.getJSONObject("pubKey"); - String pubKeyBase58 = pubKeyObj.getString("value"); - // 生成ParticipantNode对象 - ParticipantCertData participantCertData = new ParticipantCertData(id, address, name, new PubKey(Bytes.fromBase58(pubKeyBase58).toBytes()), null); - participantNodes[i] = participantCertData; - } - ledgerInitSettingData.setConsensusParticipants(participantNodes); - } - - return new LedgerInitOpTemplate(ledgerInitSettingData); - } - - public static UserRegisterOperation convertUserRegisterOperation(JSONObject jsonObject) { - JSONObject user = jsonObject.getJSONObject("userID"); - return new UserRegisterOpTemplate(blockchainIdentity(user)); - } - - public static ContractCodeDeployOperation convertContractCodeDeployOperation(JSONObject jsonObject) { - JSONObject contract = jsonObject.getJSONObject("contractID"); - BlockchainIdentityData blockchainIdentity = blockchainIdentity(contract); - - String chainCodeStr = jsonObject.getString("chainCode"); - ContractCodeDeployOpTemplate contractCodeDeployOpTemplate = new ContractCodeDeployOpTemplate(blockchainIdentity, - BytesUtils.toBytes(chainCodeStr)); - return contractCodeDeployOpTemplate; - } - - public static ContractEventSendOperation convertContractEventSendOperation(JSONObject jsonObject) { - JSONObject contractAddressObj = jsonObject.getJSONObject("contractAddress"); - String contractAddress = contractAddressObj.getString("value"); - String argsStr = jsonObject.getString("args"); - String event = jsonObject.getString("event"); - return new ContractEventSendOpTemplate(Bytes.fromBase58(contractAddress), event, - BytesValueEncoding.encodeArray(new Object[] { argsStr }, null)); - } - - private static BlockchainIdentityData blockchainIdentity(JSONObject jsonObject) { - JSONObject addressObj = jsonObject.getJSONObject("address"); - // base58值 - String addressBase58 = addressObj.getString("value"); - Bytes address = Bytes.fromBase58(addressBase58); - - JSONObject pubKeyObj = jsonObject.getJSONObject("pubKey"); - // base58值 - String pubKeyBase58 = pubKeyObj.getString("value"); - PubKey pubKey = new PubKey(Bytes.fromBase58(pubKeyBase58).toBytes()); - - // 生成对应的对象 - return new BlockchainIdentityData(address, pubKey); - } - - public static class CryptoConfig implements CryptoSetting { - - private short hashAlgorithm; - - private boolean autoVerifyHash; - - @Override - public CryptoProvider[] getSupportedProviders() { - return new CryptoProvider[0]; - } - - @Override - public short getHashAlgorithm() { - return hashAlgorithm; - } - - @Override - public boolean getAutoVerifyHash() { - return autoVerifyHash; - } - - public void setHashAlgorithm(short hashAlgorithm) { - this.hashAlgorithm = hashAlgorithm; - } - - public void setAutoVerifyHash(boolean autoVerifyHash) { - this.autoVerifyHash = autoVerifyHash; - } - } - - public static class ParticipantCertData implements ParticipantNode { - private int id; - private Bytes address; - private String name; - private PubKey pubKey; - private ParticipantNodeState participantNodeState; - - public ParticipantCertData() { - } - - public ParticipantCertData(ParticipantNode participantNode) { - this.address = participantNode.getAddress(); - this.name = participantNode.getName(); - this.pubKey = participantNode.getPubKey(); - } - - public ParticipantCertData(int id, Bytes address, String name, PubKey pubKey, ParticipantNodeState participantNodeState) { - this.id = id; - this.address = address; - this.name = name; - this.pubKey = pubKey; - - this.participantNodeState = participantNodeState; - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public String getName() { - return name; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - @Override - public int getId() { - return id; - } - - @Override - public ParticipantNodeState getParticipantNodeState() { - return participantNodeState; - } - - } - - public static class KvData implements TypedKVEntry { - - private String key; - - private long version; - - private DataType dataType; - - private Object value; - - public KvData() { - } - - public KvData(String key, long version, DataType dataType) { - this(key, version, dataType, null); - } - - public KvData(String key, long version, DataType dataType, Object value) { - this.key = key; - this.version = version; - this.dataType = dataType; - this.value = value; - } - - public void setKey(String key) { - this.key = key; - } - - public void setVersion(long version) { - this.version = version; - } - - public void setDataType(DataType dataType) { - this.dataType = dataType; - } - - public void setValue(Object value) { - this.value = value; - } - - @Override - public String getKey() { - return key; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public DataType getType() { - return dataType; - } - - @Override - public Object getValue() { - return value; - } - } -} \ No newline at end of file diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestToStringConverter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestToStringConverter.java deleted file mode 100644 index 390cd404..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestToStringConverter.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: my.utils.http.converters.HashDigestToStringConverter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/14 下午2:24 - * Description: HashDigest转为字符串 - */ -package com.jd.blockchain.sdk.converters; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.utils.http.StringConverter; - -/** - * HashDigest转为字符串 - * @author shaozhuguang - * @create 2018/9/14 - * @since 1.0.0 - */ - -public class HashDigestToStringConverter implements StringConverter { - - @Override - public String toString(Object param) { - if (param instanceof HashDigest) { - return ((HashDigest) param).toBase58(); - } - return null; - } -} \ No newline at end of file diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestsResponseConverter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestsResponseConverter.java deleted file mode 100644 index c19e3bbb..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestsResponseConverter.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jd.blockchain.sdk.converters; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.transaction.TxResponseMessage; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.http.HttpServiceContext; -import com.jd.blockchain.utils.http.ResponseConverter; -import com.jd.blockchain.utils.http.agent.ServiceRequest; -import com.jd.blockchain.utils.http.converters.JsonResponseConverter; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; -import com.jd.blockchain.utils.web.client.WebServiceException; -import com.jd.blockchain.utils.web.model.WebResponse; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Created by zhangshuang3 on 2018/10/17. - */ -public class HashDigestsResponseConverter implements ResponseConverter { - - private JsonResponseConverter jsonConverter = new JsonResponseConverter(WebResponse.class); - - @Override - public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext) throws Exception { - WebResponse response = (WebResponse) jsonConverter.getResponse(request, responseStream, null); - if (response == null) { - return null; - } - if (response.getError() != null) { - throw new WebServiceException(response.getError().getErrorCode(), response.getError().getErrorMessage()); - } - if (response.getData() == null) { - return null; - } - - -// byte[] serializeBytes = BytesUtils.readBytes(responseStream); -// String jsonChar = new String(serializeBytes, "UTF-8"); -// JSONArray jsonArray = JSON.parseArray(jsonChar); -// List hashDigests = new ArrayList<>(); -// for (Object obj : jsonArray) { -// if (obj instanceof JSONObject) { -// String base58Str = ((JSONObject)obj).getString("value"); -// hashDigests.add(new HashDigest(Base58Utils.decode(base58Str))); -// } -// } - return deserialize(response.getData()); - } - - private Object deserialize(Object object) { - List hashDigests = new ArrayList<>(); - if (object instanceof JSONArray) { - JSONArray jsonArray = (JSONArray)object; - for (Object obj : jsonArray) { - if (obj instanceof Map) { - Map objMap = (Map)obj; - String base58Str = objMap.get("value"); - hashDigests.add(new HashDigest(Base58Utils.decode(base58Str))); - } - } - } - return hashDigests.toArray(new HashDigest[hashDigests.size()]); - } -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/HttpBlockchainQueryService.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/HttpBlockchainQueryService.java deleted file mode 100644 index d13fa436..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/HttpBlockchainQueryService.java +++ /dev/null @@ -1,602 +0,0 @@ -package com.jd.blockchain.sdk.proxy; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.sdk.BlockchainExtendQueryService; -import com.jd.blockchain.sdk.converters.HashDigestsResponseConverter; -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.utils.http.*; -import com.jd.blockchain.utils.web.client.WebResponseConverterFactory; -import com.jd.blockchain.sdk.converters.HashDigestToStringConverter; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -/** - * 作为内部使用的适配接口,用于声明 HTTP 协议的服务请求; - * - * @author huanghaiquan - * - */ -@HttpService(responseConverterFactory=WebResponseConverterFactory.class) -public interface HttpBlockchainQueryService extends BlockchainExtendQueryService { - - /** - * 返回所有的账本的 hash 列表;
- * - * 注:账本的 hash 既是该账本的创世区块的 hash; - * - * @return Base64编码的账本 hash 的集合; - */ - @HttpAction(method=HttpMethod.GET, path="ledgers", responseConverter = HashDigestsResponseConverter.class) - @Override - HashDigest[] getLedgerHashs(); - - /** - * 获取账本信息; - * - * @param ledgerHash - * @return 账本对象;如果不存在,则返回 null; - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}") - @Override - LedgerInfo getLedger(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 获取最新区块 - * - * @param ledgerHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/latest") - @Override - LedgerBlock getLatestBlock(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 获取指定区块高度中新增的交易总数(即该区块中交易集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/additional-count") - @Override - long getAdditionalTransactionCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long blockHeight); - - /** - * 获取指定区块Hash中新增的交易总数(即该区块中交易集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/additional-count") - @Override - long getAdditionalTransactionCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 获取指定账本最新区块新增的交易数量 - * @param ledgerHash - * 账本Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/txs/additional-count") - @Override - long getAdditionalTransactionCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 获取指定区块高度中新增的数据账户总数(即该区块中数据账户集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/additional-count") - @Override - long getAdditionalDataAccountCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long blockHeight); - - /** - * 获取指定区块Hash中新增的数据账户总数(即该区块中数据账户集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/additional-count") - @Override - long getAdditionalDataAccountCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 获取指定账本中附加的数据账户数量 - * @param ledgerHash - * 账本Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/accounts/additional-count") - @Override - long getAdditionalDataAccountCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - - /** - * 获取指定区块高度中新增的用户总数(即该区块中用户集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/additional-count") - @Override - long getAdditionalUserCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long blockHeight); - - /** - * 获取指定区块Hash中新增的用户总数(即该区块中用户集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/additional-count") - @Override - long getAdditionalUserCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 获取指定账本中新增的用户数量 - * @param ledgerHash - * 账本Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/users/additional-count") - @Override - long getAdditionalUserCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 获取指定区块高度中新增的合约总数(即该区块中合约集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHeight - * 区块高度 - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/additional-count") - @Override - long getAdditionalContractCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long blockHeight); - - /** - * 获取指定区块Hash中新增的合约总数(即该区块中合约集合的数量) - * @param ledgerHash - * 账本Hash - * @param blockHash - * 区块Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/additional-count") - @Override - long getAdditionalContractCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 获取指定账本中新增的合约数量 - * @param ledgerHash - * 账本Hash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/contracts/additional-count") - @Override - long getAdditionalContractCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - - /** - * 获取账本信息; - * - * @param ledgerHash - * @return 账本对象;如果不存在,则返回 null; - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/admininfo") - @Override - LedgerAdminInfo getLedgerAdminInfo(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 返回指定账本的参与列表 - * - * @param ledgerHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/participants") - @Override - ParticipantNode[] getConsensusParticipants(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 返回指定账本的元数据 - * - * @param ledgerHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/metadata") - @Override - LedgerMetadata getLedgerMetadata(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 返回指定账本序号的区块; - * - * @param ledgerHash - * 账本hash; - * @param blockHeight - * 高度; - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}") - @Override - LedgerBlock getBlock(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long blockHeight); - - /** - * 返回指定区块hash的区块; - * - * @param ledgerHash - * 账本hash; - * @param blockHash - * 区块hash; - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}") - @Override - LedgerBlock getBlock(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 返回指定高度的区块中记录的交易总数; - * - * @param ledgerHash - * @param height - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/count") - @Override - long getTransactionCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long height); - - /** - * 返回指定hash的区块中记录的交易总数; - * - * @param ledgerHash - * @param blockHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/count") - @Override - long getTransactionCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 返回账本的交易总数 - * - * @param ledgerHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/txs/count") - @Override - long getTransactionTotalCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 返回指定账本和区块的数据账户总数 - * - * @param ledgerHash - * @param height - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/count") - @Override - long getDataAccountCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long height); - - /** - * 返回指定账本和区块的数据账户总数 - * - * @param ledgerHash - * @param blockHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/count") - @Override - long getDataAccountCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 返回指定账本的数据账户总数 - * - * @param ledgerHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/accounts/count") - @Override - long getDataAccountTotalCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 返回指定账本和区块的用户总数 - * - * @param ledgerHash - * @param height - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/count") - @Override - long getUserCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long height); - - /** - * 返回指定账本和区块的用户总数 - * - * @param ledgerHash - * @param blockHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/count") - @Override - long getUserCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 返回指定账本的用户总数 - * - * @param ledgerHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/users/count") - @Override - long getUserTotalCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 返回指定账本和区块的合约总数 - * - * @param ledgerHash - * @param height - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/count") - @Override - long getContractCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long height); - - /** - * 返回指定账本和区块的合约总数 - * - * @param ledgerHash - * @param blockHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/count") - @Override - long getContractCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash); - - /** - * 返回指定账本的合约总数 - * - * @param ledgerHash - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/contracts/count") - @Override - long getContractTotalCount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash); - - /** - * 分页返回指定账本序号的区块中的交易列表; - * - * @param ledgerHash - * 账本hash; - * @param height - * 账本高度; - * @param fromIndex - * 开始的记录数; - * @param count - * 本次返回的记录数;
- * 最小为1,最大值受到系统参数的限制;
- * 注:通过 {@link #getBlock(String, long)} 方法获得的区块信息中可以得到区块的总交易数 - * {@link Block#getTxCount()}; - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs") - @Override - LedgerTransaction[] getTransactions(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHeight") long height, - @RequestParam(name="fromIndex", required = false) int fromIndex, - @RequestParam(name="count", required = false) int count); - - /** - * 分页返回指定账本序号的区块中的交易列表; - * - * @param ledgerHash - * 账本hash; - * @param blockHash - * 账本高度; - * @param fromIndex - * 开始的记录数; - * @param count - * 本次返回的记录数;
- * 如果参数值为 -1,则返回全部的记录;
- * 注:通过 {@link #getBlock(String, String)} 方法获得的区块信息中可以得到区块的总交易数 - * {@link Block#getTxCount()}; - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs") - @Override - LedgerTransaction[] getTransactions(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="blockHash", converter=HashDigestToStringConverter.class) HashDigest blockHash, - @RequestParam(name="fromIndex", required = false) int fromIndex, - @RequestParam(name="count", required = false) int count); - - /** - * 根据交易内容的哈希获取对应的交易记录; - * - * @param ledgerHash - * 账本hash; - * @param contentHash - * 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值; - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/txs/{contentHash}") - @Override - LedgerTransaction getTransactionByContentHash(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="contentHash", converter=HashDigestToStringConverter.class) HashDigest contentHash); - - /** - * - * 返回交易状态 - * - * @param ledgerHash - * 账本hash; - * @param contentHash - * 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值; - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/txs/state/{contentHash}") - @Override - TransactionState getTransactionStateByContentHash(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="contentHash", converter=HashDigestToStringConverter.class) HashDigest contentHash); - - /** - * 返回用户信息; - * - * @param ledgerHash - * @param address - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/users/address/{address}") - @Override - UserInfo getUser(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="address") String address); - - /** - * 返回数据账户信息; - * - * @param ledgerHash - * @param address - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/accounts/address/{address}") - @Override - BlockchainIdentity getDataAccount(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="address") String address); - - /** - * 返回数据账户中指定的键的最新值;
- * - * 返回结果的顺序与指定的键的顺序是一致的;
- * - * 如果某个键不存在,则返回版本为 -1 的数据项; - * - * @param ledgerHash - * @param address - * @param keys - * @return - */ - @HttpAction(method=HttpMethod.POST, path="ledgers/{ledgerHash}/accounts/{address}/entries") - @Override - TypedKVEntry[] getDataEntries(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="address") String address, - @RequestParam(name="keys", array = true) String... keys); - - @HttpAction(method=HttpMethod.POST, path="ledgers/{ledgerHash}/accounts/{address}/entries-version") - @Override - TypedKVEntry[] getDataEntries(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="address") String address, - @RequestBody KVInfoVO kvInfoVO); - - /** - * 返回数据账户中指定序号的最新值; - * 返回结果的顺序与指定的序号的顺序是一致的;
- * - * @param ledgerHash - * 账本hash; - * @param address - * 数据账户地址; - * @param fromIndex - * 开始的记录数; - * @param count - * 本次返回的记录数;
- * 如果参数值为 -1,则返回全部的记录;
- * @return - */ - @HttpAction(method = HttpMethod.POST, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries") - @Override - TypedKVEntry[] getDataEntries(@PathParam(name = "ledgerHash") HashDigest ledgerHash, - @PathParam(name = "address") String address, - @RequestParam(name = "fromIndex", required = false) int fromIndex, - @RequestParam(name = "count", required = false) int count); - - /** - * 返回指定数据账户中KV数据的总数; - * @param ledgerHash - * @param address - * @return - */ - @HttpAction(method = HttpMethod.GET, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries/count") - @Override - long getDataEntriesTotalCount(@PathParam(name = "ledgerHash") HashDigest ledgerHash, - @PathParam(name = "address") String address); - - /** - * 返回合约账户信息; - * - * @param ledgerHash - * @param address - * @return - */ - @HttpAction(method=HttpMethod.GET, path="ledgers/{ledgerHash}/contracts/address/{address}") - @Override - ContractInfo getContract(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @PathParam(name="address") String address); - - - /** - * get more users by fromIndex and count; - * @param ledgerHash - * @param fromIndex - * @param count - * @return - */ - @HttpAction(method = HttpMethod.GET, path = "ledgers/{ledgerHash}/users") - @Override - BlockchainIdentity[] getUsers(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @RequestParam(name="fromIndex", required = false) int fromIndex, - @RequestParam(name="count", required = false) int count); - - /** - * get data accounts by ledgerHash and its range; - * @param ledgerHash - * @param fromIndex - * @param count - * @return - */ - @HttpAction(method = HttpMethod.GET, path = "ledgers/{ledgerHash}/accounts") - @Override - BlockchainIdentity[] getDataAccounts(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @RequestParam(name="fromIndex", required = false) int fromIndex, - @RequestParam(name="count", required = false) int count); - - /** - * get contract accounts by ledgerHash and its range; - * @param ledgerHash - * @param fromIndex - * @param count - * @return - */ - @HttpAction(method = HttpMethod.GET, path = "ledgers/{ledgerHash}/contracts") - @Override - BlockchainIdentity[] getContractAccounts(@PathParam(name="ledgerHash", converter=HashDigestToStringConverter.class) HashDigest ledgerHash, - @RequestParam(name="fromIndex", required = false) int fromIndex, - @RequestParam(name="count", required = false) int count); - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/ConsensusTransactionService.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/ConsensusTransactionService.java deleted file mode 100644 index 3fbc3a2d..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/ConsensusTransactionService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.sdk.service; - -import com.jd.blockchain.consensus.ActionMessage; -import com.jd.blockchain.consensus.OrderedAction; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.transaction.TransactionService; - -/** - * 带共识的交易服务; - * - * @author huanghaiquan - * - */ -public interface ConsensusTransactionService extends TransactionService { - - @OrderedAction(groupIndexer = LedgerGroupIndexer.class, responseConverter = TransactionResponseMessageConverter.class) - @Override - TransactionResponse process( - @ActionMessage(converter = TransactionRequestMessageConverter.class) TransactionRequest txRequest); - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/IncomingInfo.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/IncomingInfo.java deleted file mode 100644 index 8d893324..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/IncomingInfo.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jd.blockchain.sdk.service;//package com.jd.blockchain.sdk.bftsmart; -// -//import com.jd.blockchain.manage.GatewayIncomingSetting; -// -//import my.utils.net.NetworkAddress; -// -//public class IncomingInfo { -// -// private GatewayIncomingSetting setting; -// -//// private NetworkAddress peerAddress; -// -// /** -// * 接入的 bft 客户端配置; -// * -// * @return -// */ -// public GatewayIncomingSetting getIncomingSetting() { -// return setting; -// } -// -// public void setSetting(GatewayIncomingSetting setting) { -// this.setting = setting; -// } -// -//// /** -//// * 节点地址; -//// * -//// * @return -//// */ -//// public NetworkAddress getPeerAddress() { -//// return peerAddress; -//// } -//// -//// public void setPeerAddress(NetworkAddress peerAddress) { -//// this.peerAddress = peerAddress; -//// } -// -//} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/LedgerGroupIndexer.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/LedgerGroupIndexer.java deleted file mode 100644 index bcce4cd9..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/LedgerGroupIndexer.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jd.blockchain.sdk.service; - -import com.jd.blockchain.consensus.GroupIndexer; -import com.jd.blockchain.ledger.TransactionRequest; - -public class LedgerGroupIndexer implements GroupIndexer { - - @Override - public byte[] getGroupId(Object[] messageObjects) { - return ((TransactionRequest)messageObjects[0]).getTransactionContent().getLedgerHash().toBytes(); - } - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/PeerBlockchainServiceFactory.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/PeerBlockchainServiceFactory.java deleted file mode 100644 index c3504185..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/PeerBlockchainServiceFactory.java +++ /dev/null @@ -1,342 +0,0 @@ -package com.jd.blockchain.sdk.service; - -import com.jd.blockchain.consensus.*; -import com.jd.blockchain.consensus.client.ClientFactory; -import com.jd.blockchain.consensus.client.ClientSettings; -import com.jd.blockchain.consensus.client.ConsensusClient; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.sdk.*; -import com.jd.blockchain.sdk.proxy.HttpBlockchainQueryService; -import com.jd.blockchain.setting.GatewayIncomingSetting; -import com.jd.blockchain.setting.LedgerIncomingSetting; -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.TransactionService; -import com.jd.blockchain.utils.http.agent.HttpServiceAgent; -import com.jd.blockchain.utils.http.agent.ServiceConnection; -import com.jd.blockchain.utils.http.agent.ServiceConnectionManager; -import com.jd.blockchain.utils.http.agent.ServiceEndpoint; -import com.jd.blockchain.utils.io.ByteArray; -import com.jd.blockchain.utils.net.NetworkAddress; -import com.jd.blockchain.utils.security.AuthenticationException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.Closeable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class PeerBlockchainServiceFactory implements BlockchainServiceFactory, Closeable { - - private static Logger LOGGER = LoggerFactory.getLogger(PeerBlockchainServiceFactory.class); - - private static final Map peerBlockchainServiceFactories = new ConcurrentHashMap<>(); - - private static final Map peerManageServices = new ConcurrentHashMap<>(); - - private static final Map accessContextMap = new ConcurrentHashMap<>(); - - private ServiceConnectionManager httpConnectionManager; - - private PeerServiceProxy peerServiceProxy; - - - /** - * @param httpConnectionManager - * Http请求管理器; - * @param accessAbleLedgers - * 可用账本列表; - */ - protected PeerBlockchainServiceFactory(ServiceConnectionManager httpConnectionManager, - LedgerAccessContextImpl[] accessAbleLedgers) { - this.httpConnectionManager = httpConnectionManager; - this.peerServiceProxy = new PeerServiceProxy(accessAbleLedgers); - } - - public void addLedgerAccessContexts(LedgerAccessContextImpl[] accessContexts) { - this.peerServiceProxy.addLedgerAccessContexts(accessContexts); - } - - @Override - public BlockchainService getBlockchainService() { - return peerServiceProxy; - } - - /** - * 返回交易服务; - * - *
- * - * 返回的交易服务聚合了该节点绑定的多个账本的交易服务,并根据交易请求中指定的目标账本选择相应的交易服务进行转发; - * - * @return - */ - public TransactionService getTransactionService() { - return peerServiceProxy; - } - - /** - * 连接到指定的共识节点; - * - * @param peerAddr - * 提供对网关接入认证的节点的认证地址列表;
- * 按列表的先后顺序连接节点进行认证,从第一个成功通过的节点请求整个区块链网络的拓扑配置,并建立起和整个区块链网络的连接;
- * 此参数指定的节点列表可以是整个区块链网络的全部节点的子集,而不必包含所有节点; - * - * @return 区块链服务工厂实例; - */ - public static PeerBlockchainServiceFactory connect(AsymmetricKeypair gatewayKey, NetworkAddress peerAddr, List peerProviders) { - - if (peerProviders == null || peerProviders.isEmpty()) { - throw new AuthenticationException("No peer Provider was set!"); - } - ClientIdentificationsProvider authIdProvider = authIdProvider(gatewayKey, peerProviders); - - GatewayIncomingSetting incomingSetting = auth(peerAddr, authIdProvider); - - if (incomingSetting == null) { - throw new AuthenticationException("No peer was succeed authenticating from!"); - } - - PeerBlockchainServiceFactory factory = null; - - ServiceConnectionManager httpConnectionManager; - - PeerManageService peerManageService; - - if (peerBlockchainServiceFactories.containsKey(peerAddr)) { - factory = peerBlockchainServiceFactories.get(peerAddr); - httpConnectionManager = factory.httpConnectionManager; - } else { - httpConnectionManager = new ServiceConnectionManager(); - } - - if (peerManageServices.containsKey(peerAddr)) { - peerManageService = peerManageServices.get(peerAddr); - } else { - ServiceConnection httpConnection = httpConnectionManager.create(new ServiceEndpoint(peerAddr)); - peerManageService = new PeerManageService(httpConnection, - HttpServiceAgent.createService(HttpBlockchainQueryService.class, - httpConnection, null)); - peerManageServices.put(peerAddr, peerManageService); - } - - LedgerIncomingSetting[] ledgerSettings = incomingSetting.getLedgers(); - // 判断当前节点对应账本是否一致 - List needInitSettings = new ArrayList<>(); - for (LedgerIncomingSetting setting : ledgerSettings) { - HashDigest currLedgerHash = setting.getLedgerHash(); - if (!accessContextMap.containsKey(currLedgerHash)) { - needInitSettings.add(setting); - } - } - - if (!needInitSettings.isEmpty()) { - LedgerAccessContextImpl[] accessAbleLedgers = new LedgerAccessContextImpl[needInitSettings.size()]; - BlockchainQueryService queryService = peerManageService.getQueryService(); - - for (int i = 0; i < needInitSettings.size(); i++) { - LedgerIncomingSetting ledgerSetting = needInitSettings.get(i); - String providerName = ledgerSetting.getProviderName(); - ConsensusProvider provider = ConsensusProviders.getProvider(providerName); - byte[] clientSettingBytes = ByteArray.fromBase64(ledgerSetting.getClientSetting()); - - ClientIncomingSettings clientIncomingSettings = provider.getSettingsFactory().getIncomingSettingsEncoder().decode(clientSettingBytes); - ClientFactory clientFactory = provider.getClientFactory(); - ClientSettings clientSettings = clientFactory.buildClientSettings(clientIncomingSettings); - ConsensusClient consensusClient = clientFactory.setupClient(clientSettings); - - TransactionService autoSigningTxProcService = enableGatewayAutoSigning(gatewayKey, - ledgerSetting.getCryptoSetting(), consensusClient); - - LedgerAccessContextImpl accCtx = new LedgerAccessContextImpl(); - accCtx.ledgerHash = ledgerSetting.getLedgerHash(); - accCtx.cryptoSetting = ledgerSetting.getCryptoSetting(); - accCtx.queryService = queryService; - accCtx.txProcService = autoSigningTxProcService; - accCtx.consensusClient = consensusClient; - - accessAbleLedgers[i] = accCtx; - - accessContextMap.put(accCtx.ledgerHash, accCtx); - } - if (factory == null) { - factory = new PeerBlockchainServiceFactory(httpConnectionManager, - accessAbleLedgers); - peerBlockchainServiceFactories.put(peerAddr, factory); - } else { - factory.addLedgerAccessContexts(accessAbleLedgers); - } -// PeerBlockchainServiceFactory factory = new PeerBlockchainServiceFactory(httpConnectionManager, -// accessAbleLedgers); - } - - - -// ServiceConnectionManager httpConnectionManager = new ServiceConnectionManager(); -// ServiceConnection httpConnection = httpConnectionManager.create(new ServiceEndpoint(peerAddr)); -// BlockchainQueryService queryService = HttpServiceAgent.createService(HttpBlockchainQueryService.class, -// httpConnection, null); -// -// LedgerIncomingSetting[] ledgerSettings = incomingSetting.getLedgers(); -// -// LedgerAccessContextImpl[] accessAbleLedgers = new LedgerAccessContextImpl[ledgerSettings.length]; -// for (int i = 0; i < ledgerSettings.length; i++) { -// LedgerIncomingSetting ledgerSetting = ledgerSettings[i]; -// String providerName = ledgerSetting.getProviderName(); -// ConsensusProvider provider = ConsensusProviders.getProvider(providerName); -// byte[] clientSettingBytes = ByteArray.fromBase64(ledgerSetting.getClientSetting()); -// -// ClientIncomingSettings clientIncomingSettings = provider.getSettingsFactory().getIncomingSettingsEncoder().decode(clientSettingBytes); -// ClientFactory clientFactory = provider.getClientFactory(); -// ClientSettings clientSettings = clientFactory.buildClientSettings(clientIncomingSettings); -// ConsensusClient consensusClient = clientFactory.setupClient(clientSettings); -// -// TransactionService autoSigningTxProcService = enableGatewayAutoSigning(gatewayKey, -// ledgerSetting.getCryptoSetting(), consensusClient); -// -// -// LedgerAccessContextImpl accCtx = new LedgerAccessContextImpl(); -// accCtx.ledgerHash = ledgerSetting.getLedgerHash(); -// accCtx.cryptoSetting = ledgerSetting.getCryptoSetting(); -// accCtx.queryService = queryService; -// accCtx.txProcService = autoSigningTxProcService; -// accCtx.consensusClient = consensusClient; -// -// accessAbleLedgers[i] = accCtx; -// -// accessContextMap.put(accCtx.ledgerHash, accCtx); -// } -// -// PeerBlockchainServiceFactory factory = new PeerBlockchainServiceFactory(httpConnectionManager, -// accessAbleLedgers); - return factory; - } - - private static GatewayIncomingSetting auth(NetworkAddress peerAuthAddr, ClientIdentifications authIds) { - try { - ManagementHttpService gatewayMngService = getGatewayManageService(peerAuthAddr); - - // 接入认证,获得接入配置; - // 传递网关账户地址及签名; - GatewayIncomingSetting incomingSetting = gatewayMngService.authenticateGateway(authIds); - return incomingSetting; - } catch (Exception e) { - LOGGER.warn("Cann't authenticate gateway incoming from peer[" + peerAuthAddr.toString() + "]!--" - + e.getMessage(), e); - return null; - } - } - - private static ManagementHttpService getGatewayManageService(NetworkAddress peer) { - ServiceEndpoint peerServer = new ServiceEndpoint(peer.getHost(), peer.getPort(), false); - ManagementHttpService gatewayMngService = HttpServiceAgent.createService(ManagementHttpService.class, - peerServer); - return gatewayMngService; - } - - /** - * 启用网关自动签名; - * - * @param nodeKeyPair - * @param cryptoSetting - * @return - */ - private static TransactionService enableGatewayAutoSigning(AsymmetricKeypair nodeKeyPair, CryptoSetting cryptoSetting, - ConsensusClient consensusClient) { - NodeSigningAppender signingAppender = new NodeSigningAppender(cryptoSetting.getHashAlgorithm(), - nodeKeyPair, consensusClient); - return signingAppender.init(); - } - - @Override - public void close() { - try { - for (Map.Entry entry : accessContextMap.entrySet()) { - LedgerAccessContextImpl ctx = entry.getValue(); - ctx.consensusClient.close(); - } - httpConnectionManager.close(); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static ClientIdentificationsProvider authIdProvider(AsymmetricKeypair gatewayKey, List peerProviders) { - ClientIdentificationsProvider authIdProvider = new ClientIdentificationsProvider(); - for (String peerProvider : peerProviders) { - ConsensusProvider provider = ConsensusProviders.getProvider(peerProvider); - ClientFactory clientFactory = provider.getClientFactory(); - ClientIdentification authId = clientFactory.buildAuthId(gatewayKey); - authIdProvider.add(authId); - } - return authIdProvider; - } - - private static class LedgerAccessContextImpl implements LedgerAccessContext { - - private HashDigest ledgerHash; - - private CryptoSetting cryptoSetting; - - private TransactionService txProcService; - - private BlockchainQueryService queryService; - - private ConsensusClient consensusClient; - - @Override - public HashDigest getLedgerHash() { - return ledgerHash; - } - - @Override - public CryptoSetting getCryptoSetting() { - return cryptoSetting; - } - - @Override - public TransactionService getTransactionService() { - return txProcService; - } - - @Override - public BlockchainQueryService getQueryService() { - return queryService; - } - - } - - private static final class PeerManageService { - - public PeerManageService(ServiceConnection httpConnection, BlockchainQueryService queryService) { - this.httpConnection = httpConnection; - this.queryService = queryService; - } - - ServiceConnection httpConnection; - - BlockchainQueryService queryService; - - public ServiceConnection getHttpConnection() { - return httpConnection; - } - - public void setHttpConnection(ServiceConnection httpConnection) { - this.httpConnection = httpConnection; - } - - public BlockchainQueryService getQueryService() { - return queryService; - } - - public void setQueryService(BlockchainQueryService queryService) { - this.queryService = queryService; - } - } - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/PeerServiceProxy.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/PeerServiceProxy.java deleted file mode 100644 index 535b45f5..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/PeerServiceProxy.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.jd.blockchain.sdk.service; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.sdk.BlockchainException; -import com.jd.blockchain.sdk.LedgerAccessContext; -import com.jd.blockchain.sdk.proxy.BlockchainServiceProxy; -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.TransactionService; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * 对共识节点的区块链服务代理; - * - * @author huanghaiquan - * - */ -public class PeerServiceProxy extends BlockchainServiceProxy implements TransactionService { - - private final Lock accessLock = new ReentrantLock(); - - /** - * 许可的账本以及交易列表; - */ - private Map ledgerAccessContexts; - - public PeerServiceProxy(LedgerAccessContext[] accessAbleLedgers) { - this.ledgerAccessContexts = new HashMap<>(); - for (LedgerAccessContext lac : accessAbleLedgers) { - if (ledgerAccessContexts.containsKey(lac.getLedgerHash())) { - throw new IllegalArgumentException( - String.format("Ledger repeatly! --[LedgerHash=%s]", lac.getLedgerHash().toBase58())); - } - ledgerAccessContexts.put(lac.getLedgerHash(), lac); - } - } - - public void addLedgerAccessContexts(LedgerAccessContext[] accessAbleLedgers) { - try { - accessLock.lock(); - if (this.ledgerAccessContexts == null) { - throw new IllegalArgumentException("LedgerAccessContexts is null, you need init first !!!"); - } - for (LedgerAccessContext lac : accessAbleLedgers) { - if (!ledgerAccessContexts.containsKey(lac.getLedgerHash())) { - ledgerAccessContexts.put(lac.getLedgerHash(), lac); - } - } - } finally { - accessLock.unlock(); - } - } - - @Override - protected TransactionService getTransactionService(HashDigest ledgerHash) { - return getLedgerAccessContext(ledgerHash).getTransactionService(); - } - - @Override - protected BlockchainQueryService getQueryService(HashDigest ledgerHash) { - return getLedgerAccessContext(ledgerHash).getQueryService(); - } - - private LedgerAccessContext getLedgerAccessContext(HashDigest ledgerHash) { - LedgerAccessContext lac = ledgerAccessContexts.get(ledgerHash); - if (lac == null) { - throw new BlockchainException("Unsupported access ledger[" + ledgerHash.toBase58() + "] !"); - } - return lac; - } - - @Override - public HashDigest[] getLedgerHashs() { - return ledgerAccessContexts.keySet().toArray(new HashDigest[ledgerAccessContexts.size()]); - } - - /** - * 处理网关的交易转发; - */ - @Override - public TransactionResponse process(TransactionRequest txRequest) { - TransactionService targetTxService = getTransactionService(txRequest.getTransactionContent().getLedgerHash()); - return targetTxService.process(txRequest); - } -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/TransactionRequestMessageConverter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/TransactionRequestMessageConverter.java deleted file mode 100644 index 9a192577..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/TransactionRequestMessageConverter.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jd.blockchain.sdk.service; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.consensus.BinaryMessageConverter; -import com.jd.blockchain.ledger.TransactionRequest; - -public class TransactionRequestMessageConverter implements BinaryMessageConverter { - - @Override - public byte[] encode(Object message) { - return BinaryProtocol.encode(message, TransactionRequest.class); - } - - @Override - public Object decode(byte[] messageBytes) { - return BinaryProtocol.decode(messageBytes); - } - -} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/TransactionResponseMessageConverter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/TransactionResponseMessageConverter.java deleted file mode 100644 index 01a36973..00000000 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/service/TransactionResponseMessageConverter.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jd.blockchain.sdk.service; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.consensus.BinaryMessageConverter; -import com.jd.blockchain.ledger.TransactionResponse; - -public class TransactionResponseMessageConverter implements BinaryMessageConverter { - - @Override - public byte[] encode(Object message) { - return BinaryProtocol.encode(message, TransactionResponse.class); - } - - @Override - public Object decode(byte[] messageBytes) { - return BinaryProtocol.decode(messageBytes); - } - -} diff --git a/source/sdk/sdk-base/src/test/java/test/com/jd/blockchain/sdk/proxy/BlockchainServiceProxyTest.java b/source/sdk/sdk-base/src/test/java/test/com/jd/blockchain/sdk/proxy/BlockchainServiceProxyTest.java deleted file mode 100644 index 6387bd48..00000000 --- a/source/sdk/sdk-base/src/test/java/test/com/jd/blockchain/sdk/proxy/BlockchainServiceProxyTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package test.com.jd.blockchain.sdk.proxy; - -public class BlockchainServiceProxyTest { - -// private static class ArgCaptorMatcher extends CustomMatcher { -// -// private T arg; -// -// public ArgCaptorMatcher() { -// super("OK"); -// } -// -// @Override -// public boolean matches(Object item) { -// this.arg = (T) item; -// return true; -// } -// -// public T getArg() { -// return arg; -// } -// } -// -// @Test -// public void testRegisterAccount() throws IOException { -// -// BlockchainKeyPair gatewayAccount = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519); -// BlockchainKeyPair sponsorAccount = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519); -// BlockchainKeyPair subjectAccount = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519); -// long sequenceNumber = 110; -// -// ArgCaptorMatcher txReqCaptor = new ArgCaptorMatcher<>(); -// -// TransactionService consensusService = Mockito.mocker(TransactionService.class); -// BlockchainQueryService queryService = Mockito.mocker(BlockchainQueryService.class); -// -// HashDigest txContentHash =CryptoUtils.hash(CryptoAlgorithm.SHA_256).hash(UUID.randomUUID().toString().getBytes("UTF-8")); -// TxResponseMessage expectedResponse = new TxResponseMessage(txContentHash); -// expectedResponse.setExecutionState(ExecutionState.SUCCESS); -// -// when(consensusService.process(argThat(txReqCaptor))).thenReturn(expectedResponse); -// -// HashDigest ledgerHash = CryptoUtils.hash(CryptoAlgorithm.SHA_256).hash(UUID.randomUUID().toString().getBytes("UTF-8")); -// -// BlockchainTransactionService serviceProxy = new BlockchainServiceProxy(consensusService, queryService); -// -// TransactionTemplate txTemplate = serviceProxy.newTransaction(ledgerHash); -// txTemplate.setSubject(subjectAccount.getAddress(), sequenceNumber); -// -// BlockchainKeyPair regAccountKeyPair = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519); -// AccountStateType stateType = AccountStateType.MAP; -// txTemplate.users().register(regAccountKeyPair.getIdentity(), stateType); -// -// PreparedTransaction prepTx = txTemplate.prepare(); -// HashDigest txHash = prepTx.getHash(); -// prepTx.sign(sponsorAccount); -// -// TransactionResponse result = prepTx.commit(); -// -// // 验证; -// // 仅被提交一次; -// verify(consensusService, times(1)).process(any()); -// -// assertEquals(ExecutionState.SUCCESS, result.getExecutionState()); -// -// // 验证内容; -// TransactionRequest resolvedTxRequest = txReqCaptor.getArg(); -// -// TransactionContent resolvedTxContent = resolvedTxRequest.getTransactionContent(); -// -// assertEquals(txHash, resolvedTxContent.getHash()); -// -// assertEquals(subjectAccount.getAddress(), resolvedTxContent.getSubjectAccount()); -// assertEquals(sequenceNumber, resolvedTxContent.getSequenceNumber()); -// -// -// Operation[] resolvedOps = resolvedTxContent.getOperations(); -// assertEquals(1, resolvedOps.length); -// Operation resolvedOP = resolvedOps[0]; -//// assertEquals(OperationType.REGISTER_USER.CODE, resolvedOP.getCode()); -// -// UserRegisterOpTemplate accRegOP = new UserRegisterOpTemplate(); -// accRegOP.resolvFrom((OpBlob) resolvedOP); -// -// assertEquals(regAccountKeyPair.getAddress(), accRegOP.getId().getAddress()); -// assertEquals(regAccountKeyPair.getPubKey().getType(), accRegOP.getId().getPubKey().getType()); -// assertEquals(regAccountKeyPair.getPubKey().getValue(), accRegOP.getId().getPubKey().getValue()); -// assertEquals(stateType, accRegOP.getStateType()); -// } - -} diff --git a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/ClientResolveUtil.java b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/ClientResolveUtil.java deleted file mode 100644 index 72cd4cb8..00000000 --- a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/ClientResolveUtil.java +++ /dev/null @@ -1,385 +0,0 @@ -///** -// * Copyright: Copyright 2016-2020 JD.COM All Right Reserved -// * FileName: com.jd.blockchain.sdk.client.ClientResolveUtil -// * Author: shaozhuguang -// * Department: Y事业部 -// * Date: 2019/3/27 下午4:12 -// * Description: -// */ -//package com.jd.blockchain.sdk.client; -// -//import java.lang.reflect.Field; -// -//import com.jd.blockchain.ledger.*; -//import com.jd.blockchain.utils.io.ByteArray; -//import org.apache.commons.codec.binary.Base64; -// -//import com.alibaba.fastjson.JSONArray; -//import com.alibaba.fastjson.JSONObject; -//import com.jd.blockchain.crypto.CryptoProvider; -//import com.jd.blockchain.crypto.PubKey; -//import com.jd.blockchain.transaction.ContractCodeDeployOpTemplate; -//import com.jd.blockchain.transaction.ContractEventSendOpTemplate; -//import com.jd.blockchain.transaction.DataAccountKVSetOpTemplate; -//import com.jd.blockchain.transaction.DataAccountRegisterOpTemplate; -//import com.jd.blockchain.transaction.KVData; -//import com.jd.blockchain.transaction.LedgerInitOpTemplate; -//import com.jd.blockchain.transaction.LedgerInitSettingData; -//import com.jd.blockchain.transaction.UserRegisterOpTemplate; -//import com.jd.blockchain.utils.Bytes; -//import com.jd.blockchain.utils.codec.Base58Utils; -//import com.jd.blockchain.utils.codec.HexUtils; -//import com.jd.blockchain.utils.io.BytesUtils; -// -///** -// * -// * @author shaozhuguang -// * @create 2019/3/27 -// * @since 1.0.0 -// */ -// -//public class ClientResolveUtil { -// -// public static KVDataEntry[] read(KVDataEntry[] kvDataEntries) { -// if (kvDataEntries == null || kvDataEntries.length == 0) { -// return kvDataEntries; -// } -// KVDataEntry[] resolveKvDataEntries = new KVDataEntry[kvDataEntries.length]; -// // kvDataEntries是代理对象,需要处理 -// for (int i = 0; i < kvDataEntries.length; i++) { -// KVDataEntry kvDataEntry = kvDataEntries[i]; -// String key = kvDataEntry.getKey(); -// long version = kvDataEntry.getVersion(); -// DataType dataType = kvDataEntry.getType(); -// KvData innerKvData = new KvData(key, version, dataType); -// Object valueObj = kvDataEntry.getValue(); -// switch (dataType) { -// case NIL: -// break; -// case BYTES: -// case TEXT: -// case JSON: -// innerKvData.setValue(valueObj.toString()); -// break; -// case INT32: -// innerKvData.setValue(Integer.parseInt(valueObj.toString())); -// break; -// case INT64: -// innerKvData.setValue(Long.parseLong(valueObj.toString())); -// break; -// default: -// throw new IllegalStateException("Unsupported value type[" + dataType + "] to resolve!"); -// } -// resolveKvDataEntries[i] = innerKvData; -// } -// return resolveKvDataEntries; -// } -// -// public static Operation read(Operation operation) { -// -// try { -// // Class -// Class clazz = operation.getClass(); -// Field field = clazz.getSuperclass().getDeclaredField("h"); -// field.setAccessible(true); -// Object object = field.get(operation); -// if (object instanceof JSONObject) { -// JSONObject jsonObject = (JSONObject) object; -// if (jsonObject.containsKey("accountID")) { -// return convertDataAccountRegisterOperation(jsonObject); -// } else if (jsonObject.containsKey("userID")) { -// return convertUserRegisterOperation(jsonObject); -// } else if (jsonObject.containsKey("contractID")) { -// return convertContractCodeDeployOperation(jsonObject); -// } else if (jsonObject.containsKey("writeSet")) { -// return convertDataAccountKVSetOperation(jsonObject); -// } else if (jsonObject.containsKey("initSetting")) { -// return convertLedgerInitOperation(jsonObject); -// } else if (jsonObject.containsKey("contractAddress")) { -// return convertContractEventSendOperation(jsonObject); -// } -// } -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// -// return null; -// } -// -// public static Object readValueByBytesValue(BytesValue bytesValue) { -// DataType dataType = bytesValue.getType(); -// Bytes saveVal = bytesValue.getValue(); -// Object showVal; -// switch (dataType) { -// case BYTES: -// // return hex -// showVal = HexUtils.encode(saveVal.toBytes()); -// break; -// case TEXT: -// case JSON: -// showVal = saveVal.toUTF8String(); -// break; -// case INT64: -// showVal = BytesUtils.toLong(saveVal.toBytes()); -// break; -// default: -// showVal = HexUtils.encode(saveVal.toBytes()); -// break; -// } -// return showVal; -// } -// -// public static DataAccountRegisterOperation convertDataAccountRegisterOperation(JSONObject jsonObject) { -// JSONObject account = jsonObject.getJSONObject("accountID"); -// return new DataAccountRegisterOpTemplate(blockchainIdentity(account)); -// } -// -// public static DataAccountKVSetOperation convertDataAccountKVSetOperation(JSONObject jsonObject) { -// // 写入集合处理 -// JSONArray writeSetObj = jsonObject.getJSONArray("writeSet"); -// JSONObject accountAddrObj = jsonObject.getJSONObject("accountAddress"); -// String addressBase58 = accountAddrObj.getString("value"); -// Bytes address = Bytes.fromBase58(addressBase58); -// -// DataAccountKVSetOpTemplate kvOperation = new DataAccountKVSetOpTemplate(address); -// for (int i = 0; i connectionFactoryMap = new ConcurrentHashMap<>(); - - private static Logger LOGGER = LoggerFactory.getLogger(CompositeConnectionFactory.class); - - public CompositeConnectionFactory() { - init(); - } - - private void init() { - // 初始化所有实现类 - Reflections reflections = new Reflections("com.jd.blockchain.storage.service"); - - Set> connectionSet = - reflections.getSubTypesOf(DbConnectionFactory.class); - - for (Class clazz : connectionSet) { - if (clazz.equals(CompositeConnectionFactory.class)) { - continue; - } else { - try { - // 根据class生成对象 - DbConnectionFactory dbConnectionFactory = clazz.newInstance(); - String dbPrefix = dbConnectionFactory.dbPrefix(); - if (dbPrefix != null && dbPrefix.length() > 0 && - !connectionFactoryMap.containsKey(dbPrefix)) { - connectionFactoryMap.put(dbPrefix, dbConnectionFactory); - } - } catch (Exception e) { - LOGGER.error("class:{} init error {}", clazz.getName(), e.getMessage()); - } - } - } - } - - - @Override - public DbConnection connect(String dbUri) { - return connect(dbUri, null); - } - - @Override - public DbConnection connect(String dbConnectionString, String password) { - if (connectionFactoryMap.isEmpty()) { - throw new IllegalArgumentException("DB connections is empty, please init first!"); - } - - for (Map.Entry entry : connectionFactoryMap.entrySet()) { - String prefix = entry.getKey(); - if (dbConnectionString.startsWith(prefix)) { - return entry.getValue().connect(dbConnectionString, password); - } - } - - throw new IllegalArgumentException("Illegal format of composite db connection string!"); - } - - @Override - public void close() { - if (!connectionFactoryMap.isEmpty()) { - for (Map.Entry entry : connectionFactoryMap.entrySet()) { - DbConnectionFactory dbConnectionFactory = entry.getValue(); - dbConnectionFactory.close(); - } - } - } - - @Override - public String dbPrefix() { - return null; - } - - @Override - public boolean support(String scheme) { - if (!connectionFactoryMap.isEmpty()) { - for (Map.Entry entry : connectionFactoryMap.entrySet()) { - DbConnectionFactory dbConnectionFactory = entry.getValue(); - if (dbConnectionFactory.support(scheme)) { - return true; - } - } - } - return false; - } -} diff --git a/source/storage/storage-composite/src/main/java/com/jd/blockchain/storage/service/impl/composite/CompositeStorageConfiguration.java b/source/storage/storage-composite/src/main/java/com/jd/blockchain/storage/service/impl/composite/CompositeStorageConfiguration.java deleted file mode 100644 index 34dd4633..00000000 --- a/source/storage/storage-composite/src/main/java/com/jd/blockchain/storage/service/impl/composite/CompositeStorageConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.storage.service.impl.composite; - -import com.jd.blockchain.storage.service.DbConnectionFactory; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -/** - * Created by zhangshuang3 on 2018/11/26. - */ -@Configuration -@ComponentScan -public class CompositeStorageConfiguration { - - @ConditionalOnMissingBean - @Bean - public DbConnectionFactory compositeConnectionFactory() { - return new CompositeConnectionFactory(); - } -} diff --git a/source/storage/storage-composite/src/main/resources/META-INF/spring.factories b/source/storage/storage-composite/src/main/resources/META-INF/spring.factories deleted file mode 100644 index fd709f72..00000000 --- a/source/storage/storage-composite/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.jd.blockchain.storage.service.impl.composite.CompositeStorageConfiguration \ No newline at end of file diff --git a/source/storage/storage-composite/src/test/java/test/com/jd/blockchain/storage/service/impl/composite/CompositeConnectionFactoryTest.java b/source/storage/storage-composite/src/test/java/test/com/jd/blockchain/storage/service/impl/composite/CompositeConnectionFactoryTest.java deleted file mode 100644 index 661192ed..00000000 --- a/source/storage/storage-composite/src/test/java/test/com/jd/blockchain/storage/service/impl/composite/CompositeConnectionFactoryTest.java +++ /dev/null @@ -1,110 +0,0 @@ -//package test.com.jd.blockchain.storage.service.impl.composite; -//import static org.junit.Assert.*; -// -//import com.jd.blockchain.storage.service.DbConnection; -//import com.jd.blockchain.storage.service.ExPolicyKVStorage; -//import com.jd.blockchain.storage.service.VersioningKVStorage; -//import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -//import com.jd.blockchain.utils.Bytes; -//import com.jd.blockchain.utils.io.BytesUtils; -//import com.jd.blockchain.utils.io.FileUtils; -// -//import org.junit.Test; -// -//import java.io.File; -//import java.util.regex.Pattern; -// -//public class CompositeConnectionFactoryTest { -// -// public static final Pattern URI_PATTER_REDIS = Pattern -// .compile("^\\w+\\://(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:\\d+(/\\d*(/.*)*)?$"); -// -// @Test -// public void testRedisConnectionString() { -// String connStr = "redis://192.168.86.130:6379/"; -// boolean match = URI_PATTER_REDIS.matcher(connStr).matches(); -// assertTrue(match); -// -// connStr = "redis://192.168.86.131:6379/"; -// match = URI_PATTER_REDIS.matcher(connStr).matches(); -// assertTrue(match); -// -// connStr = "redis://192.168.86.132:6379/"; -// match = URI_PATTER_REDIS.matcher(connStr).matches(); -// assertTrue(match); -// -// connStr = "redis://192.168.86.133:6379/"; -// match = URI_PATTER_REDIS.matcher(connStr).matches(); -// assertTrue(match); -// } -// -// @Test -// public void testRocksDbConnect() { -// String dbUri = initEmptyDB("rocksdb_storage_test"); -// long expectedVersion; -// try (CompositeConnectionFactory dbConnFactory = new CompositeConnectionFactory()) { -//// try (CompositeConnectionFactory dbConnFactory = CompositeConnectionFactory.getInstance()) { -// DbConnection conn = dbConnFactory.connect(dbUri); -// VersioningKVStorage verStorage = conn.getStorageService().getVersioningKVStorage(); -// ExPolicyKVStorage exStorage = conn.getStorageService().getExPolicyKVStorage(); -// -// expectedVersion = test(verStorage); -// -// test(exStorage); -// } -// } -// private String initEmptyDB(String name) { -// String currDir = FileUtils.getCurrentDir(); -// String dbDir = new File(currDir, name + ".db").getAbsolutePath(); -// FileUtils.deleteFile(dbDir); -// String dbURI = "rocksdb://" + dbDir; -// return dbURI; -// } -// private long test(VersioningKVStorage verStorage) { -// String key = "k1"; -// long v = verStorage.getVersion(Bytes.fromString(key)); -// assertEquals(-1, v); -// byte[] data = verStorage.get(Bytes.fromString(key), -1); -// assertNull(data); -// data = verStorage.get(Bytes.fromString(key), 0); -// assertNull(data); -// data = verStorage.get(Bytes.fromString(key), 1); -// assertNull(data); -// -// data = BytesUtils.toBytes("data"); -// v = verStorage.set(Bytes.fromString(key), data, -1); -// assertEquals(0, v); -// v = verStorage.set(Bytes.fromString(key), data, -1); -// assertEquals(-1, v); -// v = verStorage.set(Bytes.fromString(key), data, 0); -// assertEquals(1, v); -// return v; -// } -// -// private void test(ExPolicyKVStorage exStorage) { -// String key = "kex"; -// assertFalse(exStorage.exist(Bytes.fromString(key))); -// -// byte[] data = exStorage.get(Bytes.fromString(key)); -// assertNull(data); -// -// data = BytesUtils.toBytes("data"); -// assertFalse(exStorage.set(Bytes.fromString(key), data, ExPolicyKVStorage.ExPolicy.EXISTING)); -// -// assertTrue(exStorage.set(Bytes.fromString(key), data, ExPolicyKVStorage.ExPolicy.NOT_EXISTING)); -// assertTrue(exStorage.exist(Bytes.fromString(key))); -// -// assertFalse(exStorage.set(Bytes.fromString(key), data, ExPolicyKVStorage.ExPolicy.NOT_EXISTING)); -// -// assertTrue(exStorage.set(Bytes.fromString(key), data, ExPolicyKVStorage.ExPolicy.EXISTING)); -// assertTrue(exStorage.set(Bytes.fromString(key), data, ExPolicyKVStorage.ExPolicy.EXISTING)); -// assertFalse(exStorage.set(Bytes.fromString(key), data, ExPolicyKVStorage.ExPolicy.NOT_EXISTING)); -// -// assertTrue(exStorage.exist(Bytes.fromString(key))); -// -// byte[] reloadData = exStorage.get(Bytes.fromString(key)); -// assertTrue(BytesUtils.equals(data, reloadData)); -// } -// -// -//} diff --git a/source/storage/storage-redis/.gitignore b/source/storage/storage-redis/.gitignore deleted file mode 100644 index da7560e0..00000000 --- a/source/storage/storage-redis/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.apt_generated_tests/ diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/JedisConnection.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/JedisConnection.java deleted file mode 100644 index 27ff22f4..00000000 --- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/JedisConnection.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jd.blockchain.storage.service.impl.redis; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.KVStorageService; - -import redis.clients.jedis.JedisPool; - -public class JedisConnection implements DbConnection { - - private JedisPool jedisPool; - - private RedisStorageService storage; - - public JedisConnection(JedisPool jedisPool) { - this.jedisPool = jedisPool; - this.storage = new RedisStorageService(jedisPool); - } - - @Override - public void close() { -// jedisPool.close(); - } - - @Override - public KVStorageService getStorageService() { - return storage; - } - -} diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisConnectionFactory.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisConnectionFactory.java deleted file mode 100644 index 0c03f94b..00000000 --- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisConnectionFactory.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.jd.blockchain.storage.service.impl.redis; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; - -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.Protocol; - -public class RedisConnectionFactory implements DbConnectionFactory { - - public static final Pattern URI_PATTER = Pattern - .compile("^\\w+\\://(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:\\d+(/\\d*(/.*)*)?$"); - // public static final Pattern URI_PATTER = Pattern - // .compile("^\\w+\\://(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:\\d+(/\\d+)?(/.*)*$"); - - private static final Map connections = new ConcurrentHashMap<>(); - - @Override - public DbConnection connect(String dbUri) { - return connect(dbUri, null); - } - - @Override - public synchronized DbConnection connect(String dbConnectionString, String password) { - - if (connections.containsKey(dbConnectionString)) { - // 暂不处理密码变化问题 - return connections.get(dbConnectionString); - } - - URI dbUri = URI.create(dbConnectionString); - if (!(dbUri.getScheme().equalsIgnoreCase("redis"))) { - throw new IllegalArgumentException( - String.format("Not supported db connection string with scheme \"%s\"!", dbUri.getScheme())); - } - - JedisPoolConfig config = new JedisPoolConfig(); - config.setMaxTotal(500); - config.setMaxIdle(500); - config.setMinIdle(50); - config.setMaxWaitMillis(1000 * 30); - config.setTestOnBorrow(false); - - String host = dbUri.getHost(); - int port = dbUri.getPort(); - int dbId = retriveDbIdFromPath(dbUri.getPath()); - JedisPool pool = new JedisPool(config, host, port, Protocol.DEFAULT_TIMEOUT, password, dbId, false); - JedisConnection jedisConnection = new JedisConnection(pool); - connections.put(dbConnectionString, jedisConnection); - return jedisConnection; - } - - /** - * 从 URI 路径检索数据库 ID ;
- * 预期路径参数的样式为“/{id}”开头,如果忽略路径之后加入的其它节;
- * 如果没有定义数据库ID,或者不符合样式,则返回默认的数据库ID ({@link Protocol#DEFAULT_DATABASE}); - * - * @param uriPath - * @return - */ - private int retriveDbIdFromPath(String uriPath) { - if (uriPath == null || uriPath.length() == 0) { - return Protocol.DEFAULT_DATABASE; - } - int secondIndex = uriPath.indexOf('/', 1); - String idStr; - if (secondIndex < 0) { - idStr = uriPath.substring(1).trim(); - } else { - idStr = uriPath.substring(1, secondIndex).trim(); - } - int dbId = Integer.parseInt(idStr); - if (dbId < 0) { - return Protocol.DEFAULT_DATABASE; - } - return dbId; - } - - @Override - public String dbPrefix() { - return "redis://"; - } - - @Override - public boolean support(String scheme) { - return RedisConsts.URI_SCHEME.equalsIgnoreCase(scheme); - } - - @Override - public void close() { - // TODO:  未实现连接池的关闭; - if (!connections.isEmpty()) { - for (Map.Entry entry : connections.entrySet()) { - try { - entry.getValue().close(); - } catch (IOException e) { - // 打印关闭异常日志 - } - } - } - } -} diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisConsts.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisConsts.java deleted file mode 100644 index 922ccdcc..00000000 --- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisConsts.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.storage.service.impl.redis; - -import redis.clients.util.SafeEncoder; - -public interface RedisConsts { - - public static final String URI_SCHEME = "redis"; - - public static final String OK = "OK"; - - public static final String OK_MULTI = "+OK"; - - byte[] XX = SafeEncoder.encode("XX"); - - byte[] NX = SafeEncoder.encode("NX"); - -} diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisExPolicyStorage.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisExPolicyStorage.java deleted file mode 100644 index 6a5880f2..00000000 --- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisExPolicyStorage.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jd.blockchain.storage.service.impl.redis; - -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.utils.Bytes; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.util.SafeEncoder; - -public class RedisExPolicyStorage implements ExPolicyKVStorage { - - private JedisPool jedisPool; - - public RedisExPolicyStorage(JedisPool jedisPool) { - this.jedisPool = jedisPool; - } - - @Override - public byte[] get(Bytes key) { - try (Jedis jedis = jedisPool.getResource()) { -// byte[] keyBytes = SafeEncoder.encode(key); -// byte[] valueBytes = jedis.get(keyBytes); - byte[] valueBytes = jedis.get(key.toBytes()); - return valueBytes; - } - } - - @Override - public boolean exist(Bytes key) { - try (Jedis jedis = jedisPool.getResource()) { -// byte[] keyBytes = SafeEncoder.encode(key); -// return jedis.exists(keyBytes); - return jedis.exists(key.toBytes()); - } - } - - @Override - public boolean set(Bytes key, byte[] value, ExPolicy ex) { - try (Jedis jedis = jedisPool.getResource()) { - byte[] nxxx; - switch (ex) { - case EXISTING: - nxxx = RedisConsts.XX; - break; - case NOT_EXISTING: - nxxx = RedisConsts.NX; - break; - default: - throw new IllegalArgumentException("Unsupported ExPolicy[" + ex.toString() + "]!"); - } -// byte[] keyBytes = SafeEncoder.encode(key); -// String retn = jedis.set(keyBytes, value, nxxx); - String retn = jedis.set(key.toBytes(), value, nxxx); - return RedisConsts.OK.equalsIgnoreCase(retn); - } - } - - @Override - public void batchBegin() { - // un support!!! - } - - @Override - public void batchCommit() { - // un support!!! - } -} \ No newline at end of file diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisStorageConfiguration.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisStorageConfiguration.java deleted file mode 100644 index ae5a6090..00000000 --- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisStorageConfiguration.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.storage.service.impl.redis; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -import com.jd.blockchain.storage.service.DbConnectionFactory; - -@Configuration -@ComponentScan -public class RedisStorageConfiguration { - -// @Autowired -// private JedisProperties jedisProps; - -// @Bean -// public Jedis jedis() { -// Jedis jedis = new Jedis(jedisProps.getHost(), jedisProps.getPort()); -// jedis.connect(); -// jedis.select(jedisProps.getDb()); -// return jedis; -// } - - @ConditionalOnMissingBean - @Bean - public DbConnectionFactory redisConnectionFactory() { - return new RedisConnectionFactory(); - } - -} diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisVerioningStorage.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisVerioningStorage.java deleted file mode 100644 index 000bb20e..00000000 --- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisVerioningStorage.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.jd.blockchain.storage.service.impl.redis; - -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.DataEntry; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.util.SafeEncoder; - -/** - * 基于 Redis 实现的版本化KV存储; - * - *

- * - * 版本化KV存储要求实现几个关键特性:
- * 1、每个Key都有唯一的版本序列,版本序列从 0 开始;
- * 2、对 Key 值的每一次更改都导致版本增长 1 ;
- * 3、对“写入”和“版本增长”两个操作一起是原子性的;
- * 4、“版本增长”必须以 1 顺序递增,不允许跳空递增;
- * - *

- * 由于 Redis 缺少事务特性,并且无法很好地自定义组合的原子操作( MULTI-EXEC 不适用于集群模式下),所以在此实现中只能做到前面 3 - * 点。
- * 第 4 点由调用方(账本操作层)在调用前做了版本校验,所以从整个系统来看也可以保证以上的4点要求。 - * - * @author huanghaiquan - * - */ -public class RedisVerioningStorage implements VersioningKVStorage { - - private JedisPool jedisPool; - - public RedisVerioningStorage(JedisPool jedisPool) { - this.jedisPool = jedisPool; - } - - @Override - public long getVersion(Bytes key) { - try (Jedis jedis = jedisPool.getResource()) { -// byte[] keyBytes = SafeEncoder.encode(key); -// return jedis.hlen(keyBytes) - 1; - return jedis.hlen(key.toBytes()) - 1; - } - } - - @Override - public DataEntry getEntry(Bytes key, long version) { - byte[] value = get(key, version); - if (value == null) { - return null; - } - return new VersioningKVData(key, version, value); - } - - @Override - public byte[] get(Bytes key, long version) { - try (Jedis jedis = jedisPool.getResource()) { - long ver = version; - if (ver < 0) { - //查询最新; - ver = getVersion(key); - } - if (ver < 0) { - return null; - } -// byte[] keyBytes = SafeEncoder.encode(key); -// byte[] verBytes = encodeVersionKey(ver); -// byte[] value = jedis.hget(keyBytes, verBytes); - byte[] verBytes = encodeVersionKey(ver); - byte[] value = jedis.hget(key.toBytes(), verBytes); - return value; - } - } - - @Override - public long set(Bytes key, byte[] value, long version) { - try (Jedis jedis = jedisPool.getResource()) { -// byte[] keyBytes = SafeEncoder.encode(key); - long ver = version < 0 ? 0 : version + 1; - byte[] verBytes = encodeVersionKey(ver); - // 如果不存在,则写入;由于 Redis 特性的限制,此处无法原子性地校验是 version 参数否存在跳空增长, - // 默认在外部调用已经校验了 version 为最新版本; - Long r = jedis.hsetnx(key.toBytes(), verBytes, value); - return r.longValue() == 0 ? -1 : ver; - } - } - - private byte[] encodeVersionKey(long version) { - return SafeEncoder.encode("" + version); - } - - @Override - public void batchBegin() { - // un support!!! - } - - @Override - public void batchCommit() { - // un support!!! - } - - - private static class VersioningKVData implements DataEntry{ - - private Bytes key; - - private long version; - - private byte[] value; - - public VersioningKVData(Bytes key, long version, byte[] value) { - this.key = key; - this.version = version; - this.value = value; - } - - @Override - public Bytes getKey() { - return key; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public byte[] getValue() { - return value; - } - - } - -} \ No newline at end of file diff --git a/source/storage/storage-redis/src/test/java/test/com/jd/blockchain/storage/service/impl/redis/RedisConnectionFactoryTest.java b/source/storage/storage-redis/src/test/java/test/com/jd/blockchain/storage/service/impl/redis/RedisConnectionFactoryTest.java deleted file mode 100644 index 3f3be4ed..00000000 --- a/source/storage/storage-redis/src/test/java/test/com/jd/blockchain/storage/service/impl/redis/RedisConnectionFactoryTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package test.com.jd.blockchain.storage.service.impl.redis; -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.jd.blockchain.storage.service.impl.redis.RedisConnectionFactory; - -public class RedisConnectionFactoryTest { - - @Test - public void testConnectionString() { - String connStr = "redis://192.168.1.2:6379/1"; - boolean match = RedisConnectionFactory.URI_PATTER.matcher(connStr).matches(); - - connStr = "redis://192.168.1.2:6379/"; - match = RedisConnectionFactory.URI_PATTER.matcher(connStr).matches(); - assertTrue(match); - - connStr = "redis://192.168.1.2:6379"; - match = RedisConnectionFactory.URI_PATTER.matcher(connStr).matches(); - assertTrue(match); - - connStr = "redis://192.168.1.2:6379/33/kkew"; - match = RedisConnectionFactory.URI_PATTER.matcher(connStr).matches(); - assertTrue(match); - - connStr = "redis://192.168.1.2:6379/kkf/"; - match = RedisConnectionFactory.URI_PATTER.matcher(connStr).matches(); - assertFalse(match); - } - -} diff --git a/source/storage/storage-redis/src/test/java/test/com/jd/blockchain/storage/service/impl/redis/Test.java b/source/storage/storage-redis/src/test/java/test/com/jd/blockchain/storage/service/impl/redis/Test.java deleted file mode 100644 index 56828f51..00000000 --- a/source/storage/storage-redis/src/test/java/test/com/jd/blockchain/storage/service/impl/redis/Test.java +++ /dev/null @@ -1,88 +0,0 @@ -package test.com.jd.blockchain.storage.service.impl.redis; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.impl.redis.RedisConnectionFactory; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; - -import redis.clients.jedis.Jedis; - -public class Test { - - public static void main(String[] args) { - - Bytes key = Bytes.fromString("test111"); - try (Jedis jedis = new Jedis("192.168.151.33", 6379)) { - jedis.connect(); - byte[] kbytes = key.toBytes();// BytesUtils.toBytes(key, "UTF-8"); - byte[] valueBytes = jedis.get(kbytes); - String value = BytesUtils.toString(valueBytes, "UTF-8"); - System.out.println(String.format("%s=%s", key, value)); - } - System.out.println("================================="); - - System.out.println("================= test expolicy storage ================="); - - RedisConnectionFactory connFactory = new RedisConnectionFactory(); - try(DbConnection conn = connFactory.connect("redis://192.168.151.33:6379")){ - ExPolicyKVStorage exKVStorage = conn.getStorageService().getExPolicyKVStorage(); - byte[] valueBytes = exKVStorage.get(key); - String value = BytesUtils.toString(valueBytes, "UTF-8"); - System.out.println(String.format("%s=%s", key, value)); - - System.out.println(String.format("%s=%s", key, value)); - boolean success = exKVStorage.set(key, BytesUtils.toBytes("New Value by ExPolicyStorage interface..."), ExPolicy.NOT_EXISTING); - System.out.println("update key when NX " + (success ? "success" : "fail")); - success = exKVStorage.set(key, BytesUtils.toBytes("New Value by ExPolicyStorage interface..."), ExPolicy.EXISTING); - System.out.println("update key when XX " + (success ? "success" : "fail")); - - valueBytes = exKVStorage.get(key); - value = BytesUtils.toString(valueBytes, "UTF-8"); - System.out.println(String.format("Retrieve... %s=%s", key, value)); - }catch(Exception ex) { - ex.printStackTrace(); - } - System.out.println("================================="); - - try(DbConnection conn = connFactory.connect("redis://192.168.151.33:6379/0")){ - ExPolicyKVStorage exKVStorage = conn.getStorageService().getExPolicyKVStorage(); - byte[] valueBytes = exKVStorage.get(key); - String value = BytesUtils.toString(valueBytes, "UTF-8"); - System.out.println(String.format("%s=%s", key, value)); - }catch(Exception ex) { - ex.printStackTrace(); - } - System.out.println("================================="); - - System.out.println("================= test versioning storage ================="); - Bytes addr =Bytes.fromString("User001"); - try(DbConnection conn = connFactory.connect("redis://192.168.151.33:6379/0")){ - VersioningKVStorage verStorage = conn.getStorageService().getVersioningKVStorage(); - long version = verStorage.getVersion(addr); - System.out.println(String.format("Version of key[%s]=%s", addr, version)); - byte[] v1 = BytesUtils.toBytes("value-" + version); - version = verStorage.set(addr, v1, version); - System.out.println(String.format("Update[%s] to V1, version=%s", addr, version)); - byte[] v2 = BytesUtils.toBytes("value-" + version); - version = verStorage.set(addr, v2, version); - System.out.println(String.format("Update[%s] to V2, version=%s", addr, version)); - byte[] v3 = BytesUtils.toBytes("value-" + version); - version = verStorage.set(addr, v3, version); - System.out.println(String.format("Update[%s] to V3, version=%s", addr, version)); - - version = verStorage.getVersion(addr); - System.out.println(String.format("Now the latest version of key[%s]=%s", addr, version)); - for (int i = 0; i <=version; i++) { - String value = BytesUtils.toString(verStorage.get(addr, i)); - System.out.println(String.format("The version[%s] value of key[%s] is :%s", i, addr, value)); - } - }catch(Exception ex) { - ex.printStackTrace(); - } - System.out.println("================================="); - } - -} diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/demo/rocksdb/RocksDBDemo.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/demo/rocksdb/RocksDBDemo.java deleted file mode 100644 index 61425ad1..00000000 --- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/demo/rocksdb/RocksDBDemo.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.jd.blockchain.storage.service.demo.rocksdb; - -import java.io.File; -import java.util.LinkedList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinTask; -import java.util.concurrent.RecursiveAction; - -import org.rocksdb.Options; -import org.rocksdb.RocksDB; -import org.rocksdb.RocksDBException; -import org.rocksdb.TransactionDB; -import org.rocksdb.TransactionDBOptions; - -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.security.ShaUtils; - -public class RocksDBDemo { - - private static String DB_PATH = "/Users/huanghaiquan/Documents/jd/projects/prototype/source/storage/storage-rocksdb/target/myrocks.db"; - private static String DB_0_PATH = "/Users/huanghaiquan/Documents/jd/projects/prototype/source/storage/storage-rocksdb/target/myrocks_0.db"; - private static String DB_1_PATH = "/Users/huanghaiquan/Documents/jd/projects/prototype/source/storage/storage-rocksdb/target/myrocks_1.db"; - - static { - RocksDB.loadLibrary(); - } - - private static Random rand = new Random(); - - - private static String initEmptyDB(String name) { - String currDir = FileUtils.getCurrentDir(); - String dbDir = new File(currDir, name + ".db").getAbsolutePath(); - FileUtils.deleteFile(dbDir); - return dbDir; - -// String dbURI = "rocksdb://" + dbDir; -// return dbURI; - - } - - - public static void main_test(String[] args) { - - DB_PATH = initEmptyDB("myrocks"); - - // the Options class contains a set of configurable DB options - // that determines the behaviour of the database. - try (final Options options = new Options(); ) { - options.setCreateIfMissing(true); - // a factory method that returns a RocksDB instance - try (final RocksDB db = RocksDB.open(options, DB_PATH)) { - // try (final TransactionDB db = - // TransactionDB.open(options, txnDbOptions, DB_PATH)) { - - // try (final RocksDB db0 = RocksDB.open(options, DB_0_PATH); - // final RocksDB db1 = RocksDB.open(options, DB_1_PATH)) { -// RocksDB[] dbs = { db0, db1 }; -// ConsoleUtils.info("simple test in db0"); -// simple_test(db0); -// ConsoleUtils.info("simple test in db1"); -// simple_test(db1); - - RocksDB[] dbs = { db }; - simple_test(db); - - ConsoleUtils.info("Then, I will do performance test..."); - - int count = 1000000; - int valueSize = 1024; - String keyPrefix = System.currentTimeMillis() + "_" + rand.nextInt() + "_"; - - ConsoleUtils.info("Synchronize writting ..."); - perf_writing_test(dbs, count, keyPrefix, valueSize, false); - - ConsoleUtils.info("Parallel writting ..."); - perf_writing_test(dbs, count, keyPrefix, valueSize, true); - - ConsoleUtils.info("Reading ..."); - perf_reading_test(dbs, count, keyPrefix, valueSize); - } - }catch( - - Exception e) - { - // do some error handling - e.printStackTrace(); - } - - } - - private static void simple_test(RocksDB db) throws RocksDBException { - String strKey = "hello"; - byte[] key = BytesUtils.toBytes(strKey); - byte[] value = db.get(key); - if (value == null) { - ConsoleUtils.info("Key[%s] doesn't exist! I will create it automactic.", strKey); - value = new byte[32]; - rand.nextBytes(value); - db.put(key, value); - } else { - ConsoleUtils.info("Key[%s] has been found! It's value is [%s].", strKey, Base58Utils.encode(value)); - } - } - - private static void perf_reading_test(RocksDB[] dbs, int count, String keyPrefix, int valueSize) - throws RocksDBException { - byte[] value = new byte[valueSize]; - - long startTs = System.currentTimeMillis(); - - byte[] key; - RocksDB db; - for (int i = 0; i < count; i++) { - key = BytesUtils.toBytes(keyPrefix + i); - db = dbs[i % dbs.length]; - int len = db.get(key, value); - if (len != value.length) { - throw new IllegalStateException(String.format( - "The size of value reloaded from rocksdb is out of expectation. [expected=%s][actual=%s]", - value.length, len)); - } - } - long elapsedTs = System.currentTimeMillis() - startTs; - - double tps = count * 1000.0 / elapsedTs; - ConsoleUtils.info( - "============= perf_reading_test : total keys = %s; tps= %.2f; elapsed millis = %s; value bytes = %s; ", - count, tps, elapsedTs, value.length); - } - - private static void perf_writing_test(RocksDB[] dbs, int count, String keyPrefix, int valueSize, boolean parallel) - throws RocksDBException { - byte[] value = new byte[valueSize]; - rand.nextBytes(value); - - long startTs = System.currentTimeMillis(); - - if (parallel) { - parallel_write(dbs, count, value, keyPrefix); - } else { - sync_write(dbs, count, value, keyPrefix); - } - - long elapsedTs = System.currentTimeMillis() - startTs; - - double tps = count * 1000.0 / elapsedTs; - ConsoleUtils.info( - "============= perf_writing_test [parallel=%s]: total keys = %s; tps= %.2f; elapsed millis = %s; value bytes = %s; ", - parallel, count, tps, elapsedTs, value.length); - } - - private static void sync_write(RocksDB[] dbs, int count, byte[] value, String keyPrefix) throws RocksDBException { - byte[] key; - if (dbs.length > 16) { - throw new IllegalArgumentException("Too many dbs!"); - } - //  先按默认 2 个 db 进行分片处理; - RocksDB db; - for (int i = 0; i < count; i++) { - key = BytesUtils.toBytes(keyPrefix + i); - db = dbs[i % dbs.length]; - db.put(key, value); - } - } - - private static void parallel_write(RocksDB[] dbs, int count, byte[] value, String keyPrefix) - throws RocksDBException { - // WriteTask task = new WriteTask(0, count, keyPrefix, value, dbs); - - StepWriteTask task1 = new StepWriteTask(0, count, keyPrefix, value, dbs[0], 2); - StepWriteTask task2 = new StepWriteTask(1, count, keyPrefix, value, dbs[0], 2); - - ForkJoinPool.commonPool().execute(task1); - ForkJoinPool.commonPool().execute(task2); - task1.join(); - task2.join(); - } - - private static class WriteTask extends RecursiveAction { - - private static final long serialVersionUID = -2609085082223653954L; - - private static int THRESHOLD = 2000; - - private String keyPrefix; - - private int offset; - - private int count; - - private byte[] value; - - private RocksDB[] dbs; - - public WriteTask(int offset, int count, String keyPrefix, byte[] value, RocksDB[] dbs) { - this.offset = offset; - this.count = count; - this.keyPrefix = keyPrefix; - this.value = value; - this.dbs = dbs; - } - - @Override - protected void compute() { - if (count > THRESHOLD) { - // List tasks = new LinkedList<>(); - // for (int i = 0; i < count;) { - // int c = Math.min(THRESHOLD, count - i); - // WriteTask task = new WriteTask(offset + i, c, keyPrefix, value, db); - // tasks.add(task); - // i += c; - // } - // ForkJoinTask.invokeAll(tasks); - - int count1 = count / 2; - int count2 = count - count1; - WriteTask task1 = new WriteTask(offset, count1, keyPrefix, value, dbs); - WriteTask task2 = new WriteTask(offset + count1, count2, keyPrefix, value, dbs); - ForkJoinTask.invokeAll(task1, task2); - } else { - byte[] key; - RocksDB db; - - List tasks = new LinkedList<>(); - for (int i = 0; i < dbs.length; i++) { - StepWriteTask stepTask = new StepWriteTask(offset + i, count, keyPrefix, value, dbs[i], dbs.length); - tasks.add(stepTask); - } - ForkJoinTask.invokeAll(tasks); - // for (int i = 0; i < count; i++) { - // key = BytesUtils.toBytes(keyPrefix + (offset + i)); - // db = dbs[(offset + i) % dbs.length]; - // db.put(key, value); - // } - } - } - - } - - private static class StepWriteTask extends RecursiveAction { - - private static final long serialVersionUID = -6046220943323359514L; - - private String keyPrefix; - - private int offset; - - private int step; - - private int count; - - private byte[] value; - - private RocksDB db; - - public StepWriteTask(int offset, int count, String keyPrefix, byte[] value, RocksDB db, int step) { - this.offset = offset; - this.count = count; - this.keyPrefix = keyPrefix; - this.value = value; - this.db = db; - this.step = step; - } - - @Override - protected void compute() { - try { - byte[] key; - for (int i = 0; i < count;) { - key = BytesUtils.toBytes(keyPrefix + (offset + i)); - db.put(key, value); - i += step; - } - } catch (RocksDBException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - } - -} diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/demo/rocksdb/RocksDBStoragePerformanceTest.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/demo/rocksdb/RocksDBStoragePerformanceTest.java deleted file mode 100644 index f7d34989..00000000 --- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/demo/rocksdb/RocksDBStoragePerformanceTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.jd.blockchain.storage.service.demo.rocksdb; - -import java.io.File; -import java.util.Random; - -import org.bouncycastle.util.Arrays; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.impl.rocksdb.RocksDBConnectionFactory; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.io.FileUtils; - -public class RocksDBStoragePerformanceTest { - - public static void main(String[] args) { - - String uri = initEmptyDB("perf_rocksdb_storage_test"); - try (RocksDBConnectionFactory connFactory = new RocksDBConnectionFactory()) { - DbConnection conn = connFactory.connect(uri); - KVStorageService storageService = conn.getStorageService(); - - int count = 1000000; - int size = 1024; - Bytes keyPrefix = Bytes.fromString("KEY-" + System.currentTimeMillis() + "_"); - test_versioning_writing("test_versioning_writing", keyPrefix, count, size, - storageService.getVersioningKVStorage()); - Bytes exKeyPrefix = Bytes.fromString("EX").concat(keyPrefix); - test_existance_writing("test_existance_writing", exKeyPrefix, count, size, - storageService.getExPolicyKVStorage()); - } - - } - - private static void test_versioning_writing(String name, Bytes keyPrefix, int count, int valueSize, - VersioningKVStorage storage) { - byte[] value = new byte[valueSize]; - new Random().nextBytes(value); - long startTs = System.currentTimeMillis(); - - Bytes key; - for (int i = 0; i < count; i++) { - key = keyPrefix.concat(Bytes.fromInt(i)); - value = Arrays.copyOf(value, value.length); - long v = storage.set(key, value, -1); - if (v < 0) { - throw new IllegalStateException(String.format( - "The size of value reloaded from rocksdb is out of expectation. [expected=%s][actual=%s]", 0, - v)); - } - } - long elapsedTs = System.currentTimeMillis() - startTs; - - double tps = count * 1000.0 / elapsedTs; - ConsoleUtils.info("============= [%s] : total keys = %s; tps= %.2f; elapsed millis = %s; value bytes = %s; ", - name, count, tps, elapsedTs, value.length); - } - - private static void test_existance_writing(String name, Bytes keyPrefix, int count, int valueSize, - ExPolicyKVStorage storage) { - byte[] value = new byte[valueSize]; - new Random().nextBytes(value); - long startTs = System.currentTimeMillis(); - - Bytes key; - for (int i = 0; i < count; i++) { - key = keyPrefix.concat(Bytes.fromInt(i)); - boolean success = storage.set(key, value, ExPolicy.NOT_EXISTING); - if (!success) { - throw new IllegalStateException(String.format("Key already exist! --key=%s", key)); - } - } - long elapsedTs = System.currentTimeMillis() - startTs; - - double tps = count * 1000.0 / elapsedTs; - ConsoleUtils.info("============= [%s] : total keys = %s; tps= %.2f; elapsed millis = %s; value bytes = %s; ", - name, count, tps, elapsedTs, value.length); - } - - private static String initEmptyDB(String name) { - String currDir = FileUtils.getCurrentDir(); - String dbDir = new File(currDir, name + ".db").getAbsolutePath(); - FileUtils.deleteFile(dbDir); - String dbURI = "rocksdb://" + dbDir; - return dbURI; - } - -} diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/KVWritingCache.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/KVWritingCache.java deleted file mode 100644 index b15f20bd..00000000 --- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/KVWritingCache.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jd.blockchain.storage.service.impl.rocksdb; - -import java.io.Closeable; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.LinkedBlockingQueue; - -import org.rocksdb.RocksDB; - -import com.jd.blockchain.utils.io.BytesUtils; - -public class KVWritingCache implements Closeable { - - private Map cache = new ConcurrentHashMap<>(); - - private LinkedBlockingQueue tasks = new LinkedBlockingQueue<>(1000000); - - private volatile boolean running; - - private RocksDB db; - - private Thread thrd; - - public KVWritingCache(RocksDB db) { - this.db = db; - thrd = new Thread(new Runnable() { - @Override - public void run() { - running = true; - doWritingTask(); - } - }, "KVWritingCache-Thread"); - thrd.setContextClassLoader(Thread.currentThread().getContextClassLoader()); - thrd.start(); - } - - public byte[] get(String key) { - return cache.get(key); - } - - public void set(String key, byte[] value) { - cache.put(key, value); - tasks.add(key); - } - - private void doWritingTask() { - while (running) { - dbWrite(); - } - } - - private void dbWrite() { - try { - String key = tasks.take(); - byte[] value = cache.remove(key); - byte[] keyBytes = BytesUtils.toBytes(key); - db.put(keyBytes, value); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void close() { - running = false; - thrd.interrupt(); - } -} diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBConnection.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBConnection.java deleted file mode 100644 index d0a7e89d..00000000 --- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBConnection.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jd.blockchain.storage.service.impl.rocksdb; - -import java.io.IOException; - -import org.rocksdb.Options; -import org.rocksdb.RocksDB; -import org.rocksdb.RocksDBException; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.utils.io.FileUtils; - -public class RocksDBConnection implements DbConnection { - - private Options options; - - private RocksDB db; - - private RocksDBStorageService storage; - - public RocksDBConnection(String dbPath, Options options) { - try { - String parentDir = FileUtils.getParent(dbPath); - if (!FileUtils.existDirectory(parentDir)) { - FileUtils.makeDirectory(parentDir); - } - this.db = RocksDB.open(options, dbPath); - } catch (RocksDBException e) { - throw new IllegalStateException(e.getMessage(), e); - } - this.storage = new RocksDBStorageService(db); - } - - @Override - public void close() throws IOException { - // 假的释放; - // TODO: 采用引用计数器进行优化; - // db.close(); - } - - @Override - public KVStorageService getStorageService() { - return storage; - } - - public void dbClose() { - Options options = this.options; - this.options = null; - RocksDB db = this.db; - this.db = null; - - if (options != null) { - options.close(); - } - if (db != null) { - db.close(); - } - } - -} diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBConnectionFactory.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBConnectionFactory.java deleted file mode 100644 index eb5b09f2..00000000 --- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBConnectionFactory.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.jd.blockchain.storage.service.impl.rocksdb; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; - -import javax.annotation.PreDestroy; - -import org.rocksdb.*; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import org.rocksdb.util.SizeUnit; - -public class RocksDBConnectionFactory implements DbConnectionFactory { - - static { - RocksDB.loadLibrary(); - } - - public static final String URI_SCHEME = "rocksdb"; - - public static final Pattern URI_PATTER = Pattern - .compile("^\\w+\\://(/)?\\w+(\\:)?([/\\\\].*)*$"); - - private Map connections = new ConcurrentHashMap<>(); - - @Override - public DbConnection connect(String dbUri) { - return connect(dbUri, null); - } - - @Override - public synchronized DbConnection connect(String dbConnectionString, String password) { - if (!URI_PATTER.matcher(dbConnectionString).matches()) { - throw new IllegalArgumentException("Illegal format of rocksdb connection string!"); - } - URI dbUri = URI.create(dbConnectionString.replace("\\", "/")); - if (!support(dbUri.getScheme())) { - throw new IllegalArgumentException( - String.format("Not supported db connection string with scheme \"%s\"!", dbUri.getScheme())); - } - - String uriHead = dbPrefix(); - int beginIndex = dbConnectionString.indexOf(uriHead); - String dbPath = dbConnectionString.substring(beginIndex + uriHead.length()); - - RocksDBConnection conn = connections.get(dbPath); - if (conn != null) { - return conn; - } - - Options options = initOptions(); - - conn = new RocksDBConnection(dbPath, options); - connections.put(dbPath, conn); - - return conn; - } - - - @Override - public String dbPrefix() { - return URI_SCHEME + "://"; - } - - @Override - public boolean support(String scheme) { - return URI_SCHEME.equalsIgnoreCase(scheme); - } - - @PreDestroy - @Override - public void close() { - RocksDBConnection[] conns = connections.values().toArray(new RocksDBConnection[connections.size()]); - connections.clear(); - for (RocksDBConnection conn : conns) { - conn.dbClose(); - } - } - - private Options initOptions() { - final Filter bloomFilter = new BloomFilter(32); - final BlockBasedTableConfig tableOptions = new BlockBasedTableConfig() - .setFilter(bloomFilter) - .setBlockSize(4 * SizeUnit.KB) - .setBlockSizeDeviation(10) - .setBlockCacheSize(64 * SizeUnit.GB) - .setNoBlockCache(false) - .setCacheIndexAndFilterBlocks(true) - .setBlockRestartInterval(16) - ; - final List compressionLevels = new ArrayList<>(); - compressionLevels.add(CompressionType.NO_COMPRESSION); // 0-1 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 1-2 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 2-3 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 3-4 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 4-5 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 5-6 - compressionLevels.add(CompressionType.SNAPPY_COMPRESSION); // 6-7 - - Options options = new Options() - .setAllowConcurrentMemtableWrite(true) - .setEnableWriteThreadAdaptiveYield(true) - .setCreateIfMissing(true) - .setMaxWriteBufferNumber(3) - .setTableFormatConfig(tableOptions) - .setMaxBackgroundCompactions(10) - .setMaxBackgroundFlushes(4) - .setBloomLocality(10) - .setMinWriteBufferNumberToMerge(4) - .setCompressionPerLevel(compressionLevels) - .setNumLevels(7) - .setCompressionType(CompressionType.SNAPPY_COMPRESSION) - .setCompactionStyle(CompactionStyle.UNIVERSAL) - .setMemTableConfig(new SkipListMemTableConfig()) - ; - return options; - } - -} diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBExPolicyStorage.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBExPolicyStorage.java deleted file mode 100644 index 113db171..00000000 --- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBExPolicyStorage.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jd.blockchain.storage.service.impl.rocksdb; - -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.utils.Bytes; - -public class RocksDBExPolicyStorage implements ExPolicyKVStorage { - - private RocksDBVersioningStorage versioningStorage; - - public RocksDBExPolicyStorage(RocksDBVersioningStorage versioningStorage) { - this.versioningStorage = versioningStorage; - } - - @Override - public byte[] get(Bytes key) { - return versioningStorage.get(key, 0); - } - - @Override - public boolean exist(Bytes key) { - long ver = versioningStorage.getVersion(key); - if (ver < 1) { - return ver == 0; - } - throw new IllegalStateException( - "The version of keys managed by this RocksDBExPolicyStorage is great than expected max value '0'."); - } - - @Override - public boolean set(Bytes key, byte[] value, ExPolicy ex) { - switch (ex) { - case EXISTING: - if (exist(key)) { - versioningStorage.dbSetData(key, value, 0); - return true; - } - return false; - case NOT_EXISTING: - long v = versioningStorage.set(key, value, -1); - return v == 0; - default: - throw new IllegalArgumentException("Unsupported ExPolicy[" + ex.toString() + "]!"); - } - } - - @Override - public void batchBegin() { - versioningStorage.batchBegin(); - } - - @Override - public void batchCommit() { - versioningStorage.batchCommit(); - } -} \ No newline at end of file diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBVersioningStorage.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBVersioningStorage.java deleted file mode 100644 index 98c47325..00000000 --- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBVersioningStorage.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.jd.blockchain.storage.service.impl.rocksdb; - -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.ReentrantLock; - -import org.apache.commons.collections4.map.LRUMap; -import org.rocksdb.*; - -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.DataEntry; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * 基于 Redis 实现的版本化KV存储; - * - *

- * - * 版本化KV存储要求实现几个关键特性:
- * 1、每个Key都有唯一的版本序列,版本序列从 0 开始;
- * 2、对 Key 值的每一次更改都导致版本增长 1 ;
- * 3、对“写入”和“版本增长”两个操作一起是原子性的;
- * 4、“版本增长”必须以 1 顺序递增,不允许跳空递增;
- * - *

- * 由于 Redis 缺少事务特性,并且无法很好地自定义组合的原子操作( MULTI-EXEC 不适用于集群模式下),所以在此实现中只能做到前面 3 - * 点。
- * 第 4 点由调用方(账本操作层)在调用前做了版本校验,所以从整个系统来看也可以保证以上的4点要求。 - * - * @author huanghaiquan - * - */ -public class RocksDBVersioningStorage implements VersioningKVStorage { - - private final ThreadLocal writeBatchThreadLocal = new ThreadLocal<>(); - - private static Bytes VERSION_PREFIX = Bytes.fromString("V"); - - private static Bytes DATA_PREFIX = Bytes.fromString("D"); - - private final ReentrantLock lock = new ReentrantLock(); - - private final WriteOptions writeOptions = new WriteOptions(); - - private final ReadOptions readOptions = new ReadOptions() - .setFillCache(true) - .setVerifyChecksums(false) - ; - // put、get操作都在当前对象中,处理过程已加锁,不再需要线程安全对象 - private Map versions = new LRUMap<>(1024 * 128); -// private Map versions = new LRUMap<>(1024); - - private RocksDB db; - - public RocksDBVersioningStorage(RocksDB db) { - this.db = db; - } - - protected static Bytes encodeVersionKey(Bytes dataKey) { - return VERSION_PREFIX.concat(dataKey); - } - - protected static Bytes encodeDataKey(Bytes dataKey, long version) { - return DATA_PREFIX.concat(Bytes.fromLong(version)).concat(dataKey); - } - - private byte[] dbGet(Bytes key) { - try { - byte[] keyBytes = key.toBytes(); - return db.get(readOptions, keyBytes); - } catch (RocksDBException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - protected void dbSet(Bytes key, byte[] value) { - byte[] keyBytes = key.toBytes(); - - WriteBatch writeBatch = writeBatchThreadLocal.get(); - if (writeBatch != null) { - // 表示批量 - try { - writeBatch.put(keyBytes, value); - } catch (RocksDBException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } else { - try { - this.db.put(keyBytes, value); - } catch (RocksDBException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - @Override - public long getVersion(Bytes key) { - return innerGetVersion(key).get(); - } - - protected AtomicLong innerGetVersion(Bytes key) { - AtomicLong ver; - try { - lock.lock(); - ver = versions.get(key); - if (ver == null) { - Bytes vkey = encodeVersionKey(key); - byte[] verBytes = dbGet(vkey); - if (verBytes == null) { - // TODO: 未处理无效 key 的释放; - ver = new AtomicLong(-1); - } else { - long v = BytesUtils.toLong(verBytes); - if (v < 0) { - throw new IllegalStateException( - String.format("Illegal format of version bytes in rocks db! --[key=%s]", key)); - } - ver = new AtomicLong(v); - } - versions.put(key, ver); - } - } finally { - lock.unlock(); - } - return ver; - } - - @Override - public DataEntry getEntry(Bytes key, long version) { - byte[] value = get(key, version); - if (value == null) { - return null; - } - return new VersioningKVData(key, version, value); - } - - @Override - public byte[] get(Bytes key, long version) { - long latestVersion = getVersion(key); - if (latestVersion < 0) { - return null; - } - if (version > latestVersion) { - return null; - } - long targetVersion = version < 0 ? latestVersion : version; - Bytes dKey = encodeDataKey(key, targetVersion); - byte[] value = dbGet(dKey); - return value; - } - - @Override - public synchronized long set(Bytes key, byte[] value, long version) { - AtomicLong ver = innerGetVersion(key); - long newVer = version + 1; - if (ver.compareAndSet(version, newVer)) { - // updateIfLatest 为 false 有利于同一个 key 的多版本并发写入; - dbSetToVersion(key, value, newVer); - return newVer; - } - - return -1; - } - - /** - * 向数据库更新键值到指定版本;
- * - * 操作将把最新的版本号以及对应的数据存储到数据库;
- * - * @param key - * 要写入的键; - * @param value - * 要写入的值; - * @param version - * 要写入的新版本号;将做并发检查,如果指定的值已经不是最新版本,则不会写入到数据库; - * @return 返回最新的版本号; - */ - private long dbSetToVersion(Bytes key, byte[] value, long version) { - long latestVersion; - try { - lock.lock(); - // 同步地写入版本号; - // 判断此版本是否已被并发更新为更高的值;如果版本已经不一致,则当前值已不必写入,避免数据库中新版本被错误地覆盖为低的版本; - latestVersion = innerGetVersion(key).get(); - if (version == latestVersion) { - Bytes vkey = encodeVersionKey(key); - byte[] verBytes = BytesUtils.toBytes(version); - dbSet(vkey, verBytes); - } - } finally { - lock.unlock(); - } - // 写入数据; - dbSetData(key, value, version); - return latestVersion; - } - - protected void dbSetData(Bytes key, byte[] value, long version) { - // 写入数据; - Bytes dkey = encodeDataKey(key, version); - dbSet(dkey, value); - } - - @Override - public void batchBegin() { - writeBatchThreadLocal.set(new WriteBatch()); - } - - @Override - public void batchCommit() { - WriteBatch writeBatch = writeBatchThreadLocal.get(); - if (writeBatch != null) { - writeBatch(writeBatch); - writeBatchThreadLocal.remove(); - } - } - - private void writeBatch(WriteBatch writeBatch) { - try { - db.write(writeOptions, writeBatch); - } catch (RocksDBException e) { - throw new IllegalStateException(e.getMessage(), e); - } finally { - writeBatch.close(); - } - } - - private static class VersioningKVData implements DataEntry { - - private Bytes key; - - private long version; - - private byte[] value; - - public VersioningKVData(Bytes key, long version, byte[] value) { - this.key = key; - this.version = version; - this.value = value; - } - - @Override - public Bytes getKey() { - return key; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public byte[] getValue() { - return value; - } - } -} \ No newline at end of file diff --git a/source/storage/storage-rocksdb/src/test/java/test/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBStorageTest.java b/source/storage/storage-rocksdb/src/test/java/test/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBStorageTest.java deleted file mode 100644 index d33b809f..00000000 --- a/source/storage/storage-rocksdb/src/test/java/test/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBStorageTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package test.com.jd.blockchain.storage.service.impl.rocksdb; - -import static com.jd.blockchain.storage.service.impl.rocksdb.RocksDBConnectionFactory.URI_PATTER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.impl.rocksdb.RocksDBConnectionFactory; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.FileUtils; - -public class RocksDBStorageTest { - - @Test - public void test() { - String dbUri = initEmptyDB("rocksdb_storage_test"); - long expectedVersion; - try (DbConnectionFactory dbConnFactory = new RocksDBConnectionFactory();) { - DbConnection conn = dbConnFactory.connect(dbUri); - VersioningKVStorage verStorage = conn.getStorageService().getVersioningKVStorage(); - ExPolicyKVStorage exStorage = conn.getStorageService().getExPolicyKVStorage(); - - expectedVersion = test(verStorage); - - test(exStorage); - } - - try (DbConnectionFactory dbConnFactory = new RocksDBConnectionFactory();) { - DbConnection conn = dbConnFactory.connect(dbUri); - VersioningKVStorage verStorage = conn.getStorageService().getVersioningKVStorage(); - ExPolicyKVStorage exStorage = conn.getStorageService().getExPolicyKVStorage(); - - testAfterReload(verStorage, expectedVersion); - - testAfterReload(exStorage); - } - - } - - private void test(ExPolicyKVStorage exStorage) { - Bytes key = Bytes.fromString("kex"); - assertFalse(exStorage.exist(key)); - - byte[] data = exStorage.get(key); - assertNull(data); - - data = BytesUtils.toBytes("data"); - assertFalse(exStorage.set(key, data, ExPolicy.EXISTING)); - - assertTrue(exStorage.set(key, data, ExPolicy.NOT_EXISTING)); - assertTrue(exStorage.exist(key)); - - assertFalse(exStorage.set(key, data, ExPolicy.NOT_EXISTING)); - - assertTrue(exStorage.set(key, data, ExPolicy.EXISTING)); - assertTrue(exStorage.set(key, data, ExPolicy.EXISTING)); - assertFalse(exStorage.set(key, data, ExPolicy.NOT_EXISTING)); - - assertTrue(exStorage.exist(key)); - - byte[] reloadData = exStorage.get(key); - assertTrue(BytesUtils.equals(data, reloadData)); - } - - private void testAfterReload(ExPolicyKVStorage exStorage) { - Bytes key = Bytes.fromString("kex"); - assertTrue(exStorage.exist(key)); - - byte[] data = exStorage.get(key); - assertNotNull(data); - - assertEquals("data", BytesUtils.toString(data)); - - assertFalse(exStorage.set(key, data, ExPolicy.NOT_EXISTING)); - assertFalse(exStorage.set(key, data, ExPolicy.NOT_EXISTING)); - - assertTrue(exStorage.set(key, data, ExPolicy.EXISTING)); - assertTrue(exStorage.set(key, data, ExPolicy.EXISTING)); - assertFalse(exStorage.set(key, data, ExPolicy.NOT_EXISTING)); - - assertTrue(exStorage.exist(key)); - - byte[] reloadData = exStorage.get(key); - assertEquals("data", BytesUtils.toString(data)); - } - - private long test(VersioningKVStorage verStorage) { - Bytes key = Bytes.fromString("k1"); - long v = verStorage.getVersion(key); - assertEquals(-1, v); - byte[] data = verStorage.get(key, -1); - assertNull(data); - data = verStorage.get(key, 0); - assertNull(data); - data = verStorage.get(key, 1); - assertNull(data); - - data = BytesUtils.toBytes("data"); - v = verStorage.set(key, data, -1); - assertEquals(0, v); - v = verStorage.set(key, data, -1); - assertEquals(-1, v); - v = verStorage.set(key, data, 0); - assertEquals(1, v); - return v; - } - - private void testAfterReload(VersioningKVStorage verStorage, long expectedVersion) { - Bytes key = Bytes.fromString("k1"); - long v = verStorage.getVersion(key); - assertEquals(expectedVersion, v); - byte[] data = verStorage.get(key, -1); - String strData = BytesUtils.toString(data); - assertEquals("data", strData); - } - - private String initEmptyDB(String name) { - String currDir = FileUtils.getCurrentDir(); - String dbDir = new File(currDir, name + ".db").getAbsolutePath(); - FileUtils.deleteFile(dbDir); - String dbURI = "rocksdb://" + dbDir; - return dbURI; - } - - @Test - // test rocksDB uri patter - public void testRocksDBUriPatter() { - Map cases = new HashMap<>(); - cases.put("rocksdb:///home/peer0/rocksdb", true); - cases.put("rocksdb://D:\\home\\rocksdb", true); - cases.put("rocksdb://\\home\\rocksdb", false); - cases.put("rocksdb://:\\home\\rocksdb", false); - cases.put("rocksdb://D:\\home\\", true); - cases.put("rocksdb:///home/peer0/", true); - for(Map.Entry entity : cases.entrySet()) { - assertEquals(URI_PATTER.matcher(entity.getKey()).matches(), entity.getValue()); - } - } -} diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/BatchStorageService.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/BatchStorageService.java deleted file mode 100644 index 3815a2fe..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/BatchStorageService.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.storage.service.BatchStorageService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/5 下午4:41 - * Description: - */ -package com.jd.blockchain.storage.service; - -/** - * - * @author shaozhuguang - * @create 2018/12/5 - * @since 1.0.0 - */ - -public interface BatchStorageService { - - void batchBegin(); - - void batchCommit(); -} \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/DbConnection.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/DbConnection.java deleted file mode 100644 index 67ea6eff..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/DbConnection.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.storage.service; - -import java.io.Closeable; - -public interface DbConnection extends Closeable { - - KVStorageService getStorageService(); - -} diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/DbConnectionFactory.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/DbConnectionFactory.java deleted file mode 100644 index 3d1553bc..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/DbConnectionFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.storage.service; - -import java.io.Closeable; - -public interface DbConnectionFactory extends Closeable { - - /** - * 数据库连接前缀 - * @return - */ - String dbPrefix(); - - /** - * 是否支持指定 scheme 的连接字符串; - * @param scheme - * @return - */ - boolean support(String scheme); - - DbConnection connect(String dbConnectionString); - - DbConnection connect(String dbConnectionString, String password); - - @Override - void close(); -} diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/ExPolicyKVStorage.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/ExPolicyKVStorage.java deleted file mode 100644 index ac8f3af8..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/ExPolicyKVStorage.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jd.blockchain.storage.service; - -import com.jd.blockchain.utils.Bytes; - -/** - * 支持存在性策略更新的 KV 存储; - * - * @author huanghaiquan - * - */ -public interface ExPolicyKVStorage extends BatchStorageService{ - - /** - * 返回“键”对应的“值”;
- * 如果“键”不存在,则返回 null; - * - * @param key - * @return - */ - byte[] get(Bytes key); - - /** - * 如果满足指定的存在性策略,则创建/更新指定的“键-值”; - * - * @param key - * 键; - * @param value - * 值; - * @param ex - * 如果指定 {@link ExPolicy#EXISTING} ,则只有键存在时才更新;
- * 如果指定 {@link ExPolicy#NOT_EXISTING} ,则只有键不存在时才更新/创建; - * @return 如果符合存在性策略,并执行了创建/更新操作,则返回 true,否则返回 false; - */ - boolean set(Bytes key, byte[] value, ExPolicy ex); - - /** - * 指定的 key 是否存在; - * - * @param key - * @return - */ - boolean exist(Bytes key); - - /** - * 存在性策略; - * - * @author huanghaiquan - * - */ - public static enum ExPolicy { - - /** - * 已存在; - */ - EXISTING, - - /** - * 不存在; - */ - NOT_EXISTING - } - -} diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/KVStorageService.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/KVStorageService.java deleted file mode 100644 index 94b2d7df..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/KVStorageService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.storage.service; - -public interface KVStorageService { - - ExPolicyKVStorage getExPolicyKVStorage(); - - VersioningKVStorage getVersioningKVStorage(); - -} diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/BufferedKVStorage.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/BufferedKVStorage.java deleted file mode 100644 index b038a87e..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/BufferedKVStorage.java +++ /dev/null @@ -1,580 +0,0 @@ -package com.jd.blockchain.storage.service.utils; - -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinTask; -import java.util.concurrent.RecursiveTask; - -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.Transactional; -import com.jd.blockchain.utils.DataEntry; - -/** - * {@link BufferedKVStorage} 缓冲写入的KV存储;
- * - * @author huanghaiquan - * - */ -public class BufferedKVStorage implements VersioningKVStorage, ExPolicyKVStorage, Transactional { - - private static int MAX_PARALLEL_DB_WRITE_SIZE = 500; - static { - String strSize = System.getProperty("max-parallel-dbwrite-size"); - if (strSize != null) { - try { - MAX_PARALLEL_DB_WRITE_SIZE = Integer.parseInt(strSize); - } catch (NumberFormatException e) { - // 忽略格式错误; - e.printStackTrace(); - } - } - System.out.println("------ [[ max-parallel-dbwrite-size=" + MAX_PARALLEL_DB_WRITE_SIZE + " ]] ------"); - } - - private boolean parallel; - - private VersioningKVStorage origVersioningStorage; - - private ExPolicyKVStorage origExistanceStorage; - - /** - * 版本化KV数据的缓冲区; - */ - private ConcurrentHashMap versioningCache = new ConcurrentHashMap<>(); - private Object versioningMutex = new Object(); - - /** - * 存在性KV数据的缓冲区; - */ - private ConcurrentHashMap existanceCache = new ConcurrentHashMap<>(); - private Object existanceMutex = new Object(); - - /** - * 创建实例; - * - * @param origExPolicyStorage - * 原始的存储; - * @param origVersioningStorage - * 原始的存储; - * @param parallel - * 是否并行写入; - */ - public BufferedKVStorage(ExPolicyKVStorage origExPolicyStorage, VersioningKVStorage origVersioningStorage, - boolean parallel) { - this.origExistanceStorage = origExPolicyStorage; - this.origVersioningStorage = origVersioningStorage; - this.parallel = parallel; - } - - @Override - public long getVersion(Bytes key) { - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - return origVersioningStorage.getVersion(key); - } - return ws.getLatestVersion(); - } - - @Override - public DataEntry getEntry(Bytes key, long version) { - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - return origVersioningStorage.getEntry(key, version); - } - long latestVersion = ws.getStartingVersion(); - if (version <= latestVersion) { - // 值未 - return origVersioningStorage.getEntry(key, version < 0 ? latestVersion : version); - } - if (version > ws.getLatestVersion()) { - return null; - } - // 返回缓冲的新数据;注:这些数据尚未提交到依赖的底层存储; - return ws.getEntry(version); - } - - @Override - public byte[] get(Bytes key, long version) { - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - return origVersioningStorage.get(key, version); - } - long latestVersion = ws.getStartingVersion(); - if (version <= latestVersion) { - // 值未 - return origVersioningStorage.get(key, version < 0 ? latestVersion : version); - } - if (version > ws.getLatestVersion()) { - return null; - } - // 返回缓冲的新数据;注:这些数据尚未提交到依赖的底层存储; - return ws.get(version); - } - - @Override - public long set(Bytes key, byte[] value, long version) { - if (value == null) { - throw new IllegalArgumentException("Value is null!"); - } - if (version < -1) { - version = -1; - } - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - long latestVersion = origVersioningStorage.getVersion(key); - if (version < latestVersion) { - return -1; - } - synchronized (versioningMutex) { - ws = versioningCache.get(key); - if (ws == null) { - if (version == latestVersion) { - ws = new VersioningWritingSet(key, latestVersion, value); - versioningCache.put(key, ws); - return version + 1; - } - // 指定的版本不是最新版本; - return -1; - } - // 存在并发写,退出同步之后由该 key 的 VersioningWritingSet 来控制写入; - } - } - return ws.set(value, version); - } - - /** - * 输出已缓冲的所有写入数据到原始存储,并清空缓冲区; - */ - public void flush() { - if (parallel) { - parallelFlush(); - } else { - syncFlush(); - } - - clear(); - } - - private void parallelFlush() { - // 不必在“版本”和“存在性”这两类存储接口之间保证向下写入的顺序,也不必保证不同 key 向下写入的顺序; - ParallelVersioningWritingTask versioningWritingTask = null; - if (versioningCache.size() > 0) { - VersioningWritingSet[] wss = versioningCache.values() - .toArray(new VersioningWritingSet[versioningCache.size()]); - versioningWritingTask = new ParallelVersioningWritingTask(wss, 0, wss.length, origVersioningStorage); - ForkJoinPool.commonPool().execute(versioningWritingTask); - } - - ParallelExistanceWritingTask existanceWritingTask = null; - if (existanceCache.size() > 0) { - ExistanceWritingSet[] wss = existanceCache.values().toArray(new ExistanceWritingSet[existanceCache.size()]); - existanceWritingTask = new ParallelExistanceWritingTask(wss, 0, wss.length, origExistanceStorage); - ForkJoinPool.commonPool().execute(existanceWritingTask); - } - if (versioningWritingTask != null) { - versioningWritingTask.join(); - } - if (existanceWritingTask != null) { - existanceWritingTask.join(); - } - } - - @Override - public void batchBegin() { - // un support!!! - } - - @Override - public void batchCommit() { - // un support!!! - } - - private static class ParallelVersioningWritingTask extends RecursiveTask { - - private static final long serialVersionUID = -2603448698013687038L; - - private VersioningWritingSet[] wss; - private int offset; - private int count; - private VersioningKVStorage storage; - - public ParallelVersioningWritingTask(VersioningWritingSet[] wss, int offset, int count, - VersioningKVStorage storage) { - this.wss = wss; - this.offset = offset; - this.count = count; - this.storage = storage; - } - - /** - * 返回错误任务的计数器; - */ - @Override - protected Boolean compute() { - if (count > MAX_PARALLEL_DB_WRITE_SIZE) { - int count1 = count / 2; - int count2 = count - count1; - ParallelVersioningWritingTask task1 = new ParallelVersioningWritingTask(wss, offset, count1, storage); - ParallelVersioningWritingTask task2 = new ParallelVersioningWritingTask(wss, offset + count1, count2, - storage); - ForkJoinTask.invokeAll(task1, task2); - boolean success = task1.join(); - success = task2.join() & success; - return success; - } else { - for (int i = 0; i < count; i++) { - wss[offset + i].flushTo(storage); - } - return true; - } - } - } - - private static class ParallelExistanceWritingTask extends RecursiveTask { - - private static final long serialVersionUID = -7101095718404738821L; - - private ExistanceWritingSet[] wss; - private int offset; - private int count; - private ExPolicyKVStorage storage; - - public ParallelExistanceWritingTask(ExistanceWritingSet[] wss, int offset, int count, - ExPolicyKVStorage storage) { - this.wss = wss; - this.offset = offset; - this.count = count; - this.storage = storage; - } - - /** - * 返回错误任务的计数器; - */ - @Override - protected Boolean compute() { - if (count > MAX_PARALLEL_DB_WRITE_SIZE) { - int count1 = count / 2; - int count2 = count - count1; - ParallelExistanceWritingTask task1 = new ParallelExistanceWritingTask(wss, offset, count1, storage); - ParallelExistanceWritingTask task2 = new ParallelExistanceWritingTask(wss, offset + count1, count2, - storage); - ForkJoinTask.invokeAll(task1, task2); - boolean success = task1.join(); - success = task2.join() & success; - return success; - } else { - for (int i = 0; i < count; i++) { - wss[offset + i].flushTo(storage); - } - return true; - } - } - } - - private void syncFlush() { - // 不必在“版本”和“存在性”这两类存储接口之间保证向下写入的顺序,也不必保证不同 key 向下写入的顺序; - if (versioningCache.isEmpty() && existanceCache.isEmpty()) { - return; - } - origVersioningStorage.batchBegin(); - for (VersioningWritingSet ws : versioningCache.values()) { - ws.flushTo(origVersioningStorage); - } - origVersioningStorage.batchCommit(); - origExistanceStorage.batchBegin(); - for (ExistanceWritingSet ws : existanceCache.values()) { - ws.flushTo(origExistanceStorage); - } - origExistanceStorage.batchCommit(); - } - - private void clear() { - versioningCache.clear(); - existanceCache.clear(); - } - - /** - * 清空缓冲的数据; - */ - public void cancel() { - clear(); - } - - @Override - public boolean isUpdated() { - return versioningCache.size() > 0 || existanceCache.size() > 0; - } - - @Override - public void commit() { - flush(); - } - - /* - * (non-Javadoc) - * - * @see - * com.jd.blockchain.storage.service.ExPolicyKVStorage#get(java.lang.String) - */ - @Override - public byte[] get(Bytes key) { - // 从“存在性KV存储”读取值; - ExistanceWritingSet ws = existanceCache.get(key); - if (ws == null) { - return origExistanceStorage.get(key); - } - return ws.get(); - } - - @Override - public boolean set(Bytes key, byte[] value, ExPolicy ex) { - if (value == null) { - throw new IllegalArgumentException("Value is null!"); - } - switch (ex) { - case EXISTING: - return setEx(key, value); - case NOT_EXISTING: - return setNx(key, value); - default: - throw new IllegalArgumentException("Unsupported ExistancePolicy[" + ex + "]!"); - } - } - - @Override - public boolean exist(Bytes key) { - ExistanceWritingSet ws = existanceCache.get(key); - if (ws == null) { - return origExistanceStorage.exist(key); - } - return true; - } - - /** - * 当 key 不存在时写入新的键值; - * - * @param key - * @param value - * @return - */ - private boolean setNx(Bytes key, byte[] value) { - // 从“存在性KV存储”读取值; - ExistanceWritingSet ws = existanceCache.get(key); - if (ws == null) { - boolean exist = origExistanceStorage.exist(key); - if (exist) { - return false; - } - synchronized (existanceMutex) { - ws = existanceCache.get(key); - if (ws == null) { - ws = new ExistanceWritingSet(key, value, ExPolicy.NOT_EXISTING); - existanceCache.put(key, ws); - return true; - } - // 并发写,已经存在; - return false; - } - } - // 已经存在; - return false; - } - - /** - * 当 key 已经存在时更新值; - * - * @param key - * @param value - * @return - */ - private boolean setEx(Bytes key, byte[] value) { - // 从“存在性KV存储”读取值; - ExistanceWritingSet ws = existanceCache.get(key); - if (ws == null) { - boolean exist = origExistanceStorage.exist(key); - if (!exist) { - // key 不存在; - return false; - } - synchronized (existanceMutex) { - ws = existanceCache.get(key); - if (ws == null) { - // 初始化,缓存首个更新值以及更新条件; - ws = new ExistanceWritingSet(key, value, ExPolicy.EXISTING); - existanceCache.put(key, ws); - return true; - } - // 并发写,已经存在; - } - } - // 更新值; - ws.set(value); - return true; - } - - // ============================================================= - - /** - * 记录在最新版本之上新写入但未保存的最新的数据版本序列; - * - * @author huanghaiquan - * - */ - private static class VersioningWritingSet { - - private Bytes key; - - private long startingVersion; - - private ArrayList values; - - /** - * - * @param key - * 键; - * @param version - * 新的版本; - * @param value - * 值; - */ - private VersioningWritingSet(Bytes key, long startingVersion, byte[] firstValue) { - this.key = key; - this.startingVersion = startingVersion; - this.values = new ArrayList<>(1); - this.values.add(firstValue); - } - - public byte[] get(long version) { - long idx = version - startingVersion - 1; - if (idx < 0 || idx >= values.size()) { - return null; - } - return values.get((int) idx); - } - - public synchronized long set(byte[] value, long version) { - if (getLatestVersion() == version) { - this.values.add(value); - return version + 1; - } - return -1; - } - - /** - * 当前写入序列的最新版本;
- * - * 此版本是最新的尚未写入底层存储的数据的版本; - * - * @return - */ - public long getLatestVersion() { - return startingVersion + values.size(); - } - - /** - * 当前写入序列的起始版本;
- * 同时也是底层存储的最新版本; - * - * @return - */ - public long getStartingVersion() { - return startingVersion; - } - - public DataEntry getEntry(long version) { - byte[] value = get(version); - if (value == null) { - return null; - } - return new VersioningKVData(key, version, value); - } - - public void flushTo(VersioningKVStorage storage) { - long expVersion = startingVersion; - for (byte[] value : values) { - if (storage.set(key, value, expVersion) < 0) { - throw new IllegalStateException(String.format( - "Fail on flushing data to original storage! Expected version doesn't match! --[KEY=%s][EXPECTED_VERSION=%s]", - key, expVersion)); - } - expVersion++; - } - } - } - - private static class VersioningKVData implements DataEntry { - - private Bytes key; - - private long version; - - private byte[] value; - - public VersioningKVData(Bytes key, long version, byte[] value) { - this.key = key; - this.version = version; - this.value = value; - } - - @Override - public Bytes getKey() { - return key; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public byte[] getValue() { - return value; - } - - } - - private static class ExistanceWritingSet { - - private Bytes key; - - private volatile byte[] value; - - private ExPolicy initPolicy; - - /** - * - * @param key - * 键; - * @param value - * 值; - * @param initPolicy - * 初始的写入策略; - */ - private ExistanceWritingSet(Bytes key, byte[] value, ExPolicy initPolicy) { - this.key = key; - this.value = value; - this.initPolicy = initPolicy; - } - - public void flushTo(ExPolicyKVStorage origExistanceStorage) { - if (!origExistanceStorage.set(key, value, initPolicy)) { - throw new IllegalStateException(String.format( - "Fail on flushing data to original storage! The existance policy doesn't match --[KEY=%s][POLICY=%s]", - key, initPolicy)); - } - } - - public void set(byte[] value) { - this.value = value; - } - - public byte[] get() { - return value; - } - - } - -} \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/ExistancePolicyKVStorageMap.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/ExistancePolicyKVStorageMap.java deleted file mode 100644 index ece8c975..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/ExistancePolicyKVStorageMap.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.jd.blockchain.storage.service.utils; - -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesMap; - -/** - * 基于内存的 {@link ExPolicyKVStorage} 实现; - * - * @author huanghaiquan - * - */ -public class ExistancePolicyKVStorageMap implements ExPolicyKVStorage, BytesMap { - // 要维持键的写入顺序,并且最终以相同的顺序输出; - private Map storage; - - private Object mutex = new Object(); - - public ExistancePolicyKVStorageMap() { - storage = new ConcurrentHashMap(); - } - - public ExistancePolicyKVStorageMap(Map external) { - storage = external; - } - - @Override - public byte[] get(Bytes key) { - return (byte[]) storage.get(key); - } - - @Override - public boolean exist(Bytes key) { - return storage.containsKey(key); - } - - @Override - public synchronized boolean set(Bytes key, byte[] value, ExPolicy ex) { - switch (ex) { - case EXISTING: - return setEx(key, value); - case NOT_EXISTING: - return setNx(key, value); - default: - throw new IllegalArgumentException("Unsupported ExistancePolicy[" + ex + "]!"); - } - } - - private boolean setNx(Bytes key, byte[] value) { - if (storage.containsKey(key)) { - return false; - } - synchronized (mutex) { - if (storage.containsKey(key)) { - return false; - } - storage.put(key, value); - return true; - } - } - - private boolean setEx(Bytes key, byte[] value) { - if (!storage.containsKey(key)) { - return false; - } - storage.put(key, value); - return true; - } - - @Override - public Set keySet() { - return storage.keySet(); - } - - public int getCount() { - return storage.size(); - } - - @Override - public byte[] getValue(Bytes key) { - return get(key); - } - - @Override - public void batchBegin() { - // un support!!! - } - - @Override - public void batchCommit() { - // un support!!! - } -} \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryBasedDb.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryBasedDb.java deleted file mode 100644 index bbe0856c..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryBasedDb.java +++ /dev/null @@ -1,35 +0,0 @@ -//package com.jd.blockchain.storage.service.utils; -// -// -//import com.jd.blockchain.storage.service.DbConnection; -//import com.jd.blockchain.storage.service.DbConnectionFactory; -//import com.jd.blockchain.storage.service.KVStorageService; -// -//public class MemoryBasedDb implements DbConnectionFactory, DbConnection { -// -// private MemoryKVStorage testStorage = new MemoryKVStorage(); -// -// @Override -// public boolean support(String scheme) { -// return true; -// } -// -// @Override -// public DbConnection connect(String dbConnectionString) { -// return new MemoryBasedDb(); -// } -// -// @Override -// public DbConnection connect(String dbConnectionString, String password) { -// return new MemoryBasedDb(); -// } -// -// @Override -// public void close(){ -// } -// -// @Override -// public KVStorageService getStorageService() { -// return testStorage; -// } -//} \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryDBConn.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryDBConn.java deleted file mode 100644 index 0e60fea1..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryDBConn.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.storage.service.utils; - - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.storage.service.KVStorageService; - -public class MemoryDBConn implements DbConnection { - - private MemoryKVStorage testStorage = new MemoryKVStorage(); - - @Override - public void close(){ - } - - @Override - public KVStorageService getStorageService() { - return testStorage; - } - - } \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryDBConnFactory.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryDBConnFactory.java deleted file mode 100644 index 23a4492f..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryDBConnFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.storage.service.utils.MemoryDBConnFactory - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/25 上午10:52 - * Description: - */ -package com.jd.blockchain.storage.service.utils; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * @author shaozhuguang - * @create 2018/12/25 - * @since 1.0.0 - */ - -public class MemoryDBConnFactory implements DbConnectionFactory { - - private Map memMap = new ConcurrentHashMap<>(); - - @Override - public String dbPrefix() { - return "memory://"; - } - - @Override - public boolean support(String scheme) { - return true; - } - - @Override - public synchronized DbConnection connect(String dbConnectionString) { - DbConnection mem = memMap.get(dbConnectionString); - if (mem == null) { - mem = new MemoryDBConn(); - memMap.put(dbConnectionString, mem); - } - return mem; - } - - @Override - public synchronized DbConnection connect(String dbConnectionString, String password) { - return connect(dbConnectionString); - } - - @Override - public void close() { - memMap.clear(); - } -} \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryKVStorage.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryKVStorage.java deleted file mode 100644 index a0f36c0d..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryKVStorage.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.jd.blockchain.storage.service.utils; - -import java.util.HashSet; -import java.util.Set; - -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.DataEntry; -import com.jd.blockchain.utils.io.BytesMap; - -public class MemoryKVStorage implements ExPolicyKVStorage, VersioningKVStorage, KVStorageService, BytesMap { - - private ExistancePolicyKVStorageMap exStorage = new ExistancePolicyKVStorageMap(); - private VersioningKVStorageMap verStorage = new VersioningKVStorageMap(); - - @Override - public long getVersion(Bytes key) { - return verStorage.getVersion(key); - } - - @Override - public DataEntry getEntry(Bytes key, long version) { - return verStorage.getEntry(key, version); - } - - @Override - public byte[] get(Bytes key, long version) { - return verStorage.get(key, version); - } - - @Override - public long set(Bytes key, byte[] value, long version) { - return verStorage.set(key, value, version); - } - - @Override - public byte[] get(Bytes key) { - return exStorage.get(key); - } - - @Override - public boolean exist(Bytes key) { - return exStorage.exist(key); - } - - @Override - public boolean set(Bytes key, byte[] value, ExPolicy ex) { - return exStorage.set(key, value, ex); - } - - @Override - public Set keySet() { - return getStorageKeySet(); - } - - @Override - public byte[] getValue(Bytes key) { - byte[] v = exStorage.getValue(key); - if (v == null) { - v = verStorage.getValue(key); - } - return v; - } - - public Set getStorageKeySet() { - HashSet keySet = new HashSet<>(exStorage.keySet()); - keySet.addAll(verStorage.keySet()); - return keySet; - } - - public int getStorageCount() { - return exStorage.getCount() + verStorage.getCount(); - } - -// public void printStoragedKeys() { -// String[] keys = StringUtils.toStringArray(getStorageKeySet()); -// StringUtils.sortStringArray(keys); -// for (String k : keys) { -// System.out.println(k); -// } -// } - - @Override - public ExPolicyKVStorage getExPolicyKVStorage() { - return this; - } - - @Override - public VersioningKVStorage getVersioningKVStorage() { - return this; - } - - @Override - public void batchBegin() { - // un support!!! - } - - @Override - public void batchCommit() { - // un support!!! - } -} diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVData.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVData.java deleted file mode 100644 index 73816055..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVData.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jd.blockchain.storage.service.utils; - -import com.jd.blockchain.utils.DataEntry; - -public class VersioningKVData implements DataEntry { - - private K key; - - private long version; - - private V value; - - public VersioningKVData(K key, long version, V value) { - this.key = key; - this.version = version; - this.value = value; - } - - @Override - public K getKey() { - return key; - } - - @Override - public long getVersion() { - return version; - } - - @Override - public V getValue() { - return value; - } - - } \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVStorageMap.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVStorageMap.java deleted file mode 100644 index 1c6b8def..00000000 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVStorageMap.java +++ /dev/null @@ -1,260 +0,0 @@ -package com.jd.blockchain.storage.service.utils; - -import java.util.ArrayList; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.DataEntry; -import com.jd.blockchain.utils.io.BytesMap; - -public class VersioningKVStorageMap implements VersioningKVStorage, BytesMap { - -// private Map versions = new ConcurrentHashMap<>(); -// -// // 要维持键的写入顺序,并且最终以相同的顺序输出; -// private Map cache; - - /** - * 版本化KV数据的缓冲区; - */ - private Map versioningCache = new ConcurrentHashMap<>(); - private Object versioningMutex = new Object(); - - - - public VersioningKVStorageMap() { - } - -// public VersioningKVStorageMap(Map external) { -// cache = external; -// } - - @Override - public long getVersion(Bytes key) { - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - return -1; - } - return ws.getLatestVersion(); - } - - @Override - public DataEntry getEntry(Bytes key, long version) { - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - return null; - } - long latestVersion = ws.getLatestVersion(); - if (version > ws.getLatestVersion()) { - return null; - } - if (version < 0) { - version = latestVersion; - } - // 返回缓冲的新数据;注:这些数据尚未提交到依赖的底层存储; - return ws.getEntry(version); - } - - @Override - public byte[] get(Bytes key, long version) { - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - return null; - } - long latestVersion = ws.getLatestVersion(); - if (version > ws.getLatestVersion()) { - return null; - } - if (version < 0) { - version = latestVersion; - } - // 返回缓冲的新数据;注:这些数据尚未提交到依赖的底层存储; - return ws.get(version); - } - - @Override - public long set(Bytes key, byte[] value, long version) { - if (value == null) { - throw new IllegalArgumentException("Value is null!"); - } - if (version < -1) { - version = -1; - } - VersioningWritingSet ws = versioningCache.get(key); - if (ws == null) { - long latestVersion = -1; - synchronized (versioningMutex) { - ws = versioningCache.get(key); - if (ws == null) { - if (version == latestVersion) { - ws = new VersioningWritingSet(key, latestVersion, value); - versioningCache.put(key, ws); - return version+1; - } - // 指定的版本不是最新版本; - return -1; - } - // 存在并发写,退出同步之后由该 key 的 VersioningWritingSet 来控制写入; - } - } - return ws.set(value, version); - } - - @Override - public Set keySet() { - return versioningCache.keySet(); - } - - @Override - public byte[] getValue(Bytes key) { - return get(key, getVersion(key)); - } - - public int getCount() { - return versioningCache.size(); - } - - @Override - public void batchBegin() { - // un support!!! - } - - @Override - public void batchCommit() { - // un support!!! - } - - - /** - * 记录在最新版本之上新写入但未保存的最新的数据版本序列; - * - * @author huanghaiquan - * - */ - private static class VersioningWritingSet { - - private Bytes key; - - private long startingVersion; - - private ArrayList values; - - /** - * - * @param key - * 键; - * @param version - * 新的版本; - * @param value - * 值; - */ - private VersioningWritingSet(Bytes key, long startingVersion, byte[] firstValue) { - this.key = key; - this.startingVersion = startingVersion; - this.values = new ArrayList<>(1); - this.values.add(firstValue); - } - - public byte[] get(long version) { - long idx = version - startingVersion - 1; - if (idx < 0 || idx >= values.size()) { - return null; - } - return values.get((int) idx); - } - - public synchronized long set(byte[] value, long version) { - if (getLatestVersion() == version) { - this.values.add(value); - return version + 1; - } - return -1; - } - - /** - * 当前写入序列的最新版本;
- * - * 此版本是最新的尚未写入底层存储的数据的版本; - * - * @return - */ - public long getLatestVersion() { - return startingVersion + values.size(); - } - - /** - * 当前写入序列的起始版本;
- * 同时也是底层存储的最新版本; - * - * @return - */ - public long getStartingVersion() { - return startingVersion; - } - - public DataEntry getEntry(long version) { - byte[] value = get(version); - if (value == null) { - return null; - } - return new VersioningKVData(key, version, value); - } - - public void flushTo(VersioningKVStorage storage) { - long expVersion = startingVersion; - for (byte[] value : values) { - if (storage.set(key, value, expVersion) < 0) { - throw new IllegalStateException(String.format( - "Fail on flushing data to original storage! Expected version doesn't match! --[KEY=%s][EXPECTED_VERSION=%s]", - key, expVersion)); - } - expVersion++; - } - } - } - -// private static class CachedSetEntry implements VersioningKVEntry { -// -// private String key; -// -// private long version; -// -// private byte[] value; -// -// /** -// * -// * @param key -// * 键; -// * @param version -// * 新的版本; -// * @param value -// * 值; -// */ -// private CachedSetEntry(String key, long version, byte[] value) { -// this.key = key; -// this.version = version; -// this.value = value; -// } -// -// @Override -// public String getKey() { -// return key; -// } -// -// @Override -// public long getVersion() { -// return version; -// } -// -// @Override -// public byte[] getValue() { -// return value; -// } -// -// } - - -} diff --git a/source/storage/storage-service/src/test/java/test/com/jd/blockchain/storage/service/utils/BufferedKVStorageTest.java b/source/storage/storage-service/src/test/java/test/com/jd/blockchain/storage/service/utils/BufferedKVStorageTest.java deleted file mode 100644 index 4999256c..00000000 --- a/source/storage/storage-service/src/test/java/test/com/jd/blockchain/storage/service/utils/BufferedKVStorageTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package test.com.jd.blockchain.storage.service.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.UnsupportedEncodingException; - -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.utils.BufferedKVStorage; -import com.jd.blockchain.utils.Bytes; - -public class BufferedKVStorageTest { - - @Test - public void test() throws UnsupportedEncodingException { - ExPolicyKVStorage exStorage = Mockito.mock(ExPolicyKVStorage.class); - when(exStorage.get(any())).thenReturn(null); - when(exStorage.set(any(), any(), any())).thenReturn(true); - - VersioningKVStorage verStorage = Mockito.mock(VersioningKVStorage.class); - when(verStorage.getVersion(any())).thenReturn(-1L); - when(verStorage.get(any(), anyLong())).thenReturn(null); - when(verStorage.getEntry(any(), anyLong())).thenReturn(null); - when(verStorage.set(any(), any(), anyLong())).thenAnswer(new Answer() { - @Override - public Long answer(InvocationOnMock invocation) throws Throwable { - long ver = (long) invocation.getArguments()[2]; - return ver + 1; - } - }); - - BufferedKVStorage bufStorage = new BufferedKVStorage(exStorage, verStorage, false); - - byte[] data = "ABC".getBytes("UTF-8"); - long v = bufStorage.set(Bytes.fromString("A"), data, -1); - assertEquals(0, v); - v = bufStorage.set(Bytes.fromString("A"), data, v); - assertEquals(1, v); - v = bufStorage.set(Bytes.fromString("A"), data, v); - assertEquals(2, v); - - boolean ok = bufStorage.set(Bytes.fromString("B"), data, ExPolicy.NOT_EXISTING); - assertTrue(ok); - ok = bufStorage.set(Bytes.fromString("C"), data, ExPolicy.NOT_EXISTING); - assertTrue(ok); - ok = bufStorage.set(Bytes.fromString("D"), data, ExPolicy.NOT_EXISTING); - assertTrue(ok); - - verify(verStorage, times(0)).set(any(), any(), anyLong()); - verify(exStorage, times(0)).set(any(), any(), any()); - - bufStorage.flush(); - - verify(verStorage, times(3)).set(any(), any(), anyLong()); - verify(verStorage, times(1)).set(eq(Bytes.fromString("A")), any(), eq(-1L)); - verify(verStorage, times(1)).set(eq(Bytes.fromString("A")), any(), eq(0L)); - verify(verStorage, times(1)).set(eq(Bytes.fromString("A")), any(), eq(1L)); - - verify(exStorage, times(3)).set(any(), any(), any()); - verify(exStorage, times(1)).set(eq(Bytes.fromString("B")), any(), eq(ExPolicy.NOT_EXISTING)); - verify(exStorage, times(1)).set(eq(Bytes.fromString("C")), any(), eq(ExPolicy.NOT_EXISTING)); - verify(exStorage, times(1)).set(eq(Bytes.fromString("D")), any(), eq(ExPolicy.NOT_EXISTING)); - } -} diff --git a/source/test/test-consensus-client/.gitignore b/source/test/test-consensus-client/.gitignore deleted file mode 100644 index da7560e0..00000000 --- a/source/test/test-consensus-client/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.apt_generated_tests/ diff --git a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/ConsensusSettingService.java b/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/ConsensusSettingService.java deleted file mode 100644 index 007f233c..00000000 --- a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/ConsensusSettingService.java +++ /dev/null @@ -1,20 +0,0 @@ -package test.perf.com.jd.blockchain.consensus.client; - -import com.jd.blockchain.utils.http.HttpAction; -import com.jd.blockchain.utils.http.HttpMethod; -import com.jd.blockchain.utils.http.HttpService; - -/** - * Created by zhangshuang3 on 2018/9/11. - */ -@HttpService -public interface ConsensusSettingService { - - @HttpAction(path = "/node/settings", method = HttpMethod.GET) - public String getConsensusSettingsHex(); - - @HttpAction(path = "/node/topology", method = HttpMethod.GET) - public String getConsensusTopologyHex(); - -} - diff --git a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebBooter.java b/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebBooter.java deleted file mode 100644 index f010417c..00000000 --- a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebBooter.java +++ /dev/null @@ -1,17 +0,0 @@ -package test.perf.com.jd.blockchain.consensus.client; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; - -@SpringBootApplication -@EnableAutoConfiguration -@EnableConfigurationProperties -public class WebBooter { - - public static void main(String[] args) { - SpringApplication.run(WebBooter.class, args); - } - -} diff --git a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebClient.java b/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebClient.java deleted file mode 100644 index d3e674a3..00000000 --- a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebClient.java +++ /dev/null @@ -1,110 +0,0 @@ -//package test.perf.com.jd.blockchain.consensus.client; -// -//import java.util.Random; -// -//import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; -//import com.jd.blockchain.consensus.bftsmart.BftsmartTopology; -//import com.jd.blockchain.consensus.bftsmart.client.BftsmartClientConfig; -//import com.jd.blockchain.consensus.bftsmart.client.BftsmartClientSettings; -//import com.jd.blockchain.consensus.bftsmart.client.BftsmartConsensusClient; -//import com.jd.blockchain.crypto.asymmetric.PubKey; -//import com.jd.blockchain.ledger.BlockchainKeyGenerator; -//import my.utils.http.agent.HttpServiceAgent; -//import my.utils.http.agent.ServiceEndpoint; -//import my.utils.serialize.binary.BinarySerializeUtils; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.web.bind.annotation.PathVariable; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.RequestMethod; -//import org.springframework.web.bind.annotation.RestController; -// -// -//import my.utils.codec.HexUtils; -// -//@RestController -//@RequestMapping(path="bft") -//public class WebClient { -// -// @Autowired -// private Settings settings; -// -// private Random random=new Random(); -// -// private volatile byte[] msgBytes; -// -// private BftsmartConsensusClient client; -// -// private BftsmartConsensusSettings setting; -// -// private BftsmartTopology topology; -// -// public WebClient() { -// random = new Random(); -// updateMessage(32); -// } -// -// private void init() { -// } -// -// @RequestMapping(path="/message", method=RequestMethod.GET) -// public String getMessage() { -// return String.format("[size=%s]--[%s]", msgBytes.length, HexUtils.encode(msgBytes)); -// } -// -// private void updateMessage(int size) { -// msgBytes = new byte[size]; -// random.nextBytes(msgBytes); -// } -// -// @RequestMapping(path="/message/set/{size}", method=RequestMethod.GET) -// public String setMessage(@PathVariable("size") int size) { -// if (size < 1 || size > 1024*1024*200) { -// return "Size cann't be less than 1 byte or great than 200 MB! "; -// } -// updateMessage(size); -// return getMessage(); -// } -// -// @RequestMapping(path="/test/ordered", method=RequestMethod.GET) -// public String testOrdered() { -// if (client == null) { -// throw new IllegalStateException("client not exist"); -// } -// -// //CallerInfo info = Profiler.registerInfo("jd-chain-bftsmart-performence-client-proxy", false, true); -// byte[] retn = client.getMessageService().sendOrdered(msgBytes).get(); -// if(retn.length == 1 && retn[0] == 1){ -// //Profiler.registerInfoEnd(info); -// return "OK"; -// } -// //Profiler.functionError(info); -// return "FAIL"; -// } -// -// -// @RequestMapping(path="/connect/{from}/{port}", method=RequestMethod.GET) -// public String connect(@PathVariable("from") String from, @PathVariable("port") int port){ -// if (client != null) { -// throw new IllegalStateException("Has been connected to nodes!"); -// } -// ServiceEndpoint endpoint = new ServiceEndpoint(from, port, false); -// ConsensusSettingService settingService = HttpServiceAgent.createService(ConsensusSettingService.class, endpoint); -// String hexSetting = settingService.getConsensusSettingsHex(); -// String hexTopology = settingService.getConsensusTopologyHex(); -// setting = BinarySerializeUtils.deserialize(HexUtils.decode(hexSetting)); -// topology = BinarySerializeUtils.deserialize(HexUtils.decode(hexTopology)); -// -// // 0.8.0 version -//// client = new BftsmartConsensusClient(0, setting, topology); -// -// // 0.8.1 version -// PubKey clientPubKey= BlockchainKeyGenerator.getInstance().generate().getPubKey(); -// -// BftsmartClientSettings clientSettings = new BftsmartClientConfig(0, clientPubKey,setting, topology); -// -// BftsmartConsensusClient client = new BftsmartConsensusClient(clientSettings); -// -// return "OK"; -// } -// -//} diff --git a/source/test/test-consensus-node/.gitignore b/source/test/test-consensus-node/.gitignore deleted file mode 100644 index da7560e0..00000000 --- a/source/test/test-consensus-node/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.apt_generated_tests/ diff --git a/source/test/test-consensus-node/config/hosts.config b/source/test/test-consensus-node/config/hosts.config deleted file mode 100644 index d1775d3a..00000000 --- a/source/test/test-consensus-node/config/hosts.config +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# This file defines the replicas ids, IPs and ports. -# It is used by the replicas and clients to find connection info -# to the initial replicas. -# The ports defined here are the ports used by clients to communicate -# with the replicas. Additional connections are opened by replicas to -# communicate with each other. This additional connection is opened in the -# next port defined here. For an example, consider the line "0 127.0.0.1 11000". -# That means that clients will open a communication channel to replica 0 in -# IP 127.0.0.1 and port 11000. On startup, replicas with id different than 0 -# will open a communication channel to replica 0 in port 11001. -# The same holds for replicas 1, 2, 3 ... N. - -#server id, address and port (the ids from 0 to n-1 are the service replicas) -0 127.0.0.1 11000 -1 127.0.0.1 11010 -2 127.0.0.1 11020 -3 127.0.0.1 11030 -#4 192.168.151.33 11040 -#5 192.168.151.38 11050 -#6 127.0.0.1 11060 -#7 127.0.0.1 11070 -7001 127.0.0.1 11100 diff --git a/source/test/test-consensus-node/config/system.config b/source/test/test-consensus-node/config/system.config deleted file mode 100644 index ada42b49..00000000 --- a/source/test/test-consensus-node/config/system.config +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage diff --git a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/ConsensusTester.java b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/ConsensusTester.java deleted file mode 100644 index 3eb52366..00000000 --- a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/ConsensusTester.java +++ /dev/null @@ -1,546 +0,0 @@ -//package test.perf.com.jd.blockchain.consensus.node; -// -//import java.io.IOException; -//import java.io.InputStream; -//import java.util.Collections; -//import java.util.LinkedList; -//import java.util.List; -//import java.util.Properties; -//import java.util.concurrent.CountDownLatch; -//import java.util.concurrent.CyclicBarrier; -//import java.util.concurrent.atomic.AtomicInteger; -// -//import com.jd.blockchain.consensus.*; -//import com.jd.blockchain.consensus.bftsmart.*; -//import com.jd.blockchain.consensus.bftsmart.client.BftsmartClientSettings; -//import com.jd.blockchain.consensus.bftsmart.service.BftsmartServerSettingConfig; -//import com.jd.blockchain.consensus.service.MessageHandle; -//import com.jd.blockchain.consensus.service.ServerSettings; -//import com.jd.blockchain.consensus.service.StateMachineReplicate; -//import com.jd.blockchain.crypto.asymmetric.PubKey; -//import com.jd.blockchain.ledger.BlockchainKeyGenerator; -//import com.jd.blockchain.peer.consensus.ConsensusMessageDispatcher; -//import com.jd.blockchain.peer.consensus.LedgerStateManager; -//import com.jd.blockchain.tools.keygen.KeyGenCommand; -//import my.utils.PropertiesUtils; -//import my.utils.Property; -//import my.utils.net.NetworkAddress; -//import org.springframework.core.io.ClassPathResource; -// -//import bftsmart.reconfiguration.util.HostsConfig; -//import my.utils.ConsoleUtils; -//import my.utils.concurrent.AsyncFuture; -//import my.utils.concurrent.ThreadInvoker; -//import my.utils.concurrent.ThreadInvoker.AsyncCallback; -//import my.utils.concurrent.ThreadUtils; -//import my.utils.io.BytesUtils; -//import my.utils.io.FileUtils; -// -//public class ConsensusTester { -// -// public static final String PASSWORD = "abc"; -// -// public static final String[] PUB_KEYS = { "endPsK36imXrY66pru6ttZ8dZ3TynWekmdqoM1K7ZRRoRBBiYVzM", -// "endPsK36jQE1uYpdVRSnwQXVYhgAMWTaMJiAqii7URiULoBDLUUN", -// "endPsK36fc7FSecKAJCJdFhTejbPHMLaGcihJVQCv95czCq4tW5n", -// "endPsK36m1grx8mkTMgh8XQHiiaNzajdC5hkuqP6pAuLmMbYkzd4" }; -// -// public static final String[] PRIV_KEYS = { -// "177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X", -// "177gjwQwTdXthkutDKVgKwiq6wWfLWYuxhji1U2N1C5MzqLRWCLZXo3i2g4vpfcEAQUPG8H", -// "177gjvLHUjxvAWsqVcGgV8eHgVNBvJZYDfpP9FLjTouR1gEJNiamYu1qjTNDh18XWyLg8or", -// "177gk2VtYeGbK5TS2xWhbSZA4BsT9Xj5Fb8hqCzxzgbojVVcqaDSFFrFPsLbZBx7rszyCNy" }; -// -// public static volatile boolean debug = false; -// -// public static MessageHandle consensusMessageHandler = new ConsensusMessageDispatcher(); -// public static StateMachineReplicate consensusStateManager = new LedgerStateManager(); -// -// public static void main(String[] args) { -// // DataContractRegistry.register(ActionResponse.class); -// try { -// HostsConfig hosts = new HostsConfig(); -// hosts.add(0, "127.0.0.1", 10000); -// hosts.add(1, "127.0.0.1", 10010); -// hosts.add(2, "127.0.0.1", 10020); -// hosts.add(3, "127.0.0.1", 10030); -// -// TestServceHandle handle0 = new TestServceHandle(0); -// AsyncCallback call0 = startReplica(0, hosts, handle0); -// TestServceHandle handle1 = new TestServceHandle(1); -// AsyncCallback call1 = startReplica(1, hosts, handle1); -// TestServceHandle handle2 = new TestServceHandle(2); -// AsyncCallback call2 = startReplica(2, hosts, handle2); -// TestServceHandle handle3 = new TestServceHandle(3); -// AsyncCallback call3 = startReplica(3, hosts, handle3); -// -// BftsmartConsensusServlet replica0 = call0.waitReturn(); -// BftsmartConsensusServlet replica1 = call1.waitReturn(); -// BftsmartConsensusServlet replica2 = call2.waitReturn(); -// BftsmartConsensusServlet replica3 = call3.waitReturn(); -// -// ConsoleUtils.info("All replicas have started!"); -// -// Topology tp = replica0.getTopology().copyOf(); -// -// { -// // 单步测试; -// // TestServce clientService = createClientService(0, hosts, tp); -// // debug = true; -// // ConsoleUtils.info("First message..."); -// // String resp = clientService.hello("AAAA"); -// //// String resp = clientService.hello("[SLEEP] AAAA"); -// // ConsoleUtils.info("response:[%s]", resp); -// -// // ConsoleUtils.info("Second message..."); -// // resp = clientService.hello("[SLEEP] BBBB"); -// // ConsoleUtils.info("response:[%s]", resp); -// } -// { -// // 异步调用; -// // TestServce clientService = createClientService(0, hosts, tp); -// // clientService = AsyncInvoker.asynchorize(TestServce.class, clientService); -// // debug = true; -// // long startTs = System.currentTimeMillis(); -// // ConsoleUtils.info("[%s] Async send first message...", startTs); -// // AsyncResult ayncResult = -// // AsyncInvoker.call(clientService.hello("AAAA")); -// // ayncResult.addListener(new my.utils.concurrent.AsyncCallback() { -// // @Override -// // public void complete(String replyMessage, Throwable error) { -// // if (error != null) { -// // long endTs = System.currentTimeMillis(); -// // ConsoleUtils.error("[%s][spanTS=%s] Async response error!!! --%s", endTs, -// // endTs - startTs, -// // error.getMessage()); -// // error.printStackTrace(); -// // return; -// // } -// // -// // ConsoleUtils.info("Async response:[%s]", replyMessage); -// // } -// // }); -// -// } -// -// { -// // 单客户端并发消息发送测试; -// // TestServce clientService = createClientService(0, hosts, tp); -// // testConcurrentMessageSending(clientService, 100); -// } -// -// { -// // 多客户端并发消息发送测试; -// int msgCount = 60000; -// -// AtomicInteger receiveCount = new AtomicInteger(0); -// -// // my.utils.concurrent.AsyncCallback callback = new -// // my.utils.concurrent.AsyncCallback() { -// // @Override -// // public void complete(String replyMessage, Throwable error) { -// // if (error != null) { -// // long endTs = System.currentTimeMillis(); -// // ConsoleUtils.error("[%s][spanTS=%s] Async response error!!! --%s", endTs, -// // endTs - startTs, -// // error.getMessage()); -// // error.printStackTrace(); -// // return; -// // } -// // int c = receiveCount.incrementAndGet(); -// // if (c >= msgCount) { -// // long endTs = System.currentTimeMillis(); -// // ConsoleUtils.info("\r\n============== All message has been received response! -// // [耗时:%s millis][TPS=%.2f] =====\r\n", (endTs - startTs), msgCount * 1000.0D -// // /(endTs - startTs)); -// // } -// // } -// // }; -// -// TestServce[] sessions = createSessions(10, hosts, tp); -// -// long startTs = System.currentTimeMillis(); -// ConsoleUtils.info("[%s] Async send first message...", startTs); -// AtomicInteger arrivedCounter = new AtomicInteger(0); -// my.utils.concurrent.AsyncHandle allArrivedCallback = new my.utils.concurrent.AsyncHandle() { -// -// @Override -// public void complete(String returnValue, Throwable error) { -// int c = arrivedCounter.incrementAndGet(); -// if (c >= 3) { -// long endTs = System.currentTimeMillis(); -// ConsoleUtils.info( -// "\r\n============== All message has been received by most nodes! [耗时:%s millis][TPS=%.2f] =====\r\n", -// (endTs - startTs), msgCount * 1000.0D / (endTs - startTs)); -// -// } -// if (c >= 4) { -// ConsoleUtils.info("Verify consistence of all replicas after all message received!"); -// verifyConsistence(msgCount, handle0, handle1, handle2, handle3); -// } -// } -// }; -// -// handle0.setThreshold(msgCount, allArrivedCallback); -// handle1.setThreshold(msgCount, allArrivedCallback); -// handle2.setThreshold(msgCount, allArrivedCallback); -// handle3.setThreshold(msgCount, allArrivedCallback); -// -// testConcurrentClient(sessions, msgCount, null); -// ConsoleUtils.info("Complete client sending."); -// -// boolean consistent; -// int tryTimes = 0; -// do { -// ConsoleUtils.info("Verify consistence of all replicas...[%s]", tryTimes); -// consistent = verifyConsistence(msgCount, handle0, handle1, handle2, handle3); -// if (consistent) { -// break; -// } -// tryTimes++; -// ThreadUtils.sleepUninterrupted(1000); -// } while (tryTimes < 5); -// } -// ConsoleUtils.info("----- Test finish! -----"); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// -// public static boolean verifyConsistence(int expectedMessageCount, TestServceHandle... handles) { -// try { -// for (int i = 0; i < handles.length; i++) { -// assertEquals(expectedMessageCount, handles[i].getMessageCount(), "replica[" + i + "] message count"); -// } -// -// for (int i = 0; i < expectedMessageCount; i++) { -// String msg0 = handles[0].getMessage(i); -// assertNotNULL(msg0, "replica[" + i + "]"); -// for (int j = 1; j < handles.length; j++) { -// String msg1 = handles[j].getMessage(i); -// assertEquals(msg0, msg1, "message comparison between replica[0] and replica[" + j + "]"); -// } -// } -// -// ConsoleUtils.info("========== states of all replicas are consistence! ======="); -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// } -// -// public static void assertNotNULL(Object actual, String note) { -// if (actual == null) { -// throw new IllegalStateException(String.format("%s (expected NULL, but actual[%s])", note, actual)); -// } -// } -// -// public static void assertEquals(Object expected, Object actual, String note) { -// if (expected == null && actual == null) { -// return; -// } -// if (expected == null) { -// throw new IllegalStateException(String.format("%s (expected[%s], but actual[%s])", note, expected, actual)); -// } -// if (!expected.equals(actual)) { -// throw new IllegalStateException(String.format("%s (expected[%s], but actual[%s])", note, expected, actual)); -// } -// } -// -// private static TestServce[] createSessions(int sessionCount, HostsConfig hosts, Topology tp) { -// TestServce[] clients = new TestServce[sessionCount]; -// for (int i = 0; i < clients.length; i++) { -// PubKey clientPubKey= BlockchainKeyGenerator.getInstance().generate().getPubKey(); -// TestServce clientService = createClientService(i, clientPubKey, hosts, tp.copyOf()); -// clients[i] = AsyncInvoker.asynchorize(TestServce.class, clientService); -// } -// return clients; -// } -// -// public static void testConcurrentClient(TestServce[] clients, int count, -// my.utils.concurrent.AsyncHandle callback) { -// // TestServce[] clients = createSessions(id, hosts, tp); -// -// ConsoleUtils.info("All clients has conected to replicas..."); -// -// MessageSendingTask[] tasks = new MessageSendingTask[count]; -// -// int sessionCount = clients.length; -// CyclicBarrier barrier = new CyclicBarrier(sessionCount); -// AtomicInteger counter = new AtomicInteger(0); -// for (int i = 0; i < sessionCount; i++) { -// tasks[i] = new MessageSendingTask(count, counter, clients[i], barrier, null, callback); -// Thread thrd = new Thread(tasks[i]); -// -// thrd.start(); -// } -// -// } -// -// public static void testConcurrentMessageSending(TestServce clientService, int count) { -// -// CyclicBarrier barrier = new CyclicBarrier(count); -// for (int i = 0; i < count; i++) { -// -// Thread thrd = new Thread(new Runnable() { -// -// @Override -// public void run() { -// try { -// barrier.await(); -// clientService.hello("AAAA-" + count); -// } catch (Exception e) { -// ConsoleUtils.error("Error occurred on sending message! --%s", e.getMessage()); -// e.printStackTrace(); -// } -// } -// }); -// -// thrd.start(); -// } -// } -// -// public static TestServce createClientService(int id, PubKey clientPubKey, HostsConfig hosts, Topology tp) { -// Properties systemConfig = loadConsensusSetting(); -// -// BftsmartTopology topology = (BftsmartTopology)tp.copyOf(); -// Property[] bftsmartSystemConfigs = PropertiesUtils.getOrderedValues(systemConfig); -// -// BftsmartNodeSettings[] nodesSettings = new BftsmartNodeSettings[hosts.getNum()]; -// -// for (int i = 0; i < hosts.getNum(); i++) { -// PubKey pubKey = KeyGenCommand.decodePubKey(PUB_KEYS[i]); -// BftsmartNodeConfig nodeConfig = new BftsmartNodeConfig(pubKey, i, -// new NetworkAddress(hosts.getHost(i), hosts.getPort(i), false)); -// nodesSettings[i] = nodeConfig; -// } -// -// ConsensusSettings consensusSettings = new BftsmartConsensusConfig(nodesSettings, null, -// bftsmartSystemConfigs); -// -// BftsmartClientSettings clientSettings = new BftsmartClientSettings(id, clientPubKey, consensusSettings, topology); -// BftsmartConsensusProxyFactory serviceFactory = BftsmartConsensusProxyFactory.connect(clientSettings); -// -// // BftsmartConsensusSetting consensusSetting = new BftsmartConsensusSetting(id, -// // systemConfig, hosts); -// // BftsmartConsensusServiceFactory serviceFactory = -// // BftsmartConsensusServiceFactory.connect(0, consensusSetting, -// // (BftsmartTopology) tp); -// -// return serviceFactory.getService(TestServce.class); -// } -// -// public static AsyncCallback startReplica(int id, HostsConfig hosts, -// TestServce serviceHandle) { -// Properties systemConfig = loadConsensusSetting(); -// -// Property[] bftsmartSystemConfigs = PropertiesUtils.getOrderedValues(systemConfig); -// -// BftsmartNodeSettings currNodeSettings = null; -// -// for (int i = 0; i < hosts.getNum(); i++) { -// PubKey pubKey = KeyGenCommand.decodePubKey(PUB_KEYS[i]); -// BftsmartNodeConfig nodeConfig = new BftsmartNodeConfig(pubKey, i, -// new NetworkAddress(hosts.getHost(i), hosts.getPort(i), false)); -// -// if (i == id) { -// currNodeSettings = nodeConfig; -// } -// } -// -// ServerSettings serverSettings = new BftsmartServerSettingConfig(); -// ((BftsmartServerSettingConfig) serverSettings).setRealmName(null); -// ((BftsmartServerSettingConfig) serverSettings).setReplicaSettings(currNodeSettings); -// -// // BftsmartConsensusServlet servlet = new BftsmartConsensusServlet(id, -// // systemConfig, hosts); -// BftsmartConsensusServlet servlet = new BftsmartConsensusServlet(serverSettings, consensusMessageHandler, -// consensusStateManager); -//// servlet.addServiceHandler(TestServce.class, serviceHandle); -// -// ThreadInvoker invoker = new ThreadInvoker() { -// @Override -// protected BftsmartConsensusServlet invoke() throws Exception { -// try { -// servlet.start(); -// ConsoleUtils.info("Replica[%s] start success.", id); -// return servlet; -// } catch (Exception e) { -// ConsoleUtils.info("Replica[%s] start failed!", id); -// e.printStackTrace(); -// throw e; -// } -// } -// }; -// -// return invoker.start(); -// } -// -// public static Properties loadConsensusSetting() { -// ClassPathResource ledgerInitSettingResource = new ClassPathResource("system.config"); -// try (InputStream in = ledgerInitSettingResource.getInputStream()) { -// return FileUtils.readProperties(in); -// } catch (IOException e) { -// throw new IllegalStateException(e.getMessage(), e); -// } -// } -// -// public static class TextMessageConverter implements BinaryMessageConverter { -// -// @Override -// public byte[] encode(Object message) { -// return BytesUtils.toBytes((String) message); -// } -// -// @Override -// public Object decode(byte[] messageBytes) { -// return BytesUtils.toString(messageBytes); -// } -// -// } -// -// public static class DefaultGroupIndexer implements GroupIndexer { -// -// private byte[] groupId = { (byte) 0 }; -// -// @Override -// public byte[] getGroupId(Object[] messageObjects) { -// return groupId; -// } -// -// } -// -// // =================================================== -// -// public static interface TestServce { -// @OrderedAction(groupIndexer = DefaultGroupIndexer.class, responseConverter = TextMessageConverter.class) -// String hello(@ActionMessage(converter = TextMessageConverter.class) String msg); -// } -// -// private static class TestServceHandle implements TestServce, StateHandle { -// -// private int id; -// -// private List msgs = Collections.synchronizedList(new LinkedList<>()); -// -// private AtomicInteger counter = new AtomicInteger(0); -// private int threshold; -// private my.utils.concurrent.AsyncHandle callback; -// -// public void setThreshold(int threshold, my.utils.concurrent.AsyncHandle callback) { -// this.counter.set(0); -// this.threshold = threshold; -// this.callback = callback; -// } -// -// public int getMessageCount() { -// return msgs.size(); -// } -// -// public String getMessage(int index) { -// return msgs.get(index); -// } -// -// public void clear() { -// msgs.clear(); -// } -// -// public TestServceHandle(int id) { -// this.id = id; -// } -// -// @Override -// public String hello(String msg) { -// if (debug) { -// ConsoleUtils.info("Handle message in replica[%s]. --MSG:%s", id, msg); -// } -// msgs.add(msg); -// int c = counter.incrementAndGet(); -// if (c == threshold && callback != null) { -// callback.complete("OK", null); -// } -// if (msg != null && msg.startsWith("[SLEEP]")) { -// try { -// Thread.sleep(600000); -// } catch (InterruptedException e) { -// } -// } -// return "OK"; -// } -// -// @Override -// public byte[] takeSnapshot() { -// int msgCount = getMessageCount(); -// ConsoleUtils.info("Take snapshot...[replica.id=%s][message.count=%s]", id, msgCount); -// return BytesUtils.toBytes(msgCount); -// } -// -// @Override -// public void installSnapshot(byte[] snapshot) { -// int msgCount = getMessageCount(); -// ConsoleUtils.info("Intall snapshot...[replica.id=%s][message.count=%s][snapshot.size=%s]", id, msgCount, -// snapshot == null ? 0 : snapshot.length); -// } -// -// } -// -// private static class MessageSendingTask implements Runnable { -// -// public static final String MESSAGE = "_ABCDEF"; -// -// private CyclicBarrier barrier; -// -// private CountDownLatch latch; -// -// private TestServce client; -// -// private int totalCount; -// private AtomicInteger counter; -// -// private my.utils.concurrent.AsyncHandle callback; -// -// // public MessageSendingTask(int taskId, TestServce client) { -// // this(taskId, client, null, null, null); -// // } -// -// public MessageSendingTask(int totalCount, AtomicInteger counter, TestServce client, CyclicBarrier barrier, -// CountDownLatch latch, my.utils.concurrent.AsyncHandle callback) { -// this.totalCount = totalCount; -// this.counter = counter; -// this.barrier = barrier; -// this.latch = latch; -// this.client = client; -// this.callback = callback; -// } -// -// @Override -// public void run() { -// try { -// if (barrier != null) { -// barrier.await(); -// } -// while (true) { -// int taskId = counter.incrementAndGet(); -// if (taskId > totalCount) { -// return; -// } -// AsyncFuture result = AsyncInvoker.call(client.hello(taskId + MESSAGE)); -// if (callback != null) { -// result.whenCompleteAsync(callback); -// } -// } -// -// } catch (Exception e) { -// ConsoleUtils.error("Error occurred on sending message! --%s", e.getMessage()); -// e.printStackTrace(); -// } finally { -// if (latch != null) { -// latch.countDown(); -// } -// } -// } -// -// } -// -//} diff --git a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/TestReplica.java b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/TestReplica.java deleted file mode 100644 index df8a8e4c..00000000 --- a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/TestReplica.java +++ /dev/null @@ -1,55 +0,0 @@ -package test.perf.com.jd.blockchain.consensus.node; - -import java.util.Properties; - -import bftsmart.reconfiguration.util.HostsConfig; -import com.jd.blockchain.consensus.AsyncActionResponse; -import com.jd.blockchain.consensus.action.ActionRequest; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartNodeServer; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartServerSettingConfig; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartServerSettings; -import com.jd.blockchain.consensus.service.MessageHandle; -import com.jd.blockchain.peer.consensus.ConsensusMessageDispatcher; -import com.jd.blockchain.utils.ConsoleUtils; - -public class TestReplica extends BftsmartNodeServer { - - private byte[] retnOK = {1}; - - public TestReplica(int id, Properties systemsConfig, HostsConfig hostConfig) { - super(new BftsmartServerSettingConfig(), new ConsensusMessageDispatcher(), null); - } - -// @Override -// protected AsyncActionResponse execute(ActionRequest request) { -// ConsoleUtils.info("Receive request ..."); -// return new SimpleResponse(retnOK); -// } - - private static class SimpleResponse implements AsyncActionResponse{ - - private byte[] data; - - public SimpleResponse(byte[] data) { - this.data = data; - } - - @Override - public byte[] process() { - return data; - } - - } - - @Override - public void installSnapshot(byte[] state) { - // TODO Auto-generated method stub - - } - - @Override - public byte[] getSnapshot() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/TestWebController.java b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/TestWebController.java deleted file mode 100644 index 420704bf..00000000 --- a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/TestWebController.java +++ /dev/null @@ -1,138 +0,0 @@ -package test.perf.com.jd.blockchain.consensus.node; - -import java.util.Properties; -import java.util.TreeSet; - -import javax.annotation.PostConstruct; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.Topology; -import com.jd.blockchain.utils.codec.HexUtils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import bftsmart.reconfiguration.util.HostsConfig; - -@RestController -public class TestWebController { - - @Autowired - private Settings settings; - - private Properties systemProperties; - - private HostsConfig nodesConfig; - - private TestReplica replica; - - public TestWebController() { - } - - @PostConstruct - private void init() { - nodesConfig = new HostsConfig(settings.getNodesConfig()); - systemProperties = FileUtils.readProperties(settings.getSystemConfig()); - } - - @RequestMapping(path = "/configs/consensus", method = RequestMethod.GET) - public String getSystemProperties() { - TreeSet names = new TreeSet<>(systemProperties.stringPropertyNames()); - StringBuilder content = new StringBuilder(); - for (String n : names) { - content.append(String.format("%s=%s
\r\n", n, systemProperties.getProperty(n))); - } - return content.toString(); - } - - @RequestMapping(path = "/configs/consensus/set/{key}/{value}", method = RequestMethod.GET) - public String setSystemProperty(@PathVariable("key") String key, @PathVariable("value") String value) { - systemProperties.setProperty(key, value); - return getSystemProperties(); - } - - @RequestMapping(path = "/configs/consensus/set/default", method = RequestMethod.GET) - public String setSystemDefaultProperty() { - systemProperties = FileUtils.readProperties(settings.getSystemConfig()); - return getSystemProperties(); - } - - @RequestMapping(path = "/configs/nodes", method = RequestMethod.GET) - public String getNodes() { - StringBuilder content = new StringBuilder(); - int[] ids = nodesConfig.getHostsIds(); - for (int id : ids) { - content.append(String.format("%s - %s:%s [%s]
\r\n", id, nodesConfig.getHost(id), nodesConfig.getPort(id), - nodesConfig.getServerToServerPort(id))); - } - return content.toString(); - } - - - @RequestMapping(path = "/configs/nodes/set/{id}/{host}/{port}", method = RequestMethod.GET) - public String setNode(@PathVariable("id") int id, @PathVariable("host") String host, - @PathVariable("port") int port) { - nodesConfig.add(id, host, port); - return getNodes(); - } - - @RequestMapping(path = "/node/id", method = RequestMethod.GET) - public String getNodeID() { - return "Node.ID=" + (replica == null ? 0 : replica.getId()); - } - - @RequestMapping(path = "/node/status", method = RequestMethod.GET) - public String getStatus() { - return replica == null ? "STOPPED" : "RUNNING"; - } - - @RequestMapping(path = "/node/start/{id}", method = RequestMethod.GET) - public String start(@PathVariable("id")int id) { - if (replica != null ) { - return "Already started!"; - } - TestReplica replica = new TestReplica(id, systemProperties, nodesConfig); - //after new TestConsensusReplica systemProperties field will be removed - replica.start(); - this.replica = replica; - return "success!"; - } - - @RequestMapping(path = "/node/stop", method = RequestMethod.GET) - public String stop() { - if (replica == null ) { - return "Already stopped!"; - } - TestReplica replica = this.replica; - this.replica = null; - replica.stop(); - return "stopped!"; - } - - - @RequestMapping(path = "/node/topology", method = RequestMethod.GET) - public String getNodesTopology(){ - if (replica == null ) { - throw new IllegalStateException("Replica not start"); - } - Topology tp = replica.getTopology().copyOf(); - byte[] bytesTP = BinarySerializeUtils.serialize(tp); - return HexUtils.encode(bytesTP); - } - - @RequestMapping(path = "/node/settings", method = RequestMethod.GET) - public String getNodesSettings(){ - if (replica == null ) { - throw new IllegalStateException("Replica not start"); - } - ConsensusSettings settings = replica.getConsensusSetting(); - byte[] bytesSettings = BinarySerializeUtils.serialize(settings); - return HexUtils.encode(bytesSettings); - } - -} diff --git a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/WebBooter.java b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/WebBooter.java deleted file mode 100644 index fa62c90d..00000000 --- a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/WebBooter.java +++ /dev/null @@ -1,17 +0,0 @@ -package test.perf.com.jd.blockchain.consensus.node; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; - -@SpringBootApplication -@EnableAutoConfiguration -@EnableConfigurationProperties -public class WebBooter { - - public static void main(String[] args) { - SpringApplication.run(WebBooter.class, args); - } - -} diff --git a/source/test/test-consensus-node/src/main/resources/system.config b/source/test/test-consensus-node/src/main/resources/system.config deleted file mode 100644 index bf8beec8..00000000 --- a/source/test/test-consensus-node/src/main/resources/system.config +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 800 -system.totalordermulticast.global_checkpoint_period = 5000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/GatewayTestRunner.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/GatewayTestRunner.java deleted file mode 100644 index d152cd02..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/GatewayTestRunner.java +++ /dev/null @@ -1,76 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import com.jd.blockchain.gateway.GatewayConfigProperties; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; -import com.jd.blockchain.gateway.GatewayServerBooter; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.util.CollectionUtils; - -import java.util.Map; - -public class GatewayTestRunner { - - private NetworkAddress serviceAddress; - - private GatewayServerBooter gatewayServer; - - public GatewayTestRunner(String host, int port, KeyPairConfig gatewayDefaultKey, NetworkAddress masterPeerAddres) { - this(host, port, gatewayDefaultKey, masterPeerAddres, null,null); - } - - public GatewayTestRunner(String host, int port, KeyPairConfig gatewayDefaultKey, NetworkAddress masterPeerAddres, String[] providers, - Map otherMap) { - this.serviceAddress = new NetworkAddress(host, port); - GatewayConfigProperties config = new GatewayConfigProperties(); - - config.http().setHost(host); - config.http().setPort(port); - - if (providers != null) { - for (String provider : providers) { - config.providerConfig().add(provider); - } - } - - config.setMasterPeerAddress(masterPeerAddres); - - config.keys().getDefault().setPubKeyValue(gatewayDefaultKey.getPubKeyValue()); - config.keys().getDefault().setPrivKeyValue(gatewayDefaultKey.getPrivKeyValue()); - config.keys().getDefault().setPrivKeyPassword(gatewayDefaultKey.getPrivKeyPassword()); - - if(!CollectionUtils.isEmpty(otherMap)){ - config.setDataRetrievalUrl(otherMap.get("DATA_RETRIEVAL_URL").toString()); - } - - - //get the springConfigLocation; - ClassPathResource configResource = new ClassPathResource("application-gw.properties"); - String springConfigLocation = "classPath:"+configResource.getPath(); - - this.gatewayServer = new GatewayServerBooter(config,springConfigLocation); - } - - public AsyncCallback start() { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected Object invoke() throws Exception { - gatewayServer.start(); - return null; - } - }; - - return invoker.start(); - } - - public void stop() { - gatewayServer.close(); - } - - public NetworkAddress getServiceAddress() { - return serviceAddress; - } -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegratedContext.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegratedContext.java deleted file mode 100644 index f77158bd..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegratedContext.java +++ /dev/null @@ -1,113 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; - -public class IntegratedContext { - - private HashDigest ledgerHash; - - private Map nodes = new HashMap<>(); - - public int[] getNodeIds() { - int[] ids = new int[nodes.size()]; - int i = 0; - for (Integer id : nodes.keySet()) { - ids[i] = id.intValue(); - i++; - } - Arrays.sort(ids); - return ids; - } - - public HashDigest getLedgerHash() { - return ledgerHash; - } - - public void setLedgerHash(HashDigest ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public Node getNode(int id) { - return nodes.get(id); - } - - public void addNode(Node node) { - nodes.put(node.getId(), node); - } - - public static class Node { - - private int id; - - private AsymmetricKeypair partiKeyPair; - - // private NetworkAddress consensusAddress; - private ConsensusSettings consensusSettings; - - private LedgerManager ledgerManager; - - private DbConnectionFactory storageDB; - - private LedgerBindingConfig bindingConfig; - - public Node(int id) { - this.id = id; - } - - public ConsensusSettings getConsensusAddress() { - return consensusSettings; - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - } - - public DbConnectionFactory getStorageDB() { - return storageDB; - } - - public AsymmetricKeypair getPartiKeyPair() { - return partiKeyPair; - } - - public void setPartiKeyPair(AsymmetricKeypair partiKeyPair) { - this.partiKeyPair = partiKeyPair; - } - - public int getId() { - return id; - } - - public void setConsensusSettings(ConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - } - - public void setLedgerManager(LedgerManager ledgerManager) { - this.ledgerManager = ledgerManager; - } - - public void setStorageDB(DbConnectionFactory storageDB) { - this.storageDB = storageDB; - } - - public LedgerBindingConfig getBindingConfig() { - return bindingConfig; - } - - public void setBindingConfig(LedgerBindingConfig bindingConfig) { - this.bindingConfig = bindingConfig; - } - - } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegrationTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegrationTest.java deleted file mode 100644 index 8324af7c..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegrationTest.java +++ /dev/null @@ -1,956 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.Random; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartNodeServer; -import com.jd.blockchain.consensus.bftsmart.service.BftsmartServerSettings; -import com.jd.blockchain.consensus.service.*; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.*; -import com.jd.blockchain.peer.consensus.ConsensusMessageDispatcher; -import com.jd.blockchain.peer.consensus.LedgerStateManager; -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.HexUtils; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.IntegratedContext.Node; -import test.com.jd.blockchain.intgr.perf.LedgerInitializeWebTest; -import test.com.jd.blockchain.intgr.perf.Utils; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; - -public class IntegrationTest { - // 合约测试使用的初始化数据; - BlockchainKeypair contractDataKey = BlockchainKeyGenerator.getInstance().generate(); - BlockchainKeypair contractDeployKey = BlockchainKeyGenerator.getInstance().generate(); - private String contractZipName = "AssetContract1.contract"; - private String eventName = "issue-asset"; - HashDigest txContentHash; - // String userPubKeyVal = "this is user's pubKey"; - // 保存资产总数的键; - private static final String KEY_TOTAL = "TOTAL"; - // 第二个参数; - private static final String KEY_ABC = "abc"; - - private static final String MQ_SERVER = "nats://127.0.0.1:4222"; - - private static final String MQ_TOPIC = "subject"; - - private static String memDbConnString = LedgerInitConsensusConfig.memConnectionStrings[0]; - - private static AtomicBoolean isTestTurnOn = new AtomicBoolean(false); - - public static final String PASSWORD = "abc"; - - public static final String PUB_KEYS = "3snPdw7i7Pb3B5AxpSXy6YVruvftugNQ7rB7k2KWukhBwKQhFBFagT"; - public static final String PRIV_KEYS = "177gjtSgSdUF3LwRFGhzbpZZxmXXChsnwbuuLCG1V9KYfVuuxLwXGmZCp5FGUvsenhwBQLV"; - - - public static void main_(String[] args) { - // init ledgers of all nodes ; - IntegratedContext context = initLedgers(); - - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - Node node2 = context.getNode(2); - Node node3 = context.getNode(3); - - LedgerManager ledgerManagerMock0 = Mockito.spy(node0.getLedgerManager()); - LedgerManager ledgerManagerMock1 = Mockito.spy(node1.getLedgerManager()); - LedgerManager ledgerManagerMock2 = Mockito.spy(node2.getLedgerManager()); - LedgerManager ledgerManagerMock3 = Mockito.spy(node3.getLedgerManager()); - - node0.setLedgerManager(ledgerManagerMock0); - node1.setLedgerManager(ledgerManagerMock1); - node2.setLedgerManager(ledgerManagerMock2); - node3.setLedgerManager(ledgerManagerMock3); - - //todo -// mockNodeServer(context); - - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 10200); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, node0.getBindingConfig(), node0.getStorageDB(), node0.getLedgerManager()); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 10210); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, node1.getBindingConfig(), node1.getStorageDB(), node1.getLedgerManager()); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 10220); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, node2.getBindingConfig(), node2.getStorageDB(), node2.getLedgerManager()); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 10230); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, node3.getBindingConfig(), node3.getStorageDB(), node3.getLedgerManager()); - - ThreadInvoker.AsyncCallback peerStarting0 = peer0.start(); - ThreadInvoker.AsyncCallback peerStarting1 = peer1.start(); - ThreadInvoker.AsyncCallback peerStarting2 = peer2.start(); - ThreadInvoker.AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWebTest.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(LedgerInitializeWebTest.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(LedgerInitializeWebTest.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - - GatewayTestRunner gateway0 = new GatewayTestRunner("127.0.0.1", 10300, gwkey0, peerSrvAddr0, LedgerInitConsensusConfig.bftsmartProvider, null); - - ThreadInvoker.AsyncCallback gwStarting0 = gateway0.start(); - - gwStarting0.waitReturn(); - - // 执行测试用例之前,校验每个节点的一致性; -// testConsistencyAmongNodes(context); - - testStorageErrorBlockRollbackSdk(gateway0, context); - - testConsensusFirstTimeoutSdk(gateway0, context); - - testConsensusSecondTimeoutSdk(gateway0, context); - - //todo -// testBlockHashInconsistentSdk(gateway0, context); - - testTransactionRollbackSdk(gateway0, context); - - testInvalidUserSignerSdk(gateway0, context); - - testSDK(gateway0, context); - - System.out.println("------IntegrationTest Ok--------"); - - // 执行测试用例之后,校验每个节点的一致性; -// testConsistencyAmongNodes(context); - } - - //todo -// private static void mockNodeServer(IntegratedContext context) { -// -// Bytes nodeAddress0 = AddressEncoding.generateAddress(context.getNode(0).getPartiKeyPair().getPubKey()); -// Bytes nodeAddress1 = AddressEncoding.generateAddress(context.getNode(1).getPartiKeyPair().getPubKey()); -// Bytes nodeAddress2 = AddressEncoding.generateAddress(context.getNode(2).getPartiKeyPair().getPubKey()); -// Bytes nodeAddress3 = AddressEncoding.generateAddress(context.getNode(3).getPartiKeyPair().getPubKey()); -// -// BftsmartConsensusProvider bftsmartProvider0 = new BftsmartConsensusProvider(); -// BftsmartConsensusProvider mockedBftsmartProvider0 = Mockito.spy(bftsmartProvider0); -// -// BftsmartConsensusProvider bftsmartProvider1 = new BftsmartConsensusProvider(); -// BftsmartConsensusProvider mockedBftsmartProvider1 = Mockito.spy(bftsmartProvider1); -// -// BftsmartConsensusProvider bftsmartProvider2 = new BftsmartConsensusProvider(); -// BftsmartConsensusProvider mockedBftsmartProvider2 = Mockito.spy(bftsmartProvider2); -// -// BftsmartConsensusProvider bftsmartProvider3 = new BftsmartConsensusProvider(); -// BftsmartConsensusProvider mockedBftsmartProvider3 = Mockito.spy(bftsmartProvider3); -// -// doAnswer(new Answer() { -// @Override -// public BftsmartNodeServer answer(InvocationOnMock invocation) throws Throwable { -// BftsmartServerSettings serverSettings =(BftsmartServerSettings) invocation.getArguments()[0]; -// -// MessageHandle messageHandle = new ConsensusMessageDispatcher(); -// // mock spy messageHandle -// MessageHandle mockedMessageHandle = Mockito.spy(messageHandle); -// -// StateMachineReplicate stateMachineReplicate = new LedgerStateManager(); -// -// if(nodeAddress0.equals(serverSettings.getReplicaSettings().getAddress())){ -// doAnswer(new Answer() { -// @Override -// public Object answer(InvocationOnMock invocation) throws Throwable { -// -// if (isTestTurnOn.get()) { -// Random random = new Random(); -// byte[] msg = new byte[4]; -// random.nextBytes(msg); -// invocation.getArguments()[0] = msg; -// } -// return invocation.callRealMethod(); -// } -// }).when(mockedMessageHandle).processOrdered(any(), any(), any(), any()); -// } -// -// return new BftsmartNodeServer(serverSettings, mockedMessageHandle, stateMachineReplicate); -// } -// }).when(mockedBftsmartProvider0).getServerFactory().setupServer(any(), any(), any()); -// -// ConsensusProviders.registerProvider(mockedBftsmartProvider0); -// } - /** - * 检查所有节点之间的账本是否一致; - * - * @param context - */ - private static void testConsistencyAmongNodes(IntegratedContext context) { - int[] ids = context.getNodeIds(); - Node[] nodes = new Node[ids.length]; - LedgerQuery[] ledgers = new LedgerQuery[ids.length]; - for (int i = 0; i < nodes.length; i++) { - nodes[i] = context.getNode(ids[i]); - HashDigest ledgerHash = nodes[i].getLedgerManager().getLedgerHashs()[0]; - ledgers[i] = nodes[i].getLedgerManager().getLedger(ledgerHash); - } - LedgerQuery ledger0 = ledgers[0]; - LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock(); - for (int i = 1; i < ledgers.length; i++) { - LedgerQuery otherLedger = ledgers[i]; - LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock(); - } - } - - private static void testConsensusFirstTimeoutSdk(GatewayTestRunner gateway, IntegratedContext context) { - - AtomicBoolean isTestTurnOn = new AtomicBoolean(true); - - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - - LedgerManager ledgerManagerMock0 = node0.getLedgerManager(); - LedgerManager ledgerManagerMock1 = node1.getLedgerManager(); - - doAnswer(new Answer() { - @Override - public LedgerRepository answer(InvocationOnMock invocation) throws Throwable { - if (isTestTurnOn.get()) { - Thread.sleep(5000); - } - return (LedgerRepository)invocation.callRealMethod(); - } - }).when(ledgerManagerMock0).getLedger(any()); - - doAnswer(new Answer() { - @Override - public LedgerRepository answer(InvocationOnMock invocation) throws Throwable { - if (isTestTurnOn.get()) { - Thread.sleep(5000); - } - return (LedgerRepository)invocation.callRealMethod(); - } - }).when(ledgerManagerMock1).getLedger(any()); - - testSDK(gateway, context); - - isTestTurnOn.set(false); - } - - private static void testConsensusSecondTimeoutSdk(GatewayTestRunner gateway, IntegratedContext context) { - AtomicBoolean isTestTurnOn = new AtomicBoolean(true); - - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - - LedgerManager ledgerManagerMock0 = node0.getLedgerManager(); - LedgerManager ledgerManagerMock1 = node1.getLedgerManager(); - - doAnswer(new Answer() { - @Override - public LedgerRepository answer(InvocationOnMock invocation) throws Throwable { - if (isTestTurnOn.get()) { - Thread.sleep(10000); - } - return (LedgerRepository)invocation.callRealMethod(); - } - }).when(ledgerManagerMock0).getLedger(any()); - - doAnswer(new Answer() { - @Override - public LedgerRepository answer(InvocationOnMock invocation) throws Throwable { - if (isTestTurnOn.get()) { - Thread.sleep(10000); - } - return (LedgerRepository)invocation.callRealMethod(); - } - }).when(ledgerManagerMock1).getLedger(any()); - - testSDK(gateway, context); - - isTestTurnOn.set(false); - } - - //todo -// private static void testBlockHashInconsistentSdk(GatewayTestRunner gateway, IntegratedContext context) { -// isTestTurnOn.set(true); -// testSDK(gateway, context); -// isTestTurnOn.set(false); -// -// } - - private static void testStorageErrorBlockRollbackSdk(GatewayTestRunner gateway, IntegratedContext context) { - - ((TestDbFactory)context.getNode(0).getStorageDB()).setErrorSetTurnOn(true); - ((TestDbFactory)context.getNode(1).getStorageDB()).setErrorSetTurnOn(true); - ((TestDbFactory)context.getNode(2).getStorageDB()).setErrorSetTurnOn(true); - ((TestDbFactory)context.getNode(3).getStorageDB()).setErrorSetTurnOn(true); - - testSDK(gateway, context); - - ((TestDbFactory)context.getNode(0).getStorageDB()).setErrorSetTurnOn(false); - ((TestDbFactory)context.getNode(1).getStorageDB()).setErrorSetTurnOn(false); - ((TestDbFactory)context.getNode(2).getStorageDB()).setErrorSetTurnOn(false); - ((TestDbFactory)context.getNode(3).getStorageDB()).setErrorSetTurnOn(false); - - } - - private static void testTransactionRollbackSdk(GatewayTestRunner gateway, IntegratedContext context) { - - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService bcsrv = gwsrvFact.getBlockchainService(); - - HashDigest[] ledgerHashs = bcsrv.getLedgerHashs(); - - AsymmetricKeypair adminKey = context.getNode(0).getPartiKeyPair(); - - // 注册用户,并验证最终写入; - BlockchainKeypair dataAccount = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = bcsrv.newTransaction(ledgerHashs[0]); - txTpl.dataAccounts().register(dataAccount.getIdentity()); - - String dataKey = "jd_code"; - String dataVal = "www.jd.com"; - - // Construct error kv version - txTpl.dataAccount(dataAccount.getAddress()).setText(dataKey, dataVal, 1); - - PreparedTransaction prepTx = txTpl.prepare(); - - prepTx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = prepTx.commit(); - - // 验证结果; - Node node0 = context.getNode(0); - LedgerManage ledgerManager = new LedgerManager(); - - KVStorageService storageService = node0.getStorageDB().connect(memDbConnString).getStorageService(); - - LedgerQuery ledgerOfNode0 = ledgerManager.register(ledgerHashs[0], storageService); - - - } - - private static void testInvalidUserSignerSdk(GatewayTestRunner gateway, IntegratedContext context) { - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService bcsrv = gwsrvFact.getBlockchainService(); - - HashDigest[] ledgerHashs = bcsrv.getLedgerHashs(); - - //Invalid signer - PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS, PASSWORD); - PubKey pubKey = KeyGenUtils.decodePubKey(PUB_KEYS); - - AsymmetricKeypair asymmetricKeypair = new AsymmetricKeypair(pubKey, privKey); - - // 注册用户,并验证最终写入; - BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = bcsrv.newTransaction(ledgerHashs[0]); - txTpl.users().register(user.getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(asymmetricKeypair); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - Node node0 = context.getNode(0); - LedgerManage ledgerManager = new LedgerManager(); - - KVStorageService storageService = node0.getStorageDB().connect(memDbConnString).getStorageService(); - - LedgerQuery ledgerOfNode0 = ledgerManager.register(ledgerHashs[0], storageService); - - } - - private static void testSDK(GatewayTestRunner gateway, IntegratedContext context) { - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService bcsrv = gwsrvFact.getBlockchainService(); - - HashDigest[] ledgerHashs = bcsrv.getLedgerHashs(); - - AsymmetricKeypair adminKey = context.getNode(0).getPartiKeyPair(); - - BlockchainKeypair newUserAcount = testSDK_RegisterUser(adminKey, ledgerHashs[0], bcsrv, context); - - // BlockchainKeyPair newDataAccount = testSDK_RegisterDataAccount(adminKey, - // ledgerHashs[0], bcsrv, context); - // - // testSDK_InsertData(adminKey, ledgerHashs[0], bcsrv, - // newDataAccount.getAddress(), context); - // - // LedgerBlock latestBlock = testSDK_Contract(adminKey, ledgerHashs[0], bcsrv, - // context); - - } - - private void testSDK_InsertData(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainService blockchainService, - String dataAccountAddress, IntegratedContext context) { - - // 在本地定义注册账号的 TX; - TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash); - - // -------------------------------------- - // 将商品信息写入到指定的账户中; - // 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引; - String dataAccount = dataAccountAddress; - - String dataKey = "jingdong" + new Random().nextInt(100000); - String dataVal = "www.jd.com"; - - txTemp.dataAccount(dataAccount).setText(dataKey, dataVal, -1); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - - // 使用私钥进行签名; - prepTx.sign(adminKey); - - // 提交交易; - TransactionResponse txResp = prepTx.commit(); - - Node node0 = context.getNode(0); - LedgerQuery ledgerOfNode0 = node0.getLedgerManager().getLedger(ledgerHash); - ledgerOfNode0.retrieveLatestBlock(); // 更新内存 - - // 先验证应答 - TypedKVEntry[] kvDataEntries = blockchainService.getDataEntries(ledgerHash, dataAccountAddress, dataKey); - for (TypedKVEntry kvDataEntry : kvDataEntries) { - String valHexText = (String) kvDataEntry.getValue(); - byte[] valBytes = HexUtils.decode(valHexText); - String valText = new String(valBytes); - System.out.println(valText); - } - } - - private static BlockchainKeypair testSDK_RegisterUser(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, IntegratedContext context) { - // 注册用户,并验证最终写入; - BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.users().register(user.getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - Node node0 = context.getNode(0); - LedgerManage ledgerManager = new LedgerManager(); - - KVStorageService storageService = node0.getStorageDB().connect(memDbConnString).getStorageService(); - - LedgerQuery ledgerOfNode0 = ledgerManager.register(ledgerHash, storageService); - - return user; - } - - private BlockchainKeypair testSDK_RegisterDataAccount(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, IntegratedContext context) { - // 注册数据账户,并验证最终写入; - BlockchainKeypair dataAccount = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.dataAccounts().register(dataAccount.getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - Node node0 = context.getNode(0); - // LedgerRepository ledgerOfNode0 = - // node0.getLedgerManager().getLedger(ledgerHash); - LedgerManage ledgerManager = new LedgerManager(); - - KVStorageService storageService = node0.getStorageDB().connect(memDbConnString).getStorageService(); - - LedgerQuery ledgerOfNode0 = ledgerManager.register(ledgerHash, storageService); - long latestBlockHeight = ledgerOfNode0.retrieveLatestBlockHeight(); - - return dataAccount; - } - - private void testSDK_Query(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainService blockchainService, - IntegratedContext context, BlockchainKeypair newUserAcount, BlockchainKeypair newDataAcount) { - - Bytes userAddress = newUserAcount.getAddress(); - Bytes dataAddress = newDataAcount.getAddress(); - - Node node0 = context.getNode(0); - // LedgerRepository ledgerOfNode0 = - // node0.getLedgerManager().getLedger(ledgerHash); - LedgerManage ledgerManager = new LedgerManager(); - - KVStorageService storageService = node0.getStorageDB().connect(memDbConnString).getStorageService(); - - LedgerQuery ledgerOfNode0 = ledgerManager.register(ledgerHash, storageService); - - // getLedgerHashs - HashDigest[] ledgerHashs = blockchainService.getLedgerHashs(); - for (HashDigest hashDigest : ledgerHashs) { - if (hashDigest.equals(ledgerHash)) { - break; - } - System.out.println("Query getLedgerHashs error! ledgerHash not exist!"); - } - - // getLedger - LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash); - long ledgerHeight = ledgerInfo.getLatestBlockHeight(); - - // getConsensusParticipants - ParticipantNode[] consensusParticipants = blockchainService.getConsensusParticipants(ledgerHash); - for (int i = 0; i < 4; i++) { - } - - // getBlock - for (int i = 0; i < ledgerHeight + 1; i++) { - LedgerBlock expectBlock = ledgerOfNode0.getBlock(i); - } - - // getTransactionCount according to blockhash - for (int i = 0; i < ledgerHeight + 1; i++) { - LedgerBlock expectBlock = ledgerOfNode0.getBlock(i); - long expectTransactionCount = ledgerOfNode0.getTransactionSet(expectBlock).getTotalCount(); - long actualTransactionCount = blockchainService.getTransactionCount(ledgerHash, expectBlock.getHash()); - } - - // getDataAccountCount according to blockhash - for (int i = 0; i < ledgerHeight + 1; i++) { - LedgerBlock expectBlock = ledgerOfNode0.getBlock(i); - long expectDataCount = ledgerOfNode0.getDataAccountSet(expectBlock).getTotal(); - long actualDataCount = blockchainService.getDataAccountCount(ledgerHash, expectBlock.getHash()); - } - - // getUserCount according to blockhash - for (int i = 0; i < ledgerHeight + 1; i++) { - LedgerBlock expectBlock = ledgerOfNode0.getBlock(i); - long expectUserCount = ledgerOfNode0.getUserAccountSet(expectBlock).getTotal(); - long actualUserCount = blockchainService.getUserCount(ledgerHash, expectBlock.getHash()); - } - - // getContractCount according to blockhash - for (int i = 0; i < ledgerHeight + 1; i++) { - LedgerBlock expectBlock = ledgerOfNode0.getBlock(i); - long expectContractCount = ledgerOfNode0.getContractAccountSet(expectBlock).getTotal(); - long actualContractCount = blockchainService.getContractCount(ledgerHash, expectBlock.getHash()); - } - - // getTransactionCount according to height - // getDataAccountCount according to height - // getUserCount according to height - // getContractCount according to height - long expectTransactionTotal = 0; - long expectUserTotal = 0; - long expectDataTotal = 0; - long expectContractTotal = 0; - for (int i = 0; i < ledgerHeight + 1; i++) { - // actual block acount total - long transactionCount = blockchainService.getTransactionCount(ledgerHash, i); - long userCount = blockchainService.getUserCount(ledgerHash, i); - long dataCount = blockchainService.getDataAccountCount(ledgerHash, i); - long contractCount = blockchainService.getContractCount(ledgerHash, i); - - // expect block acount total - LedgerBlock ledgerBlock = ledgerOfNode0.getBlock(i); - expectTransactionTotal = ledgerOfNode0.getTransactionSet(ledgerBlock).getTotalCount(); - expectUserTotal = ledgerOfNode0.getUserAccountSet(ledgerBlock).getTotal(); - expectDataTotal = ledgerOfNode0.getDataAccountSet(ledgerBlock).getTotal(); - expectContractTotal = ledgerOfNode0.getContractAccountSet(ledgerBlock).getTotal(); - } - - // getTransactionTotalCount - long actualTransactionTotal = blockchainService.getTransactionTotalCount(ledgerHash); - - // getUserTotalCount - long actualUserTotal = blockchainService.getUserTotalCount(ledgerHash); - - // getDataAccountTotalCount - long actualDataAccountTotal = blockchainService.getDataAccountTotalCount(ledgerHash); - - // getContractTotalCount - long actualContractAccountTotal = blockchainService.getContractTotalCount(ledgerHash); - - // getTransactions - // getTransactionByContentHash - // getTransactionStateByContentHash - // ledger-core not implement - // for (int i = 0; i < ledgerHeight + 1; i++) { - // LedgerBlock ledgerBlock = ledgerOfNode0.getBlock(i); - // HashDigest blockHash = ledgerBlock.getHash(); - // long expectCount = - // ledgerOfNode0.getTransactionSet(ledgerBlock).getTotalCount(); - // long actualCount = blockchainService.getTransactionCount(ledgerHash, i); - // LedgerTransaction[] ledgerTransactions1 = - // blockchainService.getTransactions(ledgerHash, i, 0, (int)(actualCount - 1)); - // LedgerTransaction[] ledgerTransactions2 = - // blockchainService.getTransactions(ledgerHash, blockHash, 0, (int)(expectCount - // - 1)); - // assertEquals(ledgerTransactions1.length, ledgerTransactions2.length); - // assertArrayEquals(ledgerTransactions1, ledgerTransactions2); - // - // for (LedgerTransaction ledgerTransaction : ledgerTransactions1) { - // assertEquals(ledgerTransaction, - // blockchainService.getTransactionByContentHash(ledgerHash, - // ledgerTransaction.getTransactionContent().getHash())); - // assertEquals(TransactionState.SUCCESS, - // blockchainService.getTransactionStateByContentHash(ledgerHash, - // ledgerTransaction.getTransactionContent().getHash())); - // } - // } - // getUser - UserInfo userInfo = blockchainService.getUser(ledgerHash, userAddress.toString()); - - // getDataAccount - BlockchainIdentity accountHeader = blockchainService.getDataAccount(ledgerHash, dataAddress.toString()); - - // getDataEntries - - return; - } - - public static ConsensusProvider getConsensusProvider(String providerName) { - return ConsensusProviders.getProvider(providerName); - } - - private static IntegratedContext initLedgers() { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_integration(); - Properties props = LedgerInitializeWebTest.loadConsensusSetting(LedgerInitConsensusConfig.bftsmartConfig.getConfigPath()); - ConsensusProvider csProvider = getConsensusProvider(LedgerInitConsensusConfig.bftsmartConfig.getProvider()); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - LedgerInitializeWebTest.NodeWebContext nodeCtx0 = new LedgerInitializeWebTest.NodeWebContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - LedgerInitializeWebTest.NodeWebContext nodeCtx1 = new LedgerInitializeWebTest.NodeWebContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - LedgerInitializeWebTest.NodeWebContext nodeCtx2 = new LedgerInitializeWebTest.NodeWebContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - LedgerInitializeWebTest.NodeWebContext nodeCtx3 = new LedgerInitializeWebTest.NodeWebContext(3, initAddr3); - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWebTest.PRIV_KEYS[0], - LedgerInitializeWebTest.PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWebTest.PRIV_KEYS[1], - LedgerInitializeWebTest.PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWebTest.PRIV_KEYS[2], - LedgerInitializeWebTest.PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWebTest.PRIV_KEYS[3], - LedgerInitializeWebTest.PASSWORD); - - String encodedPassword = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWebTest.PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - TestDbFactory dbFactory0 = new TestDbFactory(new CompositeConnectionFactory()); - dbFactory0.setErrorSetTurnOn(false); - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri("memory://local/0"); - LedgerBindingConfig bindingConfig0 = new LedgerBindingConfig(); - AsyncCallback callback0 = nodeCtx0.startInitCommand(privkey0, encodedPassword, initSetting, csProps, - csProvider, testDb0, consolePrompter, bindingConfig0, quitLatch, dbFactory0); - - - TestDbFactory dbFactory1 = new TestDbFactory(new CompositeConnectionFactory()); - dbFactory1.setErrorSetTurnOn(false); - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri("memory://local/1"); - LedgerBindingConfig bindingConfig1 = new LedgerBindingConfig(); - AsyncCallback callback1 = nodeCtx1.startInitCommand(privkey1, encodedPassword, initSetting, csProps, - csProvider, testDb1, consolePrompter, bindingConfig1, quitLatch, dbFactory1); - - - TestDbFactory dbFactory2 = new TestDbFactory(new CompositeConnectionFactory()); - dbFactory2.setErrorSetTurnOn(false); - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri("memory://local/2"); - LedgerBindingConfig bindingConfig2 = new LedgerBindingConfig(); - AsyncCallback callback2 = nodeCtx2.startInitCommand(privkey2, encodedPassword, initSetting, csProps, - csProvider, testDb2, consolePrompter, bindingConfig2, quitLatch, dbFactory2); - - TestDbFactory dbFactory3 = new TestDbFactory(new CompositeConnectionFactory()); - dbFactory3.setErrorSetTurnOn(false); - DBConnectionConfig testDb3 = new DBConnectionConfig(); - testDb3.setConnectionUri("memory://local/3"); - LedgerBindingConfig bindingConfig3 = new LedgerBindingConfig(); - AsyncCallback callback3 = nodeCtx3.startInitCommand(privkey3, encodedPassword, initSetting, csProps, - csProvider, testDb3, consolePrompter, bindingConfig3, quitLatch, dbFactory3); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - LedgerQuery ledger0 = nodeCtx0.registLedger(ledgerHash0); - LedgerQuery ledger1 = nodeCtx1.registLedger(ledgerHash1); - LedgerQuery ledger2 = nodeCtx2.registLedger(ledgerHash2); - LedgerQuery ledger3 = nodeCtx3.registLedger(ledgerHash3); - - IntegratedContext context = new IntegratedContext(); - - context.setLedgerHash(ledgerHash0); - - Node node0 = new Node(0); - node0.setConsensusSettings(csProps); - node0.setLedgerManager(nodeCtx0.getLedgerManager()); - node0.setStorageDB(nodeCtx0.getStorageDB()); - node0.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(0).getPubKey(), privkey0)); - node0.setBindingConfig(bindingConfig0); - context.addNode(node0); - - Node node1 = new Node(1); - node1.setConsensusSettings(csProps); - node1.setLedgerManager(nodeCtx1.getLedgerManager()); - node1.setStorageDB(nodeCtx1.getStorageDB()); - node1.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(1).getPubKey(), privkey1)); - node1.setBindingConfig(bindingConfig1); - context.addNode(node1); - - Node node2 = new Node(2); - node2.setConsensusSettings(csProps); - node2.setLedgerManager(nodeCtx2.getLedgerManager()); - node2.setStorageDB(nodeCtx2.getStorageDB()); - node2.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(2).getPubKey(), privkey2)); - node2.setBindingConfig(bindingConfig2); - context.addNode(node2); - - Node node3 = new Node(3); - node3.setConsensusSettings(csProps); - node3.setLedgerManager(nodeCtx3.getLedgerManager()); - node3.setStorageDB(nodeCtx3.getStorageDB()); - node3.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(3).getPubKey(), privkey3)); - node3.setBindingConfig(bindingConfig3); - context.addNode(node3); - - nodeCtx0.closeServer(); - nodeCtx1.closeServer(); - nodeCtx2.closeServer(); - nodeCtx3.closeServer(); - - return context; - } - - public static LedgerInitProperties loadInitSetting_integration() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web2.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private LedgerBlock testSDK_Contract(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, IntegratedContext context) { - // valid the basic data in contract; - prepareContractData(adminKey, ledgerHash, blockchainService, context); - - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - byte[] contractCode = getChainCodeBytes(); - - txTpl.users().register(userKey.getIdentity()); - - txTpl.contracts().deploy(contractDeployKey.getIdentity(), contractCode); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - txResp.getContentHash(); - - Node node0 = context.getNode(0); - LedgerQuery ledgerOfNode0 = node0.getLedgerManager().getLedger(ledgerHash); - LedgerBlock block = ledgerOfNode0.getBlock(txResp.getBlockHeight()); - byte[] contractCodeInDb = ledgerOfNode0.getContractAccountSet(block).getAccount(contractDeployKey.getAddress()) - .getChainCode(); - txContentHash = ptx.getHash(); - - // execute the contract; - testContractExe(adminKey, ledgerHash, userKey, blockchainService, context); - - return block; - } - - private void testContractExe(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainKeypair userKey, - BlockchainService blockchainService, IntegratedContext context) { - LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash); - LedgerBlock previousBlock = blockchainService.getBlock(ledgerHash, ledgerInfo.getLatestBlockHeight() - 1); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - -// txTpl.contractEvents().send(contractDeployKey.getAddress(), eventName, -// ("888##abc##" + contractDataKey.getAddress() + "##" + previousBlock.getHash().toBase58() + "##" -// + userKey.getAddress() + "##" + contractDeployKey.getAddress() + "##" + txContentHash.toBase58() -// + "##SOME-VALUE").getBytes()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - txResp.getContentHash(); - - LedgerInfo latestLedgerInfo = blockchainService.getLedger(ledgerHash); - - Node node0 = context.getNode(0); - LedgerQuery ledgerOfNode0 = node0.getLedgerManager().getLedger(ledgerHash); - LedgerBlock backgroundLedgerBlock = ledgerOfNode0.retrieveLatestBlock(); - - // 验证合约中的赋值,外部可以获得; - DataAccountQuery dataAccountSet = ledgerOfNode0.getDataAccountSet(backgroundLedgerBlock); - AsymmetricKeypair key = Crypto.getSignatureFunction("ED25519").generateKeypair(); - PubKey pubKey = key.getPubKey(); - Bytes dataAddress = AddressEncoding.generateAddress(pubKey); - - // 验证userAccount,从合约内部赋值,然后外部验证;由于目前不允许输入重复的key,所以在内部合约中构建的key,不便于在外展示,屏蔽之; - // UserAccountSet userAccountSet = - // ledgerOfNode0.getUserAccountSet(backgroundLedgerBlock); - // PubKey userPubKey = new PubKey(CryptoAlgorithm.ED25519, - // userPubKeyVal.getBytes()); - // String userAddress = AddressEncoding.generateAddress(userPubKey); - // assertEquals(userAddress, userAccountSet.getUser(userAddress).getAddress()); - } - - private void prepareContractData(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainService blockchainService, - IntegratedContext context) { - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - // 注册数据账户,并验证最终写入; - txTpl.dataAccounts().register(contractDataKey.getIdentity()); - DataAccountKVSetOperation kvsetOP = txTpl.dataAccount(contractDataKey.getAddress()) - .setText("A", "Value_A_0", -1).setText("B", "Value_B_0", -1) - .setText(KEY_TOTAL, "total value,dataAccount", -1) - .setText(KEY_ABC, "abc value,dataAccount", -1) - // 所有的模拟数据都在这个dataAccount中填充; - .setBytes("ledgerHash", ledgerHash.getRawDigest(), -1).getOperation(); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - Node node0 = context.getNode(0); - - LedgerQuery ledgerOfNode0 = node0.getLedgerManager().getLedger(ledgerHash); - LedgerBlock block = ledgerOfNode0.getBlock(txResp.getBlockHeight()); - BytesValue val1InDb = ledgerOfNode0.getDataAccountSet(block).getAccount(contractDataKey.getAddress()) - .getDataset().getValue("A"); - BytesValue val2InDb = ledgerOfNode0.getDataAccountSet(block).getAccount(contractDataKey.getAddress()) - .getDataset().getValue(KEY_TOTAL); - } - - /** - * 根据合约构建字节数组; - * - * @return - */ - private byte[] getChainCodeBytes() { - // 构建合约的字节数组; - byte[] contractCode = null; - File file = null; - InputStream input = null; - try { - ClassPathResource contractPath = new ClassPathResource(contractZipName); - file = new File(contractPath.getURI()); - input = new FileInputStream(file); - // 这种暴力的读取压缩包,在class解析时有问题,所有需要改进; - contractCode = new byte[input.available()]; - input.read(contractCode); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (input != null) { - input.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return contractCode; - } -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/LedgerInitConsensusConfig.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/LedgerInitConsensusConfig.java deleted file mode 100644 index cceb97e7..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/LedgerInitConsensusConfig.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.intgr.LedgerInitConsensusConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/21 下午5:52 - * Description: - */ -package test.com.jd.blockchain.intgr; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.utils.io.FileUtils; - -import test.com.jd.blockchain.intgr.perf.LedgerPerformanceTest; - -import java.io.File; - -/** - * - * @author shaozhuguang - * @create 2018/12/21 - * @since 1.0.0 - */ - -public class LedgerInitConsensusConfig { - - public static ConsensusConfig mqConfig = new ConsensusConfig(); - - public static ConsensusConfig bftsmartConfig = new ConsensusConfig(); - - public static String[] redisConnectionStrings = new String[4]; - - public static String[] memConnectionStrings = new String[4]; - - public static String[] rocksdbConnectionStrings = new String[4]; - - public static String[] rocksdbDirStrings = new String[4]; - - public static String[] mqProvider = new String[1]; - - public static String[] bftsmartProvider = new String[1]; - - public static String[] mqAndbftsmartProvider = new String[2]; - - static { - mqConfig.provider = "com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider"; - mqConfig.configPath = "mq.config"; - - bftsmartConfig.provider = "com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"; - bftsmartConfig.configPath = "bftsmart.config"; - -// for (int i = 0; i < redisConnectionStrings.length; i++) { -// redisConnectionStrings[i] = "redis://127.0.0.1:6379/" + i; -// } - redisConnectionStrings[0] = "redis://192.168.54.112:6379"; - redisConnectionStrings[1] = "redis://192.168.54.112:6379/1"; - redisConnectionStrings[2] = "redis://192.168.54.112:6379/2"; - redisConnectionStrings[3] = "redis://192.168.54.112:6379/3"; - - for (int i = 0; i < memConnectionStrings.length; i++) { - memConnectionStrings[i] = "memory://local/" + i; - } - - mqProvider[0] = mqConfig.provider; - bftsmartProvider[0] = bftsmartConfig.provider; - - mqAndbftsmartProvider[0] = mqConfig.provider; - mqAndbftsmartProvider[1] = bftsmartConfig.provider; - - for (int i = 0; i < rocksdbConnectionStrings.length; i++) { - String currDir = FileUtils.getCurrentDir() + File.separator + "rocks.db"; - String dbDir = new File(currDir, "rocksdb" + i + ".db").getAbsolutePath(); - rocksdbDirStrings[i] = dbDir; - rocksdbConnectionStrings[i] = "rocksdb://" + dbDir; - } - } - - public static ConsensusProvider getConsensusProvider(String providerName) { - return ConsensusProviders.getProvider(providerName); - } - - public static class ConsensusConfig { - - String provider; - - String configPath; - - public String getProvider() { - return provider; - } - - public String getConfigPath() { - return configPath; - } - } -} \ No newline at end of file diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/PeerTestRunner.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/PeerTestRunner.java deleted file mode 100644 index 0a0722f0..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/PeerTestRunner.java +++ /dev/null @@ -1,63 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.peer.PeerServerBooter; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class PeerTestRunner { - - private NetworkAddress serviceAddress; - - private volatile PeerServerBooter peerServer; - - private LedgerBindingConfig ledgerBindingConfig; - - public DbConnectionFactory getDBConnectionFactory() { - return peerServer.getDBConnectionFactory(); - } - - public NetworkAddress getServiceAddress() { - return serviceAddress; - } - - public LedgerBindingConfig getLedgerBindingConfig() { - return ledgerBindingConfig; - } - - public PeerTestRunner(NetworkAddress serviceAddress, LedgerBindingConfig ledgerBindingConfig) { - this(serviceAddress, ledgerBindingConfig, null, null); - } - - public PeerTestRunner(NetworkAddress serviceAddress, LedgerBindingConfig ledgerBindingConfig, - DbConnectionFactory dbConnectionFactory, LedgerManager ledgerManager) { - this.serviceAddress = serviceAddress; - this.ledgerBindingConfig = ledgerBindingConfig; - if (dbConnectionFactory == null) { - this.peerServer = new PeerServerBooter(ledgerBindingConfig, serviceAddress.getHost(), serviceAddress.getPort(),null); - }else { - this.peerServer = new PeerServerBooter(ledgerBindingConfig, serviceAddress.getHost(), serviceAddress.getPort(),null, - dbConnectionFactory, ledgerManager); - } - } - - public AsyncCallback start() { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected Object invoke() throws Exception { - peerServer.start(); - - return null; - } - }; - - return invoker.start(); - } - - public void stop() { - peerServer.close(); - } -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/PresetAnswerPrompter.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/PresetAnswerPrompter.java deleted file mode 100644 index d6ccbc6a..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/PresetAnswerPrompter.java +++ /dev/null @@ -1,33 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import java.util.Properties; - -import com.jd.blockchain.tools.initializer.ConsolePrompter; - -public class PresetAnswerPrompter extends ConsolePrompter { - - private Properties answers = new Properties(); - - private String defaultAnswer; - - public PresetAnswerPrompter(String defaultAnswer) { - this.defaultAnswer = defaultAnswer; - } - - public void setAnswer(String tag, String answer) { - answers.setProperty(tag, answer); - } - - public void setDefaultAnswer(String defaultAnswer) { - this.defaultAnswer = defaultAnswer; - } - - @Override - public String confirm(String tag, String format, Object... args) { - System.out.print(String.format(format, args)); - String answer = answers.getProperty(tag, defaultAnswer); - System.out.println(String.format("\r\n [Mocked answer:%s]", answer)); - return answer; - } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/TestDbFactory.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/TestDbFactory.java deleted file mode 100644 index 0b9c7ed6..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/TestDbFactory.java +++ /dev/null @@ -1,140 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.when; - -import java.util.concurrent.atomic.AtomicBoolean; - -import com.jd.blockchain.storage.service.*; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -public class TestDbFactory implements DbConnectionFactory{ - - private DbConnectionFactory innerDbFactory; - - private AtomicBoolean errorSetTurnOn = new AtomicBoolean(false); - - public TestDbFactory(DbConnectionFactory innerDbFactory) { - this.innerDbFactory = innerDbFactory; - } - - - Answer exKVStorageMockedAnswer = new Answer() { - - @Override - public ExPolicyKVStorage answer(InvocationOnMock invocation) throws Throwable { - - ExPolicyKVStorage reallyExKVStorage = (ExPolicyKVStorage) invocation.callRealMethod(); - - ExPolicyKVStorage mockExKVStorage = Mockito.spy(reallyExKVStorage); - - //按条件开关触发异常; - doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - if (isErrorSetTurnOn()) { - return false; - } - return (Boolean) invocation.callRealMethod(); - } - }).when(mockExKVStorage).set(any(), any(), any()); - - return mockExKVStorage; - } - }; - - Answer verKVStorageMockedAnswer = new Answer() { - - @Override - public VersioningKVStorage answer(InvocationOnMock invocation) throws Throwable { - - VersioningKVStorage reallyVerKVStorage = (VersioningKVStorage) invocation.callRealMethod(); - - VersioningKVStorage mockVerKVStorage = Mockito.spy(reallyVerKVStorage); - - //按条件开关触发异常; - doAnswer(new Answer() { - - @Override - public Long answer(InvocationOnMock invocation) throws Throwable { - if (isErrorSetTurnOn()) { - return (long)(-1); - } - return (Long) invocation.callRealMethod(); - } - }).when(mockVerKVStorage).set(any(), any(), anyLong()); - - return mockVerKVStorage; - } - }; - - Answer storageMockedAnswer = new Answer() { - - @Override - public KVStorageService answer(InvocationOnMock invocation) throws Throwable { - - KVStorageService reallyStorage = (KVStorageService) invocation.callRealMethod(); - - TestMemoryKVStorage testMemoryKVStorage = new TestMemoryKVStorage((MemoryKVStorage)reallyStorage); - - KVStorageService mockedStorage = Mockito.spy(testMemoryKVStorage); - - doAnswer(exKVStorageMockedAnswer).when(mockedStorage).getExPolicyKVStorage(); - - doAnswer(verKVStorageMockedAnswer).when(mockedStorage).getVersioningKVStorage(); - - return mockedStorage; - } - - }; - - - @Override - public String dbPrefix() { - return innerDbFactory.dbPrefix(); - } - - @Override - public boolean support(String scheme) { - return innerDbFactory.support(scheme); - } - - @Override - public DbConnection connect(String dbConnectionString) { - - DbConnection reallyDbConn = innerDbFactory.connect(dbConnectionString); - - DbConnection mockDbConn = Mockito.spy(reallyDbConn); - - when(mockDbConn.getStorageService()).then(storageMockedAnswer); - return mockDbConn; - } - - @Override - public DbConnection connect(String dbConnectionString, String password) { - return connect(dbConnectionString); - } - - @Override - public void close() { - innerDbFactory.close(); - - } - - public boolean isErrorSetTurnOn() { - return errorSetTurnOn.get(); - } - - public void setErrorSetTurnOn(boolean errorSetTurnOn) { - this.errorSetTurnOn.set(errorSetTurnOn);; - } - - - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/TestMemoryKVStorage.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/TestMemoryKVStorage.java deleted file mode 100644 index 15e99f60..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/TestMemoryKVStorage.java +++ /dev/null @@ -1,24 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; - -public class TestMemoryKVStorage extends MemoryKVStorage { - - private MemoryKVStorage memoryKVStorage; - - public TestMemoryKVStorage(MemoryKVStorage memoryKVStorage) { - this.memoryKVStorage = memoryKVStorage; - } - - @Override - public ExPolicyKVStorage getExPolicyKVStorage() { - return memoryKVStorage; - } - - @Override - public VersioningKVStorage getVersioningKVStorage() { - return memoryKVStorage; - } -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/consensus/ConsensusTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/consensus/ConsensusTest.java deleted file mode 100644 index e91d804e..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/consensus/ConsensusTest.java +++ /dev/null @@ -1,463 +0,0 @@ -package test.com.jd.blockchain.intgr.consensus; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; - -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.PreparedTransaction; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionTemplate; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnection; -//import com.jd.blockchain.storage.service.utils.MemoryBasedDb; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitCommand; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.GatewayTestRunner; -import test.com.jd.blockchain.intgr.IntegratedContext; -import test.com.jd.blockchain.intgr.IntegratedContext.Node; -import test.com.jd.blockchain.intgr.PeerTestRunner; -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; -import test.com.jd.blockchain.intgr.perf.LedgerInitTestConfiguration; -import test.com.jd.blockchain.intgr.perf.TransactionCommitter; -import test.com.jd.blockchain.intgr.perf.Utils; - -public class ConsensusTest { - - public static final int CONCURRENT_USER_COUNT = 2; - public static final int USER_TX_COUNT = 1; - - public static void main_(String[] args) { - // init ledgers of all nodes ; - IntegratedContext context = initLedgers(); - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - Node node2 = context.getNode(2); - Node node3 = context.getNode(3); - - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 10200); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, node0.getBindingConfig(), node0.getStorageDB(), null); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 10210); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, node1.getBindingConfig(), node1.getStorageDB(), null); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 10220); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, node2.getBindingConfig(), node2.getStorageDB(), null); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 10230); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, node3.getBindingConfig(), node3.getStorageDB(), null); - - AsyncCallback peerStarting0 = peer0.start(); - AsyncCallback peerStarting1 = peer1.start(); - AsyncCallback peerStarting2 = peer2.start(); - AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(Utils.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(Utils.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(Utils.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway0 = new GatewayTestRunner("127.0.0.1", 10300, gwkey0, peerSrvAddr0); - - KeyPairConfig gwkey1 = new KeyPairConfig(); - gwkey1.setPubKeyValue(Utils.PUB_KEYS[1]); - gwkey1.setPrivKeyValue(Utils.PRIV_KEYS[1]); - gwkey1.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway1 = new GatewayTestRunner("127.0.0.1", 10310, gwkey1, peerSrvAddr1); - - AsyncCallback gwStarting0 = gateway0.start(); - AsyncCallback gwStarting1 = gateway1.start(); - - gwStarting0.waitReturn(); - gwStarting1.waitReturn(); - - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway0.getServiceAddress()); - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - - int batchSize = CONCURRENT_USER_COUNT * USER_TX_COUNT; - BlockchainKeypair[] keys = generateKeys(batchSize); - - HashDigest ledgerHash = node0.getLedgerManager().getLedgerHashs()[0]; - LedgerQuery ledger = node0.getLedgerManager().getLedger(ledgerHash); - - PreparedTransaction[] ptxs = prepareTransactions_RegisterDataAcount(keys, node0.getPartiKeyPair(), ledgerHash, - blockchainService); - - LedgerBlock latestBlock = ledger.getLatestBlock(); - - ConsoleUtils.info("\r\n-----------------------------------------------"); - ConsoleUtils.info("------ 开始执行交易 [当前区块高度=%s] ------", latestBlock.getHeight()); - ConsoleUtils.info("-----------------------------------------------\r\n"); - long startTs = System.currentTimeMillis(); - - // for (PreparedTransaction ptx : ptxs) { - // ptx.commit(); - // } - - CyclicBarrier barrier = new CyclicBarrier(CONCURRENT_USER_COUNT); - CountDownLatch latch = new CountDownLatch(CONCURRENT_USER_COUNT); - for (int i = 0; i < CONCURRENT_USER_COUNT; i++) { - TransactionCommitter committer = new TransactionCommitter(ptxs, i * USER_TX_COUNT, USER_TX_COUNT); - committer.start(barrier, latch); - } - try { - latch.await(); - } catch (InterruptedException e) { - ConsoleUtils.error("Error occurred on waiting accomplishing all tx committing. --%s", e.getMessage()); - } - - long elapsedTs = System.currentTimeMillis() - startTs; - - latestBlock = ledger.retrieveLatestBlock(); - ConsoleUtils.info("全部交易执行完成! -- 当前区块高度=%s; 交易数=%s; 总耗时= %s ms; TPS=%.2f", latestBlock.getHeight(), batchSize, - elapsedTs, (batchSize * 1000.00D / elapsedTs)); - } - - private static BlockchainKeypair[] generateKeys(int count) { - BlockchainKeypair[] keys = new BlockchainKeypair[count]; - for (int i = 0; i < count; i++) { - keys[i] = BlockchainKeyGenerator.getInstance().generate(); - } - return keys; - } - - private static PreparedTransaction[] prepareTransactions_RegisterDataAcount(BlockchainKeypair[] userKeys, - AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainService blockchainService) { - PreparedTransaction[] ptxs = new PreparedTransaction[userKeys.length]; - for (int i = 0; i < ptxs.length; i++) { - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.users().register(userKeys[i].getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - ptxs[i] = ptx; - } - - return ptxs; - } - - public static ConsensusProvider getConsensusProvider() { - return ConsensusProviders.getProvider("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"); - } - - private static IntegratedContext initLedgers() { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_integration(); - Properties props = Utils.loadConsensusSetting(); - ConsensusProvider csProvider = getConsensusProvider(); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeInitContext nodeCtx0 = new NodeInitContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeInitContext nodeCtx1 = new NodeInitContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeInitContext nodeCtx2 = new NodeInitContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeInitContext nodeCtx3 = new NodeInitContext(3, initAddr3); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[0], Utils.PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[1], Utils.PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[2], Utils.PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[3], Utils.PASSWORD); - - String encodedPassword = KeyGenUtils.encodePasswordAsBase58(Utils.PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri("memory://local/0"); - LedgerBindingConfig bindingConfig0 = new LedgerBindingConfig(); - AsyncCallback callback0 = nodeCtx0.startInitCommand(privkey0, encodedPassword, initSetting, csProps, - csProvider, testDb0, consolePrompter, bindingConfig0, quitLatch); - - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri("memory://local/1"); - LedgerBindingConfig bindingConfig1 = new LedgerBindingConfig(); - AsyncCallback callback1 = nodeCtx1.startInitCommand(privkey1, encodedPassword, initSetting, csProps, - csProvider, testDb1, consolePrompter, bindingConfig1, quitLatch); - - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri("memory://local/2"); - LedgerBindingConfig bindingConfig2 = new LedgerBindingConfig(); - AsyncCallback callback2 = nodeCtx2.startInitCommand(privkey2, encodedPassword, initSetting, csProps, - csProvider, testDb2, consolePrompter, bindingConfig2, quitLatch); - - DBConnectionConfig testDb3 = new DBConnectionConfig(); - testDb3.setConnectionUri("memory://local/3"); - LedgerBindingConfig bindingConfig3 = new LedgerBindingConfig(); - AsyncCallback callback3 = nodeCtx3.startInitCommand(privkey3, encodedPassword, initSetting, csProps, - csProvider, testDb3, consolePrompter, bindingConfig3, quitLatch); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - nodeCtx0.registLedger(ledgerHash0); - nodeCtx1.registLedger(ledgerHash1); - nodeCtx2.registLedger(ledgerHash2); - nodeCtx3.registLedger(ledgerHash3); - - IntegratedContext context = new IntegratedContext(); - - Node node0 = new Node(0); - node0.setConsensusSettings(csProps); - node0.setLedgerManager(nodeCtx0.getLedgerManager()); - node0.setStorageDB(nodeCtx0.getStorageDB()); - node0.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(0).getPubKey(), privkey0)); - node0.setBindingConfig(bindingConfig0); - context.addNode(node0); - - Node node1 = new Node(1); - node1.setConsensusSettings(csProps); - node1.setLedgerManager(nodeCtx1.getLedgerManager()); - node1.setStorageDB(nodeCtx1.getStorageDB()); - node1.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(1).getPubKey(), privkey1)); - node1.setBindingConfig(bindingConfig1); - context.addNode(node1); - - Node node2 = new Node(2); - node2.setConsensusSettings(csProps); - node2.setLedgerManager(nodeCtx2.getLedgerManager()); - node2.setStorageDB(nodeCtx2.getStorageDB()); - node2.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(2).getPubKey(), privkey2)); - node2.setBindingConfig(bindingConfig2); - context.addNode(node2); - - Node node3 = new Node(3); - node3.setConsensusSettings(csProps); - node3.setLedgerManager(nodeCtx3.getLedgerManager()); - node3.setStorageDB(nodeCtx3.getStorageDB()); - node3.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(3).getPubKey(), privkey3)); - node3.setBindingConfig(bindingConfig3); - context.addNode(node3); - - nodeCtx0.closeServer(); - nodeCtx1.closeServer(); - nodeCtx2.closeServer(); - nodeCtx3.closeServer(); - - return context; - } - - public static LedgerInitProperties loadInitSetting_integration() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private static class NodeInitContext { - - private NetworkAddress serverAddress; - - private DBConnectionConfig dbConnConfig; - - private volatile ConfigurableApplicationContext ctx; - - private volatile LedgerInitProcess initProcess; - - private volatile LedgerInitializeWebController controller; - - private volatile LedgerManager ledgerManager; - - private volatile CompositeConnectionFactory db; - - private int id; - - public int getId() { - return controller.getId(); - } - - public TransactionContent getInitTxContent() { - return controller.getInitTxContent(); - } - - public LedgerInitProposal getLocalPermission() { - return controller.getLocalPermission(); - } - - public LedgerInitDecision getLocalDecision() { - return controller.getLocalDecision(); - } - - public NodeInitContext(int id, NetworkAddress serverAddress) { - this.id = id; - this.serverAddress = serverAddress; - } - - public LedgerQuery registLedger(HashDigest ledgerHash) { - // LedgerManage ledgerManager = ctx.getBean(LedgerManage.class); - // - // DbConnectionFactory dbConnFactory = ctx.getBean(DbConnectionFactory.class); - // DbConnection conn = dbConnFactory.connect(dbConnConfig.getUri(), - // dbConnConfig.getPassword()); - - DbConnection conn = db.connect(dbConnConfig.getUri(), dbConnConfig.getPassword()); - LedgerQuery ledgerRepo = ledgerManager.register(ledgerHash, conn.getStorageService()); - return ledgerRepo; - } - - public SignatureDigest createPermissionRequestSignature(int requesterId, PrivKey privKey) { - return controller.signPermissionRequest(requesterId, privKey); - } - - public AsyncCallback startInit(PrivKey privKey, LedgerInitProperties setting, - ConsensusSettings csProps, ConsensusProvider csProvider, DBConnectionConfig dbConnConfig, - Prompter prompter, CountDownLatch quitLatch) { - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - doStartServer(); - - // NodeWebContext.this.initProcess = ctx.getBean(LedgerInitProcess.class); - NodeInitContext.this.dbConnConfig = dbConnConfig; - HashDigest ledgerHash = NodeInitContext.this.initProcess.initialize(id, privKey, setting, - dbConnConfig, prompter); - - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public AsyncCallback startInitCommand(PrivKey privKey, String base58Pwd, - LedgerInitProperties ledgerSetting, ConsensusSettings csProps, ConsensusProvider csProvider, - DBConnectionConfig dbConnConfig, Prompter prompter, LedgerBindingConfig conf, - CountDownLatch quitLatch) { - this.db = new CompositeConnectionFactory(); - this.dbConnConfig = dbConnConfig; - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - LedgerInitCommand initCmd = new LedgerInitCommand(); - HashDigest ledgerHash = initCmd.startInit(id, privKey, base58Pwd, ledgerSetting, dbConnConfig, prompter, conf, db); - NodeInitContext.this.ledgerManager = initCmd.getLedgerManager(); - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public LedgerInitProposal preparePermision(PrivKey privKey, LedgerInitProperties initProps) { - return controller.prepareLocalPermission(id, privKey, initProps); - } - - public boolean consensusPermission(PrivKey privKey) { - return controller.consensusPermisions(privKey); - } - - public LedgerInitDecision prepareLedger(DBConnectionConfig dbConnConfig, PrivKey privKey) { - controller.connectDb(dbConnConfig); - return controller.makeLocalDecision(privKey); - } - - public void startServer() { - ThreadInvoker invoker = new ThreadInvoker() { - - @Override - protected Object invoke() throws Exception { - doStartServer(); - return null; - } - }; - - invoker.startAndWait(); - } - - public void setPrompter(Prompter prompter) { - controller.setPrompter(prompter); - } - - public void doStartServer() { - String argServerAddress = String.format("--server.address=%s", serverAddress.getHost()); - String argServerPort = String.format("--server.port=%s", serverAddress.getPort()); - String nodebug = "--debug=false"; - String[] innerArgs = { argServerAddress, argServerPort, nodebug }; - - ctx = SpringApplication.run(LedgerInitTestConfiguration.class, innerArgs); - - ctx.setId("Node-" + id); - controller = ctx.getBean(LedgerInitializeWebController.class); - ledgerManager = ctx.getBean(LedgerManager.class); - db = ctx.getBean(CompositeConnectionFactory.class); - initProcess = ctx.getBean(LedgerInitProcess.class); - } - - public void closeServer() { - if (this.ctx != null) { - this.ctx.close(); - this.ctx = null; - } - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - // return ctx.getBean(LedgerManager.class); - } - - public CompositeConnectionFactory getStorageDB() { - return db; - // return ctx.getBean(MemoryBasedDb.class); - } - } -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/DBType.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/DBType.java deleted file mode 100644 index e15078e8..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/DBType.java +++ /dev/null @@ -1,11 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -public enum DBType { - - DEFAULT, - - REDIS, - - ROCKSDB - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/GlobalPerformanceTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/GlobalPerformanceTest.java deleted file mode 100644 index a7ef9fae..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/GlobalPerformanceTest.java +++ /dev/null @@ -1,475 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; - -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.PreparedTransaction; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionTemplate; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitCommand; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.GatewayTestRunner; -import test.com.jd.blockchain.intgr.IntegratedContext; -import test.com.jd.blockchain.intgr.IntegratedContext.Node; -import test.com.jd.blockchain.intgr.PeerTestRunner; -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; - -public class GlobalPerformanceTest { - - public static final int CONCURRENT_USER_COUNT = 1; - public static final int USER_TX_COUNT = 1; - - public static void test(String[] args) { - // init ledgers of all nodes ; - IntegratedContext context = initLedgers(); - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - Node node2 = context.getNode(2); - Node node3 = context.getNode(3); - - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 10200); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, node0.getBindingConfig(), node0.getStorageDB(), null); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 10210); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, node1.getBindingConfig(), node1.getStorageDB(), null); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 10220); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, node2.getBindingConfig(), node2.getStorageDB(), null); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 10230); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, node3.getBindingConfig(), node3.getStorageDB(), null); - - AsyncCallback peerStarting0 = peer0.start(); - AsyncCallback peerStarting1 = peer1.start(); - AsyncCallback peerStarting2 = peer2.start(); - AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(Utils.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(Utils.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(Utils.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway0 = new GatewayTestRunner("127.0.0.1", 10300, gwkey0, peerSrvAddr0); - - KeyPairConfig gwkey1 = new KeyPairConfig(); - gwkey1.setPubKeyValue(Utils.PUB_KEYS[1]); - gwkey1.setPrivKeyValue(Utils.PRIV_KEYS[1]); - gwkey1.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway1 = new GatewayTestRunner("127.0.0.1", 10310, gwkey1, peerSrvAddr1); - - AsyncCallback gwStarting0 = gateway0.start(); - AsyncCallback gwStarting1 = gateway1.start(); - - gwStarting0.waitReturn(); - gwStarting1.waitReturn(); - - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway0.getServiceAddress()); - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - - int batchSize = CONCURRENT_USER_COUNT * USER_TX_COUNT; - BlockchainKeypair[] keys = generateKeys(batchSize); - - HashDigest ledgerHash = node0.getLedgerManager().getLedgerHashs()[0]; - LedgerQuery ledger = node0.getLedgerManager().getLedger(ledgerHash); - - PreparedTransaction[] ptxs = prepareTransactions_RegisterDataAcount(keys, node0.getPartiKeyPair(), ledgerHash, - blockchainService); - - LedgerBlock latestBlock = ledger.getLatestBlock(); - - ConsoleUtils.info("\r\n-----------------------------------------------"); - ConsoleUtils.info("------ 开始执行交易 [当前区块高度=%s] ------", latestBlock.getHeight()); - ConsoleUtils.info("-----------------------------------------------\r\n"); - long startTs = System.currentTimeMillis(); - - // for (PreparedTransaction ptx : ptxs) { - // ptx.commit(); - // } - - CyclicBarrier barrier = new CyclicBarrier(CONCURRENT_USER_COUNT); - CountDownLatch latch = new CountDownLatch(CONCURRENT_USER_COUNT); - for (int i = 0; i < CONCURRENT_USER_COUNT; i++) { - TransactionCommitter committer = new TransactionCommitter(ptxs, i * USER_TX_COUNT, USER_TX_COUNT); - committer.start(barrier, latch); - } - try { - latch.await(); - } catch (InterruptedException e) { - ConsoleUtils.error("Error occurred on waiting accomplishing all tx committing. --%s", e.getMessage()); - } - - long elapsedTs = System.currentTimeMillis() - startTs; - - latestBlock = ledger.retrieveLatestBlock(); - ConsoleUtils.info("全部交易执行完成! -- 当前区块高度=%s; 交易数=%s; 总耗时= %s ms; TPS=%.2f", latestBlock.getHeight(), batchSize, - elapsedTs, (batchSize * 1000.00D / elapsedTs)); - } - - private static BlockchainKeypair[] generateKeys(int count) { - BlockchainKeypair[] keys = new BlockchainKeypair[count]; - for (int i = 0; i < count; i++) { - keys[i] = BlockchainKeyGenerator.getInstance().generate(); - } - return keys; - } - - private static PreparedTransaction[] prepareTransactions_RegisterDataAcount(BlockchainKeypair[] userKeys, - AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainService blockchainService) { - PreparedTransaction[] ptxs = new PreparedTransaction[userKeys.length]; - for (int i = 0; i < ptxs.length; i++) { - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.users().register(userKeys[i].getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - ptxs[i] = ptx; - } - - return ptxs; - } - - public static ConsensusProvider getConsensusProvider() { - return ConsensusProviders.getProvider("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"); - } - - private static IntegratedContext initLedgers() { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_integration(); - Properties props = Utils.loadConsensusSetting(); - ConsensusProvider csProvider = getConsensusProvider(); - ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props, - Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeInitContext nodeCtx0 = new NodeInitContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeInitContext nodeCtx1 = new NodeInitContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeInitContext nodeCtx2 = new NodeInitContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeInitContext nodeCtx3 = new NodeInitContext(3, initAddr3); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[0], Utils.PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[1], Utils.PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[2], Utils.PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[3], Utils.PASSWORD); - - String encodedPassword = KeyGenUtils.encodePasswordAsBase58(Utils.PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri("memory://local/0"); - LedgerBindingConfig bindingConfig0 = new LedgerBindingConfig(); - AsyncCallback callback0 = nodeCtx0.startInitCommand(privkey0, encodedPassword, initSetting, csProps, - csProvider, testDb0, consolePrompter, bindingConfig0, quitLatch); - - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri("memory://local/1"); - LedgerBindingConfig bindingConfig1 = new LedgerBindingConfig(); - AsyncCallback callback1 = nodeCtx1.startInitCommand(privkey1, encodedPassword, initSetting, csProps, - csProvider, testDb1, consolePrompter, bindingConfig1, quitLatch); - - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri("memory://local/2"); - LedgerBindingConfig bindingConfig2 = new LedgerBindingConfig(); - AsyncCallback callback2 = nodeCtx2.startInitCommand(privkey2, encodedPassword, initSetting, csProps, - csProvider, testDb2, consolePrompter, bindingConfig2, quitLatch); - - DBConnectionConfig testDb3 = new DBConnectionConfig(); - testDb3.setConnectionUri("memory://local/3"); - LedgerBindingConfig bindingConfig3 = new LedgerBindingConfig(); - AsyncCallback callback3 = nodeCtx3.startInitCommand(privkey3, encodedPassword, initSetting, csProps, - csProvider, testDb3, consolePrompter, bindingConfig3, quitLatch); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - nodeCtx0.registLedger(ledgerHash0); - nodeCtx1.registLedger(ledgerHash1); - nodeCtx2.registLedger(ledgerHash2); - nodeCtx3.registLedger(ledgerHash3); - - IntegratedContext context = new IntegratedContext(); - - Node node0 = new Node(0); - node0.setConsensusSettings(csProps); - node0.setLedgerManager(nodeCtx0.getLedgerManager()); - node0.setStorageDB(nodeCtx0.getStorageDB()); - node0.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(0).getPubKey(), privkey0)); - node0.setBindingConfig(bindingConfig0); - context.addNode(node0); - - Node node1 = new Node(1); - node1.setConsensusSettings(csProps); - node1.setLedgerManager(nodeCtx1.getLedgerManager()); - node1.setStorageDB(nodeCtx1.getStorageDB()); - node1.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(1).getPubKey(), privkey1)); - node1.setBindingConfig(bindingConfig1); - context.addNode(node1); - - Node node2 = new Node(2); - node2.setConsensusSettings(csProps); - node2.setLedgerManager(nodeCtx2.getLedgerManager()); - node2.setStorageDB(nodeCtx2.getStorageDB()); - node2.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(2).getPubKey(), privkey2)); - node2.setBindingConfig(bindingConfig2); - context.addNode(node2); - - Node node3 = new Node(3); - node3.setConsensusSettings(csProps); - node3.setLedgerManager(nodeCtx3.getLedgerManager()); - node3.setStorageDB(nodeCtx3.getStorageDB()); - node3.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(3).getPubKey(), privkey3)); - node3.setBindingConfig(bindingConfig3); - context.addNode(node3); - - nodeCtx0.closeServer(); - nodeCtx1.closeServer(); - nodeCtx2.closeServer(); - nodeCtx3.closeServer(); - - return context; - } - - public static LedgerInitProperties loadInitSetting_integration() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private static class NodeInitContext { - - private NetworkAddress serverAddress; - - private DBConnectionConfig dbConnConfig; - - private volatile ConfigurableApplicationContext ctx; - - private volatile LedgerInitProcess initProcess; - - private volatile LedgerInitializeWebController controller; - - private volatile LedgerManager ledgerManager; - - private volatile CompositeConnectionFactory db; - - private List conns = new ArrayList<>(); - - private int id; - - public int getId() { - return controller.getId(); - } - - public TransactionContent getInitTxContent() { - return controller.getInitTxContent(); - } - - public LedgerInitProposal getLocalPermission() { - return controller.getLocalPermission(); - } - - public LedgerInitDecision getLocalDecision() { - return controller.getLocalDecision(); - } - - public NodeInitContext(int id, NetworkAddress serverAddress) { - this.id = id; - this.serverAddress = serverAddress; - } - - public LedgerQuery registLedger(HashDigest ledgerHash) { - // LedgerManage ledgerManager = ctx.getBean(LedgerManage.class); - // - // DbConnectionFactory dbConnFactory = ctx.getBean(DbConnectionFactory.class); - // DbConnection conn = dbConnFactory.connect(dbConnConfig.getUri(), - // dbConnConfig.getPassword()); - - DbConnection conn = db.connect(dbConnConfig.getUri(), dbConnConfig.getPassword()); - conns.add(conn); - LedgerQuery ledgerRepo = ledgerManager.register(ledgerHash, conn.getStorageService()); - return ledgerRepo; - } - - public SignatureDigest createPermissionRequestSignature(int requesterId, PrivKey privKey) { - return controller.signPermissionRequest(requesterId, privKey); - } - - public AsyncCallback startInit(PrivKey privKey, LedgerInitProperties setting, - ConsensusSettings csProps, ConsensusProvider csProvider, DBConnectionConfig dbConnConfig, - Prompter prompter, CountDownLatch quitLatch) { - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - doStartServer(); - - // NodeWebContext.this.initProcess = ctx.getBean(LedgerInitProcess.class); - NodeInitContext.this.dbConnConfig = dbConnConfig; - HashDigest ledgerHash = NodeInitContext.this.initProcess.initialize(id, privKey, setting, - dbConnConfig, prompter); - - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public AsyncCallback startInitCommand(PrivKey privKey, String base58Pwd, - LedgerInitProperties ledgerSetting, ConsensusSettings csProps, ConsensusProvider csProvider, - DBConnectionConfig dbConnConfig, Prompter prompter, LedgerBindingConfig conf, - CountDownLatch quitLatch) { - this.db = new CompositeConnectionFactory(); - this.dbConnConfig = dbConnConfig; - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - LedgerInitCommand initCmd = new LedgerInitCommand(); - HashDigest ledgerHash = initCmd.startInit(id, privKey, base58Pwd, ledgerSetting, dbConnConfig, - prompter, conf, db); - NodeInitContext.this.ledgerManager = initCmd.getLedgerManager(); - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public LedgerInitProposal preparePermision(PrivKey privKey, LedgerInitProperties initProps) { - return controller.prepareLocalPermission(id, privKey, initProps); - } - - public boolean consensusPermission(PrivKey privKey) { - return controller.consensusPermisions(privKey); - } - - public LedgerInitDecision prepareLedger(DBConnectionConfig dbConnConfig, PrivKey privKey) { - controller.connectDb(dbConnConfig); - return controller.makeLocalDecision(privKey); - } - - public void startServer() { - ThreadInvoker invoker = new ThreadInvoker() { - - @Override - protected Object invoke() throws Exception { - doStartServer(); - return null; - } - }; - - invoker.startAndWait(); - } - - public void setPrompter(Prompter prompter) { - controller.setPrompter(prompter); - } - - public void doStartServer() { - String argServerAddress = String.format("--server.address=%s", serverAddress.getHost()); - String argServerPort = String.format("--server.port=%s", serverAddress.getPort()); - String nodebug = "--debug=false"; - String[] innerArgs = { argServerAddress, argServerPort, nodebug }; - - ctx = SpringApplication.run(LedgerInitTestConfiguration.class, innerArgs); - - ctx.setId("Node-" + id); - controller = ctx.getBean(LedgerInitializeWebController.class); - ledgerManager = ctx.getBean(LedgerManager.class); - db = ctx.getBean(CompositeConnectionFactory.class); - initProcess = ctx.getBean(LedgerInitProcess.class); - } - - public void closeServer() { - try { - if (this.ctx != null) { - this.ctx.close(); - this.ctx = null; - } - } catch (Exception e1) { - // Ignore; - } - for (DbConnection conn : conns) { - try { - conn.close(); - } catch (Exception e) { - // Ignore; - } - } - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - // return ctx.getBean(LedgerManager.class); - } - - public CompositeConnectionFactory getStorageDB() { - return db; - // return ctx.getBean(MemoryBasedDb.class); - } - } -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitTestConfiguration.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitTestConfiguration.java deleted file mode 100644 index 235e4d4b..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitTestConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; - -//import com.jd.blockchain.storage.service.utils.MemoryBasedDb; -import com.jd.blockchain.tools.initializer.web.InitWebSecurityConfiguration; -import com.jd.blockchain.tools.initializer.web.InitWebServerConfiguration; - -@SpringBootApplication -@EnableAutoConfiguration -@EnableConfigurationProperties -@Import(value = { InitWebServerConfiguration.class, InitWebSecurityConfiguration.class }) -public class LedgerInitTestConfiguration { - - @Bean - public MemoryDBConnFactory getStorageDB() { - return new MemoryDBConnFactory(); - } - -// @Bean -// public LedgerManager getLedgerManager() { -// return new LedgerManager(); -// } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitWebTestConfiguration.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitWebTestConfiguration.java deleted file mode 100644 index 4b513b74..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitWebTestConfiguration.java +++ /dev/null @@ -1,29 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -//import com.jd.blockchain.storage.service.utils.MemoryBasedDb; -import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; -import com.jd.blockchain.tools.initializer.web.InitWebSecurityConfiguration; -import com.jd.blockchain.tools.initializer.web.InitWebServerConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; - -@SpringBootApplication -@EnableAutoConfiguration -@EnableConfigurationProperties -@Import(value = { InitWebServerConfiguration.class, InitWebSecurityConfiguration.class }) -public class LedgerInitWebTestConfiguration { - - @Bean - public MemoryDBConnFactory getStorageDB() { - return new MemoryDBConnFactory(); - } - -// @Bean -// public LedgerManager getLedgerManager() { -// return new LedgerManager(); -// } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeTest.java deleted file mode 100644 index 71efc4e5..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeTest.java +++ /dev/null @@ -1,277 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.UserAccountQuery; -import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; -//import com.jd.blockchain.storage.service.utils.MemoryBasedDb; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.InitConsensusServiceFactory; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; - -public class LedgerInitializeTest { - - public static final String PASSWORD = "abc"; - - public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; - - - public static final String[] PRIV_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - - private Map serviceRegisterMap = new ConcurrentHashMap<>(); - - public static ConsensusProvider getConsensusProvider() { - return ConsensusProviders.getProvider("com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider"); - } - - public void testInitWith4Nodes() { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting(); - - NodeContext node0 = new NodeContext(initSetting.getConsensusParticipant(0).getInitializerAddress(), - serviceRegisterMap); - NodeContext node1 = new NodeContext(initSetting.getConsensusParticipant(1).getInitializerAddress(), - serviceRegisterMap); - NodeContext node2 = new NodeContext(initSetting.getConsensusParticipant(2).getInitializerAddress(), - serviceRegisterMap); - NodeContext node3 = new NodeContext(initSetting.getConsensusParticipant(3).getInitializerAddress(), - serviceRegisterMap); - - String[] memoryConnString = new String[] { "memory://local/0", "memory://local/1", "memory://local/2", - "memory://local/3" }; - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri(memoryConnString[0]); - AsyncCallback callback0 = node0.startInit(0, privkey0, initSetting, testDb0, consolePrompter); - - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri(memoryConnString[1]); - AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, testDb1, consolePrompter); - - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri(memoryConnString[2]); - AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, testDb2, consolePrompter); - - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - DBConnectionConfig testDb03 = new DBConnectionConfig(); - testDb03.setConnectionUri(memoryConnString[3]); - AsyncCallback callback3 = node3.startInit(3, privkey3, initSetting, testDb03, consolePrompter); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - LedgerQuery ledger0 = node0.registLedger(ledgerHash0, memoryConnString[0]); - LedgerQuery ledger1 = node1.registLedger(ledgerHash1, memoryConnString[1]); - LedgerQuery ledger2 = node2.registLedger(ledgerHash2, memoryConnString[2]); - LedgerQuery ledger3 = node3.registLedger(ledgerHash3, memoryConnString[3]); - - LedgerBlock genesisBlock = ledger0.getLatestBlock(); - - UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); - Bytes address0 = AddressEncoding.generateAddress(pubKey0); - UserAccount user0_0 = userset0.getAccount(address0); - - PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); - Bytes address1 = AddressEncoding.generateAddress(pubKey1); - UserAccount user1_0 = userset0.getAccount(address1); - - PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); - Bytes address2 = AddressEncoding.generateAddress(pubKey2); - UserAccount user2_0 = userset0.getAccount(address2); - - PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); - Bytes address3 = AddressEncoding.generateAddress(pubKey3); - UserAccount user3_0 = userset0.getAccount(address3); - } - - public static LedgerInitProperties loadInitSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web2.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("bftsmart.config"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static class NodeContext { - - private LedgerManager ledgerManager = new LedgerManager(); - - private MemoryDBConnFactory memoryDBConnFactory = new MemoryDBConnFactory(); -// private MemoryBasedDb storageDb = new MemoryBasedDb(); - - private InitConsensusServiceFactory initCsServiceFactory; - - private LedgerInitProcess initProcess; - - private AsymmetricKeypair partiKey; - - public AsymmetricKeypair getPartiKey() { - return partiKey; - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - } - - public MemoryDBConnFactory getMemoryDBConnFactory() { - return memoryDBConnFactory; - } - -// public MemoryBasedDb () { -// return storageDb; -// } - - public NodeContext(NetworkAddress address, Map serviceRegisterMap) { - this.initCsServiceFactory = new MultiThreadInterInvokerFactory(serviceRegisterMap); - LedgerInitializeWebController initController = new LedgerInitializeWebController(memoryDBConnFactory, - initCsServiceFactory); - serviceRegisterMap.put(address, initController); - this.initProcess = initController; - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter) { - - partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter); - } - }; - - return invoker.start(); - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties initProps, - DBConnectionConfig dbConnConfig, Prompter prompter, boolean autoVerifyHash) { - - initProps.getCryptoProperties().setVerifyHash(autoVerifyHash); - initProps.getCryptoProperties().setHashAlgorithm("SHA256"); - - partiKey = new AsymmetricKeypair(initProps.getConsensusParticipant(0).getPubKey(), privKey); - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, initProps, dbConnConfig, prompter); - } - }; - - return invoker.start(); - } - - public LedgerQuery registLedger(HashDigest ledgerHash, String connString) { - return ledgerManager.register(ledgerHash, memoryDBConnFactory.connect(connString).getStorageService()); - } - } - - private static class MultiThreadInterInvokerFactory implements InitConsensusServiceFactory { - - private Map nodeConsesusServices; - - public MultiThreadInterInvokerFactory(Map nodeConsesusServices) { - this.nodeConsesusServices = nodeConsesusServices; - } - - @Override - public LedgerInitConsensusService connect(NetworkAddress endpointAddress) { - return new InitConsensusServiceProxy(nodeConsesusServices.get(endpointAddress)); - } - - } - - private static class InitConsensusServiceProxy implements LedgerInitConsensusService { - - private LedgerInitConsensusService initCsService; - - public InitConsensusServiceProxy(LedgerInitConsensusService initCsService) { - this.initCsService = initCsService; - } - - @Override - public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected LedgerInitProposal invoke() { - return initCsService.requestPermission(requesterId, signature); - } - }; - return invoker.startAndWait(); - } - - @Override - public LedgerInitDecision synchronizeDecision(LedgerInitDecision initDecision) { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected LedgerInitDecision invoke() { - return initCsService.synchronizeDecision(initDecision); - } - }; - return invoker.startAndWait(); - } - - } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java deleted file mode 100644 index b687d8f6..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java +++ /dev/null @@ -1,528 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -import com.jd.blockchain.ledger.core.*; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.boot.SpringApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -//import com.jd.blockchain.storage.service.utils.MemoryBasedDb; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitCommand; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.HttpInitConsensServiceFactory; -import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.LedgerInitConsensusConfig; -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; - -public class LedgerInitializeWebTest { - - public static final String PASSWORD = LedgerInitializeTest.PASSWORD; - - public static final String[] PUB_KEYS = LedgerInitializeTest.PUB_KEYS; - - public static final String[] PRIV_KEYS = LedgerInitializeTest.PRIV_KEYS; - - /** - * 测试一个节点向多个节点请求新建许可的过程; - */ - public void testWithSingleSteps() { - Prompter prompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - - HttpInitConsensServiceFactory httpCsSrvFactory = new HttpInitConsensServiceFactory(); - - // 加载初始化配置; - LedgerInitProperties initSetting = loadInitSetting_1(); - // 加载共识配置; - Properties props = loadConsensusSetting(LedgerInitConsensusConfig.bftsmartConfig.getConfigPath()); - // ConsensusProperties csProps = new ConsensusProperties(props); - ConsensusProvider csProvider = getConsensusProvider(); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeWebContext node0 = new NodeWebContext(0, initAddr0); - node0.startServer(); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeWebContext node1 = new NodeWebContext(1, initAddr1); - node1.startServer(); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeWebContext node2 = new NodeWebContext(2, initAddr2); - node2.startServer(); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeWebContext node3 = new NodeWebContext(3, initAddr3); - node3.startServer(); - - node0.setPrompter(prompter); - node1.setPrompter(prompter); - node2.setPrompter(prompter); - node3.setPrompter(prompter); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); - PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); - PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); - PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); - - // 测试生成“账本初始化许可”; - LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(initSetting); - initConfig.setConsensusSettings(csProvider, csProps); - LedgerInitProposal permission0 = testPreparePermisssion(node0, privkey0, initConfig); - LedgerInitProposal permission1 = testPreparePermisssion(node1, privkey1, initConfig); - LedgerInitProposal permission2 = testPreparePermisssion(node2, privkey2, initConfig); - LedgerInitProposal permission3 = testPreparePermisssion(node3, privkey3, initConfig); - - TransactionContent initTxContent0 = node0.getInitTxContent(); - TransactionContent initTxContent1 = node1.getInitTxContent(); - TransactionContent initTxContent2 = node2.getInitTxContent(); - TransactionContent initTxContent3 = node3.getInitTxContent(); - - if (!initTxContent0.getHash().equals(initTxContent1.getHash())) { - Operation[] oplist0 = initTxContent0.getOperations(); - Operation[] oplist1 = initTxContent1.getOperations(); - - LedgerInitOperation initOp0 = (LedgerInitOperation) oplist0[0]; - LedgerInitOperation initOp1 = (LedgerInitOperation) oplist1[0]; - - byte[] initOpBytes0 = BinaryProtocol.encode(initOp0, LedgerInitOperation.class); - byte[] initOpBytes1 = BinaryProtocol.encode(initOp1, LedgerInitOperation.class); - - UserRegisterOperation regOp00 = (UserRegisterOperation) oplist0[1]; - UserRegisterOperation regOp10 = (UserRegisterOperation) oplist1[1]; - byte[] regOpBytes00 = BinaryProtocol.encode(regOp00, UserRegisterOperation.class); - byte[] regOpBytes10 = BinaryProtocol.encode(regOp10, UserRegisterOperation.class); - - UserRegisterOperation regOp01 = (UserRegisterOperation) oplist0[2]; - UserRegisterOperation regOp11 = (UserRegisterOperation) oplist1[2]; - byte[] regOpBytes01 = BinaryProtocol.encode(regOp01, UserRegisterOperation.class); - byte[] regOpBytes11 = BinaryProtocol.encode(regOp11, UserRegisterOperation.class); - - UserRegisterOperation regOp02 = (UserRegisterOperation) oplist0[3]; - UserRegisterOperation regOp12 = (UserRegisterOperation) oplist1[3]; - byte[] regOpBytes02 = BinaryProtocol.encode(regOp02, UserRegisterOperation.class); - byte[] regOpBytes12 = BinaryProtocol.encode(regOp12, UserRegisterOperation.class); - - UserRegisterOperation regOp03 = (UserRegisterOperation) oplist0[4]; - UserRegisterOperation regOp13 = (UserRegisterOperation) oplist1[4]; - byte[] regOpBytes03 = BinaryProtocol.encode(regOp03, UserRegisterOperation.class); - byte[] regOpBytes13 = BinaryProtocol.encode(regOp13, UserRegisterOperation.class); - - } - - // 测试请求“账本初始化许可”; - // test request permission, and verify the response; - LedgerInitConsensusService initCsService0 = httpCsSrvFactory.connect(initAddr0); - LedgerInitConsensusService initCsService1 = httpCsSrvFactory.connect(initAddr1); - LedgerInitConsensusService initCsService2 = httpCsSrvFactory.connect(initAddr2); - LedgerInitConsensusService initCsService3 = httpCsSrvFactory.connect(initAddr3); - - testRequestPermission(node0, privkey0, node1, initCsService1); - testRequestPermission(node0, privkey0, node2, initCsService2); - testRequestPermission(node0, privkey0, node3, initCsService3); - testRequestPermission(node1, privkey1, node0, initCsService0); - testRequestPermission(node1, privkey1, node2, initCsService2); - testRequestPermission(node1, privkey1, node3, initCsService3); - testRequestPermission(node2, privkey2, node0, initCsService0); - testRequestPermission(node2, privkey2, node1, initCsService1); - testRequestPermission(node2, privkey2, node3, initCsService3); - testRequestPermission(node3, privkey3, node0, initCsService0); - testRequestPermission(node3, privkey3, node1, initCsService1); - testRequestPermission(node3, privkey3, node2, initCsService2); - - // 测试在节点之间共识彼此的“账本初始化许可” - boolean allPermitted0 = node0.consensusPermission(privkey0); - boolean allPermitted1 = node1.consensusPermission(privkey1); - boolean allPermitted2 = node2.consensusPermission(privkey2); - boolean allPermitted3 = node3.consensusPermission(privkey3); - - // 测试生成账本,并创建“账本初始化决议”; - DBConnectionConfig testDb0 = new DBConnectionConfig("memory://local/0"); - DBConnectionConfig testDb1 = new DBConnectionConfig("memory://local/1"); - DBConnectionConfig testDb2 = new DBConnectionConfig("memory://local/2"); - DBConnectionConfig testDb3 = new DBConnectionConfig("memory://local/3"); - - LedgerInitDecision dec0 = node0.prepareLedger(testDb0, privkey0); - LedgerInitDecision dec1 = node1.prepareLedger(testDb1, privkey1); - LedgerInitDecision dec2 = node2.prepareLedger(testDb2, privkey2); - LedgerInitDecision dec3 = node3.prepareLedger(testDb3, privkey3); - - testRequestDecision(node0, node1, initCsService1); - testRequestDecision(node0, node2, initCsService2); - testRequestDecision(node0, node3, initCsService3); - testRequestDecision(node1, node0, initCsService0); - testRequestDecision(node1, node2, initCsService2); - testRequestDecision(node1, node3, initCsService3); - testRequestDecision(node2, node0, initCsService0); - testRequestDecision(node2, node1, initCsService1); - testRequestDecision(node2, node3, initCsService3); - testRequestDecision(node3, node0, initCsService0); - testRequestDecision(node3, node1, initCsService1); - testRequestDecision(node3, node2, initCsService2); - } - - private LedgerInitProposal testPreparePermisssion(NodeWebContext node, PrivKey privKey, - LedgerInitConfiguration setting) { - LedgerInitProposal permission = node.preparePermision(privKey, setting); - - return permission; - } - - private void testRequestPermission(NodeWebContext fromNode, PrivKey fromPrivkey, NodeWebContext targetNode, - LedgerInitConsensusService targetNodeService) { - SignatureDigest reqSignature = fromNode.createPermissionRequestSignature(fromNode.getId(), fromPrivkey); - LedgerInitProposal targetPermission = targetNodeService.requestPermission(fromNode.getId(), reqSignature); - } - - private void testRequestDecision(NodeWebContext fromNode, NodeWebContext targetNode, - LedgerInitConsensusService targetNodeService) { - LedgerInitDecision targetDecision = targetNodeService.synchronizeDecision(fromNode.getLocalDecision()); - } - - public SignatureDigest signPermissionRequest(int requesterId, PrivKey privKey, LedgerInitProperties initSetting) { - byte[] reqAuthBytes = BytesUtils.concat(BytesUtils.toBytes(requesterId), initSetting.getLedgerSeed()); - SignatureFunction signFunc = Crypto.getSignatureFunction("ED25519"); - SignatureDigest reqAuthSign = signFunc.sign(privKey, reqAuthBytes); - return reqAuthSign; - } - - private static ConsensusProvider getConsensusProvider() { - return ConsensusProviders.getProvider("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"); - } - - public void testInitWith4Nodes() { - System.out.println("----------- is daemon=" + Thread.currentThread().isDaemon()); - - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_2(); - Properties props = loadConsensusSetting(LedgerInitConsensusConfig.bftsmartConfig.getConfigPath()); - // ConsensusProperties csProps = new ConsensusProperties(props); - ConsensusProvider csProvider = getConsensusProvider(); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeWebContext node0 = new NodeWebContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeWebContext node1 = new NodeWebContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeWebContext node2 = new NodeWebContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeWebContext node3 = new NodeWebContext(3, initAddr3); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri("memory://local/0"); - AsyncCallback callback0 = node0.startInit(privkey0, initSetting, testDb0, consolePrompter, - quitLatch); - - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri("memory://local/1"); - AsyncCallback callback1 = node1.startInit(privkey1, initSetting, testDb1, consolePrompter, - quitLatch); - - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri("memory://local/2"); - AsyncCallback callback2 = node2.startInit(privkey2, initSetting, testDb2, consolePrompter, - quitLatch); - - DBConnectionConfig testDb03 = new DBConnectionConfig(); - testDb03.setConnectionUri("memory://local/3"); - AsyncCallback callback3 = node3.startInit(privkey3, initSetting, testDb03, consolePrompter, - quitLatch); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - LedgerQuery ledger0 = node0.registLedger(ledgerHash0); - LedgerQuery ledger1 = node1.registLedger(ledgerHash1); - LedgerQuery ledger2 = node2.registLedger(ledgerHash2); - LedgerQuery ledger3 = node3.registLedger(ledgerHash3); - - LedgerBlock genesisBlock = ledger0.getLatestBlock(); - - UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); - Bytes address0 = AddressEncoding.generateAddress(pubKey0); - UserAccount user0_0 = userset0.getAccount(address0); - - PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); - Bytes address1 = AddressEncoding.generateAddress(pubKey1); - UserAccount user1_0 = userset0.getAccount(address1); - - PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); - Bytes address2 = AddressEncoding.generateAddress(pubKey2); - UserAccount user2_0 = userset0.getAccount(address2); - - PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); - Bytes address3 = AddressEncoding.generateAddress(pubKey3); - UserAccount user3_0 = userset0.getAccount(address3); - } - - public static LedgerInitProperties loadInitSetting_1() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web1.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static LedgerInitProperties loadInitSetting_2() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web2.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting(String configPath) { - ClassPathResource ledgerInitSettingResource = new ClassPathResource(configPath); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static class NodeWebContext { - - private NetworkAddress serverAddress; - - private DBConnectionConfig dbConnConfig; - - // private MQConnectionConfig mqConnConfig; - - private volatile ConfigurableApplicationContext ctx; - - private volatile LedgerInitProcess initProcess; - - private volatile LedgerInitializeWebController controller; - - private volatile LedgerManager ledgerManager; - - private volatile DbConnectionFactory db; - - private int id; - - public int getId() { - return controller.getId(); - } - - public TransactionContent getInitTxContent() { - return controller.getInitTxContent(); - } - - public LedgerInitProposal getLocalPermission() { - return controller.getLocalPermission(); - } - - public LedgerInitDecision getLocalDecision() { - return controller.getLocalDecision(); - } - - public NodeWebContext(int id, NetworkAddress serverAddress) { - this.id = id; - this.serverAddress = serverAddress; - } - - public LedgerQuery registLedger(HashDigest ledgerHash) { - // LedgerManage ledgerManager = ctx.getBean(LedgerManage.class); - // - // DbConnectionFactory dbConnFactory = ctx.getBean(DbConnectionFactory.class); - // DbConnection conn = dbConnFactory.connect(dbConnConfig.getUri(), - // dbConnConfig.getPassword()); - - // DbConnection conn = db.connect(dbConnConfig.getUri(), - // dbConnConfig.getPassword()); - DbConnection conn = db.connect(dbConnConfig.getUri()); - LedgerQuery ledgerRepo = ledgerManager.register(ledgerHash, conn.getStorageService()); - - return ledgerRepo; - } - - public LedgerRepository ledgerRepository(HashDigest ledgerHash) { - return ledgerManager.getLedger(ledgerHash); - } - - public SignatureDigest createPermissionRequestSignature(int requesterId, PrivKey privKey) { - return controller.signPermissionRequest(requesterId, privKey); - } - - public AsyncCallback startInit(PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter, CountDownLatch quitLatch) { - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - doStartServer(); - - // NodeWebContext.this.initProcess = ctx.getBean(LedgerInitProcess.class); - NodeWebContext.this.dbConnConfig = dbConnConfig; - HashDigest ledgerHash = NodeWebContext.this.initProcess.initialize(id, privKey, setting, - dbConnConfig, prompter); - - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - - public AsyncCallback startInitCommand(PrivKey privKey, String base58Pwd, - LedgerInitProperties ledgerSetting, ConsensusSettings csProps, ConsensusProvider csProvider, - DBConnectionConfig dbConnConfig, Prompter prompter, LedgerBindingConfig conf, - CountDownLatch quitLatch, DbConnectionFactory db) { - this.dbConnConfig = dbConnConfig; - // this.mqConnConfig = mqConnConfig; - this.db = db; - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - LedgerInitCommand initCmd = new LedgerInitCommand(); - HashDigest ledgerHash = initCmd.startInit(id, privKey, base58Pwd, ledgerSetting, dbConnConfig, - prompter, conf, db); - - LedgerManager lm = initCmd.getLedgerManager(); - - NodeWebContext.this.ledgerManager = lm; - - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - - public LedgerInitProposal preparePermision(PrivKey privKey, LedgerInitConfiguration initConfig) { - return controller.prepareLocalPermission(id, privKey, initConfig); - } - - public boolean consensusPermission(PrivKey privKey) { - return controller.consensusPermisions(privKey); - } - - public LedgerInitDecision prepareLedger(DBConnectionConfig dbConnConfig, PrivKey privKey) { - controller.connectDb(dbConnConfig); - return controller.makeLocalDecision(privKey); - } - - public void startServer() { - ThreadInvoker invoker = new ThreadInvoker() { - - @Override - protected Object invoke() throws Exception { - doStartServer(); - return null; - } - }; - - invoker.startAndWait(); - } - - public void setPrompter(Prompter prompter) { - controller.setPrompter(prompter); - } - - public void doStartServer() { - String argServerAddress = String.format("--server.address=%s", serverAddress.getHost()); - String argServerPort = String.format("--server.port=%s", serverAddress.getPort()); - String nodebug = "--debug=false"; - String[] innerArgs = { argServerAddress, argServerPort, nodebug }; - - ctx = SpringApplication.run(LedgerInitWebTestConfiguration.class, innerArgs); - - ctx.setId("Node-" + id); - controller = ctx.getBean(LedgerInitializeWebController.class); - ledgerManager = ctx.getBean(LedgerManager.class); - db = ctx.getBean(CompositeConnectionFactory.class); - initProcess = ctx.getBean(LedgerInitProcess.class); - } - - public void closeServer() { - if (this.ctx != null) { - this.ctx.close(); - this.ctx = null; - } - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - // return ctx.getBean(LedgerManager.class); - } - - public DbConnectionFactory getStorageDB() { - return db; - } - } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java deleted file mode 100644 index c9d74a1d..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java +++ /dev/null @@ -1,727 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.DoubleStream; - -import com.jd.blockchain.ledger.*; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.LedgerSecurityException; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.LedgerDataQuery; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerSecurityManager; -import com.jd.blockchain.ledger.core.MultiIDsPolicy; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionBatchProcessor; -import com.jd.blockchain.service.TransactionBatchResultHandle; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.storage.service.impl.redis.JedisConnection; -import com.jd.blockchain.storage.service.impl.redis.RedisConnectionFactory; -import com.jd.blockchain.storage.service.impl.redis.RedisStorageService; -import com.jd.blockchain.storage.service.impl.rocksdb.RocksDBConnectionFactory; -import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.ArgumentSet; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; -import test.com.jd.blockchain.intgr.perf.Utils.NodeContext; - -//import com.jd.blockchain.storage.service.utils.MemoryBasedDb; - -/** - * 账本性能测试;
- * - * 可用的参数:
- * -o: 优化模式执行;此时merkle树在加载时不做检查; - *

- * - * -redis: 基于 redis 数据库进行测试;需要预先启动redis数据库,4个节点分别连接到本机 redis://127.0.0.1 的端口为 - * 6079、6179、6279、6379 的 4 个数据库实例; - *

- * - * -rocksdb: 基于 rocksDB 进行测试;不需要预先配置数据库,4个节点连接到当前路径下的4个RocksDB数据库目录: - * rocksdb0.db、rocksdb1.db、rocksdb2.db、rocksdb3.db; - *

- * - * -silent: 采用静默模式启动测试用例;否则会在准备就绪后等待输入任意键才正式开始测试,并在完成测试后等待输入任意键才退出; - * - * - * @author huanghaiquan - * - */ -public class LedgerPerformanceTest { - static { - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - } - - public static final LedgerSecurityManager DEFAULT_SECURITY_MANAGER = new FreedomLedgerSecurityManager(); - - public static void test(String[] args) { - NodeContext[] nodes = null; - try { - boolean usertest = ArgumentSet.hasOption(args, "-usertest"); - boolean optimized = ArgumentSet.hasOption(args, "-o"); - boolean useRedis = ArgumentSet.hasOption(args, "-redis"); - boolean useRocksDB = ArgumentSet.hasOption(args, "-rocksdb"); - boolean silent = ArgumentSet.hasOption(args, "-silent"); - boolean contract = ArgumentSet.hasOption(args, "-contract"); - boolean mqConsensus = ArgumentSet.hasOption(args, "-mq"); - DBType dbType = DBType.DEFAULT; - if (useRedis) { - dbType = DBType.REDIS; - } - if (useRocksDB) { - dbType = DBType.ROCKSDB; - } - - CryptoAlgorithm hashAlg = ArgumentSet.hasOption(args, "-160") ? Crypto.getAlgorithm("RIPEMD160") - : Crypto.getAlgorithm("SHA256"); - System.out.println( - String.format("----- LedgerPerformanceTest [HashAlgorithm=%s][DBType=%s] ----", hashAlg, dbType)); - // 初始化,并获取其中一个节点的账本,单独进行性能测试; - String provider = "com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"; - String config = "bftsmart.config"; - if (mqConsensus) { - provider = "com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider"; - config = "mq.config"; - } - nodes = initLedgers(optimized, hashAlg, dbType, provider, config); - - NodeContext testNode = nodes[0]; - LedgerManager ledgerManager = testNode.getLedgerManager(); - HashDigest ledgerHash = ledgerManager.getLedgerHashs()[0]; - - DefaultOperationHandleRegisteration opHandler = new DefaultOperationHandleRegisteration(); - - System.out.println("Ledger is ready!"); - - int batchSize = 1000; - int batchCount = 30; - - if (args.length > 0) { - if (!args[0].startsWith("-")) { - batchSize = Integer.parseInt(args[0]); - } - } - if (args.length > 1) { - if (!args[1].startsWith("-")) { - batchCount = Integer.parseInt(args[1]); - } - } - if (contract) { - testContract(ledgerHash, testNode.getPartiKey(), ledgerManager, opHandler, batchSize, batchCount, - silent); - } - - if (usertest) { - testUserRegistering(ledgerHash, testNode.getPartiKey(), ledgerManager, opHandler, batchSize, batchCount, - silent); - } else { - testKVWrite(ledgerHash, testNode.getPartiKey(), ledgerManager, opHandler, batchSize, batchCount, - silent); - } - } catch (Exception e) { - System.out.println("----------- error [" + e.getMessage() + "]-----------"); - e.printStackTrace(); - } finally { - if (nodes != null) { - for (NodeContext node : nodes) { - node.getStorageDb().close(); - } - } - } - } - - /** - * 执行针对“注册用户”的性能测试; - * - * @param ledgerHash - * @param adminKey - * @param ledgerManager - * @param opHandler - * @param batchSize - * @param batchCount - * @param silent - */ - private static void testUserRegistering(HashDigest ledgerHash, AsymmetricKeypair adminKey, - LedgerManager ledgerManager, DefaultOperationHandleRegisteration opHandler, int batchSize, int batchCount, - boolean silent) { - LedgerRepository ledger = ledgerManager.getLedger(ledgerHash); - ConsoleUtils.info("\r\n\r\n================= 准备测试交易 [注册用户] ================="); - - int totalCount = batchSize * batchCount; - List txList = prepareUserRegisterRequests(ledgerHash, totalCount, adminKey); - - // 预热; - ConsoleUtils.info("preheat......"); - int preheatTxBatch = 10; - int preheatTxBatchSize = 10; - int preheatTotalTx = preheatTxBatch * preheatTxBatchSize; - List preheatTxList = prepareUserRegisterRequests(ledgerHash, preheatTotalTx, adminKey); - execPerformanceTest(preheatTxBatch, preheatTxBatchSize, preheatTxList, ledger, ledgerManager, opHandler, false); - preheatTxList.clear(); - preheatTxList = null; - - if (!silent) { - ConsoleUtils.confirm("\r\nTest is ready! Any key to continue..."); - } - - execPerformanceTest(batchCount, batchSize, txList, ledger, ledgerManager, opHandler, true); - - if (!silent) { - ConsoleUtils.confirm("\r\nTest completed! Any key to quit..."); - } - - } - - /** - * 执行针对“写入数据”的性能测试; - * - * @param ledgerHash - * @param adminKey - * @param ledgerManager - * @param opHandler - * @param batchSize - * @param batchCount - * @param silent - */ - private static void testKVWrite(HashDigest ledgerHash, AsymmetricKeypair adminKey, LedgerManager ledgerManager, - DefaultOperationHandleRegisteration opHandler, int batchSize, int batchCount, boolean silent) { - LedgerRepository ledger = ledgerManager.getLedger(ledgerHash); - ConsoleUtils.info("\r\n\r\n================= 准备测试交易 [写入数据] ================="); - - // 创建数据账户; - BlockchainIdentity[] dataAccounts = new BlockchainIdentity[10]; - List dataAccountRegTxList = prepareDataAccountRegisterRequests(ledgerHash, dataAccounts, - adminKey, false); - execPerformanceTest(1, dataAccounts.length, dataAccountRegTxList, ledger, ledgerManager, opHandler, false); - - // 预热; - ConsoleUtils.info("preheat......"); - int preheatTxBatch = 10; - int preheatTxBatchSize = 10; - int preheatTotalTx = preheatTxBatch * preheatTxBatchSize; - List preheatTxList = prepareDataWriteRequests(ledgerHash, dataAccounts, preheatTotalTx, - adminKey, false); - execPerformanceTest(preheatTxBatch, preheatTxBatchSize, preheatTxList, ledger, ledgerManager, opHandler, false); - preheatTxList.clear(); - preheatTxList = null; - - // 准备正式数据; - int totalCount = batchSize * batchCount; - List txList = prepareDataWriteRequests(ledgerHash, dataAccounts, totalCount, adminKey, - false); - - Prompter consolePrompter = new PresetAnswerPrompter("N"); - - if (!silent) { -// ConsoleUtils.confirm("\r\nTest is ready! Any key to continue..."); - consolePrompter.confirm("testKVWrite", "Test is ready! Any key to continue..."); - } - - execPerformanceTest(batchCount, batchSize, txList, ledger, ledgerManager, opHandler, true); - - if (!silent) { -// ConsoleUtils.confirm("\r\nTest completed! Any key to quit..."); - consolePrompter.confirm("testKVWrite", "Test completed! Any key to quit..."); - } - - } - - /** - * 执行针对“执行合约”的性能测试; - * - * @param ledgerHash - * @param adminKey - * @param ledgerManager - * @param opHandler - * @param batchSize - * @param batchCount - * @param silent - */ - private static void testContract(HashDigest ledgerHash, AsymmetricKeypair adminKey, LedgerManager ledgerManager, - DefaultOperationHandleRegisteration opHandler, int batchSize, int batchCount, boolean silent) { - LedgerRepository ledger = ledgerManager.getLedger(ledgerHash); - ConsoleUtils.info("\r\n\r\n================= 准备测试交易 [执行合约] ================="); - - LedgerBlock latestBlock = ledger.getLatestBlock(); - LedgerDataQuery previousDataSet = ledger.getLedgerData(latestBlock); - LedgerEditor newEditor = ledger.createNextBlock(); - TransactionBatchProcessor txProc = new TransactionBatchProcessor(DEFAULT_SECURITY_MANAGER, newEditor, - ledger, opHandler); - - // 准备请求 - int totalCount = batchSize * batchCount; - List contractTxList = prepareContractRequests(ledgerHash, adminKey, totalCount, false, - txProc); - - Prompter consolePrompter = new PresetAnswerPrompter("N"); - - if (!silent) { -// ConsoleUtils.confirm("\r\nTest is ready! Any key to continue..."); - consolePrompter.confirm("testContract", "Test is ready! Any key to continue..."); - } - - execPerformanceTest(batchCount, batchSize, contractTxList, ledger, ledgerManager, opHandler, true); - - if (!silent) { -// ConsoleUtils.confirm("\r\nTest completed! Any key to quit..."); - consolePrompter.confirm("testContract", "Test completed! Any key to quit..."); - } - - } - - private static void execPerformanceTest(int batchCount, int batchSize, List txList, - LedgerRepository ledger, LedgerManager ledgerManager, DefaultOperationHandleRegisteration opHandler, - boolean statistic) { - double[] tpss = new double[batchCount]; - long batchStartTs = System.currentTimeMillis(); - for (int i = 0; i < batchCount; i++) { - LedgerBlock latestBlock = ledger.getLatestBlock(); - LedgerDataQuery previousDataSet = ledger.getLedgerData(latestBlock); - if (statistic) { - ConsoleUtils.info("------ 开始执行交易, 即将生成区块[高度:%s] ------", (latestBlock.getHeight() + 1)); - } - long startTs = System.currentTimeMillis(); - - LedgerEditor newEditor = ledger.createNextBlock(); - TransactionBatchProcessor txProc = new TransactionBatchProcessor(DEFAULT_SECURITY_MANAGER, newEditor, - ledger, opHandler); - - testTxExec(txList, i * batchSize, batchSize, txProc); - - if (statistic) { - long elapsedTs = System.currentTimeMillis() - startTs; - - tpss[i] = batchSize * 1000.00D / elapsedTs; - ConsoleUtils.info("新区块已生成! 交易数=%s; 总耗时= %s ms; TPS=%.2f", batchSize, elapsedTs, tpss[i]); - } - } - if (!statistic) { - return; - } - long batchElapsedTs = System.currentTimeMillis() - batchStartTs; - double globalTPS = batchSize * batchCount * 1000.00D / batchElapsedTs; - double avgTPS = DoubleStream.of(tpss).average().getAsDouble(); - double maxTPS = DoubleStream.of(tpss).max().getAsDouble(); - double variance = DoubleStream.of(tpss).reduce(0, (r, i) -> r + Math.pow(i - avgTPS, 2)) / tpss.length; - double stdDeviation = Math.sqrt(variance); - - ConsoleUtils.info("\r\n**********************************************"); - ConsoleUtils.info("区块数:%s; 交易总数:%s; 总体TPS:%.2f;\r\n单区块TPS均值:%.2f;单区块TPS峰值:%.2f;单区块TPS波动(标准差):%.2f", batchCount, - batchSize * batchCount, globalTPS, avgTPS, maxTPS, stdDeviation); - ConsoleUtils.info("**********************************************\r\n"); - } - - private static void testTxExec(List txList, int from, int count, - TransactionBatchProcessor txProc) { - for (int i = 0; i < count; i++) { - txProc.schedule(txList.get(from + i)); - } - TransactionBatchResultHandle handle = txProc.prepare(); - handle.commit(); - } - - public static List prepareUserRegisterRequests(HashDigest ledgerHash, int count, - AsymmetricKeypair adminKey) { - long startTs = System.currentTimeMillis(); - List txList = new ArrayList<>(); - for (int i = 0; i < count; i++) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - txbuilder.users().register(userKey.getIdentity()); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - txList.add(reqBuilder.buildRequest()); - } - long elapsedTs = System.currentTimeMillis() - startTs; - ConsoleUtils.info( - "============ Performance of Preparing user registering tx requests... TOTAL=%s; TPS=%.2f; TIME=%s millis ============", - count, (count * 1000.0 / elapsedTs), elapsedTs); - ConsoleUtils.info("====================================================="); - return txList; - } - - public static List prepareDataAccountRegisterRequests(HashDigest ledgerHash, - BlockchainIdentity[] dataAccounts, AsymmetricKeypair adminKey, boolean statistic) { - int count = dataAccounts.length; - long startTs = System.currentTimeMillis(); - List txList = new ArrayList<>(); - for (int i = 0; i < count; i++) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - BlockchainKeypair dataAccountKey = BlockchainKeyGenerator.getInstance().generate(); - dataAccounts[i] = dataAccountKey.getIdentity(); - txbuilder.dataAccounts().register(dataAccounts[i]); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - txList.add(reqBuilder.buildRequest()); - } - if (statistic) { - long elapsedTs = System.currentTimeMillis() - startTs; - ConsoleUtils.info( - "============ Performance of Preparing data account registering tx requests... TOTAL=%s; TPS=%.2f; TIME=%s millis ============", - count, (count * 1000.0 / elapsedTs), elapsedTs); - ConsoleUtils.info("====================================================="); - } - return txList; - } - - public static List prepareDataWriteRequests(HashDigest ledgerHash, - BlockchainIdentity[] dataAccounts, int count, AsymmetricKeypair adminKey, boolean statistic) { - long startTs = System.currentTimeMillis(); - List txList = new ArrayList<>(); - for (int i = 0; i < count; i++) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - // BlockchainKeyPair dataAccountKey = - // BlockchainKeyGenerator.getInstance().generate(); - BlockchainIdentity targetAccount = dataAccounts[count % dataAccounts.length]; - txbuilder.dataAccount(targetAccount.getAddress()).setText("key-" + startTs + "-" + i, "value-" + i, -1L); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - txList.add(reqBuilder.buildRequest()); - } - if (statistic) { - long elapsedTs = System.currentTimeMillis() - startTs; - ConsoleUtils.info( - "============ Performance of Preparing data account registering tx requests... TOTAL=%s; TPS=%.2f; TIME=%s millis ============", - count, (count * 1000.0 / elapsedTs), elapsedTs); - ConsoleUtils.info("====================================================="); - } - return txList; - } - - public static ConsensusProvider getConsensusProvider(String provider) { - return ConsensusProviders.getProvider(provider); - } - - public static List prepareContractRequests(HashDigest ledgerHash, AsymmetricKeypair adminKey, - int count, boolean statistic, TransactionBatchProcessor txProc) { - - // deploy contract - byte[] chainCode; - try { -// InputStream input = LedgerPerformanceTest.class.getClassLoader().getResourceAsStream("Setkv.contract"); - InputStream input = LedgerPerformanceTest.class.getClassLoader().getResourceAsStream("example1.jar"); - chainCode = new byte[input.available()]; - input.read(chainCode); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - TxBuilder txbuilder = new TxBuilder(ledgerHash); - BlockchainKeypair contractAccountKey = BlockchainKeyGenerator.getInstance().generate(); - BlockchainIdentity contractIdentity = contractAccountKey.getIdentity(); - txbuilder.contracts().deploy(contractIdentity, chainCode); - - // create data account - BlockchainKeypair dataAccountKey = BlockchainKeyGenerator.getInstance().generate(); - BlockchainIdentity dataIdentity = dataAccountKey.getIdentity(); - - txbuilder.dataAccounts().register(dataIdentity); - - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - TransactionResponse resp = txProc.schedule(reqBuilder.buildRequest()); - System.out.println(resp.isSuccess()); - TransactionBatchResultHandle handle = txProc.prepare(); - handle.commit(); - try { - - Thread.sleep(1000); - } catch (Exception e) { - e.printStackTrace(); - } - - long startTs = System.currentTimeMillis(); - List txList = new ArrayList<>(); - for (int i = 0; i < count; i++) { - txbuilder = new TxBuilder(ledgerHash); - String args = dataIdentity.getAddress().toString() + "##" + Integer.toString(i) + "##" - + Integer.toString(i); - txbuilder.contractEvents().send(contractIdentity.getAddress(), "print", BytesDataList.singleText("hello")); -// txbuilder.contractEvents().send(contractIdentity.getAddress(), "print", args.getBytes()); - reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - txList.add(reqBuilder.buildRequest()); - } - if (statistic) { - long elapsedTs = System.currentTimeMillis() - startTs; - ConsoleUtils.info( - "============ Performance of Preparing contract execute tx requests... TOTAL=%s; TPS=%.2f; TIME=%s millis ============", - count, (count * 1000.0 / elapsedTs), elapsedTs); - ConsoleUtils.info("====================================================="); - } - return txList; - } - - public static NodeContext[] initLedgers(boolean optimized, CryptoAlgorithm hashAlg, DBType dbType, String provider, - String config) { - Map serviceRegisterMap = new ConcurrentHashMap<>(); - - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting(); - Properties props = loadConsensusSetting(config); - ConsensusProvider csProvider = getConsensusProvider(provider); - ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props, - Utils.loadParticipantNodes()); - - DBSetting dbsetting0; - DBSetting dbsetting1; - DBSetting dbsetting2; - DBSetting dbsetting3; - if (dbType == DBType.REDIS) { - dbsetting0 = DBSetting.createRedisDBSetting("redis://127.0.0.1:6079"); - dbsetting1 = DBSetting.createRedisDBSetting("redis://127.0.0.1:6179"); - dbsetting2 = DBSetting.createRedisDBSetting("redis://127.0.0.1:6279"); - dbsetting3 = DBSetting.createRedisDBSetting("redis://127.0.0.1:6379"); - - cleanRedisDB(dbsetting0); - cleanRedisDB(dbsetting1); - cleanRedisDB(dbsetting2); - cleanRedisDB(dbsetting3); - } else if (dbType == DBType.ROCKSDB) { - String currDir = FileUtils.getCurrentDir() + File.separator + "rocks.db"; - - String dbDir0 = new File(currDir, "rocksdb0.db").getAbsolutePath(); - String dbDir1 = new File(currDir, "rocksdb1.db").getAbsolutePath(); - String dbDir2 = new File(currDir, "rocksdb2.db").getAbsolutePath(); - String dbDir3 = new File(currDir, "rocksdb3.db").getAbsolutePath(); - - // clean db first; - FileUtils.deleteFile(dbDir0); - FileUtils.deleteFile(dbDir1); - FileUtils.deleteFile(dbDir2); - FileUtils.deleteFile(dbDir3); - - dbsetting0 = DBSetting.createRocksDBSetting("rocksdb://" + dbDir0); - dbsetting1 = DBSetting.createRocksDBSetting("rocksdb://" + dbDir1); - dbsetting2 = DBSetting.createRocksDBSetting("rocksdb://" + dbDir2); - dbsetting3 = DBSetting.createRocksDBSetting("rocksdb://" + dbDir3); - } else { - dbsetting0 = DBSetting.createMemoryDBSetting("memory://local/0"); - dbsetting1 = DBSetting.createMemoryDBSetting("memory://local/1"); - dbsetting2 = DBSetting.createMemoryDBSetting("memory://local/2"); - dbsetting3 = DBSetting.createMemoryDBSetting("memory://local/3"); - } - - NodeContext node0 = new NodeContext(initSetting.getConsensusParticipant(0).getInitializerAddress(), - serviceRegisterMap, dbsetting0.connectionFactory); - NodeContext node1 = new NodeContext(initSetting.getConsensusParticipant(1).getInitializerAddress(), - serviceRegisterMap, dbsetting1.connectionFactory); - NodeContext node2 = new NodeContext(initSetting.getConsensusParticipant(2).getInitializerAddress(), - serviceRegisterMap, dbsetting2.connectionFactory); - NodeContext node3 = new NodeContext(initSetting.getConsensusParticipant(3).getInitializerAddress(), - serviceRegisterMap, dbsetting3.connectionFactory); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[0], Utils.PASSWORD); - AsyncCallback callback0 = node0.startInit(0, privkey0, initSetting, csProps, csProvider, - dbsetting0.connectionConfig, consolePrompter, !optimized, hashAlg); - - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[1], Utils.PASSWORD); - AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, csProps, csProvider, - dbsetting1.connectionConfig, consolePrompter, !optimized, hashAlg); - - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[2], Utils.PASSWORD); - AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, csProps, csProvider, - dbsetting2.connectionConfig, consolePrompter, !optimized, hashAlg); - - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[3], Utils.PASSWORD); - AsyncCallback callback3 = node3.startInit(3, privkey3, initSetting, csProps, csProvider, - dbsetting3.connectionConfig, consolePrompter, !optimized, hashAlg); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - node0.registLedger(ledgerHash0, dbsetting0.connectionConfig); - node1.registLedger(ledgerHash1, dbsetting1.connectionConfig); - node2.registLedger(ledgerHash2, dbsetting2.connectionConfig); - node3.registLedger(ledgerHash3, dbsetting3.connectionConfig); - - return new NodeContext[] { node0, node1, node2, node3 }; - } - - private static void cleanRedisDB(DBSetting dbsetting) { - RedisConnectionFactory redisConnFactory = (RedisConnectionFactory) dbsetting.connectionFactory; - JedisConnection dbConn = (JedisConnection) redisConnFactory.connect(dbsetting.connectionConfig.getUri()); - RedisStorageService redisStorage = (RedisStorageService) dbConn.getStorageService(); - redisStorage.clearDB(); - dbConn.close(); - } - - public static LedgerInitProperties loadInitSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web2.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting(String config) { - ClassPathResource ledgerInitSettingResource = new ClassPathResource(config); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static class DBSetting { - - private DBConnectionConfig connectionConfig; - - private DbConnectionFactory connectionFactory; - - public static DBSetting createMemoryDBSetting(String uri) { - DBSetting setting = new DBSetting(); - setting.connectionConfig = new DBConnectionConfig(uri); - setting.connectionFactory = new MemoryDBConnFactory(); - return setting; - } - - public static DBSetting createRedisDBSetting(String uri) { - DBSetting setting = new DBSetting(); - setting.connectionConfig = new DBConnectionConfig(uri); - setting.connectionFactory = new RedisConnectionFactory(); - return setting; - } - - public static DBSetting createRocksDBSetting(String uri) { - DBSetting setting = new DBSetting(); - setting.connectionConfig = new DBConnectionConfig(uri); - setting.connectionFactory = new RocksDBConnectionFactory(); - return setting; - } - - } - - private static class FreedomLedgerSecurityManager implements LedgerSecurityManager { - - public static final FreedomLedgerSecurityManager INSTANCE = new FreedomLedgerSecurityManager(); - - @Override - public SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes) { - return new FreedomSecurityPolicy(endpoints, nodes); - } - - } - - private static class FreedomSecurityPolicy implements SecurityPolicy { - - private Set endpoints; - private Set nodes; - - public FreedomSecurityPolicy(Set endpoints, Set nodes) { - this.endpoints = endpoints; - this.nodes = nodes; - } - - @Override - public Set getEndpoints() { - return endpoints; - } - - @Override - public Set getNodes() { - return nodes; - } - - @Override - public boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - } - - @Override - public void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - } - - @Override - public void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException { - } - - @Override - public void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) - throws LedgerSecurityException { - } - - @Override - public boolean isEndpointValid(MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public boolean isNodeValid(MultiIDsPolicy midPolicy) { - return true; - } - - @Override - public void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { - } - - @Override - public void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { - } - - } -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/PerformanceTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/PerformanceTest.java deleted file mode 100644 index 97124985..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/PerformanceTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.impl.redis.RedisConnectionFactory; -import com.jd.blockchain.utils.ArgumentSet; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.security.ShaUtils; - -import java.io.IOException; -import java.util.Random; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinTask; -import java.util.concurrent.RecursiveAction; - -public class PerformanceTest { - - public static void main(String[] args) { - try { - boolean testLedger = !ArgumentSet.hasOption(args, "-test=storage"); - if (testLedger) { -// LedgerPerformanceTest.test(new String[]{"-silent", "-usertest", "-o"}); - LedgerPerformanceTest.test(new String[]{"-silent", "-o", "-rocksdb"}); - return; - } - - // GlobalPerformanceTest.test(args); - -// testRedisWriting(args); - } catch (Exception e) { - e.printStackTrace(); - }finally { - ForkJoinPool.commonPool().shutdown(); - } - } - - private static void testRedisWriting(String[] args) { - ConsoleUtils.info("-------------------- start redis test --------------------"); - RedisConnectionFactory redisConnFactory = new RedisConnectionFactory(); - DbConnection conn = redisConnFactory.connect("redis://127.0.0.1:6079"); - KVStorageService storage = conn.getStorageService(); - VersioningKVStorage vs = storage.getVersioningKVStorage(); - - byte[] data = BytesUtils.toBytes("TestDATA"); - - int count = 100000; - if (args.length > 0) { - count = Integer.parseInt(args[0]); - } - if (args.length > 0) { - for (String arg : args) { - if (arg.startsWith("-threshold=")) { - int threshold = Integer.parseInt(arg.substring("-threshold=".length())); - if (threshold > 0) { - RedisWriteTestTask.THRESHOLD = threshold; - } - } - } - } - - Random rand = new Random(); - byte[] nameBytes = new byte[16]; - rand.nextBytes(nameBytes); - String name = Base58Utils.encode(ShaUtils.hash_256(nameBytes)); - rand.nextBytes(nameBytes); - name = name + "/" + Base58Utils.encode(ShaUtils.hash_256(nameBytes)); - rand.nextBytes(nameBytes); - name = name + "/" + Base58Utils.encode(ShaUtils.hash_256(nameBytes)); - - long startTS = System.currentTimeMillis(); - - RedisWriteTestTask task = new RedisWriteTestTask(name, 0, count, data, vs); - ForkJoinPool.commonPool().invoke(task); - - long elapsedTS = System.currentTimeMillis() - startTS; - - double globalTPS = count * 1000.00D / elapsedTS; - - ConsoleUtils.info("\r\n**********************************************"); - ConsoleUtils.info("写入KEY总数:%s; 总体TPS:%.2f;", count, globalTPS); - ConsoleUtils.info("**********************************************\r\n"); - - try { - conn.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static class RedisWriteTestTask extends RecursiveAction { - - private static final long serialVersionUID = -8415596564326385834L; - - public static int THRESHOLD = 800; - - private int offset; - - private int count; - - private byte[] data; - - private String name; - - private VersioningKVStorage vs; - - public RedisWriteTestTask(String name, int offset, int count, byte[] data, VersioningKVStorage vs) { - this.name = name; - this.offset = offset; - this.count = count; - this.data = data; - this.vs = vs; - } - - @Override - protected void compute() { - if (count > THRESHOLD) { - int count1 = count / 2; - RedisWriteTestTask task1 = new RedisWriteTestTask(name, offset, count1, data, vs); - RedisWriteTestTask task2 = new RedisWriteTestTask(name, offset + count1, count - count1, data, vs); - ForkJoinTask.invokeAll(task1, task2); - } else { - for (int i = 0; i < count; i++) { - String key = String.format("[%s][%s]-TEST-KEY-%s", name, offset, i); - vs.set(Bytes.fromString(key), data, -1); - } - } - } - - } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/TransactionCommitter.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/TransactionCommitter.java deleted file mode 100644 index 5f66263d..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/TransactionCommitter.java +++ /dev/null @@ -1,46 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; - -import com.jd.blockchain.ledger.PreparedTransaction; -import com.jd.blockchain.utils.ConsoleUtils; - -public class TransactionCommitter { - - private PreparedTransaction[] ptxs; - private int startIndex; - private int count; - - public TransactionCommitter(PreparedTransaction[] ptxs, int startIndex, int count) { - this.ptxs = ptxs; - this.startIndex = startIndex; - this.count = count; - } - - public void start(CyclicBarrier barrier, CountDownLatch latch) { - Thread thrd = new Thread(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - } catch (Exception e) { - System.out.println(" Barrier await error! --" + e.getMessage()); - e.printStackTrace(); - } - ConsoleUtils.info("Start committing... [%s]", startIndex); - try { - for (int i = 0; i < count; i++) { - ptxs[startIndex + i].commit(); - } - } catch (Exception e) { - System.out.println("Error occured on committing! --" + e.getMessage()); - e.printStackTrace(); - } - latch.countDown(); - } - }); - thrd.start(); - } - -} diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java deleted file mode 100644 index d1e9409c..00000000 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java +++ /dev/null @@ -1,294 +0,0 @@ -package test.com.jd.blockchain.intgr.perf; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.ledger.ParticipantNodeState; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerConfiguration; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.InitConsensusServiceFactory; -import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class Utils { - - public static final String PASSWORD = "abc"; - - public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; - - public static final String[] PRIV_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private Map serviceRegisterMap = new ConcurrentHashMap<>(); - - public static LedgerInitProperties loadInitSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web2.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("bftsmart.config"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static ParticipantNode[] loadParticipantNodes() { - ParticipantNode[] participantNodes = new ParticipantNode[PUB_KEYS.length]; - for (int i = 0; i < PUB_KEYS.length; i++) { - participantNodes[i] = new PartNode(i, KeyGenUtils.decodePubKey(PUB_KEYS[i]), ParticipantNodeState.ACTIVED); - } - return participantNodes; - } - - public static class NodeContext { - - private LedgerManager ledgerManager = new LedgerManager(); - - private DbConnectionFactory dbConnFactory; - - private InitConsensusServiceFactory initCsServiceFactory; - - private LedgerInitProcess initProcess; - - private AsymmetricKeypair partiKey; - - public AsymmetricKeypair getPartiKey() { - return partiKey; - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - } - - public DbConnectionFactory getStorageDb() { - return dbConnFactory; - } - - public NodeContext(NetworkAddress address, Map serviceRegisterMap, - DbConnectionFactory dbConnFactory) { - this.dbConnFactory = dbConnFactory; - this.initCsServiceFactory = new MultiThreadInterInvokerFactory(serviceRegisterMap); - LedgerInitializeWebController initController = new LedgerInitializeWebController(dbConnFactory, - initCsServiceFactory); - serviceRegisterMap.put(address, initController); - this.initProcess = initController; - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter) { - - partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter); - } - }; - - return invoker.start(); - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, - ConsensusSettings csProps, ConsensusProvider consensusProvider, DBConnectionConfig dbConnConfig, - Prompter prompter, boolean autoVerifyHash) { - CryptoAlgorithm algorithm = Crypto.getAlgorithm("SHA256"); - return startInit(currentId, privKey, setting, csProps, consensusProvider, dbConnConfig, prompter, - autoVerifyHash, algorithm); - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, - ConsensusSettings csProps, ConsensusProvider consensusProvider, DBConnectionConfig dbConnConfig, - Prompter prompter, boolean autoVerifyHash, CryptoAlgorithm hashAlg) { - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig cryptoSetting = new CryptoConfig(); - cryptoSetting.setSupportedProviders(supportedProviders); - cryptoSetting.setSupportedProviders(supportedProviders); - cryptoSetting.setAutoVerifyHash(autoVerifyHash); - cryptoSetting.setHashAlgorithm(hashAlg); - - return startInit(currentId, privKey, setting, csProps, consensusProvider, dbConnConfig, prompter, - cryptoSetting); - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, - ConsensusSettings csProps, ConsensusProvider consensusProvider, DBConnectionConfig dbConnConfig, - Prompter prompter, CryptoSetting cryptoSetting) { - - LedgerInitConfiguration ledgerInitConfig = LedgerInitConfiguration.create(setting); - ledgerInitConfig.getLedgerSettings().setCryptoSetting(cryptoSetting); - - partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter); - } - }; - - return invoker.start(); - } - - public LedgerQuery registLedger(HashDigest ledgerHash, DBConnectionConfig dbConnConf) { - return ledgerManager.register(ledgerHash, dbConnFactory.connect(dbConnConf.getUri()).getStorageService()); - } - } - - private static class MultiThreadInterInvokerFactory implements InitConsensusServiceFactory { - - private Map nodeConsesusServices; - - public MultiThreadInterInvokerFactory(Map nodeConsesusServices) { - this.nodeConsesusServices = nodeConsesusServices; - } - - @Override - public LedgerInitConsensusService connect(NetworkAddress endpointAddress) { - return new InitConsensusServiceProxy(nodeConsesusServices.get(endpointAddress)); - } - - } - - private static class InitConsensusServiceProxy implements LedgerInitConsensusService { - - private LedgerInitConsensusService initCsService; - - public InitConsensusServiceProxy(LedgerInitConsensusService initCsService) { - this.initCsService = initCsService; - } - - @Override - public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected LedgerInitProposal invoke() { - return initCsService.requestPermission(requesterId, signature); - } - }; - return invoker.startAndWait(); - } - - @Override - public LedgerInitDecision synchronizeDecision(LedgerInitDecision initDecision) { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected LedgerInitDecision invoke() { - return initCsService.synchronizeDecision(initDecision); - } - }; - return invoker.startAndWait(); - } - - } - - private static class PartNode implements ParticipantNode { - - private int id; - - private Bytes address; - - private String name; - - private PubKey pubKey; - - private ParticipantNodeState participantNodeState; - - public PartNode(int id, PubKey pubKey, ParticipantNodeState participantNodeState) { - this(id, id + "", pubKey, participantNodeState); - } - - public PartNode(int id, String name, PubKey pubKey, ParticipantNodeState participantNodeState) { - this.id = id; - this.name = name; - this.pubKey = pubKey; - this.address = AddressEncoding.generateAddress(pubKey); - this.participantNodeState = participantNodeState; - } - - @Override - public int getId() { - return id; - } - - @Override - public Bytes getAddress() { - return address; - } - - @Override - public String getName() { - return name; - } - - @Override - public PubKey getPubKey() { - return pubKey; - } - - @Override - public ParticipantNodeState getParticipantNodeState() { - return participantNodeState; - } - - } - -} diff --git a/source/test/test-integration/src/main/resources/Performance.contract b/source/test/test-integration/src/main/resources/Performance.contract deleted file mode 100644 index ff4bd63d..00000000 Binary files a/source/test/test-integration/src/main/resources/Performance.contract and /dev/null differ diff --git a/source/test/test-integration/src/main/resources/bftsmart.config b/source/test/test-integration/src/main/resources/bftsmart.config deleted file mode 100644 index 80ed0f6a..00000000 --- a/source/test/test-integration/src/main/resources/bftsmart.config +++ /dev/null @@ -1,155 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Participant0 ###### -############################################ - -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=8910 -system.server.0.network.secure=false - -############################################ -###### #Consensus Participant1 ###### -############################################ - -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=8920 -system.server.1.network.secure=false - -############################################ -###### #Consensus Participant2 ###### -############################################ - -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=8930 -system.server.2.network.secure=false - -############################################ -###### Consensus Participant3 ###### -############################################ - -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=8940 -system.server.3.network.secure=false - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -#system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 5000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -#system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage \ No newline at end of file diff --git a/source/test/test-integration/src/main/resources/example1.jar b/source/test/test-integration/src/main/resources/example1.jar deleted file mode 100644 index 7b76b919..00000000 Binary files a/source/test/test-integration/src/main/resources/example1.jar and /dev/null differ diff --git a/source/test/test-integration/src/main/resources/ledger_init_test.init b/source/test/test-integration/src/main/resources/ledger_init_test.init deleted file mode 100644 index b936de8c..00000000 --- a/source/test/test-integration/src/main/resources/ledger_init_test.init +++ /dev/null @@ -1,85 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=endPsK36koyFr1D245Sa9j83vt6pZUdFBJoJRB3xAsWM6cwhRbna -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=false -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=endPsK36sC5JdPCDPDAXUwZtS3sxEmqEhFcC4whayAsTTh8Z6eoZ -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=endPsK36jEG281HMHeh6oSqzqLkT95DTnCM6REDURjdb2c67uR3R -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=endPsK36nse1dck4uF19zPvAMijCV336Y3zWdgb4rQG8QoRj5ktR -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/main/resources/ledger_init_test_integration.init b/source/test/test-integration/src/main/resources/ledger_init_test_integration.init deleted file mode 100644 index f80de5eb..00000000 --- a/source/test/test-integration/src/main/resources/ledger_init_test_integration.init +++ /dev/null @@ -1,85 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PapsDoW185c3kfK6p8s6SwiJAdEUzgnfeuUox12nxgzXu -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=true -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=true - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7Ph1SYLQt9uqVEqiuvNXjxCdGvEdN6otJsg5rbr7Aze7kf -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PezptA6dNBkotPjmKEbTkY8fmusLBnfj8Cf7eFwhWDwKr -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=true - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PerZYfRzEB61SAN9tFK4yHm9wUSRtkLSSGXHkQRbB5PkS -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/main/resources/ledger_init_test_web2.init b/source/test/test-integration/src/main/resources/ledger_init_test_web2.init deleted file mode 100644 index 5be0e69d..00000000 --- a/source/test/test-integration/src/main/resources/ledger_init_test_web2.init +++ /dev/null @@ -1,74 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name==myledger - -#声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=9800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=9810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=9820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=9830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/main/resources/mq.config b/source/test/test-integration/src/main/resources/mq.config deleted file mode 100644 index 730b7acc..00000000 --- a/source/test/test-integration/src/main/resources/mq.config +++ /dev/null @@ -1,12 +0,0 @@ -system.msg.queue.server=nats://127.0.0.1:4222 -system.msg.queue.topic.tx=tx-topic -system.msg.queue.topic.bl=bl-topic -system.msg.queue.topic.msg=msg-topic -system.msg.queue.block.txsize=1000 -system.msg.queue.block.maxdelay=2000 - -system.servers.num=4 -system.server.0.pubkey=endPsK36koyFr1D245Sa9j83vt6pZUdFBJoJRB3xAsWM6cwhRbna -system.server.1.pubkey=endPsK36sC5JdPCDPDAXUwZtS3sxEmqEhFcC4whayAsTTh8Z6eoZ -system.server.2.pubkey=endPsK36jEG281HMHeh6oSqzqLkT95DTnCM6REDURjdb2c67uR3R -system.server.3.pubkey=endPsK36nse1dck4uF19zPvAMijCV336Y3zWdgb4rQG8QoRj5ktR \ No newline at end of file diff --git a/source/test/test-integration/src/main/resources/system.config b/source/test/test-integration/src/main/resources/system.config deleted file mode 100644 index 407d70ca..00000000 --- a/source/test/test-integration/src/main/resources/system.config +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 4000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 10000 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 1 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 4000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = false - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java deleted file mode 100644 index a109e456..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java +++ /dev/null @@ -1,743 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.intgr.perf.IntegrationBase - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/25 下午3:40 - * Description: - */ -package test.com.jd.blockchain.intgr; - -import static com.jd.blockchain.transaction.ContractReturnValue.decode; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicLong; - -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.*; -import org.apache.commons.io.FileUtils; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.contract.ReadContract; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.transaction.GenericValueHolder; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * - * @author shaozhuguang - * @create 2018/12/25 - * @since 1.0.0 - */ - -public class IntegrationBase { - public static String KEY_TOTAL = "total"; - - static { - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - } - - public static final String PASSWORD = "abc"; - - public static final String[] PUB_KEYS = { - "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; - - public static final String[] PRIV_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - - public static final AtomicLong validLong = new AtomicLong(); - - public static KeyPairResponse testSDK_RegisterUser(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService) { - // 注册用户,并验证最终写入; - BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.users().register(user.getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - KeyPairResponse keyPairResponse = new KeyPairResponse(); - keyPairResponse.keyPair = user; - keyPairResponse.txResp = txResp; - keyPairResponse.txHash = transactionHash; - return keyPairResponse; - } - - public static KeyPairResponse testSDK_BlockFullRollBack(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService) { - - BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); - - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - - //Register user account - txTpl.users().register(user.getIdentity()); - - PreparedTransaction prepTx = txTpl.prepare(); - - HashDigest transactionHash = prepTx.getHash(); - - prepTx.sign(adminKey); - - //Commit transaction - TransactionResponse transactionResponse = prepTx.commit(); - - //The whole block will rollback, due to storage error - assertEquals(transactionResponse.getExecutionState().CODE, TransactionState.IGNORED_BY_BLOCK_FULL_ROLLBACK.CODE); - - KeyPairResponse keyPairResponse = new KeyPairResponse(); - keyPairResponse.keyPair = user; - keyPairResponse.txResp = transactionResponse; - keyPairResponse.txHash = transactionHash; - return keyPairResponse; - } - - - public static KeyPairResponse testSDK_RegisterDataAccount(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService) { - // 注册数据账户,并验证最终写入; - BlockchainKeypair dataAccount = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.dataAccounts().register(dataAccount.getIdentity()); -// txTpl.dataAccount(dataAccount.getAddress()).setInt64("total", 200, -1); -// txTpl.dataAccount(dataAccount.getAddress()).set("param1", "v", -1); -// txTpl.dataAccount(dataAccount.getAddress()).set("param2", 200, -1); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - KeyPairResponse keyPairResponse = new KeyPairResponse(); - keyPairResponse.keyPair = dataAccount; - keyPairResponse.txResp = txResp; - keyPairResponse.txHash = transactionHash; - return keyPairResponse; - } - - public static KvResponse testSDK_InsertData(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, Bytes dataAccount) { - - // 在本地定义注册账号的 TX; - TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash); - - // -------------------------------------- - // 将商品信息写入到指定的账户中; - // 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引; - String dataKey = "jingdong" + System.currentTimeMillis() + new Random().nextInt(100000); - String dataVal = "www.jd.com"; - - txTemp.dataAccount(dataAccount).setText(dataKey, dataVal, -1); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - - HashDigest transactionHash = prepTx.getHash(); - - // 使用私钥进行签名; - prepTx.sign(adminKey); - - // 提交交易; - TransactionResponse txResp = prepTx.commit(); - - KvResponse kvResponse = new KvResponse(); - kvResponse.ledgerHash = ledgerHash; - kvResponse.dataAccount = dataAccount; - kvResponse.txResp = txResp; - kvResponse.txHash = transactionHash; - kvResponse.key = dataKey; - kvResponse.value = dataVal; - return kvResponse; - } - - public static KeyPairResponse testSDK_RegisterParticipant(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService) { - // 注册参与方,并验证最终写入; - BlockchainKeypair participant = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - - txTpl.participants().register("peer4", new BlockchainIdentityData(participant.getPubKey()), new NetworkAddress("127.0.0.1", 20000)); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - KeyPairResponse keyPairResponse = new KeyPairResponse(); - keyPairResponse.keyPair = participant; - keyPairResponse.txResp = txResp; - keyPairResponse.txHash = transactionHash; - return keyPairResponse; - } - - public static KeyPairResponse testSDK_UpdateParticipantState(AsymmetricKeypair adminKey, BlockchainKeypair participantKeyPair, HashDigest ledgerHash, - BlockchainService blockchainService) { - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - - ParticipantInfoData participantInfoData = new ParticipantInfoData("peer4", participantKeyPair.getPubKey(), new NetworkAddress("127.0.0.1", 20000)); - - txTpl.states().update(new BlockchainIdentityData(participantInfoData.getPubKey()), participantInfoData.getNetworkAddress(), ParticipantNodeState.ACTIVED); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - KeyPairResponse keyPairResponse = new KeyPairResponse(); - keyPairResponse.keyPair = participantKeyPair; - keyPairResponse.txResp = txResp; - keyPairResponse.txHash = transactionHash; - return keyPairResponse; - } - - public static void validKeyPair(IntegrationBase.KeyPairResponse keyPairResponse, LedgerQuery ledgerRepository, - KeyPairType keyPairType) { - TransactionResponse txResp = keyPairResponse.txResp; - HashDigest transactionHash = keyPairResponse.txHash; - BlockchainKeypair keyPair = keyPairResponse.keyPair; - long index = validLong.incrementAndGet(); - System.out.printf("validKeyPair start %s \r\n", index); - ledgerRepository.retrieveLatestBlock(); - - assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS); - assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight()); - assertEquals(txResp.getContentHash(), transactionHash); - assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash()); - if (keyPairType == KeyPairType.USER) { - assertTrue(ledgerRepository.getUserAccountSet(ledgerRepository.getLatestBlock()) - .contains(keyPair.getAddress())); - } - - if (keyPairType == KeyPairType.DATAACCOUNT) { - assertNotNull(ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock()) - .getAccount(keyPair.getAddress())); - } - System.out.printf("validKeyPair end %s \r\n", index); - } - - public static void validKeyPair(IntegrationBase.KeyPairResponse keyPairResponse, LedgerQuery ledgerRepository, - KeyPairType keyPairType, CountDownLatch countDownLatch) { - - TransactionResponse txResp = keyPairResponse.txResp; - HashDigest transactionHash = keyPairResponse.txHash; - BlockchainKeypair keyPair = keyPairResponse.keyPair; - ledgerRepository.retrieveLatestBlock(); - - assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS); - assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight()); - assertEquals(txResp.getContentHash(), transactionHash); - assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash()); - if (keyPairType == KeyPairType.USER) { - assertTrue(ledgerRepository.getUserAccountSet(ledgerRepository.getLatestBlock()) - .contains(keyPair.getAddress())); - } - - if (keyPairType == KeyPairType.DATAACCOUNT) { - assertNotNull(ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock()) - .getAccount(keyPair.getAddress())); - } - countDownLatch.countDown(); - } - - public static void validKvWrite(IntegrationBase.KvResponse kvResponse, LedgerQuery ledgerRepository, - BlockchainService blockchainService) { - // 先验证应答 - TransactionResponse txResp = kvResponse.getTxResp(); - HashDigest transactionHash = kvResponse.getTxHash(); - HashDigest ledgerHash = kvResponse.getLedgerHash(); - String daAddress = kvResponse.getDataAccount().toBase58(); - String dataKey = kvResponse.getKey(); - String dataVal = kvResponse.getValue(); - - ledgerRepository.retrieveLatestBlock(); - - assertEquals(TransactionState.SUCCESS, txResp.getExecutionState()); - assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight()); - assertEquals(txResp.getContentHash(), transactionHash); - assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash()); - - TypedKVEntry[] kvDataEntries = blockchainService.getDataEntries(ledgerHash, daAddress, dataKey); - for (TypedKVEntry kvDataEntry : kvDataEntries) { - assertEquals(dataKey, kvDataEntry.getKey()); - String valHexText = (String) kvDataEntry.getValue(); - assertEquals(dataVal, valHexText); - } - } - - public static LedgerQuery[] buildLedgers(LedgerBindingConfig[] bindingConfigs, - DbConnectionFactory[] dbConnectionFactories) { - int[] ids = { 0, 1, 2, 3 }; - LedgerQuery[] ledgers = new LedgerQuery[ids.length]; - LedgerManager[] ledgerManagers = new LedgerManager[ids.length]; - for (int i = 0; i < ids.length; i++) { - ledgerManagers[i] = new LedgerManager(); - HashDigest ledgerHash = bindingConfigs[0].getLedgerHashs()[0]; - DbConnection conn = dbConnectionFactories[i] - .connect(bindingConfigs[i].getLedger(ledgerHash).getDbConnection().getUri()); - ledgers[i] = ledgerManagers[i].register(ledgerHash, conn.getStorageService()); - } - return ledgers; - } - - public static void testConsistencyAmongNodes(LedgerQuery[] ledgers) { - LedgerQuery ledger0 = ledgers[0]; - LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock(); - for (int i = 1; i < ledgers.length; i++) { - LedgerQuery otherLedger = ledgers[i]; - LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock(); - assertEquals(ledger0.getHash(), otherLedger.getHash()); - assertEquals(ledger0.getLatestBlockHeight(), otherLedger.getLatestBlockHeight()); - assertEquals(ledger0.getLatestBlockHash(), otherLedger.getLatestBlockHash()); - - assertEquals(latestBlock0.getHeight(), otherLatestBlock.getHeight()); - assertEquals(latestBlock0.getHash(), otherLatestBlock.getHash()); - assertEquals(latestBlock0.getAdminAccountHash(), otherLatestBlock.getAdminAccountHash()); - assertEquals(latestBlock0.getTransactionSetHash(), otherLatestBlock.getTransactionSetHash()); - assertEquals(latestBlock0.getUserAccountSetHash(), otherLatestBlock.getUserAccountSetHash()); - assertEquals(latestBlock0.getDataAccountSetHash(), otherLatestBlock.getDataAccountSetHash()); - assertEquals(latestBlock0.getContractAccountSetHash(), otherLatestBlock.getContractAccountSetHash()); - assertEquals(latestBlock0.getPreviousHash(), otherLatestBlock.getPreviousHash()); - } - } - - public static PeerTestRunner[] peerNodeStart(HashDigest ledgerHash, String dbType) { - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 12000); - LedgerBindingConfig bindingConfig0 = loadBindingConfig(0, ledgerHash, dbType); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, bindingConfig0); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 12010); - LedgerBindingConfig bindingConfig1 = loadBindingConfig(1, ledgerHash, dbType); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, bindingConfig1); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 12020); - LedgerBindingConfig bindingConfig2 = loadBindingConfig(2, ledgerHash, dbType); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, bindingConfig2); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 12030); - LedgerBindingConfig bindingConfig3 = loadBindingConfig(3, ledgerHash, dbType); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, bindingConfig3); - - ThreadInvoker.AsyncCallback peerStarting0 = peer0.start(); - ThreadInvoker.AsyncCallback peerStarting1 = peer1.start(); - ThreadInvoker.AsyncCallback peerStarting2 = peer2.start(); - ThreadInvoker.AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - return new PeerTestRunner[] { peer0, peer1, peer2, peer3 }; - } - - public static LedgerBindingConfig loadBindingConfig(int id, HashDigest ledgerHash, String dbType) { - LedgerBindingConfig ledgerBindingConfig; - String newLedger = ledgerHash.toBase58(); - String resourceClassPath = "ledger-binding-" + dbType + "-" + id + ".conf"; - String ledgerBindingUrl = IntegrationBase.class.getResource("/") + resourceClassPath; - - try { - URL url = new URL(ledgerBindingUrl); - File ledgerBindingConf = new File(url.getPath()); - System.out.printf("URL-ledgerBindingConf = %s \r\n", url.getPath()); - if (ledgerBindingConf.exists()) { - List readLines = FileUtils.readLines(ledgerBindingConf); - - List writeLines = new ArrayList<>(); - - if (readLines != null && !readLines.isEmpty()) { - String oldLedgerLine = null; - for (String readLine : readLines) { - if (readLine.startsWith("ledger")) { - oldLedgerLine = readLine; - break; - } - } - String[] oldLedgerArray = oldLedgerLine.split("="); - - String oldLedger = oldLedgerArray[1]; - if (!oldLedger.equalsIgnoreCase(newLedger)) { - for (String readLine : readLines) { - String newLine = readLine.replace(oldLedger, newLedger); - if (dbType.equalsIgnoreCase("rocksdb")) { - if (newLine.contains("db.uri")) { - String[] propArray = newLine.split("="); - String dbKey = propArray[0]; - String dbValue = LedgerInitConsensusConfig.rocksdbConnectionStrings[id]; - newLine = dbKey + "=" + dbValue; - } - } - writeLines.add(newLine); - } - } else if (dbType.equalsIgnoreCase("rocksdb")) { - for (String readLine : readLines) { - String newLine = readLine; - if (readLine.contains("db.uri")) { - String[] propArray = readLine.split("="); - String dbKey = propArray[0]; - String dbValue = LedgerInitConsensusConfig.rocksdbConnectionStrings[id]; - newLine = dbKey + "=" + dbValue; - } - writeLines.add(newLine); - } - } - if (!writeLines.isEmpty()) { - FileUtils.writeLines(ledgerBindingConf, writeLines); - } - } - } - } catch (Exception e) { - - } - - ClassPathResource res = new ClassPathResource(resourceClassPath); - try (InputStream in = res.getInputStream()) { - ledgerBindingConfig = LedgerBindingConfig.resolve(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - return ledgerBindingConfig; - } - - public static class KeyPairResponse { - HashDigest txHash; - - BlockchainKeypair keyPair; - - TransactionResponse txResp; - - public BlockchainKeypair getKeyPair() { - return keyPair; - } - - public TransactionResponse getTxResp() { - return txResp; - } - - public HashDigest getTxHash() { - return txHash; - } - } - - public static class KvResponse { - - Bytes dataAccount; - - HashDigest ledgerHash; - - HashDigest txHash; - - TransactionResponse txResp; - - String key; - - String value; - - public HashDigest getTxHash() { - return txHash; - } - - public TransactionResponse getTxResp() { - return txResp; - } - - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - - public HashDigest getLedgerHash() { - return ledgerHash; - } - - public Bytes getDataAccount() { - return dataAccount; - } - } - - public enum KeyPairType { - USER, DATAACCOUNT - } - - // 合约测试使用的初始化数据; - static BlockchainKeypair contractDataKey = BlockchainKeyGenerator.getInstance().generate(); - static BlockchainKeypair contractDeployKey = BlockchainKeyGenerator.getInstance().generate(); - // 保存资产总数的键; - // 第二个参数; - private static String contractZipName = "contract-read.jar"; - static HashDigest txContentHash; - - public static LedgerBlock testSDK_Contract(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, LedgerQuery ledgerRepository) { - KeyPairResponse keyPairResponse = testSDK_RegisterDataAccount(adminKey,ledgerHash,blockchainService); - - System.out.println("adminKey=" + AddressEncoding.generateAddress(adminKey.getPubKey())); - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - System.out.println("userKey=" + userKey.getAddress()); - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.users().register(userKey.getIdentity()); - - // 定义交易; - byte[] contractCode = getChainCodeBytes(); - txTpl.contracts().deploy(contractDeployKey.getIdentity(), contractCode); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - assertTrue(txResp.isSuccess()); - - // 验证结果; - assertEquals(ptx.getHash(),txResp.getContentHash()); - - LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight()); - byte[] contractCodeInDb = ledgerRepository.getContractAccountSet(block) - .getAccount(contractDeployKey.getAddress()).getChainCode(); - assertArrayEquals(contractCode, contractCodeInDb); - - // execute the contract; -// testContractExe(adminKey, ledgerHash, keyPairResponse.keyPair, blockchainService, ledgerRepository); -// testContractExe1(adminKey, ledgerHash, keyPairResponse.keyPair, blockchainService, ledgerRepository); - testExeReadContract(adminKey, ledgerHash, blockchainService); - return block; - } - -// private static void testContractExe(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainKeypair dataKey, -// BlockchainService blockchainService, LedgerRepository ledgerRepository) { -// LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash); -// LedgerBlock previousBlock = blockchainService.getBlock(ledgerHash, ledgerInfo.getLatestBlockHeight() - 1); -// -// // 定义交易; -// TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); -// -// Byte byteObj = Byte.parseByte("123"); -//// txTpl.contract(contractDeployKey.getAddress(),AssetContract2.class).issue(byteObj, -//// contractDeployKey.getAddress().toBase58(),321123); -// txTpl.contract(contractDeployKey.getAddress(),AssetContract2.class).issue(byteObj, -// dataKey.getAddress().toBase58(),Bytes.fromString("123321")); -// -// // 签名; -// PreparedTransaction ptx = txTpl.prepare(); -// ptx.sign(adminKey); -// -// // 提交并等待共识返回; -// TransactionResponse txResp = ptx.commit(); -// -// // 验证结果; -// Assert.assertTrue(txResp.isSuccess()); -// assertEquals(ptx.getHash(),txResp.getContentHash()); -// LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight()); -// KVDataEntry[] kvDataEntries = ledgerRepository.getDataAccountSet(block).getDataAccount(dataKey.getAddress()).getDataEntries(0,1); -// assertEquals("100",kvDataEntries[0].getValue().toString()); -// } - -// private static void testContractExe1(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainKeypair dataKey, -// BlockchainService blockchainService,LedgerRepository ledgerRepository) { -// LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash); -// LedgerBlock previousBlock = blockchainService.getBlock(ledgerHash, ledgerInfo.getLatestBlockHeight() - 1); -// -// // 定义交易; -// TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); -// -// AssetContract2 assetContract = txTpl.contract(contractDeployKey.getAddress(), AssetContract2.class); -// ContractBizContent contractBizContent = () -> new String[]{"param1","param2"}; -// assetContract.issue(contractBizContent,dataKey.getAddress().toBase58(),123456); -// -// // 签名; -// PreparedTransaction ptx = txTpl.prepare(); -// ptx.sign(adminKey); -// -// // 提交并等待共识返回; -// TransactionResponse txResp = ptx.commit(); -// -// // 验证结果; -// Assert.assertTrue(txResp.isSuccess()); -// assertEquals(ptx.getHash(),txResp.getContentHash()); -// LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight()); -// KVDataEntry[] kvDataEntries = ledgerRepository.getDataAccountSet(block).getDataAccount(dataKey.getAddress()).getDataEntries(1,2); -// assertEquals("value1",kvDataEntries[0].getValue().toString()); -// assertEquals(888L,kvDataEntries[1].getValue()); -// } - - private static void testExeReadContract(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainService blockchainService) { - - // 首先注册一个数据账户 - BlockchainKeypair newDataAccount = BlockchainKeyGenerator.getInstance().generate(); - - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.dataAccounts().register(newDataAccount.getIdentity()); - - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - ptx.commit(); - - // 再提交一个KV写入 - String key1 = "JingDong", value1 = "www.jd.com"; - String key2 = "JD", value2 = "JingDong"; - String key3 = "Test", value3 = "OK"; - - TransactionTemplate txKv = blockchainService.newTransaction(ledgerHash); - txKv.dataAccount(newDataAccount.getAddress()) - .setText(key1, value1, -1) - .setBytes(key2, Bytes.fromString(value2), -1) - .setBytes(key3, Bytes.fromString(value3).toBytes(), -1); - PreparedTransaction kvPtx = txKv.prepare(); - kvPtx.sign(adminKey); - - // 提交并等待共识返回; - kvPtx.commit(); - - // 下面才是执行Read交易 - // 定义交易; - TransactionTemplate txContract = blockchainService.newTransaction(ledgerHash); - - ReadContract readContract1 = txContract.contract(contractDeployKey.getAddress(), ReadContract.class); - - GenericValueHolder result1 = decode(readContract1.read(newDataAccount.getAddress().toBase58(), key1)); - - ReadContract readContract2 = txContract.contract(contractDeployKey.getAddress(), ReadContract.class); - - readContract2.read(newDataAccount.getAddress().toBase58(), key2); - - ReadContract readContract3 = txContract.contract(contractDeployKey.getAddress(), ReadContract.class); - - GenericValueHolder result3 = decode(readContract3.readVersion(newDataAccount.getAddress().toBase58(), key2)); - - // 签名; - PreparedTransaction contractPtx = txContract.prepare(); - contractPtx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse readTxResp = contractPtx.commit(); - - OperationResult[] operationResults = readTxResp.getOperationResults(); - - // 通过EventResult获取结果 - System.out.printf("readContract1.result = %s \r\n", result1.get()); - System.out.printf("readContract3.result = %s \r\n", result3.get()); - - for (int i = 0; i < operationResults.length; i++) { - OperationResult opResult = operationResults[i]; - System.out.printf("Operation[%s].result = %s \r\n", opResult.getIndex(), BytesValueEncoding.decode(opResult.getResult())); - } - - - -// // 打印结果 -// for (OperationResult or : operationResults) { -// System.out.printf("操作[%s].Result = %s \r\n", or.getIndex(), ContractSerializeUtils.resolve(or.getResult())); -// } -// -// // 验证结果 -// assertNotNull(contractReturn); -// assertEquals(contractReturn.length, 3); -// -// String returnVal1 = contractReturn[0]; -// assertEquals(value1, returnVal1); -// -// String returnVal2 = contractReturn[1]; -// assertEquals(value2, returnVal2); -// -// String returnVal3 = contractReturn[2]; -// assertEquals("0", returnVal3); - } - - /** - * 根据合约构建字节数组; - * - * @return - */ - private static byte[] getChainCodeBytes() { - // 构建合约的字节数组; - byte[] contractCode = null; - File file = null; - InputStream input = null; - try { - ClassPathResource contractPath = new ClassPathResource(contractZipName); - file = new File(contractPath.getURI()); - assertTrue("contract zip file is not exist.", file.exists() == true); - input = new FileInputStream(file); - // 这种暴力的读取压缩包,在class解析时有问题,所有需要改进; - contractCode = new byte[input.available()]; - input.read(contractCode); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (input != null) { - input.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return contractCode; - } -} \ No newline at end of file diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java deleted file mode 100644 index 4d9cf522..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java +++ /dev/null @@ -1,251 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.IntegratedContext.Node; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest.NodeWebContext; -import test.com.jd.blockchain.intgr.perf.Utils; - -public class IntegrationBaseTest { - - LedgerInitConsensusConfig.ConsensusConfig bftsmartConfig = LedgerInitConsensusConfig.bftsmartConfig; - - public IntegratedContext context = initLedgers(bftsmartConfig.getConfigPath(), bftsmartConfig.getProvider()); - public GatewayTestRunner gateway0; - public GatewayTestRunner gateway1; - - public void startPeer() { - // init ledgers of all nodes ; - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - Node node2 = context.getNode(2); - Node node3 = context.getNode(3); - - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 13200); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, node0.getBindingConfig(), node0.getStorageDB(), null); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 13210); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, node1.getBindingConfig(), node1.getStorageDB(), null); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 13220); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, node2.getBindingConfig(), node2.getStorageDB(), null); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 13230); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, node3.getBindingConfig(), node3.getStorageDB(), null); - - AsyncCallback peerStarting0 = peer0.start(); - AsyncCallback peerStarting1 = peer1.start(); - AsyncCallback peerStarting2 = peer2.start(); - AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - gateway0 = new GatewayTestRunner("127.0.0.1", 13300, gwkey0, peerSrvAddr0); - - KeyPairConfig gwkey1 = new KeyPairConfig(); - gwkey1.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[1]); - gwkey1.setPrivKeyValue(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1]); - gwkey1.setPrivKeyPassword(encodedBase58Pwd); - gateway1 = new GatewayTestRunner("127.0.0.1", 13310, gwkey1, peerSrvAddr1); - - AsyncCallback gwStarting0 = gateway0.start(); - AsyncCallback gwStarting1 = gateway1.start(); - - gwStarting0.waitReturn(); - gwStarting1.waitReturn(); - } - - public void testConsistencyAmongNodes(IntegratedContext context) { - int[] ids = context.getNodeIds(); - Node[] nodes = new Node[ids.length]; - LedgerQuery[] ledgers = new LedgerQuery[ids.length]; - for (int i = 0; i < nodes.length; i++) { - nodes[i] = context.getNode(ids[i]); - HashDigest ledgerHash = nodes[i].getLedgerManager().getLedgerHashs()[0]; - ledgers[i] = nodes[i].getLedgerManager().getLedger(ledgerHash); - } - LedgerQuery ledger0 = ledgers[0]; - LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock(); - for (int i = 1; i < ledgers.length; i++) { - LedgerQuery otherLedger = ledgers[i]; - LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock(); - assertEquals(ledger0.getHash(), otherLedger.getHash()); - assertEquals(ledger0.getLatestBlockHeight(), otherLedger.getLatestBlockHeight()); - assertEquals(ledger0.getLatestBlockHash(), otherLedger.getLatestBlockHash()); - - assertEquals(latestBlock0.getHeight(), otherLatestBlock.getHeight()); - assertEquals(latestBlock0.getHash(), otherLatestBlock.getHash()); - assertEquals(latestBlock0.getAdminAccountHash(), otherLatestBlock.getAdminAccountHash()); - assertEquals(latestBlock0.getTransactionSetHash(), otherLatestBlock.getTransactionSetHash()); - assertEquals(latestBlock0.getUserAccountSetHash(), otherLatestBlock.getUserAccountSetHash()); - assertEquals(latestBlock0.getDataAccountSetHash(), otherLatestBlock.getDataAccountSetHash()); - assertEquals(latestBlock0.getContractAccountSetHash(), otherLatestBlock.getContractAccountSetHash()); - assertEquals(latestBlock0.getPreviousHash(), otherLatestBlock.getPreviousHash()); - } - } - - private IntegratedContext initLedgers(String configPath, String providerName) { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_integration(); - Properties props = LedgerInitializeWeb4SingleStepsTest.loadConsensusSetting(configPath); - ConsensusProvider csProvider = LedgerInitConsensusConfig.getConsensusProvider(providerName); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeWebContext nodeCtx0 = new NodeWebContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeWebContext nodeCtx1 = new NodeWebContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeWebContext nodeCtx2 = new NodeWebContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeWebContext nodeCtx3 = new NodeWebContext(3, initAddr3); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - String encodedPassword = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri(LedgerInitConsensusConfig.memConnectionStrings[0]); - LedgerBindingConfig bindingConfig0 = new LedgerBindingConfig(); - AsyncCallback callback0 = nodeCtx0.startInitCommand(privkey0, encodedPassword, initSetting, testDb0, - consolePrompter, bindingConfig0, quitLatch); - - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri(LedgerInitConsensusConfig.memConnectionStrings[1]); - LedgerBindingConfig bindingConfig1 = new LedgerBindingConfig(); - AsyncCallback callback1 = nodeCtx1.startInitCommand(privkey1, encodedPassword, initSetting, testDb1, - consolePrompter, bindingConfig1, quitLatch); - - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri(LedgerInitConsensusConfig.memConnectionStrings[2]); - LedgerBindingConfig bindingConfig2 = new LedgerBindingConfig(); - AsyncCallback callback2 = nodeCtx2.startInitCommand(privkey2, encodedPassword, initSetting, testDb2, - consolePrompter, bindingConfig2, quitLatch); - - DBConnectionConfig testDb3 = new DBConnectionConfig(); - testDb3.setConnectionUri(LedgerInitConsensusConfig.memConnectionStrings[3]); - LedgerBindingConfig bindingConfig3 = new LedgerBindingConfig(); - AsyncCallback callback3 = nodeCtx3.startInitCommand(privkey3, encodedPassword, initSetting, testDb3, - consolePrompter, bindingConfig3, quitLatch); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - assertNotNull(ledgerHash0); - assertEquals(ledgerHash0, ledgerHash1); - assertEquals(ledgerHash0, ledgerHash2); - assertEquals(ledgerHash0, ledgerHash3); - - LedgerQuery ledger0 = nodeCtx0.registLedger(ledgerHash0); - LedgerQuery ledger1 = nodeCtx1.registLedger(ledgerHash1); - LedgerQuery ledger2 = nodeCtx2.registLedger(ledgerHash2); - LedgerQuery ledger3 = nodeCtx3.registLedger(ledgerHash3); - - assertNotNull(ledger0); - assertNotNull(ledger1); - assertNotNull(ledger2); - assertNotNull(ledger3); - - IntegratedContext context = new IntegratedContext(); - - Node node0 = new Node(0); - node0.setConsensusSettings(csProps); - node0.setLedgerManager(nodeCtx0.getLedgerManager()); - node0.setStorageDB(nodeCtx0.getStorageDB()); - node0.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(0).getPubKey(), privkey0)); - node0.setBindingConfig(bindingConfig0); - context.addNode(node0); - - Node node1 = new Node(1); - node1.setConsensusSettings(csProps); - node1.setLedgerManager(nodeCtx1.getLedgerManager()); - node1.setStorageDB(nodeCtx1.getStorageDB()); - node1.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(1).getPubKey(), privkey1)); - node1.setBindingConfig(bindingConfig1); - context.addNode(node1); - - Node node2 = new Node(2); - node2.setConsensusSettings(csProps); - node2.setLedgerManager(nodeCtx2.getLedgerManager()); - node2.setStorageDB(nodeCtx2.getStorageDB()); - node2.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(2).getPubKey(), privkey2)); - node2.setBindingConfig(bindingConfig2); - context.addNode(node2); - - Node node3 = new Node(3); - node3.setConsensusSettings(csProps); - node3.setLedgerManager(nodeCtx3.getLedgerManager()); - node3.setStorageDB(nodeCtx3.getStorageDB()); - node3.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(3).getPubKey(), privkey3)); - node3.setBindingConfig(bindingConfig3); - context.addNode(node3); - - nodeCtx0.closeServer(); - nodeCtx1.closeServer(); - nodeCtx2.closeServer(); - nodeCtx3.closeServer(); - - return context; - } - - public static LedgerInitProperties loadInitSetting_integration() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java deleted file mode 100644 index 3512d6b0..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java +++ /dev/null @@ -1,362 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInfo; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.PreparedTransaction; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionTemplate; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.IntegratedContext.Node; -import test.com.jd.blockchain.intgr.contract.AssetContract; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest.NodeWebContext; -import test.com.jd.blockchain.intgr.perf.Utils; - -/** - * 测试合约,提交后不立即进行验证,因为此时可能还没有完成正式结块; - */ -public class IntegrationTest2 { - // 合约测试使用的初始化数据; - BlockchainKeypair contractDeployKey = BlockchainKeyGenerator.getInstance().generate(); - private String contractZipName = "contract.jar"; - private String eventName = "issue-asset"; - - @Test - public void test() { - // init ledgers of all nodes ; - IntegratedContext context = initLedgers(LedgerInitConsensusConfig.mqConfig, - LedgerInitConsensusConfig.memConnectionStrings); - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - Node node2 = context.getNode(2); - Node node3 = context.getNode(3); - - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 13200); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, node0.getBindingConfig(), node0.getStorageDB(), null); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 13210); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, node1.getBindingConfig(), node1.getStorageDB(), null); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 13220); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, node2.getBindingConfig(), node2.getStorageDB(), null); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 13230); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, node3.getBindingConfig(), node3.getStorageDB(), null); - - AsyncCallback peerStarting0 = peer0.start(); - AsyncCallback peerStarting1 = peer1.start(); - AsyncCallback peerStarting2 = peer2.start(); - AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway0 = new GatewayTestRunner("127.0.0.1", 13300, gwkey0, peerSrvAddr0); - - KeyPairConfig gwkey1 = new KeyPairConfig(); - gwkey1.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[1]); - gwkey1.setPrivKeyValue(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1]); - gwkey1.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway1 = new GatewayTestRunner("127.0.0.1", 13310, gwkey1, peerSrvAddr1); - - AsyncCallback gwStarting0 = gateway0.start(); - AsyncCallback gwStarting1 = gateway1.start(); - - gwStarting0.waitReturn(); - gwStarting1.waitReturn(); - - // 执行测试用例之前,校验每个节点的一致性; - testConsistencyAmongNodes(context); - - testSDK(gateway0, context); - - // 执行测试用例之后,校验每个节点的一致性; - testConsistencyAmongNodes(context); - } - - private void testConsistencyAmongNodes(IntegratedContext context) { - int[] ids = context.getNodeIds(); - Node[] nodes = new Node[ids.length]; - LedgerQuery[] ledgers = new LedgerQuery[ids.length]; - for (int i = 0; i < nodes.length; i++) { - nodes[i] = context.getNode(ids[i]); - HashDigest ledgerHash = nodes[i].getLedgerManager().getLedgerHashs()[0]; - ledgers[i] = nodes[i].getLedgerManager().getLedger(ledgerHash); - } - LedgerQuery ledger0 = ledgers[0]; - LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock(); - for (int i = 1; i < ledgers.length; i++) { - LedgerQuery otherLedger = ledgers[i]; - LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock(); - assertEquals(ledger0.getHash(), otherLedger.getHash()); - assertEquals(ledger0.getLatestBlockHeight(), otherLedger.getLatestBlockHeight()); - assertEquals(ledger0.getLatestBlockHash(), otherLedger.getLatestBlockHash()); - - assertEquals(latestBlock0.getHeight(), otherLatestBlock.getHeight()); - assertEquals(latestBlock0.getHash(), otherLatestBlock.getHash()); - assertEquals(latestBlock0.getAdminAccountHash(), otherLatestBlock.getAdminAccountHash()); - assertEquals(latestBlock0.getTransactionSetHash(), otherLatestBlock.getTransactionSetHash()); - assertEquals(latestBlock0.getUserAccountSetHash(), otherLatestBlock.getUserAccountSetHash()); - assertEquals(latestBlock0.getDataAccountSetHash(), otherLatestBlock.getDataAccountSetHash()); - assertEquals(latestBlock0.getContractAccountSetHash(), otherLatestBlock.getContractAccountSetHash()); - assertEquals(latestBlock0.getPreviousHash(), otherLatestBlock.getPreviousHash()); - } - } - - private void testSDK(GatewayTestRunner gateway, IntegratedContext context) { - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService bcsrv = gwsrvFact.getBlockchainService(); - - HashDigest[] ledgerHashs = bcsrv.getLedgerHashs(); - - AsymmetricKeypair adminKey = context.getNode(0).getPartiKeyPair(); - - testSDK_Contract(adminKey, ledgerHashs[0], bcsrv, context); - - } - - private IntegratedContext initLedgers(LedgerInitConsensusConfig.ConsensusConfig config, String[] dbConns) { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_integration(); - Properties props = LedgerInitializeWeb4SingleStepsTest.loadConsensusSetting(config.getConfigPath()); - ConsensusProvider csProvider = LedgerInitConsensusConfig.getConsensusProvider(config.getProvider()); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeWebContext nodeCtx0 = new NodeWebContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeWebContext nodeCtx1 = new NodeWebContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeWebContext nodeCtx2 = new NodeWebContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeWebContext nodeCtx3 = new NodeWebContext(3, initAddr3); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - String encodedPassword = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri(dbConns[0]); - LedgerBindingConfig bindingConfig0 = new LedgerBindingConfig(); - AsyncCallback callback0 = nodeCtx0.startInitCommand(privkey0, encodedPassword, initSetting, testDb0, - consolePrompter, bindingConfig0, quitLatch); - - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri(dbConns[1]); - LedgerBindingConfig bindingConfig1 = new LedgerBindingConfig(); - AsyncCallback callback1 = nodeCtx1.startInitCommand(privkey1, encodedPassword, initSetting, testDb1, - consolePrompter, bindingConfig1, quitLatch); - - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri(dbConns[2]); - LedgerBindingConfig bindingConfig2 = new LedgerBindingConfig(); - AsyncCallback callback2 = nodeCtx2.startInitCommand(privkey2, encodedPassword, initSetting, testDb2, - consolePrompter, bindingConfig2, quitLatch); - - DBConnectionConfig testDb3 = new DBConnectionConfig(); - testDb3.setConnectionUri(dbConns[3]); - LedgerBindingConfig bindingConfig3 = new LedgerBindingConfig(); - AsyncCallback callback3 = nodeCtx3.startInitCommand(privkey3, encodedPassword, initSetting, testDb3, - consolePrompter, bindingConfig3, quitLatch); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - assertNotNull(ledgerHash0); - assertEquals(ledgerHash0, ledgerHash1); - assertEquals(ledgerHash0, ledgerHash2); - assertEquals(ledgerHash0, ledgerHash3); - - LedgerQuery ledger0 = nodeCtx0.registLedger(ledgerHash0); - LedgerQuery ledger1 = nodeCtx1.registLedger(ledgerHash1); - LedgerQuery ledger2 = nodeCtx2.registLedger(ledgerHash2); - LedgerQuery ledger3 = nodeCtx3.registLedger(ledgerHash3); - - assertNotNull(ledger0); - assertNotNull(ledger1); - assertNotNull(ledger2); - assertNotNull(ledger3); - - IntegratedContext context = new IntegratedContext(); - - Node node0 = new Node(0); - node0.setConsensusSettings(csProps); - node0.setLedgerManager(nodeCtx0.getLedgerManager()); - node0.setStorageDB(nodeCtx0.getStorageDB()); - node0.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(0).getPubKey(), privkey0)); - node0.setBindingConfig(bindingConfig0); - context.addNode(node0); - - Node node1 = new Node(1); - node1.setConsensusSettings(csProps); - node1.setLedgerManager(nodeCtx1.getLedgerManager()); - node1.setStorageDB(nodeCtx1.getStorageDB()); - node1.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(1).getPubKey(), privkey1)); - node1.setBindingConfig(bindingConfig1); - context.addNode(node1); - - Node node2 = new Node(2); - node2.setConsensusSettings(csProps); - node2.setLedgerManager(nodeCtx2.getLedgerManager()); - node2.setStorageDB(nodeCtx2.getStorageDB()); - node2.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(2).getPubKey(), privkey2)); - node2.setBindingConfig(bindingConfig2); - context.addNode(node2); - - Node node3 = new Node(3); - node3.setConsensusSettings(csProps); - node3.setLedgerManager(nodeCtx3.getLedgerManager()); - node3.setStorageDB(nodeCtx3.getStorageDB()); - node3.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(3).getPubKey(), privkey3)); - node3.setBindingConfig(bindingConfig3); - context.addNode(node3); - - nodeCtx0.closeServer(); - nodeCtx1.closeServer(); - nodeCtx2.closeServer(); - nodeCtx3.closeServer(); - - return context; - } - - public static LedgerInitProperties loadInitSetting_integration() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private void testSDK_Contract(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, IntegratedContext context) { - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - byte[] contractCode = getChainCodeBytes(); - - txTpl.contracts().deploy(contractDeployKey.getIdentity(), contractCode); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - assertTrue(txResp.isSuccess()); - - // execute the contract; - testContractExe(adminKey, ledgerHash, userKey, blockchainService, context); - } - - private void testContractExe(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainKeypair userKey, - BlockchainService blockchainService, IntegratedContext context) { - LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash); - LedgerBlock previousBlock = blockchainService.getBlock(ledgerHash, ledgerInfo.getLatestBlockHeight() - 1); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - - txTpl.contract(contractDeployKey.getAddress(), AssetContract.class).issue(10,"abc"); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - assertTrue(txResp.isSuccess()); - } - - /** - * 根据合约构建字节数组; - * - * @return - */ - private byte[] getChainCodeBytes() { - // 构建合约的字节数组; - byte[] contractCode = null; - File file = null; - InputStream input = null; - try { - ClassPathResource contractPath = new ClassPathResource(contractZipName); - file = new File(contractPath.getURI()); - assertTrue("contract zip file is not exist.", file.exists() == true); - input = new FileInputStream(file); - // 这种暴力的读取压缩包,在class解析时有问题,所有需要改进; - contractCode = new byte[input.available()]; - input.read(contractCode); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (input != null) { - input.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return contractCode; - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java deleted file mode 100644 index 28efbdb2..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java +++ /dev/null @@ -1,204 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.GatewayConfigProperties; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.ledger.ParticipantStateUpdateInfo; -import com.jd.blockchain.ledger.ParticipantStateUpdateInfoData; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; - -import org.junit.Test; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4Nodes; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static test.com.jd.blockchain.intgr.IntegrationBase.*; - -public class IntegrationTest4Bftsmart { - - private static final boolean isRegisterUser = true; - - private static final boolean isRegisterDataAccount = true; - - private static final boolean isRegisterParticipant = true; - - private static final boolean isParticipantStateUpdate = true; - - private static final boolean isWriteKv = true; - - private static final String DB_TYPE_MEM = "mem"; - - private static final String DB_TYPE_REDIS = "redis"; - - private static final String DB_TYPE_ROCKSDB = "rocksdb"; - - public static final String BFTSMART_PROVIDER = "com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"; - - @Test - public void test4Memory() { - test(LedgerInitConsensusConfig.bftsmartProvider, DB_TYPE_MEM, LedgerInitConsensusConfig.memConnectionStrings); - } - - @Test - public void test4Redis() { -// test(LedgerInitConsensusConfig.bftsmartProvider, DB_TYPE_REDIS, LedgerInitConsensusConfig.redisConnectionStrings); - } - - public void test(String[] providers, String dbType, String[] dbConnections) { - - - final ExecutorService sendReqExecutors = Executors.newFixedThreadPool(20); - - - // 内存账本初始化 - HashDigest ledgerHash = initLedger(dbConnections); - - // 启动Peer节点 - PeerTestRunner[] peerNodes = peerNodeStart(ledgerHash, dbType); - - DbConnectionFactory dbConnectionFactory0 = peerNodes[0].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory1 = peerNodes[1].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory2 = peerNodes[2].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory3 = peerNodes[3].getDBConnectionFactory(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); - - GatewayConfigProperties.KeyPairConfig gwkey0 = new GatewayConfigProperties.KeyPairConfig(); - gwkey0.setPubKeyValue(IntegrationBase.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(IntegrationBase.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway = new GatewayTestRunner("127.0.0.1", 11000, gwkey0, - peerNodes[0].getServiceAddress(), providers,null); - - ThreadInvoker.AsyncCallback gwStarting = gateway.start(); - - gwStarting.waitReturn(); - - // 执行测试用例之前,校验每个节点的一致性; - LedgerQuery[] ledgers = buildLedgers(new LedgerBindingConfig[]{ - peerNodes[0].getLedgerBindingConfig(), - peerNodes[1].getLedgerBindingConfig(), - peerNodes[2].getLedgerBindingConfig(), - peerNodes[3].getLedgerBindingConfig(), - }, - new DbConnectionFactory[]{ - dbConnectionFactory0, - dbConnectionFactory1, - dbConnectionFactory2, - dbConnectionFactory3}); - - IntegrationBase.testConsistencyAmongNodes(ledgers); - - LedgerQuery ledgerRepository = ledgers[0]; - - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(IntegrationBase.PUB_KEYS[0]); - - AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); - - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - - int size = 15; - CountDownLatch countDownLatch = new CountDownLatch(size); - if (isRegisterUser) { - for (int i = 0; i < size; i++) { - sendReqExecutors.execute(() -> { - - System.out.printf(" sdk execute time = %s threadId = %s \r\n", System.currentTimeMillis(), Thread.currentThread().getId()); - IntegrationBase.KeyPairResponse userResponse = IntegrationBase.testSDK_RegisterUser(adminKey, ledgerHash, blockchainService); - -// validKeyPair(userResponse, ledgerRepository, IntegrationBase.KeyPairType.USER); - countDownLatch.countDown(); - }); - } - } - try { - countDownLatch.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - if (isRegisterDataAccount) { - IntegrationBase.KeyPairResponse dataAccountResponse = IntegrationBase.testSDK_RegisterDataAccount(adminKey, ledgerHash, blockchainService); - - validKeyPair(dataAccountResponse, ledgerRepository, IntegrationBase.KeyPairType.DATAACCOUNT); - - if (isWriteKv) { - - for (int m = 0; m < 13; m++) { - BlockchainKeypair da = dataAccountResponse.keyPair; - IntegrationBase.KvResponse kvResponse = IntegrationBase.testSDK_InsertData(adminKey, ledgerHash, blockchainService, da.getAddress()); - validKvWrite(kvResponse, ledgerRepository, blockchainService); - } - } - } - - long participantCount = ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipantCount(); - - long userCount = ledgerRepository.getUserAccountSet(ledgerRepository.retrieveLatestBlock()).getTotal(); - - System.out.printf("before add participant: participantCount = %d, userCount = %d\r\n", (int)participantCount, (int)userCount); - - IntegrationBase.KeyPairResponse participantResponse; - if (isRegisterParticipant) { - participantResponse = IntegrationBase.testSDK_RegisterParticipant(adminKey, ledgerHash, blockchainService); - } - - participantCount = ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipantCount(); - - userCount = ledgerRepository.getUserAccountSet(ledgerRepository.retrieveLatestBlock()).getTotal(); - - System.out.printf("after add participant: participantCount = %d, userCount = %d\r\n", (int)participantCount, (int)userCount); - - BftsmartConsensusSettings consensusSettings = (BftsmartConsensusSettings) ConsensusProviders.getProvider(BFTSMART_PROVIDER).getSettingsFactory().getConsensusSettingsEncoder().decode(ledgerRepository.getAdminInfo().getSettings().getConsensusSetting().toBytes()); - System.out.printf("update participant state before ,old consensus env node num = %d\r\n", consensusSettings.getNodes().length); - - for (int i = 0; i < participantCount; i++) { - System.out.printf("part%d state = %d\r\n",i, ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipants()[i].getParticipantNodeState().CODE); - } - - if (isParticipantStateUpdate) { - IntegrationBase.testSDK_UpdateParticipantState(adminKey, new BlockchainKeypair(participantResponse.getKeyPair().getPubKey(), participantResponse.getKeyPair().getPrivKey()), ledgerHash, blockchainService); - } - - BftsmartConsensusSettings consensusSettingsNew = (BftsmartConsensusSettings) ConsensusProviders.getProvider(BFTSMART_PROVIDER).getSettingsFactory().getConsensusSettingsEncoder().decode(ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getSettings().getConsensusSetting().toBytes()); - - System.out.printf("update participant state after ,new consensus env node num = %d\r\n", consensusSettingsNew.getNodes().length); - for (int i = 0; i < participantCount; i++) { - System.out.printf("part%d state = %d\r\n",i, ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipants()[i].getParticipantNodeState().CODE); - } - - try { - System.out.println("----------------- Init Completed -----------------"); - Thread.sleep(Integer.MAX_VALUE); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - IntegrationBase.testConsistencyAmongNodes(ledgers); - } - private HashDigest initLedger(String[] dbConnections) { - LedgerInitializeWeb4Nodes ledgerInit = new LedgerInitializeWeb4Nodes(); - HashDigest ledgerHash = ledgerInit.testInitWith4Nodes(LedgerInitConsensusConfig.bftsmartConfig, dbConnections); - System.out.printf("LedgerHash = %s \r\n", ledgerHash.toBase58()); - return ledgerHash; - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Contract.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Contract.java deleted file mode 100644 index 098b7385..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Contract.java +++ /dev/null @@ -1,122 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.GatewayConfigProperties; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4Nodes; - -import java.io.File; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static test.com.jd.blockchain.intgr.IntegrationBase.*; - -public class IntegrationTest4Contract { - private static final boolean isContractDeployAndExe = true; - private static final String DB_TYPE_MEM = "mem"; - - @Test - public void test4Memory() { - test(LedgerInitConsensusConfig.bftsmartProvider, DB_TYPE_MEM, LedgerInitConsensusConfig.memConnectionStrings); - } - - public void test(String[] providers, String dbType, String[] dbConnections) { - final ExecutorService sendReqExecutors = Executors.newFixedThreadPool(10); - // 内存账本初始化 - HashDigest ledgerHash = initLedger(dbConnections); - // 启动Peer节点 - PeerTestRunner[] peerNodes = peerNodeStart(ledgerHash, dbType); - DbConnectionFactory dbConnectionFactory0 = peerNodes[0].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory1 = peerNodes[1].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory2 = peerNodes[2].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory3 = peerNodes[3].getDBConnectionFactory(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); - - GatewayConfigProperties.KeyPairConfig gwkey0 = new GatewayConfigProperties.KeyPairConfig(); - gwkey0.setPubKeyValue(IntegrationBase.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(IntegrationBase.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway = new GatewayTestRunner("127.0.0.1", 11000, gwkey0, - peerNodes[0].getServiceAddress(), providers,null); - - ThreadInvoker.AsyncCallback gwStarting = gateway.start(); - - gwStarting.waitReturn(); - - // 执行测试用例之前,校验每个节点的一致性; - LedgerQuery[] ledgers = buildLedgers(new LedgerBindingConfig[]{ - peerNodes[0].getLedgerBindingConfig(), - peerNodes[1].getLedgerBindingConfig(), - peerNodes[2].getLedgerBindingConfig(), - peerNodes[3].getLedgerBindingConfig(), - }, - new DbConnectionFactory[]{ - dbConnectionFactory0, - dbConnectionFactory1, - dbConnectionFactory2, - dbConnectionFactory3}); - - IntegrationBase.testConsistencyAmongNodes(ledgers); - - LedgerQuery ledgerRepository = ledgers[0]; - - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(IntegrationBase.PUB_KEYS[0]); - - AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); - - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - - if(isContractDeployAndExe){ - // 合约测试需要runtime路径 - try { - ClassPathResource contractPath = new ClassPathResource(""); - File file = new File(contractPath.getURI()); - String runTimePath = file.getParentFile().getParent() + File.separator + "runtime"; - File runTime = new File(runTimePath); - if (!runTime.exists()) { - runTime.mkdir(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - - IntegrationBase.testSDK_Contract(adminKey,ledgerHash,blockchainService,ledgerRepository); - } - - try { - System.out.println("----------------- Init Completed -----------------"); - Thread.sleep(Integer.MAX_VALUE); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - IntegrationBase.testConsistencyAmongNodes(ledgers); - } - private HashDigest initLedger(String[] dbConnections) { - LedgerInitializeWeb4Nodes ledgerInit = new LedgerInitializeWeb4Nodes(); - HashDigest ledgerHash = ledgerInit.testInitWith4Nodes(LedgerInitConsensusConfig.bftsmartConfig, dbConnections); - System.out.printf("LedgerHash = %s \r\n", ledgerHash.toBase58()); - return ledgerHash; - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java deleted file mode 100644 index c8426253..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java +++ /dev/null @@ -1,213 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; -import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.*; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.FileUtils; - -import org.junit.Test; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4Nodes; - -import java.util.HashMap; -import java.util.Map; - -import static test.com.jd.blockchain.intgr.IntegrationBase.*; - -public class IntegrationTest4MQ { - - private static final boolean isRegisterUser = true; - - private static final boolean isRegisterDataAccount = true; - - private static final boolean isRegisterParticipant = true; - - private static final boolean isParticipantStateUpdate = true; - - private static final boolean isWriteKv = true; - private static final boolean isContract = false; - - private static final boolean isOnline = true; - private static final int online_time = 60000*60; - - private static final String DB_TYPE_MEM = "mem"; - - private static final String DB_TYPE_REDIS = "redis"; - - private static final String DB_TYPE_ROCKSDB = "rocksdb"; - - private static final String DATA_RETRIEVAL_URL= "http://192.168.151.39:10001"; - - public static final String MQ_PROVIDER = "com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider"; - - @Test - public void test4Memory() { - test(LedgerInitConsensusConfig.mqProvider, DB_TYPE_MEM, LedgerInitConsensusConfig.memConnectionStrings); - } - - @Test - public void test4Redis() { -// test(LedgerInitConsensusConfig.mqProvider, DB_TYPE_REDIS, LedgerInitConsensusConfig.redisConnectionStrings); - } - - @Test - public void test4Rocksdb() { - test(LedgerInitConsensusConfig.mqProvider, DB_TYPE_ROCKSDB, LedgerInitConsensusConfig.rocksdbConnectionStrings); - } - - public void test(String[] providers, String dbType, String[] dbConnections) { - - // 内存账本初始化 - HashDigest ledgerHash = initLedger(dbType, dbConnections); - - // 启动Peer节点 - PeerTestRunner[] peerNodes = peerNodeStart(ledgerHash, dbType); - - DbConnectionFactory dbConnectionFactory0 = peerNodes[0].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory1 = peerNodes[1].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory2 = peerNodes[2].getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory3 = peerNodes[3].getDBConnectionFactory(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(IntegrationBase.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(IntegrationBase.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - - Map otherMap = new HashMap(); - otherMap.put("DATA_RETRIEVAL_URL",DATA_RETRIEVAL_URL); - GatewayTestRunner gateway = new GatewayTestRunner("127.0.0.1", 11000, gwkey0, - peerNodes[0].getServiceAddress(), providers, otherMap); - - AsyncCallback gwStarting = gateway.start(); - - gwStarting.waitReturn(); - - // 执行测试用例之前,校验每个节点的一致性; - LedgerQuery[] ledgers = buildLedgers(new LedgerBindingConfig[]{ - peerNodes[0].getLedgerBindingConfig(), - peerNodes[1].getLedgerBindingConfig(), - peerNodes[2].getLedgerBindingConfig(), - peerNodes[3].getLedgerBindingConfig(), - }, - new DbConnectionFactory[]{ - dbConnectionFactory0, - dbConnectionFactory1, - dbConnectionFactory2, - dbConnectionFactory3}); - - IntegrationBase.testConsistencyAmongNodes(ledgers); - - LedgerQuery ledgerRepository = ledgers[0]; - - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(IntegrationBase.PUB_KEYS[0]); - - AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); - - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - - if (isRegisterUser) { - IntegrationBase.KeyPairResponse userResponse = IntegrationBase.testSDK_RegisterUser(adminKey, ledgerHash, blockchainService); - - validKeyPair(userResponse, ledgerRepository, IntegrationBase.KeyPairType.USER); - } - - if (isRegisterDataAccount) { - IntegrationBase.KeyPairResponse dataAccountResponse = IntegrationBase.testSDK_RegisterDataAccount(adminKey, ledgerHash, blockchainService); - - validKeyPair(dataAccountResponse, ledgerRepository, IntegrationBase.KeyPairType.DATAACCOUNT); - - if (isWriteKv) { - BlockchainKeypair da = dataAccountResponse.keyPair; - IntegrationBase.KvResponse kvResponse = IntegrationBase.testSDK_InsertData(adminKey, ledgerHash, blockchainService, da.getAddress()); - validKvWrite(kvResponse, ledgerRepository, blockchainService); - } - } - - if(isContract){ - IntegrationBase integrationBase = new IntegrationBase(); - integrationBase.testSDK_Contract(adminKey, ledgerHash, blockchainService,ledgerRepository); - } - - long participantCount = ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipantCount(); - - long userCount = ledgerRepository.getUserAccountSet(ledgerRepository.retrieveLatestBlock()).getTotal(); - - System.out.printf("before add participant: participantCount = %d, userCount = %d\r\n", (int)participantCount, (int)userCount); - - IntegrationBase.KeyPairResponse participantResponse; - if (isRegisterParticipant) { - participantResponse = IntegrationBase.testSDK_RegisterParticipant(adminKey, ledgerHash, blockchainService); - } - - participantCount = ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipantCount(); - - userCount = ledgerRepository.getUserAccountSet(ledgerRepository.retrieveLatestBlock()).getTotal(); - - System.out.printf("after add participant: participantCount = %d, userCount = %d\r\n", (int)participantCount, (int)userCount); - - MsgQueueConsensusSettings consensusSettings = (MsgQueueConsensusSettings) ConsensusProviders.getProvider(MQ_PROVIDER).getSettingsFactory().getConsensusSettingsEncoder().decode(ledgerRepository.getAdminInfo().getSettings().getConsensusSetting().toBytes()); - - System.out.printf("update participant state before ,old consensus env node num = %d\r\n", consensusSettings.getNodes().length); - - for (int i = 0; i < participantCount; i++) { - System.out.printf("part%d state = %d\r\n",i, ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipants()[i].getParticipantNodeState().CODE); - } - - if (isParticipantStateUpdate) { - IntegrationBase.testSDK_UpdateParticipantState(adminKey, new BlockchainKeypair(participantResponse.getKeyPair().getPubKey(), participantResponse.getKeyPair().getPrivKey()), ledgerHash, blockchainService); - } - - BftsmartConsensusSettings consensusSettingsNew = (BftsmartConsensusSettings) ConsensusProviders.getProvider(MQ_PROVIDER).getSettingsFactory().getConsensusSettingsEncoder().decode(ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getSettings().getConsensusSetting().toBytes()); - - System.out.printf("update participant state after ,new consensus env node num = %d\r\n", consensusSettingsNew.getNodes().length); - - for (int i = 0; i < participantCount; i++) { - System.out.printf("part%d state = %d\r\n",i, ledgerRepository.getAdminInfo(ledgerRepository.retrieveLatestBlock()).getParticipants()[i].getParticipantNodeState().CODE); - } - - IntegrationBase.testConsistencyAmongNodes(ledgers); - - if(isOnline){ - try { - Thread.sleep(online_time); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - private HashDigest initLedger(String dbType, String[] dbConnections) { - if (dbType.equalsIgnoreCase(DB_TYPE_ROCKSDB)) { - // rocksdb 需要先删除文件 - for (String dbDir : LedgerInitConsensusConfig.rocksdbDirStrings) { - try { - FileUtils.deleteFile(dbDir); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - LedgerInitializeWeb4Nodes ledgerInit = new LedgerInitializeWeb4Nodes(); - HashDigest ledgerHash = ledgerInit.testInitWith4Nodes(LedgerInitConsensusConfig.mqConfig, dbConnections); - System.out.printf("LedgerHash = %s \r\n", ledgerHash.toBase58()); - return ledgerHash; - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java deleted file mode 100644 index 6c8c762c..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java +++ /dev/null @@ -1,542 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Random; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.TypedKVEntry; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInfo; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.PreparedTransaction; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.TransactionTemplate; -import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.DataAccountQuery; -import com.jd.blockchain.ledger.core.LedgerManage; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.HexUtils; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.contract.AssetContract; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest; - -public class IntegrationTestAll4Redis { - - public static final String PASSWORD = "abc"; - - public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; - - public static final String[] PRIV_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - - // batch transactions keys - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - BlockchainKeypair dataKey = BlockchainKeyGenerator.getInstance().generate(); - - // 合约测试使用的初始化数据; - BlockchainKeypair contractDataKey = BlockchainKeyGenerator.getInstance().generate(); - BlockchainKeypair contractDeployKey = BlockchainKeyGenerator.getInstance().generate(); - private String contractZipName = "AssetContract1.contract"; - private String eventName = "issue-asset"; - HashDigest txContentHash; - String pubKeyVal = "jd.com" + System.currentTimeMillis(); - // String userPubKeyVal = "this is user's pubKey"; - // 保存资产总数的键; - private static final String KEY_TOTAL = "TOTAL"; - // 第二个参数; - private static final String KEY_ABC = "abc"; - - @Test - public void test() { - - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 10200); - LedgerBindingConfig bindingConfig0 = loadBindingConfig(0); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, bindingConfig0); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 10210); - LedgerBindingConfig bindingConfig1 = loadBindingConfig(1); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, bindingConfig1); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 10220); - LedgerBindingConfig bindingConfig2 = loadBindingConfig(2); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, bindingConfig2); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 10230); - LedgerBindingConfig bindingConfig3 = loadBindingConfig(3); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, bindingConfig3); - - AsyncCallback peerStarting0 = peer0.start(); - AsyncCallback peerStarting1 = peer1.start(); - AsyncCallback peerStarting2 = peer2.start(); - AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - DbConnectionFactory dbConnectionFactory0 = peer0.getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory1 = peer1.getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory2 = peer2.getDBConnectionFactory(); - DbConnectionFactory dbConnectionFactory3 = peer3.getDBConnectionFactory(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(PUB_KEYS[0]); - gwkey0.setPrivKeyValue(PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway0 = new GatewayTestRunner("127.0.0.1", 11000, gwkey0, peerSrvAddr0); - - AsyncCallback gwStarting0 = gateway0.start(); - - gwStarting0.waitReturn(); - - // 执行测试用例之前,校验每个节点的一致性; - LedgerQuery[] ledgers = buildLedgers( - new LedgerBindingConfig[] { bindingConfig0, bindingConfig1, bindingConfig2, bindingConfig3 }, - new DbConnectionFactory[] { dbConnectionFactory0, dbConnectionFactory1, dbConnectionFactory2, - dbConnectionFactory3 }); - testConsistencyAmongNodes(ledgers); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); - PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); - PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); - PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); - - AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); - - testWriteBatchTransactions(gateway0, adminKey, ledgers[0]); - - testSDK(gateway0, adminKey, ledgers[0]); - - // 执行测试用例之后,校验每个节点的一致性; - testConsistencyAmongNodes(ledgers); - } - - private LedgerBindingConfig loadBindingConfig(int id) { - ClassPathResource res = new ClassPathResource("ledger-binding-redis-" + id + ".conf"); - try (InputStream in = res.getInputStream()) { - return LedgerBindingConfig.resolve(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private LedgerQuery[] buildLedgers(LedgerBindingConfig[] bindingConfigs, - DbConnectionFactory[] dbConnectionFactories) { - int[] ids = { 0, 1, 2, 3 }; - LedgerQuery[] ledgers = new LedgerQuery[ids.length]; - LedgerManager[] ledgerManagers = new LedgerManager[ids.length]; - for (int i = 0; i < ids.length; i++) { - ledgerManagers[i] = new LedgerManager(); - HashDigest ledgerHash = bindingConfigs[0].getLedgerHashs()[0]; - DbConnection conn = dbConnectionFactories[i].connect( - bindingConfigs[i].getLedger(ledgerHash).getDbConnection().getUri(), - bindingConfigs[i].getLedger(ledgerHash).getDbConnection().getPassword()); - ledgers[i] = ledgerManagers[i].register(ledgerHash, conn.getStorageService()); - } - return ledgers; - } - - private void testConsistencyAmongNodes(LedgerQuery[] ledgers) { - LedgerQuery ledger0 = ledgers[0]; - LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock(); - for (int i = 1; i < ledgers.length; i++) { - LedgerQuery otherLedger = ledgers[i]; - LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock(); - assertEquals(ledger0.getHash(), otherLedger.getHash()); - assertEquals(ledger0.getLatestBlockHeight(), otherLedger.getLatestBlockHeight()); - assertEquals(latestBlock0.getHeight(), otherLatestBlock.getHeight()); - assertEquals(latestBlock0.getAdminAccountHash(), otherLatestBlock.getAdminAccountHash()); - assertEquals(latestBlock0.getUserAccountSetHash(), otherLatestBlock.getUserAccountSetHash()); - assertEquals(latestBlock0.getDataAccountSetHash(), otherLatestBlock.getDataAccountSetHash()); - assertEquals(latestBlock0.getContractAccountSetHash(), otherLatestBlock.getContractAccountSetHash()); - assertEquals(latestBlock0.getPreviousHash(), otherLatestBlock.getPreviousHash()); - - assertEquals(latestBlock0.getTransactionSetHash(), otherLatestBlock.getTransactionSetHash()); - assertEquals(ledger0.getLatestBlockHash(), otherLedger.getLatestBlockHash()); - assertEquals(latestBlock0.getHash(), otherLatestBlock.getHash()); - } - } - - // 测试一个区块包含多个交易的写入情况,并验证写入结果; - private void testWriteBatchTransactions(GatewayTestRunner gateway, AsymmetricKeypair adminKey, - LedgerQuery ledgerRepository) { - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - - HashDigest[] ledgerHashs = blockchainService.getLedgerHashs(); - - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHashs[0]); - - // regist user account - txTpl.users().register(userKey.getIdentity()); - - // regist data account - txTpl.dataAccounts().register(dataKey.getIdentity()); - - // add kv ops for data account - DataAccountKVSetOperation dataKvsetOP = txTpl.dataAccount(dataKey.getAddress()).setText("A", "Value_A_0", -1) - .setText("B", "Value_B_0", -1).setText("C", "Value_C_0", -1).setText("D", "Value_D_0", -1) - .getOperation(); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - assertTrue(txResp.isSuccess()); - assertEquals(ledgerRepository.retrieveLatestBlockHeight(), txResp.getBlockHeight()); - - assertEquals("Value_A_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getValue("A").getBytes().toUTF8String()); - assertEquals("Value_B_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getValue("B").getBytes().toUTF8String()); - assertEquals("Value_C_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getValue("C").getBytes().toUTF8String()); - assertEquals("Value_D_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getValue("D").getBytes().toUTF8String()); - assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getVersion("A")); - assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getVersion("B")); - assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getVersion("C")); - assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()) - .getAccount(dataKey.getAddress()).getDataset().getVersion("D")); - - return; - } - - private void testSDK(GatewayTestRunner gateway, AsymmetricKeypair adminKey, LedgerQuery ledgerRepository) { - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService bcsrv = gwsrvFact.getBlockchainService(); - - HashDigest[] ledgerHashs = bcsrv.getLedgerHashs(); - BlockchainKeypair newUserAcount = testSDK_RegisterUser(adminKey, ledgerHashs[0], bcsrv, ledgerRepository); - BlockchainKeypair newDataAccount = testSDK_RegisterDataAccount(adminKey, ledgerHashs[0], bcsrv, - ledgerRepository); - testSDK_InsertData(adminKey, ledgerHashs[0], bcsrv, newDataAccount.getAddress(), ledgerRepository); - LedgerBlock latestBlock = testSDK_Contract(adminKey, ledgerHashs[0], bcsrv, ledgerRepository); - - } - - private void testSDK_InsertData(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, Bytes dataAccountAddress, LedgerQuery ledgerRepository) { - - // 在本地定义注册账号的 TX; - TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash); - - // -------------------------------------- - // 将商品信息写入到指定的账户中; - // 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引; - Bytes dataAccount = dataAccountAddress; - - String dataKey = "jingdong" + new Random().nextInt(100000); - String dataVal = "www.jd.com"; - - txTemp.dataAccount(dataAccount).setText(dataKey, dataVal, -1); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - - // 使用私钥进行签名; - prepTx.sign(adminKey); - - // 提交交易; - TransactionResponse txResp = prepTx.commit(); - - ledgerRepository.retrieveLatestBlock(); // 更新内存 - - // 先验证应答 - assertEquals(TransactionState.SUCCESS, txResp.getExecutionState()); - assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight()); - assertEquals(txResp.getContentHash(), prepTx.getHash()); - assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash()); - - TypedKVEntry[] kvDataEntries = blockchainService.getDataEntries(ledgerHash, dataAccountAddress.toString(), - dataKey); - for (TypedKVEntry kvDataEntry : kvDataEntries) { - assertEquals(dataKey, kvDataEntry.getKey()); - String valHexText = (String) kvDataEntry.getValue(); - byte[] valBytes = HexUtils.decode(valHexText); - String valText = new String(valBytes); - System.out.println(valText); - } - } - - private BlockchainKeypair testSDK_RegisterDataAccount(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, LedgerQuery ledgerRepository) { - // 注册数据账户,并验证最终写入; - BlockchainKeypair dataAccount = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.dataAccounts().register(dataAccount.getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - // LedgerRepository ledgerOfNode0 = - // node0.getLedgerManager().getLedger(ledgerHash); - LedgerManage ledgerManager = new LedgerManager(); - long latestBlockHeight = ledgerRepository.retrieveLatestBlockHeight(); - - assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS); - assertEquals(txResp.getBlockHeight(), latestBlockHeight); - assertEquals(txResp.getContentHash(), transactionHash); - assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash()); - assertNotNull(ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock()) - .getAccount(dataAccount.getAddress())); - - return dataAccount; - } - - private BlockchainKeypair testSDK_RegisterUser(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, LedgerQuery ledgerRepository) { - // 注册用户,并验证最终写入; - BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.users().register(user.getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - - HashDigest transactionHash = ptx.getHash(); - - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - LedgerManage ledgerManager = new LedgerManager(); - assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS); - assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight()); - assertEquals(txResp.getContentHash(), transactionHash); - assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash()); - assertTrue(ledgerRepository.getUserAccountSet(ledgerRepository.getLatestBlock()).contains(user.getAddress())); - - return user; - } - - public static LedgerInitProperties loadInitSetting_integration() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private LedgerBlock testSDK_Contract(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, LedgerQuery ledgerRepository) { - System.out.println("adminKey=" + AddressEncoding.generateAddress(adminKey.getPubKey())); - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - System.out.println("userKey=" + userKey.getAddress()); - // valid the basic data in contract; - // prepareContractData(adminKey, ledgerHash, - // blockchainService,ledgerRepository); - - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - txTpl.users().register(userKey.getIdentity()); - - // 定义交易; - // 注册数据账户,并验证最终写入; - txTpl.dataAccounts().register(contractDataKey.getIdentity()); - // dataAccountSet.getDataAccount(dataAddress) - DataAccount dataAccount = ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock()) - .getAccount(contractDataKey.getAddress()); - - DataAccountKVSetOperation kvsetOP = txTpl.dataAccount(contractDataKey.getAddress()) - .setText("A", "Value_A_0", -1).setText("B", "Value_B_0", -1) - .setText(KEY_TOTAL, "total value,dataAccount", -1).setText(KEY_ABC, "abc value,dataAccount", -1) - // 所有的模拟数据都在这个dataAccount中填充; - .setBytes("ledgerHash", ledgerHash.getRawDigest(), -1).getOperation(); - - byte[] contractCode = getChainCodeBytes(); - txTpl.contracts().deploy(contractDeployKey.getIdentity(), contractCode); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - assertTrue(txResp.isSuccess()); - - // 验证结果; - txResp.getContentHash(); - - LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight()); - byte[] contractCodeInDb = ledgerRepository.getContractAccountSet(block) - .getAccount(contractDeployKey.getAddress()).getChainCode(); - assertArrayEquals(contractCode, contractCodeInDb); - txContentHash = ptx.getHash(); - - // execute the contract; - testContractExe(adminKey, ledgerHash, userKey, blockchainService, ledgerRepository); - - return block; - } - - private void testContractExe(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainKeypair userKey, - BlockchainService blockchainService, LedgerQuery ledgerRepository) { - LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash); - LedgerBlock previousBlock = blockchainService.getBlock(ledgerHash, ledgerInfo.getLatestBlockHeight() - 1); - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - - txTpl.contract(contractDeployKey.getAddress(), AssetContract.class).issue(10,"abc"); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - // 验证结果; - txResp.getContentHash(); - - LedgerInfo latestLedgerInfo = blockchainService.getLedger(ledgerHash); - assertEquals(ledgerInfo.getLatestBlockHeight() + 1, latestLedgerInfo.getLatestBlockHeight()); - assertEquals(txResp.getBlockHeight(), latestLedgerInfo.getLatestBlockHeight()); - - LedgerBlock backgroundLedgerBlock = ledgerRepository.retrieveLatestBlock(); - assertEquals(txResp.getBlockHeight(), backgroundLedgerBlock.getHeight()); - - // 验证合约中的赋值,外部可以获得; - DataAccountQuery dataAccountSet = ledgerRepository.getDataAccountSet(backgroundLedgerBlock); - AsymmetricKeypair key = Crypto.getSignatureFunction("ED25519").generateKeypair(); - PubKey pubKey = key.getPubKey(); - Bytes dataAddress = AddressEncoding.generateAddress(pubKey); - assertEquals(dataAddress, dataAccountSet.getAccount(dataAddress).getID().getAddress()); - assertEquals("hello", - dataAccountSet.getAccount(dataAddress).getDataset().getValue(KEY_TOTAL, -1).getBytes().toUTF8String()); - - // 验证userAccount,从合约内部赋值,然后外部验证;内部定义动态key,外部不便于得到,临时屏蔽; - // UserAccountSet userAccountSet = - // ledgerRepository.getUserAccountSet(backgroundLedgerBlock); - // PubKey userPubKey = new PubKey(CryptoAlgorithm.ED25519, - // userPubKeyVal.getBytes()); - // String userAddress = AddressEncoding.generateAddress(userPubKey); - // assertEquals(userAddress, userAccountSet.getUser(userAddress).getAddress()); - } - - private void prepareContractData(AsymmetricKeypair adminKey, HashDigest ledgerHash, - BlockchainService blockchainService, LedgerQuery ledgerRepository) { - - // 定义交易; - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - assertTrue(txResp.isSuccess()); - - // 验证结果; - LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight()); - BytesValue val1InDb = ledgerRepository.getDataAccountSet(block).getAccount(contractDataKey.getAddress()) - .getDataset().getValue("A"); - BytesValue val2InDb = ledgerRepository.getDataAccountSet(block).getAccount(contractDataKey.getAddress()) - .getDataset().getValue(KEY_TOTAL); - assertEquals("Value_A_0", val1InDb.getBytes().toUTF8String()); - assertEquals("total value,dataAccount", val2InDb.getBytes().toUTF8String()); - } - - /** - * 根据合约构建字节数组; - * - * @return - */ - private byte[] getChainCodeBytes() { - // 构建合约的字节数组; - byte[] contractCode = null; - File file = null; - InputStream input = null; - try { - ClassPathResource contractPath = new ClassPathResource(contractZipName); - file = new File(contractPath.getURI()); - assertTrue("contract zip file is not exist.", file.exists() == true); - input = new FileInputStream(file); - // 这种暴力的读取压缩包,在class解析时有问题,所有需要改进; - contractCode = new byte[input.available()]; - input.read(contractCode); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (input != null) { - input.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return contractCode; - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java deleted file mode 100644 index c62ee9c4..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java +++ /dev/null @@ -1,386 +0,0 @@ -package test.com.jd.blockchain.intgr; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.alibaba.fastjson.JSON; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.TypedKVEntry; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.PreparedTransaction; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionTemplate; -import com.jd.blockchain.ledger.core.DataAccountQuery; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.IntegratedContext.Node; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest.NodeWebContext; -import test.com.jd.blockchain.intgr.perf.Utils; - -public class IntegrationTestDataAccount { - - LedgerInitConsensusConfig.ConsensusConfig config = LedgerInitConsensusConfig.mqConfig; - - public IntegratedContext context = initLedgers(config, LedgerInitConsensusConfig.memConnectionStrings); - public GatewayTestRunner gateway0; - public GatewayTestRunner gateway1; - - private class JsonTest { - String name; - - public JsonTest(String name) { - this.name = name; - } - - public String getName() { - return name; - } - } - - @Test - public void startPeer() { - - // init ledgers of all nodes ; - Node node0 = context.getNode(0); - Node node1 = context.getNode(1); - Node node2 = context.getNode(2); - Node node3 = context.getNode(3); - - NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 14200); - PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, node0.getBindingConfig(), node0.getStorageDB(), null); - - NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 14210); - PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, node1.getBindingConfig(), node1.getStorageDB(), null); - - NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 14220); - PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, node2.getBindingConfig(), node2.getStorageDB(), null); - - NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 14230); - PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, node3.getBindingConfig(), node3.getStorageDB(), null); - - AsyncCallback peerStarting0 = peer0.start(); - AsyncCallback peerStarting1 = peer1.start(); - AsyncCallback peerStarting2 = peer2.start(); - AsyncCallback peerStarting3 = peer3.start(); - - peerStarting0.waitReturn(); - peerStarting1.waitReturn(); - peerStarting2.waitReturn(); - peerStarting3.waitReturn(); - - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - KeyPairConfig gwkey0 = new KeyPairConfig(); - gwkey0.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); - gwkey0.setPrivKeyValue(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - gateway0 = new GatewayTestRunner("127.0.0.1", 13300, gwkey0, peerSrvAddr0); - - KeyPairConfig gwkey1 = new KeyPairConfig(); - gwkey1.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[1]); - gwkey1.setPrivKeyValue(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1]); - gwkey1.setPrivKeyPassword(encodedBase58Pwd); - gateway1 = new GatewayTestRunner("127.0.0.1", 13310, gwkey1, peerSrvAddr1); - - AsyncCallback gwStarting0 = gateway0.start(); - AsyncCallback gwStarting1 = gateway1.start(); - - gwStarting0.waitReturn(); - gwStarting1.waitReturn(); - - // 执行测试用例之前,校验每个节点的一致性; - testConsistencyAmongNodes(context); - - // temp test add - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PubKey pubKey0 = KeyGenUtils.decodePubKey(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); - AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); - - // regist data account - Bytes dataAddr = registDataAccount(gateway0, adminKey, context); - - // add kv ops to data account - testAddKvOpToDataAccount(gateway0, adminKey, context, dataAddr); - - // 执行测试用例之后,校验每个节点的一致性; - testConsistencyAmongNodes(context); - } - - private Bytes registDataAccount(GatewayTestRunner gateway, AsymmetricKeypair adminKey, IntegratedContext context) { - // 连接网关; - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - HashDigest[] ledgerHashs = blockchainService.getLedgerHashs(); - - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHashs[0]); - - // BlockchainKeyPair user = BlockchainKeyGenerator.getInstance().generate(); - BlockchainKeypair data = BlockchainKeyGenerator.getInstance().generate(); - - // regist user account - // txTpl.users().register(user.getIdentity()); - - // //regist data account - txTpl.dataAccounts().register(data.getIdentity()); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - try { - Thread.sleep(6000); - } catch (Exception e) { - e.printStackTrace(); - } - - return data.getAddress(); - - } - - // 通过调用SDK->GATEWAY,测试一个区块包含多个交易时的写入情况,并验证写入结果; - private void testAddKvOpToDataAccount(GatewayTestRunner gateway, AsymmetricKeypair adminKey, - IntegratedContext context, Bytes dataAddr) { - - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - HashDigest[] ledgerHashs = blockchainService.getLedgerHashs(); - - LedgerManager ledgerManager = context.getNode(0).getLedgerManager(); - - DbConnection memoryBasedDb = context.getNode(0).getStorageDB() - .connect(LedgerInitConsensusConfig.memConnectionStrings[0]); - - LedgerQuery ledgerRepository = ledgerManager.register(ledgerHashs[0], memoryBasedDb.getStorageService()); - - DataAccountQuery dataAccountSet = ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()); - - TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHashs[0]); - - long currentTime = System.currentTimeMillis(); - byte[] time = BytesUtils.toBytes(currentTime); - - JsonTest jsonTest = new JsonTest("Jack"); - // - // //add kv ops for data account: Bytes, string, long, json string - DataAccountKVSetOperation dataKvsetOP = txTpl.dataAccount(dataAddr).setText("A", "Value_A_0", -1) - .setText("B", "Value_B_0", -1).setInt64("C", currentTime, -1).setText("D", JSON.toJSONString(jsonTest), -1) - .getOperation(); - - // 签名; - PreparedTransaction ptx = txTpl.prepare(); - ptx.sign(adminKey); - - // 提交并等待共识返回; - TransactionResponse txResp = ptx.commit(); - - try { - Thread.sleep(6000); - } catch (Exception e) { - e.printStackTrace(); - } - - TypedKVEntry[] kvDataEntries = blockchainService.getDataEntries(ledgerHashs[0], dataAddr.toBase58(), "A", "B", - "C", "D"); - for (int i = 0; i < kvDataEntries.length; i++) { - Object result = kvDataEntries[i].getValue(); - System.out.println("result = " + result); - } - - return; - } - - public void testConsistencyAmongNodes(IntegratedContext context) { - int[] ids = context.getNodeIds(); - Node[] nodes = new Node[ids.length]; - LedgerQuery[] ledgers = new LedgerQuery[ids.length]; - for (int i = 0; i < nodes.length; i++) { - nodes[i] = context.getNode(ids[i]); - HashDigest ledgerHash = nodes[i].getLedgerManager().getLedgerHashs()[0]; - ledgers[i] = nodes[i].getLedgerManager().getLedger(ledgerHash); - } - LedgerQuery ledger0 = ledgers[0]; - LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock(); - for (int i = 1; i < ledgers.length; i++) { - LedgerQuery otherLedger = ledgers[i]; - LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock(); - assertEquals(ledger0.getHash(), otherLedger.getHash()); - assertEquals(ledger0.getLatestBlockHeight(), otherLedger.getLatestBlockHeight()); - assertEquals(ledger0.getLatestBlockHash(), otherLedger.getLatestBlockHash()); - - assertEquals(latestBlock0.getHeight(), otherLatestBlock.getHeight()); - assertEquals(latestBlock0.getHash(), otherLatestBlock.getHash()); - assertEquals(latestBlock0.getAdminAccountHash(), otherLatestBlock.getAdminAccountHash()); - assertEquals(latestBlock0.getTransactionSetHash(), otherLatestBlock.getTransactionSetHash()); - assertEquals(latestBlock0.getUserAccountSetHash(), otherLatestBlock.getUserAccountSetHash()); - assertEquals(latestBlock0.getDataAccountSetHash(), otherLatestBlock.getDataAccountSetHash()); - assertEquals(latestBlock0.getContractAccountSetHash(), otherLatestBlock.getContractAccountSetHash()); - assertEquals(latestBlock0.getPreviousHash(), otherLatestBlock.getPreviousHash()); - } - } - - private IntegratedContext initLedgers(LedgerInitConsensusConfig.ConsensusConfig config, String[] dbConns) { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_integration(); - Properties props = LedgerInitializeWeb4SingleStepsTest.loadConsensusSetting(config.getConfigPath()); - ConsensusProvider csProvider = LedgerInitConsensusConfig.getConsensusProvider(config.getProvider()); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeWebContext nodeCtx0 = new NodeWebContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeWebContext nodeCtx1 = new NodeWebContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeWebContext nodeCtx2 = new NodeWebContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeWebContext nodeCtx3 = new NodeWebContext(3, initAddr3); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], - LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - String encodedPassword = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri(dbConns[0]); - LedgerBindingConfig bindingConfig0 = new LedgerBindingConfig(); - AsyncCallback callback0 = nodeCtx0.startInitCommand(privkey0, encodedPassword, initSetting, testDb0, - consolePrompter, bindingConfig0, quitLatch); - - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri(dbConns[1]); - LedgerBindingConfig bindingConfig1 = new LedgerBindingConfig(); - AsyncCallback callback1 = nodeCtx1.startInitCommand(privkey1, encodedPassword, initSetting, testDb1, - consolePrompter, bindingConfig1, quitLatch); - - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri(dbConns[2]); - LedgerBindingConfig bindingConfig2 = new LedgerBindingConfig(); - AsyncCallback callback2 = nodeCtx2.startInitCommand(privkey2, encodedPassword, initSetting, testDb2, - consolePrompter, bindingConfig2, quitLatch); - - DBConnectionConfig testDb3 = new DBConnectionConfig(); - testDb3.setConnectionUri(dbConns[3]); - LedgerBindingConfig bindingConfig3 = new LedgerBindingConfig(); - AsyncCallback callback3 = nodeCtx3.startInitCommand(privkey3, encodedPassword, initSetting, testDb3, - consolePrompter, bindingConfig3, quitLatch); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - assertNotNull(ledgerHash0); - assertEquals(ledgerHash0, ledgerHash1); - assertEquals(ledgerHash0, ledgerHash2); - assertEquals(ledgerHash0, ledgerHash3); - - LedgerQuery ledger0 = nodeCtx0.registLedger(ledgerHash0); - LedgerQuery ledger1 = nodeCtx1.registLedger(ledgerHash1); - LedgerQuery ledger2 = nodeCtx2.registLedger(ledgerHash2); - LedgerQuery ledger3 = nodeCtx3.registLedger(ledgerHash3); - - assertNotNull(ledger0); - assertNotNull(ledger1); - assertNotNull(ledger2); - assertNotNull(ledger3); - - IntegratedContext context = new IntegratedContext(); - - Node node0 = new Node(0); - node0.setConsensusSettings(csProps); - node0.setLedgerManager(nodeCtx0.getLedgerManager()); - node0.setStorageDB(nodeCtx0.getStorageDB()); - node0.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(0).getPubKey(), privkey0)); - node0.setBindingConfig(bindingConfig0); - context.addNode(node0); - - Node node1 = new Node(1); - node1.setConsensusSettings(csProps); - node1.setLedgerManager(nodeCtx1.getLedgerManager()); - node1.setStorageDB(nodeCtx1.getStorageDB()); - node1.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(1).getPubKey(), privkey1)); - node1.setBindingConfig(bindingConfig1); - context.addNode(node1); - - Node node2 = new Node(2); - node2.setConsensusSettings(csProps); - node2.setLedgerManager(nodeCtx2.getLedgerManager()); - node2.setStorageDB(nodeCtx2.getStorageDB()); - node2.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(2).getPubKey(), privkey2)); - node2.setBindingConfig(bindingConfig2); - context.addNode(node2); - - Node node3 = new Node(3); - node3.setConsensusSettings(csProps); - node3.setLedgerManager(nodeCtx3.getLedgerManager()); - node3.setStorageDB(nodeCtx3.getStorageDB()); - node3.setPartiKeyPair(new AsymmetricKeypair(initSetting.getConsensusParticipant(3).getPubKey(), privkey3)); - node3.setBindingConfig(bindingConfig3); - context.addNode(node3); - - nodeCtx0.closeServer(); - nodeCtx1.closeServer(); - nodeCtx2.closeServer(); - nodeCtx3.closeServer(); - - return context; - } - - public static LedgerInitProperties loadInitSetting_integration() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartConfig.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartConfig.java deleted file mode 100644 index e65229d1..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartConfig.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: BftsmartConfig - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/10 下午3:43 - * Description: - */ -package test.com.jd.blockchain.intgr.batch.bftsmart; - -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.security.ShaUtils; -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * - * @author shaozhuguang - * @create 2019/1/10 - * @since 1.0.0 - */ - -public class BftsmartConfig { - - public static final String BFTSMART_DIR = "bftsmart" + File.separator; - - public static final String[] PUB_KEY = new String[64]; - - public static final String[] PRIV_KEY = new String[64]; - - public static final String PWD = Base58Utils.encode(ShaUtils.hash_256("abc".getBytes()));; - - public static final int startBftsmartPort = 26000; - - public static final int startInitPort = 15000; - - static { - load(); - } - - @Test - public void test4ConfigLoad() { - bftsmartConfigInit(4); - bftsmartLedgerInit(4); - } - - @Test - public void test8ConfigLoad() { - bftsmartConfigInit(8); - bftsmartLedgerInit(8); - } - - @Test - public void test16ConfigLoad() { - bftsmartConfigInit(16); - bftsmartLedgerInit(16); - } - - @Test - public void test32ConfigLoad() { - bftsmartConfigInit(32); - bftsmartLedgerInit(32); - } - - @Test - public void test64ConfigLoad() { - bftsmartConfigInit(64); - bftsmartLedgerInit(64); - } - - public void bftsmartLedgerInit(int size) { - String file = BFTSMART_DIR + "ledger_init_bftsmart-" + size + ".init"; - ClassPathResource res = new ClassPathResource(file); - try { - File resFile = res.getFile(); - List fileContent = org.apache.commons.io.FileUtils.readLines(resFile); - // 处理新内容 - List newFileContent = handleInitContent(fileContent, size); - org.apache.commons.io.FileUtils.writeLines(resFile, newFileContent); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private List handleInitContent(List fileContent, int size) { - List newFileContent = new ArrayList<>(); - for (String srcLine : fileContent) { - String dstLine = srcLine; - if (srcLine.startsWith("cons_parti.count")) { - dstLine = "cons_parti.count=" + size; - } else if (srcLine.startsWith("###############cons_parti_configs###############")) { - List parts = initParts(size); - newFileContent.addAll(parts); - dstLine = null; - } - if (dstLine != null) { - newFileContent.add(dstLine); - } - } - return newFileContent; - } - - private List initParts(int size) { - List parts = new ArrayList<>(); - for (int i = 0; i < size; i++) { - parts.add(""); - parts.add("#第" + i + "个参与方的名称"); - parts.add("cons_parti." + i + ".name=xx-" + i + ".com"); - parts.add("#第" + i + "个参与方的公钥文件路径"); - parts.add("cons_parti." + i + ".pubkey-path="); - parts.add("#第" + i + "个参与方的公钥内容(由keygen工具生成),此参数优先于 pubkey-path 参数"); - parts.add("cons_parti." + i + ".pubkey=" + PUB_KEY[i]); - parts.add("#第" + i + "个参与方的账本初始服务的主机"); - parts.add("cons_parti." + i + ".initializer.host=127.0.0.1"); - parts.add("#第" + i + "个参与方的账本初始服务的端口"); - int portVal = startInitPort + i * 15; - parts.add("cons_parti." + i + ".initializer.port=" + portVal); - parts.add("#第" + i + "个参与方的账本初始服务是否开启安全连接"); - parts.add("cons_parti." + i + ".initializer.secure=false"); - parts.add(""); - } - return parts; - } - - public void bftsmartConfigInit(int size) { - String file = BFTSMART_DIR + "bftsmart-" + size + ".config"; - ClassPathResource res = new ClassPathResource(file); - try { - File resFile = res.getFile(); - List fileContent = org.apache.commons.io.FileUtils.readLines(resFile); - // 处理新内容 - List newFileContent = handleContent(fileContent, size); - org.apache.commons.io.FileUtils.writeLines(resFile, newFileContent); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public List handleContent(List fileContent, int size) { - List newFileContent = new ArrayList<>(); - for (String srcLine : fileContent) { - String dstLine = srcLine; - if (srcLine.startsWith("system.initial.view")) { - dstLine = "system.initial.view = " + initViews(size); - } else if (srcLine.startsWith("system.servers.num")) { - dstLine = "system.servers.num = " + size; - } else if (srcLine.startsWith("system.servers.f")) { - dstLine = "system.servers.f = " + initFsize(size); - } else if (srcLine.startsWith("###############system.server###############")) { - List servers = initServers(size); - newFileContent.addAll(servers); - dstLine = null; - } - if (dstLine != null) { - newFileContent.add(dstLine); - } - } - return newFileContent; - } - - private List initServers(int size) { - List servers = new ArrayList<>(); - for (int i = 0; i < size; i++) { - String pubKey = "system.server." + i + ".pubkey=" + PUB_KEY[i]; - String host = "system.server." + i + ".network.host=127.0.0.1"; - int portVal = startBftsmartPort + i * 10; - String port = "system.server." + i + ".network.port=" + portVal; - String secure = "system.server." + i+ ".network.secure=false"; - servers.add("############################################"); - servers.add("###### #Consensus Participant" + i + " ######"); - servers.add("############################################"); - servers.add(""); - servers.add(pubKey); - servers.add(host); - servers.add(port); - servers.add(secure); - servers.add(""); - } - return servers; - } - - private int initFsize(int size) { - return (size - 1) / 3; - } - - private String initViews(int size) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < size; i++) { - if (stringBuilder.length() > 0) { - stringBuilder.append(","); - } - stringBuilder.append(i); - } - return stringBuilder.toString(); - } - - public static void load() { - ClassPathResource res = new ClassPathResource(BFTSMART_DIR + "bftsmart-users.conf"); - try(InputStream in = res.getInputStream()){ - loadUsers(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static void loadUsers(InputStream in) { - Properties props = FileUtils.readProperties(in, "UTF-8"); - for (int i = 0; i < PUB_KEY.length; i++) { - String currUserPubKey = "user[" + i + "]pubKeyBase58"; - String currUserPrivKey = "user[" + i + "]privKeyBase58"; - PUB_KEY[i] = props.getProperty(currUserPubKey).trim(); - PRIV_KEY[i] = props.getProperty(currUserPrivKey).trim(); - System.out.printf("user[%s] pubKey=%s \r\n", i, PUB_KEY[i]); - System.out.printf("user[%s] privKey=%s \r\n", i, PRIV_KEY[i]); - } - } -} \ No newline at end of file diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java deleted file mode 100644 index f7ddad5c..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java +++ /dev/null @@ -1,393 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: BftsmartLedgerInit - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/10 下午5:03 - * Description: - */ -package test.com.jd.blockchain.intgr.batch.bftsmart; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.gateway.GatewayConfigProperties; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.peer.PeerServerBooter; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitCommand; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; -import org.junit.Before; -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; -import test.com.jd.blockchain.intgr.GatewayTestRunner; -import test.com.jd.blockchain.intgr.IntegrationBase; -import test.com.jd.blockchain.intgr.LedgerInitConsensusConfig; -import test.com.jd.blockchain.intgr.PeerTestRunner; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; - -import static test.com.jd.blockchain.intgr.IntegrationBase.buildLedgers; -import static test.com.jd.blockchain.intgr.IntegrationBase.validKeyPair; -import static test.com.jd.blockchain.intgr.IntegrationBase.validKvWrite; - -/** - * - * @author shaozhuguang - * @create 2019/1/10 - * @since 1.0.0 - */ - -public class BftsmartLedgerInit { - -// private final ExecutorService ledgerInitPools = Executors.newFixedThreadPool(64); - - private final ExecutorService nodeStartPools = Executors.newCachedThreadPool(); - - private final ExecutorService txSendPools = Executors.newFixedThreadPool(20); - - private static String localPath = FileUtils.getCurrentDir() + File.separator + "bftsmart-rocks.db"; - - private BftsmartConfig bftsmartConfig = new BftsmartConfig(); - - private static final int peerStartPort = 20000; - - private static final int registerUserSize = 500; - - private static final int kvStorageSize = 1000; - - private static final boolean isBrowser = true; - - @Before - public void before() { - File localDir = new File(localPath); - if (!localDir.exists()) { - localDir.mkdir(); - } - } - - @Test - public void localConf4NodesLoad() { - bftsmartConfig.test4ConfigLoad(); - localConfLoad(4); - ledgerInitNodes(4); - } - - @Test - public void start4Nodes() { - localConf4NodesLoad(); - PeerTestRunner[] peerNodes = startNodes(4); - // 检查账本一致性 - LedgerQuery[] ledgers = checkNodes(peerNodes); - - txRequestTest(peerNodes, ledgers); - } - - @Test - public void localConf8NodesLoad() { - bftsmartConfig.test8ConfigLoad(); - localConfLoad(8); - ledgerInitNodes(8); - } - - @Test - public void start8Nodes() { - localConf8NodesLoad(); - PeerTestRunner[] peerNodes = startNodes(8); - // 检查账本一致性 - LedgerQuery[] ledgers = checkNodes(peerNodes); - - txRequestTest(peerNodes, ledgers); - } - - @Test - public void localConf16NodesLoad() { - bftsmartConfig.test16ConfigLoad(); - localConfLoad(16); - ledgerInitNodes(16); - } - - @Test - public void start16Nodes() { - localConf16NodesLoad(); - PeerTestRunner[] peerNodes = startNodes(16); - // 检查账本一致性 - LedgerQuery[] ledgers = checkNodes(peerNodes); - - txRequestTest(peerNodes, ledgers); - } - - @Test - public void localConf32NodesLoad() { - bftsmartConfig.test32ConfigLoad(); - localConfLoad(32); - ledgerInitNodes(32); - } - - @Test - public void start32Nodes() { - localConf32NodesLoad(); -// ledgerInitPools.shutdown(); - PeerTestRunner[] peerNodes = startNodes(32); - // 检查账本一致性 - LedgerQuery[] ledgers = checkNodes(peerNodes); - - txRequestTest(peerNodes, ledgers); - } - - @Test - public void localConf64NodesLoad() { - bftsmartConfig.test64ConfigLoad(); - localConfLoad(64); - ledgerInitNodes(64); - } - - @Test - public void start64Nodes() { - localConf64NodesLoad(); - PeerTestRunner[] peerNodes = startNodes(64); - // 检查账本一致性 - LedgerQuery[] ledgers = checkNodes(peerNodes); - - txRequestTest(peerNodes, ledgers); - } - - public void txRequestTest(PeerTestRunner[] peerNodes, LedgerQuery[] ledgers) { - // 测试K-V - GatewayTestRunner gateway = initGateWay(peerNodes[0]); - - LedgerQuery ledgerRepository = ledgers[0]; - - HashDigest ledgerHash = ledgerRepository.getHash(); - - GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(BftsmartConfig.PRIV_KEY[0], IntegrationBase.PASSWORD); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(BftsmartConfig.PUB_KEY[0]); - - AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); - - BlockchainService blockchainService = gwsrvFact.getBlockchainService(); - - CountDownLatch cdlUser = new CountDownLatch(registerUserSize); - System.out.println("--------- Register Users Start ---------"); - - for (int i = 0; i < registerUserSize; i++) { - txSendPools.execute(() -> { - IntegrationBase.KeyPairResponse userResponse = IntegrationBase.testSDK_RegisterUser(adminKey, ledgerHash, blockchainService); -// validKeyPair(userResponse, ledgerRepository, IntegrationBase.KeyPairType.USER); - cdlUser.countDown(); - }); - } - IntegrationBase.KeyPairResponse dataAccountResponse = null; - try { - System.out.println("--------- Register Users Waiting ---------"); - cdlUser.await(); - IntegrationBase.testConsistencyAmongNodes(ledgers); - System.out.println("--------- Register Users Success ---------"); - System.out.println("--------- Register DataAccount Start ---------"); - dataAccountResponse = IntegrationBase.testSDK_RegisterDataAccount(adminKey, ledgerHash, blockchainService); - validKeyPair(dataAccountResponse, ledgerRepository, IntegrationBase.KeyPairType.DATAACCOUNT); - System.out.println("--------- Register DataAccount Success ---------"); - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - -// CountDownLatch cdlKv = new CountDownLatch(kvStorageSize); -// BlockchainKeyPair da = dataAccountResponse.getKeyPair(); -// for (int i = 0; i < kvStorageSize; i++) { -// txSendPools.execute(() -> { -// IntegrationBase.testSDK_InsertData(adminKey, ledgerHash, blockchainService, da.getAddress()); -// cdlKv.countDown(); -// }); -// } - - try { -// cdlKv.await(); - Thread.sleep(2000); - IntegrationBase.testConsistencyAmongNodes(ledgers); - System.out.println("--------- TestConsistencyAmongNodes Success ---------"); - if (isBrowser) { - Thread.sleep(Integer.MAX_VALUE); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public GatewayTestRunner initGateWay(PeerTestRunner peerNode) { - String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); - - GatewayConfigProperties.KeyPairConfig gwkey0 = new GatewayConfigProperties.KeyPairConfig(); - gwkey0.setPubKeyValue(BftsmartConfig.PUB_KEY[0]); - gwkey0.setPrivKeyValue(BftsmartConfig.PRIV_KEY[0]); - gwkey0.setPrivKeyPassword(encodedBase58Pwd); - GatewayTestRunner gateway = new GatewayTestRunner("127.0.0.1", 11000, gwkey0, - peerNode.getServiceAddress(), LedgerInitConsensusConfig.bftsmartProvider,null); - - ThreadInvoker.AsyncCallback gwStarting = gateway.start(); - - gwStarting.waitReturn(); - - return gateway; - } - - public LedgerQuery[] checkNodes(PeerTestRunner[] peerNodes) { - int size = peerNodes.length; - LedgerBindingConfig[] ledgerBindingConfigs = new LedgerBindingConfig[size]; - DbConnectionFactory[] connectionFactories = new DbConnectionFactory[size]; - for (int i = 0; i < size; i++) { - ledgerBindingConfigs[i] = peerNodes[i].getLedgerBindingConfig(); - connectionFactories[i] = peerNodes[i].getDBConnectionFactory(); - } - - // 执行测试用例之前,校验每个节点的一致性; - LedgerQuery[] ledgers = buildLedgers(ledgerBindingConfigs, connectionFactories); - IntegrationBase.testConsistencyAmongNodes(ledgers); - return ledgers; - } - - public PeerTestRunner[] startNodes(int size) { - PeerTestRunner[] peerNodes = new PeerTestRunner[size]; - CountDownLatch countDownLatch = new CountDownLatch(size); - try { - for (int i = 0; i < size; i++) { - final int index = i; - nodeStartPools.execute(() -> { - try { - NetworkAddress peerSrvAddr = new NetworkAddress("127.0.0.1", peerStartPort + index * 10); - String ledgerBindingConf = BftsmartConfig.BFTSMART_DIR + "conf" + File.separator + index + File.separator + "ledger-binding.conf"; - ClassPathResource ledgerBindingConfRes = new ClassPathResource(ledgerBindingConf); - LedgerBindingConfig bindingConfig = LedgerBindingConfig.resolve(ledgerBindingConfRes.getInputStream()); - PeerTestRunner peer = new PeerTestRunner(peerSrvAddr, bindingConfig); - ThreadInvoker.AsyncCallback peerStarting = peer.start(); - peerStarting.waitReturn(); - peerNodes[index] = peer; - countDownLatch.countDown(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } - countDownLatch.await(); - } catch (Exception e) { - e.printStackTrace(); - } - return peerNodes; - } - - public void ledgerInitNodes(int size) { - try { - CountDownLatch countDownLatch = new CountDownLatch(size); - for (int i = 0; i < size; i++) { - final int index = i; - nodeStartPools.execute((() -> { - try { - // 启动tool-booter - String[] args = new String[4]; - args[0] = "-l"; - String localConf = BftsmartConfig.BFTSMART_DIR + "conf" + File.separator + index + File.separator + "local-bftsmart-" + index + ".conf"; - ClassPathResource localConfRes = new ClassPathResource(localConf); - args[1] = localConfRes.getFile().getAbsolutePath(); - args[2] = "-i"; - String ledgerInit = BftsmartConfig.BFTSMART_DIR + "ledger_init_bftsmart-" + size + ".init"; - ClassPathResource ledgerInitRes = new ClassPathResource(ledgerInit); - args[3] = ledgerInitRes.getFile().getAbsolutePath(); - LedgerInitCommand.main(args); - countDownLatch.countDown(); - } catch (Exception e) { - e.printStackTrace(); - } - })); - } - countDownLatch.await(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void localConfLoad(int size) { - for (int i = 0; i < size; i++) { - localConfAllLoad(i, size); - } - } - - public void localConfAllLoad(int index, int size) { - String file = BftsmartConfig.BFTSMART_DIR + "conf" + File.separator + index + File.separator + "local-bftsmart-" + index + ".conf"; - ClassPathResource res = new ClassPathResource(file); - try { - File resFile = res.getFile(); - // 处理新内容 - List newFileContent = handleLocalConfContent(index, size); - org.apache.commons.io.FileUtils.writeLines(resFile, newFileContent); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public List handleLocalConfContent(int index, int size) throws Exception { - List newFileContent = new ArrayList<>(); - newFileContent.add("#当前参与方的 id"); - newFileContent.add("local.parti.id=" + index); - newFileContent.add(""); - - newFileContent.add("#当前参与方的公钥"); - newFileContent.add("local.parti.pubkey=" + BftsmartConfig.PUB_KEY[index]); - newFileContent.add(""); - - newFileContent.add("#当前参与方的私钥(密文编码)"); - newFileContent.add("local.parti.privkey=" + BftsmartConfig.PRIV_KEY[index]); - newFileContent.add(""); - - newFileContent.add("#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入"); - newFileContent.add("local.parti.pwd=" + BftsmartConfig.PWD); - newFileContent.add(""); - - String outDir = BftsmartConfig.BFTSMART_DIR + "conf" + File.separator + index + File.separator; - ClassPathResource outDirRes = new ClassPathResource(outDir); - - newFileContent.add("#账本初始化完成后生成的\"账本绑定配置文件\"的输出目录"); - newFileContent.add("ledger.binding.out=" + outDirRes.getFile().getAbsolutePath()); - newFileContent.add(""); - - String dbDir = new File(localPath, "rocksdb" + index + ".db").getAbsolutePath(); - FileUtils.deleteFile(dbDir); - - newFileContent.add("#账本数据库的连接字符"); - newFileContent.add("ledger.db.uri=rocksdb://" + dbDir); - newFileContent.add(""); - - newFileContent.add("#账本数据库的连接口令"); - newFileContent.add("ledger.db.pwd="); - newFileContent.add(""); - - - String consensusDir = BftsmartConfig.BFTSMART_DIR + "bftsmart-" + size + ".config"; - ClassPathResource consensusDirRes = new ClassPathResource(consensusDir); - - newFileContent.add("#共识配置文件路径"); - newFileContent.add("consensus.conf=" + consensusDirRes.getFile().getAbsolutePath()); - newFileContent.add(""); - - newFileContent.add("#共识Providers配置"); - newFileContent.add("consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"); - return newFileContent; - } -} \ No newline at end of file diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartTestBase.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartTestBase.java deleted file mode 100644 index 9a485a22..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartTestBase.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: BftsmartTestBase - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/10 下午3:32 - * Description: - */ -package test.com.jd.blockchain.intgr.batch.bftsmart; - -import static com.jd.blockchain.crypto.KeyGenUtils.encodePrivKey; -import static com.jd.blockchain.crypto.KeyGenUtils.encodePubKey; - -import org.junit.Test; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.security.ShaUtils; - -/** - * - * @author shaozhuguang - * @create 2019/1/10 - * @since 1.0.0 - */ - -public class BftsmartTestBase { - - private final int userSize = 64; - - private final byte[] pwdBytes= ShaUtils.hash_256("abc".getBytes()); - - private final String base58Pwd = Base58Utils.encode(pwdBytes); - - @Test - public void newUsers() { - SignatureFunction signFunc = Crypto.getSignatureFunction("ED25519"); - for (int i = 0; i < userSize; i++) { - AsymmetricKeypair kp = signFunc.generateKeypair(); - - String base58PubKey = encodePubKey(kp.getPubKey()); - - String base58PrivKey = encodePrivKey(kp.getPrivKey(), pwdBytes); - - System.out.printf("user[%s] privKeyBase58 = %s \r\n", i, base58PrivKey); - System.out.printf("user[%s] pubKeyBase58 = %s \r\n", i, base58PubKey); - System.out.println("------------------------------------------------------"); - } - System.out.printf("pwdBase58 = %s \r\n", base58Pwd); - } -} \ No newline at end of file diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/capability/LedgerPerfCapabilityTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/capability/LedgerPerfCapabilityTest.java deleted file mode 100644 index 6e23c83f..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/capability/LedgerPerfCapabilityTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.intgr.perf.LedgerPerfCapabilityTest - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/6 上午11:15 - * Description: - */ -package test.com.jd.blockchain.intgr.capability; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.UserRegisterOperation; -import org.junit.Test; -import test.com.jd.blockchain.intgr.perf.LedgerPerformanceTest; - -/** - * - * @author shaozhuguang - * @create 2018/12/6 - * @since 1.0.0 - */ - -public class LedgerPerfCapabilityTest { - - private final String CONSENSUS = "-mq"; - - private final String SILENT = "-silent"; - - private final String ROCKSDB = "-rocksdb"; - - private final String USERTEST = "-usertest"; - - static { - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - } - - @Test - public void testKvStorage4Memory() { - LedgerPerformanceTest.test(new String[]{SILENT}); - } - - @Test - public void testUserRegister4Memory() { - LedgerPerformanceTest.test(new String[]{USERTEST, SILENT}); - } - - @Test - public void testKvStorage4Rocksdb() { - LedgerPerformanceTest.test(new String[]{ROCKSDB, SILENT}); - } - - @Test - public void testUserRegister4Rocksdb() { - LedgerPerformanceTest.test(new String[]{USERTEST, ROCKSDB, SILENT}); - } - - public void testUserRegister4Redis() { - //test example not verify redis - LedgerPerformanceTest.test(new String[]{"-redis", "-usertest"}); - } - - public void testContract(){LedgerPerformanceTest.test(new String[]{"-contract", "-silent"});} -} \ No newline at end of file diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/AssetContract.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/AssetContract.java deleted file mode 100644 index 68d223fb..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/AssetContract.java +++ /dev/null @@ -1,39 +0,0 @@ -package test.com.jd.blockchain.intgr.contract; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEvent; - -/** - * 示例:一个“资产管理”智能合约; - * - * @author huanghaiquan - * - */ -@Contract -public interface AssetContract { - - /** - * 发行资产; - * - * @param amount - * 新发行的资产数量; - * @param assetHolderAddress - * 新发行的资产的持有账户; - */ - @ContractEvent(name = "issue-asset") - void issue(long amount, String assetHolderAddress); - - /** - * 转移资产 - * - * @param fromAddress - * 转出账户; - * @param toAddress - * 转入账户; - * @param amount - * 转移的资产数额; - */ - @ContractEvent(name = "transfer-asset") - void transfer(String fromAddress, String toAddress, long amount); - -} \ No newline at end of file diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/AssetContractImpl.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/AssetContractImpl.java deleted file mode 100644 index 9c1ec6e1..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/AssetContractImpl.java +++ /dev/null @@ -1,5 +0,0 @@ -package test.com.jd.blockchain.intgr.contract; - -public class AssetContractImpl { - -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/ContractInvocationTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/ContractInvocationTest.java deleted file mode 100644 index 46698426..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/contract/ContractInvocationTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package test.com.jd.blockchain.intgr.contract; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ContractInvocationTest { - - @Test - public void test() { - - } - -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitWebTestConfiguration.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitWebTestConfiguration.java deleted file mode 100644 index f48f9ecc..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitWebTestConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package test.com.jd.blockchain.intgr.initializer; - -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -import com.jd.blockchain.tools.initializer.web.InitWebSecurityConfiguration; -import com.jd.blockchain.tools.initializer.web.InitWebServerConfiguration; - -@SpringBootApplication -@Configuration -@EnableConfigurationProperties -@Import(value = { InitWebServerConfiguration.class, InitWebSecurityConfiguration.class }) -public class LedgerInitWebTestConfiguration { - - @Bean - public CompositeConnectionFactory getCompositeConnectionFactory() { - return new CompositeConnectionFactory(); - } - -// @Bean -// public LedgerManager getLedgerManager() { -// return new LedgerManager(); -// } - -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java deleted file mode 100644 index 217c0491..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java +++ /dev/null @@ -1,332 +0,0 @@ -package test.com.jd.blockchain.intgr.initializer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.RolesConfigureOperation; -import com.jd.blockchain.ledger.UserAuthorizeOperation; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.UserAccountQuery; -import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.InitConsensusServiceFactory; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.IntegrationBase; -import test.com.jd.blockchain.intgr.LedgerInitConsensusConfig; -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; - -public class LedgerInitializeTest { - - static { - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(RolesConfigureOperation.class); - DataContractRegistry.register(UserAuthorizeOperation.class); - } - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - public static final String PASSWORD = IntegrationBase.PASSWORD; - - public static final String[] PUB_KEYS = IntegrationBase.PUB_KEYS; - - public static final String[] PRIV_KEYS = IntegrationBase.PRIV_KEYS; - - private Map serviceRegisterMap = new ConcurrentHashMap<>(); - - public void testMQInitByMemWith4Nodes() { - testInitWith4Nodes(LedgerInitConsensusConfig.mqConfig, LedgerInitConsensusConfig.memConnectionStrings); - } - - public void testMQInitByRedisWith4Nodes() { - testInitWith4Nodes(LedgerInitConsensusConfig.mqConfig, LedgerInitConsensusConfig.redisConnectionStrings); - } - - @Test - public void testBftsmartInitWith4Nodes() { - testInitWith4Nodes(LedgerInitConsensusConfig.bftsmartConfig, LedgerInitConsensusConfig.memConnectionStrings); - } - - public void testInitWith4Nodes(LedgerInitConsensusConfig.ConsensusConfig config, String[] dbConnections) { - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting(); - Properties props = loadConsensusSetting(config.getConfigPath()); -// ConsensusProvider csProvider = LedgerInitConsensusConfig.getConsensusProvider(config.getProvider()); -// ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props); - - NodeContext node0 = new NodeContext(initSetting.getConsensusParticipant(0).getInitializerAddress(), - serviceRegisterMap); - NodeContext node1 = new NodeContext(initSetting.getConsensusParticipant(1).getInitializerAddress(), - serviceRegisterMap); - NodeContext node2 = new NodeContext(initSetting.getConsensusParticipant(2).getInitializerAddress(), - serviceRegisterMap); - NodeContext node3 = new NodeContext(initSetting.getConsensusParticipant(3).getInitializerAddress(), - serviceRegisterMap); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri(dbConnections[0]); - AsyncCallback callback0 = node0.startInit(0, privkey0, initSetting, testDb0, consolePrompter); - - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri(dbConnections[1]); - AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, testDb1, consolePrompter); - - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri(dbConnections[2]); - AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, testDb2, consolePrompter); - - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - DBConnectionConfig testDb03 = new DBConnectionConfig(); - testDb03.setConnectionUri(dbConnections[3]); - AsyncCallback callback3 = node3.startInit(3, privkey3, initSetting, testDb03, consolePrompter); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - assertNotNull(ledgerHash0); - assertEquals(ledgerHash0, ledgerHash1); - assertEquals(ledgerHash0, ledgerHash2); - assertEquals(ledgerHash0, ledgerHash3); - - LedgerQuery ledger0 = node0.registLedger(ledgerHash0, dbConnections[0]); - LedgerQuery ledger1 = node1.registLedger(ledgerHash1, dbConnections[1]); - LedgerQuery ledger2 = node2.registLedger(ledgerHash2, dbConnections[2]); - LedgerQuery ledger3 = node3.registLedger(ledgerHash3, dbConnections[3]); - - assertNotNull(ledger0); - assertNotNull(ledger1); - assertNotNull(ledger2); - assertNotNull(ledger3); - - LedgerBlock genesisBlock = ledger0.getLatestBlock(); - assertEquals(0, genesisBlock.getHeight()); - assertEquals(ledgerHash0, genesisBlock.getHash()); - - UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); - Bytes address0 = AddressEncoding.generateAddress(pubKey0); - UserAccount user0_0 = userset0.getAccount(address0); - assertNotNull(user0_0); - - PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); - Bytes address1 = AddressEncoding.generateAddress(pubKey1); - UserAccount user1_0 = userset0.getAccount(address1); - assertNotNull(user1_0); - - PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); - Bytes address2 = AddressEncoding.generateAddress(pubKey2); - UserAccount user2_0 = userset0.getAccount(address2); - assertNotNull(user2_0); - - PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); - Bytes address3 = AddressEncoding.generateAddress(pubKey3); - UserAccount user3_0 = userset0.getAccount(address3); - assertNotNull(user3_0); - } - - public static LedgerInitProperties loadInitSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting(String configPath) { - ClassPathResource ledgerInitSettingResource = new ClassPathResource(configPath); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private static class ConsensusConfig { - String provider; - - String configPath; - - public String getProvider() { - return provider; - } - - public String getConfigPath() { - return configPath; - } - } - - public static class NodeContext { - - private LedgerManager ledgerManager = new LedgerManager(); - - private MemoryDBConnFactory storageDb = new MemoryDBConnFactory(); - - private InitConsensusServiceFactory initCsServiceFactory; - - private LedgerInitProcess initProcess; - - private AsymmetricKeypair partiKey; - - public AsymmetricKeypair getPartiKey() { - return partiKey; - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - } - - public MemoryDBConnFactory getStorageDb() { - return storageDb; - } - - public NodeContext(NetworkAddress address, Map serviceRegisterMap) { - this.initCsServiceFactory = new MultiThreadInterInvokerFactory(serviceRegisterMap); - LedgerInitializeWebController initController = new LedgerInitializeWebController(storageDb, - initCsServiceFactory); - serviceRegisterMap.put(address, initController); - this.initProcess = initController; - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter) { - - partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter); - } - }; - - return invoker.start(); - } - - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter, boolean autoVerifyHash) { - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig cryptoSetting = new CryptoConfig(); - cryptoSetting.setSupportedProviders(supportedProviders); - cryptoSetting.setAutoVerifyHash(autoVerifyHash); - cryptoSetting.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); - - setting.getCryptoProperties().setHashAlgorithm("SHA256"); - setting.getCryptoProperties().setVerifyHash(autoVerifyHash); - - partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter); - } - }; - - return invoker.start(); - } - - public LedgerQuery registLedger(HashDigest ledgerHash, String memConn) { - return ledgerManager.register(ledgerHash, storageDb.connect(memConn).getStorageService()); - } - } - - private static class MultiThreadInterInvokerFactory implements InitConsensusServiceFactory { - - private Map nodeConsesusServices; - - public MultiThreadInterInvokerFactory(Map nodeConsesusServices) { - this.nodeConsesusServices = nodeConsesusServices; - } - - @Override - public LedgerInitConsensusService connect(NetworkAddress endpointAddress) { - return new InitConsensusServiceProxy(nodeConsesusServices.get(endpointAddress)); - } - - } - - private static class InitConsensusServiceProxy implements LedgerInitConsensusService { - - private LedgerInitConsensusService initCsService; - - public InitConsensusServiceProxy(LedgerInitConsensusService initCsService) { - this.initCsService = initCsService; - } - - @Override - public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected LedgerInitProposal invoke() { - return initCsService.requestPermission(requesterId, signature); - } - }; - return invoker.startAndWait(); - } - - @Override - public LedgerInitDecision synchronizeDecision(LedgerInitDecision initDecision) { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected LedgerInitDecision invoke() { - return initCsService.synchronizeDecision(initDecision); - } - }; - return invoker.startAndWait(); - } - - } - -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java deleted file mode 100644 index 1ccf994c..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java +++ /dev/null @@ -1,287 +0,0 @@ -package test.com.jd.blockchain.intgr.initializer; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.*; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import com.jd.blockchain.tools.initializer.*; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import org.junit.Test; -import org.springframework.boot.SpringApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.io.ClassPathResource; -import test.com.jd.blockchain.intgr.IntegrationBase; -import test.com.jd.blockchain.intgr.LedgerInitConsensusConfig; -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; -import test.com.jd.blockchain.intgr.perf.Utils; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -import static org.junit.Assert.*; - -public class LedgerInitializeWeb4Nodes { - - public static final String PASSWORD = IntegrationBase.PASSWORD; - - public static final String[] PUB_KEYS = IntegrationBase.PUB_KEYS; - - public static final String[] PRIV_KEYS = IntegrationBase.PRIV_KEYS; - - static { - try { - // 首先获取当前Resource路径 - ClassPathResource ledgerInitSettingResource = new ClassPathResource(""); - String path = ledgerInitSettingResource.getURL().getPath(); - System.out.println("-----" + path + "-----"); - // 将参数注册进去 - System.setProperty("peer.log", path); - System.setProperty("init.log", path); - System.setProperty("gateway.log", path); - System.setProperty("jdchain.log", path); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testMQInitByMemWith4Nodes() { - testInitWith4Nodes(LedgerInitConsensusConfig.mqConfig, LedgerInitConsensusConfig.memConnectionStrings); - } - - @Test - public void testMQInitByRedisWith4Nodes() { - testInitWith4Nodes(LedgerInitConsensusConfig.mqConfig, LedgerInitConsensusConfig.redisConnectionStrings); - } - - @Test - public void testBftsmartLedgerInitByMemWith4Nodes() { - testInitWith4Nodes(LedgerInitConsensusConfig.bftsmartConfig, LedgerInitConsensusConfig.memConnectionStrings); - } - - @Test - public void testBftsmartLedgerInitByRedisWith4Nodes() { - testInitWith4Nodes(LedgerInitConsensusConfig.bftsmartConfig, LedgerInitConsensusConfig.redisConnectionStrings); - } - - public HashDigest testInitWith4Nodes(LedgerInitConsensusConfig.ConsensusConfig config, String[] dbConns) { - System.out.println("----------- is daemon=" + Thread.currentThread().isDaemon()); - - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting_2(); - Properties props = loadConsensusSetting(config.getConfigPath()); - ConsensusProvider csProvider = LedgerInitConsensusConfig.getConsensusProvider(config.getProvider()); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeWebContext node0 = new NodeWebContext(0, initAddr0); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeWebContext node1 = new NodeWebContext(1, initAddr1); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeWebContext node2 = new NodeWebContext(2, initAddr2); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeWebContext node3 = new NodeWebContext(3, initAddr3); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - - CountDownLatch quitLatch = new CountDownLatch(4); - - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri(dbConns[0]); - AsyncCallback callback0 = node0.startInit(privkey0, initSetting, testDb0, consolePrompter, - quitLatch); - - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri(dbConns[1]); - AsyncCallback callback1 = node1.startInit(privkey1, initSetting, testDb1, consolePrompter, - quitLatch); - - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri(dbConns[2]); - AsyncCallback callback2 = node2.startInit(privkey2, initSetting, testDb2, consolePrompter, - quitLatch); - - DBConnectionConfig testDb03 = new DBConnectionConfig(); - testDb03.setConnectionUri(dbConns[3]); - AsyncCallback callback3 = node3.startInit(privkey3, initSetting, testDb03, consolePrompter, - quitLatch); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - assertNotNull(ledgerHash0); - assertEquals(ledgerHash0, ledgerHash1); - assertEquals(ledgerHash0, ledgerHash2); - assertEquals(ledgerHash0, ledgerHash3); - - LedgerQuery ledger0 = node0.registLedger(ledgerHash0); - LedgerQuery ledger1 = node1.registLedger(ledgerHash1); - LedgerQuery ledger2 = node2.registLedger(ledgerHash2); - LedgerQuery ledger3 = node3.registLedger(ledgerHash3); - - assertNotNull(ledger0); - assertNotNull(ledger1); - assertNotNull(ledger2); - assertNotNull(ledger3); - - LedgerBlock genesisBlock = ledger0.getLatestBlock(); - assertEquals(0, genesisBlock.getHeight()); - assertEquals(ledgerHash0, genesisBlock.getHash()); - - UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); - Bytes address0 = AddressEncoding.generateAddress(pubKey0); - System.out.printf("localNodeAddress0 = %s \r\n", address0.toBase58()); - UserAccount user0_0 = userset0.getAccount(address0); - assertNotNull(user0_0); - - PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); - Bytes address1 = AddressEncoding.generateAddress(pubKey1); - UserAccount user1_0 = userset0.getAccount(address1); - assertNotNull(user1_0); - System.out.printf("localNodeAddress1 = %s \r\n", address1.toBase58()); - - PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); - Bytes address2 = AddressEncoding.generateAddress(pubKey2); - UserAccount user2_0 = userset0.getAccount(address2); - assertNotNull(user2_0); - System.out.printf("localNodeAddress2 = %s \r\n", address2.toBase58()); - - PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); - Bytes address3 = AddressEncoding.generateAddress(pubKey3); - UserAccount user3_0 = userset0.getAccount(address3); - assertNotNull(user3_0); - System.out.printf("localNodeAddress3 = %s \r\n", address3.toBase58()); - - return ledgerHash0; - } - - public static LedgerInitProperties loadInitSetting_2() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web2.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting(String configPath) { - ClassPathResource ledgerInitSettingResource = new ClassPathResource(configPath); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static class NodeWebContext { - - private NetworkAddress serverAddress; - - private DBConnectionConfig dbConnConfig; - - private volatile ConfigurableApplicationContext ctx; - - private volatile LedgerInitProcess initProcess; - - private volatile LedgerInitializeWebController controller; - - private volatile LedgerManager ledgerManager; - - private volatile CompositeConnectionFactory db; - - private int id; - - public int getId() { - return controller.getId(); - } - - public TransactionContent getInitTxContent() { - return controller.getInitTxContent(); - } - - public LedgerInitProposal getLocalPermission() { - return controller.getLocalPermission(); - } - - public LedgerInitDecision getLocalDecision() { - return controller.getLocalDecision(); - } - - public NodeWebContext(int id, NetworkAddress serverAddress) { - this.id = id; - this.serverAddress = serverAddress; - } - - public LedgerQuery registLedger(HashDigest ledgerHash) { - DbConnection conn = db.connect(dbConnConfig.getUri()); - LedgerQuery ledgerRepo = ledgerManager.register(ledgerHash, conn.getStorageService()); - return ledgerRepo; - } - - public AsyncCallback startInit(PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter, CountDownLatch quitLatch) { - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - doStartServer(); - - NodeWebContext.this.dbConnConfig = dbConnConfig; - HashDigest ledgerHash = NodeWebContext.this.initProcess.initialize(id, privKey, setting, - dbConnConfig, prompter); - - System.out.printf("ledgerHash = %s \r\n", ledgerHash.toBase58()); - - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public void doStartServer() { - String argServerAddress = String.format("--server.address=%s", serverAddress.getHost()); - String argServerPort = String.format("--server.port=%s", serverAddress.getPort()); - String nodebug = "--debug=false"; - String[] innerArgs = { argServerAddress, argServerPort, nodebug }; - - ctx = SpringApplication.run(LedgerInitWebTestConfiguration.class, innerArgs); - - ctx.setId("Node-" + id); - controller = ctx.getBean(LedgerInitializeWebController.class); - ledgerManager = ctx.getBean(LedgerManager.class); - db = ctx.getBean(CompositeConnectionFactory.class); - initProcess = ctx.getBean(LedgerInitProcess.class); - } - } -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java deleted file mode 100644 index e478c70f..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java +++ /dev/null @@ -1,466 +0,0 @@ -package test.com.jd.blockchain.intgr.initializer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -import org.springframework.boot.SpringApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitCommand; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.HttpInitConsensServiceFactory; -import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.transaction.SignatureUtils; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.LedgerInitConsensusConfig; -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; -import test.com.jd.blockchain.intgr.perf.Utils; - -public class LedgerInitializeWeb4SingleStepsTest { - - public static final String PASSWORD = LedgerInitializeTest.PASSWORD; - - public static final String[] PUB_KEYS = LedgerInitializeTest.PUB_KEYS; - - public static final String[] PRIV_KEYS = LedgerInitializeTest.PRIV_KEYS; - - /** - * 测试一个节点向多个节点请求新建许可的过程; - */ - - public void testWithSingleSteps() { - - } - - public void testWithSingleSteps(LedgerInitConsensusConfig.ConsensusConfig consensusConfig, String[] dbConns) { - Prompter prompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - - HttpInitConsensServiceFactory httpCsSrvFactory = new HttpInitConsensServiceFactory(); - - // 加载初始化配置; - LedgerInitProperties initSetting = loadInitSetting_1(); - // 加载共识配置; - Properties props = loadConsensusSetting(consensusConfig.getConfigPath()); - ConsensusProvider csProvider = LedgerInitConsensusConfig.getConsensusProvider(consensusConfig.getProvider()); - ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props, - Utils.loadParticipantNodes()); - - // 启动服务器; - NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); - NodeWebContext node0 = new NodeWebContext(0, initAddr0); - node0.startServer(); - - NetworkAddress initAddr1 = initSetting.getConsensusParticipant(1).getInitializerAddress(); - NodeWebContext node1 = new NodeWebContext(1, initAddr1); - node1.startServer(); - - NetworkAddress initAddr2 = initSetting.getConsensusParticipant(2).getInitializerAddress(); - NodeWebContext node2 = new NodeWebContext(2, initAddr2); - node2.startServer(); - - NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); - NodeWebContext node3 = new NodeWebContext(3, initAddr3); - node3.startServer(); - - node0.setPrompter(prompter); - node1.setPrompter(prompter); - node2.setPrompter(prompter); - node3.setPrompter(prompter); - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - - PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); - PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); - PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); - PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); - - // 测试生成“账本初始化许可”; - LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(initSetting); - initConfig.setConsensusSettings(csProvider, csProps); - LedgerInitProposal permission0 = testPreparePermisssion(node0, privkey0, initConfig); - LedgerInitProposal permission1 = testPreparePermisssion(node1, privkey1, initConfig); - LedgerInitProposal permission2 = testPreparePermisssion(node2, privkey2, initConfig); - LedgerInitProposal permission3 = testPreparePermisssion(node3, privkey3, initConfig); - - TransactionContent initTxContent0 = node0.getInitTxContent(); - TransactionContent initTxContent1 = node1.getInitTxContent(); - TransactionContent initTxContent2 = node2.getInitTxContent(); - TransactionContent initTxContent3 = node3.getInitTxContent(); - - assertTrue(SignatureUtils.verifySignature(initTxContent0, permission0.getTransactionSignature(), pubKey0)); - assertTrue(SignatureUtils.verifySignature(initTxContent1, permission1.getTransactionSignature(), pubKey1)); - assertTrue(SignatureUtils.verifySignature(initTxContent2, permission2.getTransactionSignature(), pubKey2)); - assertTrue(SignatureUtils.verifySignature(initTxContent3, permission3.getTransactionSignature(), pubKey3)); - - assertNotNull(initTxContent0.getHash()); - if (!initTxContent0.getHash().equals(initTxContent1.getHash())) { - assertNull(initTxContent0.getLedgerHash()); - assertNull(initTxContent1.getLedgerHash()); - Operation[] oplist0 = initTxContent0.getOperations(); - Operation[] oplist1 = initTxContent1.getOperations(); - assertEquals(oplist0.length, oplist1.length); - - LedgerInitOperation initOp0 = (LedgerInitOperation) oplist0[0]; - LedgerInitOperation initOp1 = (LedgerInitOperation) oplist1[0]; - - byte[] initOpBytes0 = BinaryProtocol.encode(initOp0, LedgerInitOperation.class); - byte[] initOpBytes1 = BinaryProtocol.encode(initOp1, LedgerInitOperation.class); - assertTrue(BytesUtils.equals(initOpBytes0, initOpBytes1)); - - UserRegisterOperation regOp00 = (UserRegisterOperation) oplist0[1]; - UserRegisterOperation regOp10 = (UserRegisterOperation) oplist1[1]; - byte[] regOpBytes00 = BinaryProtocol.encode(regOp00, UserRegisterOperation.class); - byte[] regOpBytes10 = BinaryProtocol.encode(regOp10, UserRegisterOperation.class); - assertTrue(BytesUtils.equals(regOpBytes00, regOpBytes10)); - - UserRegisterOperation regOp01 = (UserRegisterOperation) oplist0[2]; - UserRegisterOperation regOp11 = (UserRegisterOperation) oplist1[2]; - byte[] regOpBytes01 = BinaryProtocol.encode(regOp01, UserRegisterOperation.class); - byte[] regOpBytes11 = BinaryProtocol.encode(regOp11, UserRegisterOperation.class); - assertTrue(BytesUtils.equals(regOpBytes01, regOpBytes11)); - - UserRegisterOperation regOp02 = (UserRegisterOperation) oplist0[3]; - UserRegisterOperation regOp12 = (UserRegisterOperation) oplist1[3]; - byte[] regOpBytes02 = BinaryProtocol.encode(regOp02, UserRegisterOperation.class); - byte[] regOpBytes12 = BinaryProtocol.encode(regOp12, UserRegisterOperation.class); - assertTrue(BytesUtils.equals(regOpBytes02, regOpBytes12)); - - UserRegisterOperation regOp03 = (UserRegisterOperation) oplist0[4]; - UserRegisterOperation regOp13 = (UserRegisterOperation) oplist1[4]; - byte[] regOpBytes03 = BinaryProtocol.encode(regOp03, UserRegisterOperation.class); - byte[] regOpBytes13 = BinaryProtocol.encode(regOp13, UserRegisterOperation.class); - assertTrue(BytesUtils.equals(regOpBytes03, regOpBytes13)); - - } - assertEquals(initTxContent0.getHash(), initTxContent1.getHash()); - assertEquals(initTxContent0.getHash(), initTxContent2.getHash()); - assertEquals(initTxContent0.getHash(), initTxContent3.getHash()); - - assertNull(initTxContent0.getLedgerHash()); - assertNull(initTxContent1.getLedgerHash()); - assertNull(initTxContent2.getLedgerHash()); - assertNull(initTxContent3.getLedgerHash()); - - // 测试请求“账本初始化许可”; - // test request permission, and verify the response; - LedgerInitConsensusService initCsService0 = httpCsSrvFactory.connect(initAddr0); - LedgerInitConsensusService initCsService1 = httpCsSrvFactory.connect(initAddr1); - LedgerInitConsensusService initCsService2 = httpCsSrvFactory.connect(initAddr2); - LedgerInitConsensusService initCsService3 = httpCsSrvFactory.connect(initAddr3); - - testRequestPermission(node0, privkey0, node1, initCsService1); - testRequestPermission(node0, privkey0, node2, initCsService2); - testRequestPermission(node0, privkey0, node3, initCsService3); - testRequestPermission(node1, privkey1, node0, initCsService0); - testRequestPermission(node1, privkey1, node2, initCsService2); - testRequestPermission(node1, privkey1, node3, initCsService3); - testRequestPermission(node2, privkey2, node0, initCsService0); - testRequestPermission(node2, privkey2, node1, initCsService1); - testRequestPermission(node2, privkey2, node3, initCsService3); - testRequestPermission(node3, privkey3, node0, initCsService0); - testRequestPermission(node3, privkey3, node1, initCsService1); - testRequestPermission(node3, privkey3, node2, initCsService2); - - // 测试在节点之间共识彼此的“账本初始化许可” - boolean allPermitted0 = node0.consensusPermission(privkey0); - boolean allPermitted1 = node1.consensusPermission(privkey1); - boolean allPermitted2 = node2.consensusPermission(privkey2); - boolean allPermitted3 = node3.consensusPermission(privkey3); - - assertTrue(allPermitted0); - assertTrue(allPermitted1); - assertTrue(allPermitted2); - assertTrue(allPermitted3); - - // 测试生成账本,并创建“账本初始化决议”; - DBConnectionConfig testDb0 = new DBConnectionConfig(dbConns[0]); - DBConnectionConfig testDb1 = new DBConnectionConfig(dbConns[1]); - DBConnectionConfig testDb2 = new DBConnectionConfig(dbConns[2]); - DBConnectionConfig testDb3 = new DBConnectionConfig(dbConns[3]); - - LedgerInitDecision dec0 = node0.prepareLedger(testDb0, privkey0); - LedgerInitDecision dec1 = node1.prepareLedger(testDb1, privkey1); - LedgerInitDecision dec2 = node2.prepareLedger(testDb2, privkey2); - LedgerInitDecision dec3 = node3.prepareLedger(testDb3, privkey3); - - assertEquals(dec0.getLedgerHash(), dec1.getLedgerHash()); - assertEquals(dec0.getLedgerHash(), dec2.getLedgerHash()); - assertEquals(dec0.getLedgerHash(), dec3.getLedgerHash()); - - testRequestDecision(node0, node1, initCsService1); - testRequestDecision(node0, node2, initCsService2); - testRequestDecision(node0, node3, initCsService3); - testRequestDecision(node1, node0, initCsService0); - testRequestDecision(node1, node2, initCsService2); - testRequestDecision(node1, node3, initCsService3); - testRequestDecision(node2, node0, initCsService0); - testRequestDecision(node2, node1, initCsService1); - testRequestDecision(node2, node3, initCsService3); - testRequestDecision(node3, node0, initCsService0); - testRequestDecision(node3, node1, initCsService1); - testRequestDecision(node3, node2, initCsService2); - } - - private LedgerInitProposal testPreparePermisssion(NodeWebContext node, PrivKey privKey, - LedgerInitConfiguration setting) { - LedgerInitProposal permission = node.preparePermision(privKey, setting); - - assertEquals(node.getId(), permission.getParticipantId()); - assertNotNull(permission.getTransactionSignature()); - - return permission; - } - - private void testRequestPermission(NodeWebContext fromNode, PrivKey fromPrivkey, NodeWebContext targetNode, - LedgerInitConsensusService targetNodeService) { - SignatureDigest reqSignature = fromNode.createPermissionRequestSignature(fromNode.getId(), fromPrivkey); - LedgerInitProposal targetPermission = targetNodeService.requestPermission(fromNode.getId(), reqSignature); - assertEquals(targetNode.getId(), targetPermission.getParticipantId()); - assertEquals(targetNode.getLocalPermission().getTransactionSignature(), - targetPermission.getTransactionSignature()); - } - - private void testRequestDecision(NodeWebContext fromNode, NodeWebContext targetNode, - LedgerInitConsensusService targetNodeService) { - LedgerInitDecision targetDecision = targetNodeService.synchronizeDecision(fromNode.getLocalDecision()); - assertEquals(targetNode.getId(), targetDecision.getParticipantId()); - assertEquals(targetNode.getLocalDecision().getLedgerHash(), targetDecision.getLedgerHash()); - assertEquals(targetNode.getLocalDecision().getSignature(), targetDecision.getSignature()); - } - - public static LedgerInitProperties loadInitSetting_1() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web1.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting(String configPath) { - ClassPathResource ledgerInitSettingResource = new ClassPathResource(configPath); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static class NodeWebContext { - - private NetworkAddress serverAddress; - - private DBConnectionConfig dbConnConfig; - - private volatile ConfigurableApplicationContext ctx; - - private volatile LedgerInitProcess initProcess; - - private volatile LedgerInitializeWebController controller; - - private volatile LedgerManager ledgerManager; - - private volatile CompositeConnectionFactory db; - - private int id; - - public int getId() { - return controller.getId(); - } - - public TransactionContent getInitTxContent() { - return controller.getInitTxContent(); - } - - public LedgerInitProposal getLocalPermission() { - return controller.getLocalPermission(); - } - - public LedgerInitDecision getLocalDecision() { - return controller.getLocalDecision(); - } - - public NodeWebContext(int id, NetworkAddress serverAddress) { - this.id = id; - this.serverAddress = serverAddress; - } - - public LedgerQuery registLedger(HashDigest ledgerHash) { - // LedgerManage ledgerManager = ctx.getBean(LedgerManage.class); - // - // DbConnectionFactory dbConnFactory = ctx.getBean(DbConnectionFactory.class); - // DbConnection conn = dbConnFactory.connect(dbConnConfig.getUri(), - // dbConnConfig.getPassword()); - - // DbConnection conn = db.connect(dbConnConfig.getUri(), - // dbConnConfig.getPassword()); - DbConnection conn = db.connect(dbConnConfig.getUri()); - LedgerQuery ledgerRepo = ledgerManager.register(ledgerHash, conn.getStorageService()); - return ledgerRepo; - } - - public SignatureDigest createPermissionRequestSignature(int requesterId, PrivKey privKey) { - return controller.signPermissionRequest(requesterId, privKey); - } - - public AsyncCallback startInit(PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter, CountDownLatch quitLatch) { - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - doStartServer(); - - // NodeWebContext.this.initProcess = ctx.getBean(LedgerInitProcess.class); - NodeWebContext.this.dbConnConfig = dbConnConfig; - HashDigest ledgerHash = NodeWebContext.this.initProcess.initialize(id, privKey, setting, - dbConnConfig, prompter); - - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public AsyncCallback startInitCommand(PrivKey privKey, String base58Pwd, - LedgerInitProperties ledgerSetting, DBConnectionConfig dbConnConfig, Prompter prompter, - LedgerBindingConfig conf, CountDownLatch quitLatch) { - this.db = new CompositeConnectionFactory(); - this.dbConnConfig = dbConnConfig; - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - LedgerInitCommand initCmd = new LedgerInitCommand(); - HashDigest ledgerHash = initCmd.startInit(id, privKey, base58Pwd, ledgerSetting, dbConnConfig, - prompter, conf, db); - NodeWebContext.this.ledgerManager = initCmd.getLedgerManager(); - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public LedgerInitProposal preparePermision(PrivKey privKey, LedgerInitConfiguration setting) { - return controller.prepareLocalPermission(id, privKey, setting); - } - - public boolean consensusPermission(PrivKey privKey) { - return controller.consensusPermisions(privKey); - } - - public LedgerInitDecision prepareLedger(DBConnectionConfig dbConnConfig, PrivKey privKey) { - controller.connectDb(dbConnConfig); - return controller.makeLocalDecision(privKey); - } - - public void startServer() { - ThreadInvoker invoker = new ThreadInvoker() { - - @Override - protected Object invoke() throws Exception { - doStartServer(); - return null; - } - }; - - invoker.startAndWait(); - } - - public void setPrompter(Prompter prompter) { - controller.setPrompter(prompter); - } - - public void doStartServer() { - String argServerAddress = String.format("--server.address=%s", serverAddress.getHost()); - String argServerPort = String.format("--server.port=%s", serverAddress.getPort()); - String nodebug = "--debug=false"; - String[] innerArgs = { argServerAddress, argServerPort, nodebug }; - - ctx = SpringApplication.run(LedgerInitWebTestConfiguration.class, innerArgs); - - ctx.setId("Node-" + id); - controller = ctx.getBean(LedgerInitializeWebController.class); - ledgerManager = ctx.getBean(LedgerManager.class); - db = ctx.getBean(CompositeConnectionFactory.class); - initProcess = ctx.getBean(LedgerInitProcess.class); - } - - public void closeServer() { - if (this.ctx != null) { - this.ctx.close(); - this.ctx = null; - } - } - - public LedgerManager getLedgerManager() { - return ledgerManager; - // return ctx.getBean(LedgerManager.class); - } - - public CompositeConnectionFactory getStorageDB() { - return db; - // return ctx.getBean(MemoryBasedDb.class); - } - } - - private static class ConsensusConfig { - String provider; - - String configPath; - - public String getProvider() { - return provider; - } - - public String getConfigPath() { - return configPath; - } - } - -} diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java deleted file mode 100644 index f9ca3833..00000000 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java +++ /dev/null @@ -1,207 +0,0 @@ -package test.com.jd.blockchain.intgr.ledger; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionRequestBuilder; -import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.LedgerDataQuery; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.TransactionBatchProcessor; -import com.jd.blockchain.service.TransactionBatchResultHandle; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -import test.com.jd.blockchain.intgr.PresetAnswerPrompter; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest; -import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest.NodeContext; -import test.com.jd.blockchain.intgr.perf.LedgerPerformanceTest; -import test.com.jd.blockchain.intgr.perf.Utils; - -public class LedgerBlockGeneratingTest { - - @Test - public void testBlocksGenerating() { - // 初始化,并获取其中一个节点的账本,单独进行性能测试; - NodeContext node = initLedgers(false)[0]; - - LedgerManager ledgerManager = node.getLedgerManager(); - HashDigest ledgerHash = ledgerManager.getLedgerHashs()[0]; - - DefaultOperationHandleRegisteration opHandler = new DefaultOperationHandleRegisteration(); - - test(ledgerHash, node.getPartiKey(), ledgerManager, opHandler, 1000, 5); - } - - private static void test(HashDigest ledgerHash, AsymmetricKeypair adminKey, LedgerManager ledgerManager, - DefaultOperationHandleRegisteration opHandler, int batchSize, int batchCount) { - LedgerRepository ledger = ledgerManager.getLedger(ledgerHash); - long height = ledger.getLatestBlockHeight(); - assertEquals(0L, height); - - ConsoleUtils.info("\r\n\r\n================= 准备测试交易 [注册用户] ================="); - int totalCount = batchSize * batchCount; - List txList = prepareUserRegisterRequests(ledgerHash, totalCount, adminKey); - - for (int i = 0; i < batchCount; i++) { - LedgerBlock latestBlock = ledger.getLatestBlock(); - assertEquals(height + i, latestBlock.getHeight()); - - LedgerDataQuery previousDataSet = ledger.getLedgerData(latestBlock); - ConsoleUtils.info("------ 开始执行交易, 即将生成区块[%s] ------", (latestBlock.getHeight() + 1)); - long startTs = System.currentTimeMillis(); - - LedgerEditor newEditor = ledger.createNextBlock(); - TransactionBatchProcessor txProc = new TransactionBatchProcessor( - LedgerPerformanceTest.DEFAULT_SECURITY_MANAGER, newEditor, ledger, opHandler); - - testTxExec(txList, i * batchSize, batchSize, txProc); - - long elapsedTs = System.currentTimeMillis() - startTs; - - ConsoleUtils.info("新区块已生成! 交易数=%s; 总耗时= %s ms; TPS=%.2f", batchSize, elapsedTs, - (batchSize * 1000.00D / elapsedTs)); - - } - - } - - private static void testTxExec(List txList, int from, int count, - TransactionBatchProcessor txProc) { - for (int i = 0; i < count; i++) { - txProc.schedule(txList.get(from + i)); - } - TransactionBatchResultHandle handle = txProc.prepare(); - handle.commit(); - } - - private static List prepareUserRegisterRequests(HashDigest ledgerHash, int count, - AsymmetricKeypair adminKey) { - List txList = new ArrayList<>(); - for (int i = 0; i < count; i++) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - txbuilder.users().register(userKey.getIdentity()); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - txList.add(reqBuilder.buildRequest()); - } - return txList; - } - - public static ConsensusProvider getConsensusProvider() { - return ConsensusProviders.getProvider("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"); - } - - public static NodeContext[] initLedgers(boolean optimized) { - Map serviceRegisterMap = new ConcurrentHashMap<>(); - - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - LedgerInitProperties initSetting = loadInitSetting(); - Properties props = loadConsensusSetting(); - ConsensusProvider csProvider = getConsensusProvider(); - ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props, - Utils.loadParticipantNodes()); - - NodeContext node0 = new NodeContext(initSetting.getConsensusParticipant(0).getInitializerAddress(), - serviceRegisterMap); - NodeContext node1 = new NodeContext(initSetting.getConsensusParticipant(1).getInitializerAddress(), - serviceRegisterMap); - NodeContext node2 = new NodeContext(initSetting.getConsensusParticipant(2).getInitializerAddress(), - serviceRegisterMap); - NodeContext node3 = new NodeContext(initSetting.getConsensusParticipant(3).getInitializerAddress(), - serviceRegisterMap); - - String[] memConns = new String[] { "memory://local/0", "memory://local/1", "memory://local/2", - "memory://local/3" }; - - PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[0], - LedgerInitializeTest.PASSWORD); - DBConnectionConfig testDb0 = new DBConnectionConfig(); - testDb0.setConnectionUri(memConns[0]); - AsyncCallback callback0 = node0.startInit(0, privkey0, initSetting, testDb0, consolePrompter, - !optimized); - - PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[1], - LedgerInitializeTest.PASSWORD); - DBConnectionConfig testDb1 = new DBConnectionConfig(); - testDb1.setConnectionUri(memConns[1]); - AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, testDb1, consolePrompter, - !optimized); - - PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[2], - LedgerInitializeTest.PASSWORD); - DBConnectionConfig testDb2 = new DBConnectionConfig(); - testDb2.setConnectionUri(memConns[2]); - AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, testDb2, consolePrompter, - !optimized); - - PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[3], - LedgerInitializeTest.PASSWORD); - DBConnectionConfig testDb03 = new DBConnectionConfig(); - testDb03.setConnectionUri(memConns[3]); - AsyncCallback callback3 = node3.startInit(3, privkey3, initSetting, testDb03, consolePrompter, - !optimized); - - HashDigest ledgerHash0 = callback0.waitReturn(); - HashDigest ledgerHash1 = callback1.waitReturn(); - HashDigest ledgerHash2 = callback2.waitReturn(); - HashDigest ledgerHash3 = callback3.waitReturn(); - - node0.registLedger(ledgerHash0, memConns[0]); - node1.registLedger(ledgerHash1, memConns[1]); - node2.registLedger(ledgerHash2, memConns[2]); - node3.registLedger(ledgerHash3, memConns[3]); - - return new NodeContext[] { node0, node1, node2, node3 }; - } - - public static LedgerInitProperties loadInitSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_web2.init"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - LedgerInitProperties setting = LedgerInitProperties.resolve(in); - return setting; - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static Properties loadConsensusSetting() { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("bftsmart.config"); - try (InputStream in = ledgerInitSettingResource.getInputStream()) { - return FileUtils.readProperties(in); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } -} diff --git a/source/test/test-integration/src/test/resources/Example1.jar b/source/test/test-integration/src/test/resources/Example1.jar deleted file mode 100644 index a22feef9..00000000 Binary files a/source/test/test-integration/src/test/resources/Example1.jar and /dev/null differ diff --git a/source/test/test-integration/src/test/resources/bftsmart.config b/source/test/test-integration/src/test/resources/bftsmart.config deleted file mode 100644 index 80ed0f6a..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart.config +++ /dev/null @@ -1,155 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Participant0 ###### -############################################ - -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=8910 -system.server.0.network.secure=false - -############################################ -###### #Consensus Participant1 ###### -############################################ - -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=8920 -system.server.1.network.secure=false - -############################################ -###### #Consensus Participant2 ###### -############################################ - -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=8930 -system.server.2.network.secure=false - -############################################ -###### Consensus Participant3 ###### -############################################ - -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=8940 -system.server.3.network.secure=false - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -#system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 5000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -#system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-16.config b/source/test/test-integration/src/test/resources/bftsmart/bftsmart-16.config deleted file mode 100644 index f598f118..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-16.config +++ /dev/null @@ -1,136 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=15 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=500 - -###############system.server############### - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - diff --git a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-32.config b/source/test/test-integration/src/test/resources/bftsmart/bftsmart-32.config deleted file mode 100644 index f598f118..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-32.config +++ /dev/null @@ -1,136 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=15 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=500 - -###############system.server############### - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - diff --git a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-4.config b/source/test/test-integration/src/test/resources/bftsmart/bftsmart-4.config deleted file mode 100644 index f598f118..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-4.config +++ /dev/null @@ -1,136 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=15 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=500 - -###############system.server############### - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - diff --git a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-64.config b/source/test/test-integration/src/test/resources/bftsmart/bftsmart-64.config deleted file mode 100644 index f598f118..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-64.config +++ /dev/null @@ -1,136 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=15 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=500 - -###############system.server############### - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - diff --git a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-8.config b/source/test/test-integration/src/test/resources/bftsmart/bftsmart-8.config deleted file mode 100644 index f598f118..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-8.config +++ /dev/null @@ -1,136 +0,0 @@ - -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=15 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=500 - -###############system.server############### - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - diff --git a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-users.conf b/source/test/test-integration/src/test/resources/bftsmart/bftsmart-users.conf deleted file mode 100644 index 3ee2c79f..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/bftsmart-users.conf +++ /dev/null @@ -1,128 +0,0 @@ -user[0]privKeyBase58=177gk1jTpc8qhaNtNn3Gku36zHL21WhQ7UjuCzVNBULuRgDeMrje9Av2SGgUmwgYbKNeguE -user[0]pubKeyBase58=endPsK36hceJEHbT876oATzGzkM2Wj1fpCzUgcbXWZ5iu1M3XTCf -user[1]privKeyBase58=177gjzU7GVC2kbhQ9fYTv1Zuz2bSBb4mcWdge6qEyvr6cTUuaqtXd9faYMeFYgW9YaBvkrk -user[1]pubKeyBase58=endPsK36cRmi1LhvTWNHjEJq3E5UQ2dBLvhpsABUPisE3zgqx2Z1 -user[2]privKeyBase58=177gjvto4zeC2MhYtK3hpvfxrhXhsRSt7q9WaKtZBLxXhWKLdH3YRYRfY8EazdWfgUhMdM8 -user[2]pubKeyBase58=endPsK36dDC65ACSFPmYtgHSQYqaTHWh5A6KWvNPYZwYDfKKsSYV -user[3]privKeyBase58=177gjweFgu9gzWJWXBgj18b8csnYQ77Ky7Gq1Adj92v9K6KywxbiizCejqkYm2oppYotznr -user[3]pubKeyBase58=endPsK36odY2z3kYTAbWnk6uySiyP3FTGY8f4TnNzD9VvDinZ47n -user[4]privKeyBase58=177gjxr5bPmfLZwaZ69i1ZexvpoLThdkahj8tVKNHtPtxqbCPkvhS9w2CEUcKE2YDmPWBt2 -user[4]pubKeyBase58=endPsK36g2yE2YJCZFEWfA2oDSyUZBPBvkRo3ANqgguVcyZrBBXK -user[5]privKeyBase58=177gjy6uro6c6QqcMFqu6cWg37r6vMqLwxvpotUK6vrfhSVLhsRDu5Mx7c4QyP9fMXa1BME -user[5]pubKeyBase58=endPsK36fMpdDaKWXiDo6jFjzGSsiEvC9URB8rUmNZo8sa1FHqNJ -user[6]privKeyBase58=177gjyinU15F85ERGxU9gaZBtrqy5enmwPJUZgxwu8gg6irVNZT6pEpw3W4hXwCyGVo1SPN -user[6]pubKeyBase58=endPsK36fDBPcSozjcZQyzUYL78cFQKZva3z3kknsCVcdoSg2p9i -user[7]privKeyBase58=177gk1VvWwysYDWKG1ndnzTuB2cpsztHdWHWurL72hSTGD1jcuU7KvV2WWdfnX2B2cTebRk -user[7]pubKeyBase58=endPsK36jbtQAgnEPEFofsjZV4LXRqcvoUs9zfzQ6j2php8aiX8q -user[8]privKeyBase58=177gk2KA4Yj2cTZqYwHfnB1CPAktzzPALdRiSUTezUZjFqVedmnQrZHYKcyK1crSNAevDh8 -user[8]pubKeyBase58=endPsK36ox5HmNDXBrHznL4BU7KVLBbAzDhRG2cbKc25m8wpnvKa -user[9]privKeyBase58=177gjyty49KxKiKGsz4pZF2ULrcVvKBErwfKwkk9b1ox8Tne9iVvtR45Sj7QsoRmQnJHPFf -user[9]pubKeyBase58=endPsK36n9w1ErHGnSqwRUQnJnyuBPQ5QmSCxGzB1k75X4NT4qBC -user[10]privKeyBase58=177gjv53KYZMqJVbfAwYtyPcajGmLjrau8Awf6unkbcNjxmHq7qRovMPrZc6ga21ue1Wa7d -user[10]pubKeyBase58=endPsK36q8B6kenwFiZvhKUThdJM4YFmBh1SoCz1tnF1j3Mcjau4 -user[11]privKeyBase58=177gjzMmTmPLTfeiXwv2k2jMn53svpEnKfUANwJXPmt3gcXnfWRdYVg61bpg98XZ66DW1S1 -user[11]pubKeyBase58=endPsK36kaUmnTESBpakavXpviV76hfGj78BJwSAfDhCaxs59QoZ -user[12]privKeyBase58=177gjwJjhm4eYRP9f2QHPewrM5dzoTojXFf1J8UhcNXT3VseVBknK9x6YickwYQkXKL6AGp -user[12]pubKeyBase58=endPsK36crfPSgzCjs6anNJ47AWdPYKS3bME3kkvAawaN1vqs8N1 -user[13]privKeyBase58=177gjzWtyyLdVtHK7GAQk54xUA9Y456KVCMD2SzWCxbd3d21Jzyxniq6xmYeff9oSVctHnB -user[13]pubKeyBase58=endPsK36j5KZYRhDhsgTsC5ZdKp1rcJX5K7nnmxeYwuRkDe7Rysp -user[14]privKeyBase58=177gjw7PK4xTAHgHdhuPWs6FUkTeeXax7U1Ccxp3XmogPsbAiEqo4wak7h2oXsJwJSRLLyE -user[14]pubKeyBase58=endPsK36gd4NXmvPkUWqJuMLg3a7ySGot26n4e53kSrxXsfXBjKG -user[15]privKeyBase58=177gjwBZXWsnyPKwaEF19h21W2ubcdyzuyUANHZcXqY8hfM7x1RYN38J2mWyZCyoNh7Pp1F -user[15]pubKeyBase58=endPsK36jNqThhuRtjiBBgrTRyGMzvQJh2CHRptd8SPzLxYwXcMR -user[16]privKeyBase58=177gjukkSbRFXy5x3NkBKopranzRE15Gmpny1M752dSqSjxi8FgdodVcydYTXyoFpcaJKT8 -user[16]pubKeyBase58=endPsK36ptiZM2QjMrNUwNgYj8xk1Rgj5Zf5sjSL7XAC7yn62puk -user[17]privKeyBase58=177gk1PxxA8hE4pBHJDo7ZsWUFNCQSKZBd57SwnfjgaWUD2pHBTADjxt6S2zSisoDL7gc9i -user[17]pubKeyBase58=endPsK36efCKq91s34hpf8Y2SBkrBr6xSJ14BNh58T5fzL2PFpND -user[18]privKeyBase58=177gjzzvgUt8Gpfw2fHhSe4Fcz7XWa7vzde43HW8RaECq1RrdiVkmJU9tBBYikmJMGjE2X1 -user[18]pubKeyBase58=endPsK36qwTfPUGx5o43K697bFGrex27z9hKyxs3rrfdu6S5LzLe -user[19]privKeyBase58=177gjsZV6iHWFPPRERKxWp7be2iKoNTH5uYjsEKvULTTRamKyhzM2FUJU6952skGx5D3WNs -user[19]pubKeyBase58=endPsK36drkcb7vVK9Gt8kYJQZpdxSmcRTBDZvShehy4Hcy3KCcK -user[20]privKeyBase58=177gk2Y7YjjwYcJ58BTRSpQvDcQcrNy4Kr7MC9vavgBbN3D789NaW5kF7kKTno32hoUQKcy -user[20]pubKeyBase58=endPsK36q9x98p2gKCd3yG9VEPtSU7bDMkYkiQYvBrsLWqUTmJMh -user[21]privKeyBase58=177gk1xuWkrnRogZVR6zZm88jfwY77DYLWqsw38ySAqB7P5gTMwVbacqBQ1WfRDE88ApfuH -user[21]pubKeyBase58=endPsK36kC2xs3j4iYFvroXqGEmRKwwncTQD79DX3NXzaUXeKaYZ -user[22]privKeyBase58=177gjtGutJvehWKacyPQxm1vFVWm8W23YNNydhMh6pkjzN3s894ga9fUe5LuoQCz6iBcHv6 -user[22]pubKeyBase58=endPsK36njitppxk4mSTFQZ8paMrFkCcxyiJmf4qtCFuurmuTcdB -user[23]privKeyBase58=177gjy13tQybqBwqqeer1L5MZ9rZQJ7zdhyJfHNmnx6t1ALqAAcWbmYpjswMCrwqiWXKc1w -user[23]pubKeyBase58=endPsK36n8niT9ZA8CFDfQgNSDekYQfVzqCSMu9uaVf2SSMz8hhJ -user[24]privKeyBase58=177gk2Xog1oV3udGppyb7pRbioBfXtr9CbYXdhn2h13tLAHfRnXdF2t3psjUHBQ9cR9DHvE -user[24]pubKeyBase58=endPsK36edG59E2cBMHZdGPeUaBMaT6jb9NAiR89DP7LUgT7rKCA -user[25]privKeyBase58=177gjuQRNBMaCsFvPF8vnNdjbvfcchVNgGvoJfoQdwJdypn8jYVm8ZXQy89J6Mi5cKFcJQ1 -user[25]pubKeyBase58=endPsK36g8mv52w79ABiDJ8FYoNEi2rFr9QqsHk2gUFCKJSeBnHp -user[26]privKeyBase58=177gjxFrM9exKoEC6LmFVRwW42V44Fbc3FX1PmVgwXB89MXdHz3ivbkHjK7sDxU8wbnWFeK -user[26]pubKeyBase58=endPsK36cLtDH1mKrfVfYhq8hgc5i2U5GjvsiGKJy4CjDuFsbgdw -user[27]privKeyBase58=177gjzjuMCRtGkWMcFTKR3ohYy6s5oGmHtpUwtX4joHJeBCMHhbRj2n3ZPVy5rPzeHr8YvS -user[27]pubKeyBase58=endPsK36qSTJh43PcmUZ3yJNJZo26KGff6gUPWG7CBjw2SDT6dNi -user[28]privKeyBase58=177gjxFUGbrTHdjA65sFWbAQnrsxXMuUA2UuXXnJ32wVVxeLuUpCswEpa2Z6LzeiR1DXvmn -user[28]pubKeyBase58=endPsK36guc4hCb7aiGC3RTrPd8s9czjnQmsXhvHSTp2CXUWnkhK -user[29]privKeyBase58=177gk1c7jZPrPx3r16oaUw15e94qKD6UYz72qDxyDCNHYHhKHmMp1dsWCora8knyRy3EYvC -user[29]pubKeyBase58=endPsK36icvZ2cvfXPoCyADDAgvFw2Hey9GstaFdBXYwfvU31viQ -user[30]privKeyBase58=177gju3UWrfHE1KHZkqLDB7t4bfFHgP92TGBc3C7rFSMTX9NBZX9ZhXk2EQnVyBvkRjHki1 -user[30]pubKeyBase58=endPsK36dtpxCZmyqoYqVcERoRLo4hC5VWo5LXg3dQx2uhPg5w4g -user[31]privKeyBase58=177gjsWzFrHvu5x6Pk353j2UdnTBffcq7TWWwZMX2VifrGDJT135ccuLWQL9PMD114LVzGZ -user[31]pubKeyBase58=endPsK36rf95mB5Vg5tsPxsoaYCBQEoAPEeFiRxZGcxmDUdyNhaf -user[32]privKeyBase58=177gjxVGMzaeT3Gc5iUu8YXgcsCFtX8zHGrxj4tSNduMnfKun6kC4RW56tnBJSBCnNnAdSD -user[32]pubKeyBase58=endPsK36pk5Gs4axsXRPecJAidcF9HeR3FM5tT1KyxRL91y7RAVa -user[33]privKeyBase58=177gk2FXVprLzfkZZUnNkuwr3TAPrEHm6Xj8dsc1uSq4pD5qfoRLFXbT861hDchYFU9XY8A -user[33]pubKeyBase58=endPsK36i76UE9Vg7uJRTtc7adLz5dxJ8VEiqirdRPhQY7QPGQZq -user[34]privKeyBase58=177gjzRCPGL9iSmSKLzUCrYwNtCS2mAzTyBdpRLLJbE25uPBsu68CCGvZp4ppkuora4c8Fe -user[34]pubKeyBase58=endPsK36oBLXYvPMBzm3itx6HnV6BKx1pd8PMXiK1kdhEh3FPs4M -user[35]privKeyBase58=177gjvNmrWKsh6nidSXbKMpPDUjA6azArLgwZ8DbPMeP2doXxgXyZSXuJcgAEEacF5fd32Q -user[35]pubKeyBase58=endPsK36k4npwVVZzeyWB3MRiKRprXQSDL4BMko6RGQfBiSbgGR7 -user[36]privKeyBase58=177gjzYa8Rp9HVE8cwPxTBRCvenWqkV5YWzPGcmRVJpUyd41PPstL2vMHj3G31HMCFngGf9 -user[36]pubKeyBase58=endPsK36jnVe7WNb5FJKuZ74RrQSyuf258Rb72LGWqfgs4EF7C61 -user[37]privKeyBase58=177gjz1YcRRb7KvA5vtJHis59tk5DH6R7k1gugxkVrwaUYsTsXhkjnqEXa2wSsUPyMGXsEX -user[37]pubKeyBase58=endPsK36pY59gVHWf2pHg5v69DPrbYGu4TUbjDHuUcivbEFfG2Bi -user[38]privKeyBase58=177gjvLDQxsVk4uNsZCSLX9k55Kmw2VgDPDv7cMjhJdorWdx8GkyfqtrnGw5SaPfLnRq76N -user[38]pubKeyBase58=endPsK36brD47DbWcpfbzVZ7mqcuLSBhqe6S4tWB5VHNeU3HrCGS -user[39]privKeyBase58=177gjy1mp1DBCDiSqEHRCVtZuP7dTrFSqvbpm4xUYHAVpqaLaxki9ajCJwHr47UMEgd6E7U -user[39]pubKeyBase58=endPsK36fZrfkLA16yAh3YfKn7sfjoCgNB6JML5DNCiWaj2Qjb5t -user[40]privKeyBase58=177gjtUDrLtvxCCKq7M8EMj7LkmbrfpA1gCc4YWzMF3BhnCuGnGzrJBByhfFnHScNWPg9k7 -user[40]pubKeyBase58=endPsK36pRBC9S2G9rh3BPs7SHgQtDLmQxSgFcE6JuLr6nMDJEKc -user[41]privKeyBase58=177gjxP1PK2XcBVZedJ1KfUQs9EViFVu3AgvqS1YHKYiKz2AtRAS4oLrhSFcL7cmfQTxepV -user[41]pubKeyBase58=endPsK36dez73AKqFPs4YsDNnXsCEV4ybGBdBe6wH1a2Xozc55F2 -user[42]privKeyBase58=177gjt2b87GPSS8eFctAkPELqWg6PhXkeBN1eeyDHtacC8YN9pQMB7X53PsnkQr6ZKdKBRR -user[42]pubKeyBase58=endPsK36qQjdrLEjkd3ukEBTJN6DAZQFxWhKH5iZuwAhAUgUK6bC -user[43]privKeyBase58=177gjwtLzpD6nPUzwr8V1L28sxPyBBScLoDdWhKSWeyfsyVqyuR31eroxjyjVcZpFFWMefa -user[43]pubKeyBase58=endPsK36cKze8GEMCQdMaHueetv3VMr6WRh3mTTeKN3TSkUitqTd -user[44]privKeyBase58=177gju6CW6A6WbTD9SDEXDgTAkdJQEh65qiULbvwJSoCNrcvaRqRebZ3AjdmaRqHWFQqHMN -user[44]pubKeyBase58=endPsK36r3jc7212WrVUAxkoz3DMVZSnhGSovT84EJESSo7sAGo5 -user[45]privKeyBase58=177gjuK9Dn1AYL9GzATY26xdKVcdNSiLNcb4h2He5QWebh3czW8Z2ZBPZDh6aJ1CvDHokPH -user[45]pubKeyBase58=endPsK36ihMZ4WDY3g7LN1N4MuAQYBiCZfiDYBVcsQNk3LQtyS3s -user[46]privKeyBase58=177gjzuuC7XSuFySNnuG4Vdxq9KiXKnEze6r3gS6142AtVdcLBcFGEiEKSoxN79LZioXxGP -user[46]pubKeyBase58=endPsK36jwD38VaqUEJX3BScdhTWz8t4JeRPAJvHmk8ohjNCY6a3 -user[47]privKeyBase58=177gjwK2m3Xut94h7apKB9wJJTL4VMogUhDM4L9A6iBpGhvQsNK2g2b2zakeuUhNRVbvVSN -user[47]pubKeyBase58=endPsK36mzgNV7LrB6uH3dwqsBp5V65YjimrFQNPNqHTWUbRuca9 -user[48]privKeyBase58=177gjxucknnafMMd7xQFGgTtVvgKLmRV5zCKj9uPPsiHhXVnb9WDemjmedf13rTsrwcXi5J -user[48]pubKeyBase58=endPsK36qEgVVZYjMzFRxKEaqmdfHDVrEfC6EaLQWDXJgpNjdRhr -user[49]privKeyBase58=177gjtE4XqdWT4duP34L8p1PpLfSumuPwWQnbYdzv8qwW2JJXYt9FpvedYgK7C8zvofM9Q8 -user[49]pubKeyBase58=endPsK36o9VZGMzJmgK8hFR3dFjE94QQNDRPVbsnugB46mhZ4nJQ -user[50]privKeyBase58=177gk2BLKbHnM6xjikbBa2i9uibkJP65Wd2hZQB69fChaxBNMo2GiZjqJbtaxCGwQsBEXUw -user[50]pubKeyBase58=endPsK36eV7Cm6Py8zRg8EfowKDf52mjCbAZdjgezim2Ubj6QVvE -user[51]privKeyBase58=177gjyiWv6wZ1GwMzHw94LJXZdMb7HHRV6XseQM4Be44ffaBVv6GuKpFQLRpQU35hBB4WcT -user[51]pubKeyBase58=endPsK36bkC8rzNy1kBgvv1x7yTHxARegtddrcBm4MRezJnTbzYf -user[52]privKeyBase58=177gjxhwn23LwwjN2Nu3pnN7R1skSukrGqyquDMf5LBxHJQ6RqJzscpXZNu2hTa8AHBaX29 -user[52]pubKeyBase58=endPsK36hAw55q6e3Fn1bkqQwYbW3goYUDs5HAXVM3PtNzxHoh1y -user[53]privKeyBase58=177gjwSd4r9pyJEazwM2ur1sBm3tkCEGifMFPjmPZqZcoTxyy711a2kvgrAiFFu9fMuphit -user[53]pubKeyBase58=endPsK36qkt9RiY2E6RCrwhDuGh5V6K3ZnvcspFuu7xLYvd9b3BS -user[54]privKeyBase58=177gjsD52ce6yn2oZWt21Q7Z6TGovc6eLSD415E99kk6gghAU2VwKH2L7E3gcQh31JHS2Ct -user[54]pubKeyBase58=endPsK36t48ddNpAjpez8b5TFocL4Qm16EyNyv3DqJAABcgJSuys -user[55]privKeyBase58=177gjwzeLxFNECpTsZgaHj7asXDw2tfA6ARDemXLuQJcEyPd24trrvbw59gWNqkRCZ9toqM -user[55]pubKeyBase58=endPsK36qfjKsFh1jsSfT2MKCMwrabYCpKmT3YBd7WbCkRdeLpcW -user[56]privKeyBase58=177gjsefMKGDuAGp29VFQk71yZNhR6zVDejV13R2tfNkhM7b3ftT8htfPdk8axdWBN96p5u -user[56]pubKeyBase58=endPsK36fbEiN5bZfdbiSYt56NvCwhhVHEBuzCHrdn3bUe3HBQp6 -user[57]privKeyBase58=177gjwQGxVjAdzb21Ktm6wNeyKskLppREjtwVxJpwgUYB5FQWJb96qyV9opBjdrs4DFhbHb -user[57]pubKeyBase58=endPsK36ePXN8pAmW7ZnXqu5eCuMa2Xnh9byXHGofpFVsSj1guCM -user[58]privKeyBase58=177gjxRcVAPULLEc6DNZzaimCKz1y6PcfotrKeH5TKpVK1trekX9xjbG3MG6aSgvgrmTGuc -user[58]pubKeyBase58=endPsK36oUSQMP6VTEJjv3bVgtF3mKstRiQFr9dtFx4RHfXaZUkQ -user[59]privKeyBase58=177gjtSeghrFfEeeicuoNFW4ciTJaBWRgdQ4Unp18uUA1uMwjptvjEWnyio2da5u611rRGH -user[59]pubKeyBase58=endPsK36ez3ihRJYW8m5rN4pi4f74cvJbwe8bZ4acNKZLvWX6UsN -user[60]privKeyBase58=177gjzuueMnccbKkoj6EnZxXZhtySEUqWe7Y9qdDPjEKTHEzJvZLWCmgDCADCbBSG7595qm -user[60]pubKeyBase58=endPsK36jmL17it2cqcjjqEuev4bKGBtKhqaRHgTiQHakytGDU3H -user[61]privKeyBase58=177gjuDD2rqj5kyXTJ4effaABK3FUDUNeRJXH4RFv7yQoQ7yqvVkFPUCiWoDAu1F3Rde4hq -user[61]pubKeyBase58=endPsK36rcaHXedAuHARU3Zy5E1UTKvE9Yr5yrp36DPP8Ge7VsCz -user[62]privKeyBase58=177gjuYzszWekfBatM3yg23fVDYHKkoTKTVP6PCQfFDQTfDZN7bTd7DKMr3fQvXrVC3d8Je -user[62]pubKeyBase58=endPsK36tQXnk4u9Tw9Gm4CDUTDPuag2qv6Yyn3RoBqPgD9zxjax -user[63]privKeyBase58=177gjzS5W8CZdhduphojGqeQgp3ZtwGkfRVwWQpTN6K5cUWRM2F4hwUrfURu4nrixf5V418 -user[63]pubKeyBase58=endPsK36q36veT5yUTKkBkhyDhXzWRRLNDjR9fEbWTiD5Eoy8ygN \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/0/local-bftsmart-0.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/0/local-bftsmart-0.conf deleted file mode 100644 index 751c76f3..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/0/local-bftsmart-0.conf +++ /dev/null @@ -1,26 +0,0 @@ -#当前参与方的 id -local.parti.id=0 - -#当前参与方的公钥 -local.parti.pubkey=endPsK36hceJEHbT876oATzGzkM2Wj1fpCzUgcbXWZ5iu1M3XTCf - -#当前参与方的私钥(密文编码) -local.parti.privkey=177gk1jTpc8qhaNtNn3Gku36zHL21WhQ7UjuCzVNBULuRgDeMrje9Av2SGgUmwgYbKNeguE - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入 -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录 -ledger.binding.out=/Users/shaozhuguang/Documents/ideaProjects/jdchain-release/source/test/test-integration/target/test-classes/bftsmart/conf/0 - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///Users/shaozhuguang/Documents/ideaProjects/jdchain-release/source/test/test-integration/bftsmart-rocks.db/rocksdb0.db - -#账本数据库的连接口令 -ledger.db.pwd= - -#共识配置文件路径 -consensus.conf=/Users/shaozhuguang/Documents/ideaProjects/jdchain-release/source/test/test-integration/target/test-classes/bftsmart/bftsmart-4.config - -#共识Providers配置 -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/1/local-bftsmart-1.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/1/local-bftsmart-1.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/1/local-bftsmart-1.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/10/local-bftsmart-10.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/10/local-bftsmart-10.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/10/local-bftsmart-10.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/11/local-bftsmart-11.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/11/local-bftsmart-11.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/11/local-bftsmart-11.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/12/local-bftsmart-12.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/12/local-bftsmart-12.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/12/local-bftsmart-12.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/13/local-bftsmart-13.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/13/local-bftsmart-13.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/13/local-bftsmart-13.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/14/local-bftsmart-14.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/14/local-bftsmart-14.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/14/local-bftsmart-14.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/15/local-bftsmart-15.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/15/local-bftsmart-15.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/15/local-bftsmart-15.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/16/local-bftsmart-16.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/16/local-bftsmart-16.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/16/local-bftsmart-16.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/17/local-bftsmart-17.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/17/local-bftsmart-17.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/17/local-bftsmart-17.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/18/local-bftsmart-18.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/18/local-bftsmart-18.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/18/local-bftsmart-18.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/19/local-bftsmart-19.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/19/local-bftsmart-19.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/19/local-bftsmart-19.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/2/local-bftsmart-2.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/2/local-bftsmart-2.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/2/local-bftsmart-2.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/20/local-bftsmart-20.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/20/local-bftsmart-20.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/20/local-bftsmart-20.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/21/local-bftsmart-21.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/21/local-bftsmart-21.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/21/local-bftsmart-21.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/22/local-bftsmart-22.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/22/local-bftsmart-22.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/22/local-bftsmart-22.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/23/local-bftsmart-23.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/23/local-bftsmart-23.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/23/local-bftsmart-23.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/24/local-bftsmart-24.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/24/local-bftsmart-24.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/24/local-bftsmart-24.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/25/local-bftsmart-25.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/25/local-bftsmart-25.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/25/local-bftsmart-25.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/26/local-bftsmart-26.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/26/local-bftsmart-26.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/26/local-bftsmart-26.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/27/local-bftsmart-27.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/27/local-bftsmart-27.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/27/local-bftsmart-27.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/28/local-bftsmart-28.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/28/local-bftsmart-28.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/28/local-bftsmart-28.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/29/local-bftsmart-29.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/29/local-bftsmart-29.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/29/local-bftsmart-29.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/3/local-bftsmart-3.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/3/local-bftsmart-3.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/3/local-bftsmart-3.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/30/local-bftsmart-30.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/30/local-bftsmart-30.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/30/local-bftsmart-30.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/31/local-bftsmart-31.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/31/local-bftsmart-31.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/31/local-bftsmart-31.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/32/local-bftsmart-32.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/32/local-bftsmart-32.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/32/local-bftsmart-32.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/33/local-bftsmart-33.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/33/local-bftsmart-33.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/33/local-bftsmart-33.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/34/local-bftsmart-34.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/34/local-bftsmart-34.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/34/local-bftsmart-34.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/35/local-bftsmart-35.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/35/local-bftsmart-35.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/35/local-bftsmart-35.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/36/local-bftsmart-36.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/36/local-bftsmart-36.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/36/local-bftsmart-36.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/37/local-bftsmart-37.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/37/local-bftsmart-37.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/37/local-bftsmart-37.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/38/local-bftsmart-38.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/38/local-bftsmart-38.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/38/local-bftsmart-38.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/39/local-bftsmart-39.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/39/local-bftsmart-39.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/39/local-bftsmart-39.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/4/local-bftsmart-4.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/4/local-bftsmart-4.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/4/local-bftsmart-4.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/40/local-bftsmart-40.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/40/local-bftsmart-40.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/40/local-bftsmart-40.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/41/local-bftsmart-41.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/41/local-bftsmart-41.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/41/local-bftsmart-41.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/42/local-bftsmart-42.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/42/local-bftsmart-42.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/42/local-bftsmart-42.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/43/local-bftsmart-43.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/43/local-bftsmart-43.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/43/local-bftsmart-43.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/44/local-bftsmart-44.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/44/local-bftsmart-44.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/44/local-bftsmart-44.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/45/local-bftsmart-45.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/45/local-bftsmart-45.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/45/local-bftsmart-45.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/46/local-bftsmart-46.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/46/local-bftsmart-46.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/46/local-bftsmart-46.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/47/local-bftsmart-47.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/47/local-bftsmart-47.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/47/local-bftsmart-47.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/48/local-bftsmart-48.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/48/local-bftsmart-48.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/48/local-bftsmart-48.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/49/local-bftsmart-49.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/49/local-bftsmart-49.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/49/local-bftsmart-49.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/5/local-bftsmart-5.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/5/local-bftsmart-5.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/5/local-bftsmart-5.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/50/local-bftsmart-50.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/50/local-bftsmart-50.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/50/local-bftsmart-50.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/51/local-bftsmart-51.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/51/local-bftsmart-51.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/51/local-bftsmart-51.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/52/local-bftsmart-52.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/52/local-bftsmart-52.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/52/local-bftsmart-52.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/53/local-bftsmart-53.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/53/local-bftsmart-53.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/53/local-bftsmart-53.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/54/local-bftsmart-54.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/54/local-bftsmart-54.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/54/local-bftsmart-54.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/55/local-bftsmart-55.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/55/local-bftsmart-55.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/55/local-bftsmart-55.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/56/local-bftsmart-56.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/56/local-bftsmart-56.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/56/local-bftsmart-56.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/57/local-bftsmart-57.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/57/local-bftsmart-57.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/57/local-bftsmart-57.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/58/local-bftsmart-58.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/58/local-bftsmart-58.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/58/local-bftsmart-58.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/59/local-bftsmart-59.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/59/local-bftsmart-59.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/59/local-bftsmart-59.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/6/local-bftsmart-6.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/6/local-bftsmart-6.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/6/local-bftsmart-6.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/60/local-bftsmart-60.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/60/local-bftsmart-60.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/60/local-bftsmart-60.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/61/local-bftsmart-61.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/61/local-bftsmart-61.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/61/local-bftsmart-61.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/62/local-bftsmart-62.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/62/local-bftsmart-62.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/62/local-bftsmart-62.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/63/local-bftsmart-63.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/63/local-bftsmart-63.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/63/local-bftsmart-63.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/7/local-bftsmart-7.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/7/local-bftsmart-7.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/7/local-bftsmart-7.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/8/local-bftsmart-8.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/8/local-bftsmart-8.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/8/local-bftsmart-8.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/conf/9/local-bftsmart-9.conf b/source/test/test-integration/src/test/resources/bftsmart/conf/9/local-bftsmart-9.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/conf/9/local-bftsmart-9.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-16.init b/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-16.init deleted file mode 100644 index e65e8595..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-16.init +++ /dev/null @@ -1,10 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -#ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=16 - -###############cons_parti_configs############### \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-32.init b/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-32.init deleted file mode 100644 index 3820cf5e..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-32.init +++ /dev/null @@ -1,10 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -#ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=32 - -###############cons_parti_configs############### \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-4.init b/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-4.init deleted file mode 100644 index 41a48616..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-4.init +++ /dev/null @@ -1,10 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -#ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -###############cons_parti_configs############### \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-64.init b/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-64.init deleted file mode 100644 index 405ea0fd..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-64.init +++ /dev/null @@ -1,10 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -#ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=64 - -###############cons_parti_configs############### \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-8.init b/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-8.init deleted file mode 100644 index 861d9fba..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/ledger_init_bftsmart-8.init +++ /dev/null @@ -1,10 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -#ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=8 - -###############cons_parti_configs############### \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-0.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-0.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-0.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-1.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-1.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-1.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-10.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-10.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-10.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-11.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-11.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-11.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-12.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-12.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-12.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-13.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-13.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-13.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-14.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-14.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-14.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-15.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-15.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-15.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-16.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-16.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-16.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-17.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-17.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-17.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-18.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-18.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-18.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-19.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-19.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-19.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-2.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-2.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-2.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-20.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-20.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-20.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-21.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-21.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-21.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-22.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-22.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-22.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-23.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-23.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-23.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-24.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-24.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-24.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-25.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-25.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-25.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-26.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-26.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-26.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-27.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-27.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-27.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-28.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-28.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-28.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-29.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-29.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-29.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-3.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-3.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-3.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-30.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-30.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-30.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-31.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-31.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-31.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-32.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-32.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-32.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-33.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-33.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-33.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-34.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-34.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-34.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-35.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-35.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-35.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-36.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-36.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-36.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-37.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-37.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-37.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-38.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-38.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-38.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-39.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-39.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-39.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-4.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-4.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-4.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-40.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-40.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-40.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-41.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-41.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-41.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-42.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-42.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-42.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-43.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-43.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-43.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-44.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-44.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-44.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-45.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-45.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-45.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-46.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-46.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-46.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-47.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-47.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-47.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-48.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-48.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-48.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-49.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-49.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-49.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-5.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-5.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-5.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-50.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-50.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-50.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-51.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-51.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-51.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-52.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-52.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-52.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-53.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-53.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-53.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-54.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-54.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-54.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-55.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-55.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-55.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-56.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-56.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-56.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-57.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-57.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-57.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-58.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-58.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-58.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-59.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-59.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-59.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-6.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-6.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-6.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-60.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-60.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-60.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-61.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-61.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-61.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-62.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-62.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-62.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-63.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-63.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-63.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-7.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-7.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-7.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-8.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-8.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-8.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-9.conf b/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-9.conf deleted file mode 100644 index 6f399577..00000000 --- a/source/test/test-integration/src/test/resources/bftsmart/local-bftsmart-9.conf +++ /dev/null @@ -1,38 +0,0 @@ -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsuHdbf3PU68Sm1ZU2aMcyB7sLWj94xwBUoUKvTgHq7qGUfg6ynDB62hocYYXSRXD4X - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=../conf/ - -#账本数据库的连接字符 -ledger.db.uri=rocksdb:///export/App08/peer/rocks.db/rocksdb0.db - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf=../conf/init/system.config - -//ledger.base.server=nats://192.168.151.39:4222 -ledger.base.server=rabbit://192.168.151.39:5672 - -#MQ订阅交易主题; -ledger.base.topic.tx=tx-topic - -#MQ订阅交易结块主题; -ledger.base.topic.bl=bl-topic - -#当前开启的共识算法;msg-queue/bft-smart -ledger.consensus.type=msg-queue - -#发起结块的交易数间隔; -ledger.commit.interv.tx=10 - -#发起结块的时间间隔,单位ms; -ledger.commit.interv.ts=5000 diff --git a/source/test/test-integration/src/test/resources/contract-read.jar b/source/test/test-integration/src/test/resources/contract-read.jar deleted file mode 100644 index ddf9c668..00000000 Binary files a/source/test/test-integration/src/test/resources/contract-read.jar and /dev/null differ diff --git a/source/test/test-integration/src/test/resources/contract.jar b/source/test/test-integration/src/test/resources/contract.jar deleted file mode 100644 index ba409a52..00000000 Binary files a/source/test/test-integration/src/test/resources/contract.jar and /dev/null differ diff --git a/source/test/test-integration/src/test/resources/jdchain.policy b/source/test/test-integration/src/test/resources/jdchain.policy deleted file mode 100644 index a76a7d6f..00000000 --- a/source/test/test-integration/src/test/resources/jdchain.policy +++ /dev/null @@ -1,13 +0,0 @@ -grant codeBase "file:${java.ext.dirs}/*" { - permission java.security.AllPermission; -}; -grant codeBase "file:/E:/gitCode\\block\\prototype\\source\\*" { - permission java.security.AllPermission; -}; -grant { - permission java.io.FilePermission "f:\\tmp\\1.txt", "read"; - permission java.util.PropertyPermission "file.encoding", "read"; - permission java.lang.RuntimePermission "setSecurityManager"; - permission java.util.PropertyPermission "*", " read,write"; - permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; -}; diff --git a/source/test/test-integration/src/test/resources/keys/parti2.pub b/source/test/test-integration/src/test/resources/keys/parti2.pub deleted file mode 100644 index dde44b8e..00000000 --- a/source/test/test-integration/src/test/resources/keys/parti2.pub +++ /dev/null @@ -1 +0,0 @@ -3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-mem-0.conf b/source/test/test-integration/src/test/resources/ledger-binding-mem-0.conf deleted file mode 100644 index 0c79d2ba..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-mem-0.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=0 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=a.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeP3fY7jJbNwL8CiL2wU21AF9unDWQjVEW5w -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=memory://local/0 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-mem-1.conf b/source/test/test-integration/src/test/resources/ledger-binding-mem-1.conf deleted file mode 100644 index 8c0b420f..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-mem-1.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=1 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=b.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNnz88dH6CA6PwkVdn3nFRibUKP3sFT2byG -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=memory://local/1 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-mem-2.conf b/source/test/test-integration/src/test/resources/ledger-binding-mem-2.conf deleted file mode 100644 index 8605cdb8..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-mem-2.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=2 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=c.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNmdpT4DiTwLUP9jRQhwdRBRiXeHno456vy -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=memory://local/2 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-mem-3.conf b/source/test/test-integration/src/test/resources/ledger-binding-mem-3.conf deleted file mode 100644 index bfc77145..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-mem-3.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=3 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=d.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNekdXMHqyz9Qxc2jDSBnkvvZLbty6pRDdP -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=memory://local/3 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-redis-0.conf b/source/test/test-integration/src/test/resources/ledger-binding-redis-0.conf deleted file mode 100644 index 958d8846..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-redis-0.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=0 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=a.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeP3fY7jJbNwL8CiL2wU21AF9unDWQjVEW5w -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=redis://192.168.54.112:6379 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-redis-1.conf b/source/test/test-integration/src/test/resources/ledger-binding-redis-1.conf deleted file mode 100644 index c311a690..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-redis-1.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=1 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=b.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNnz88dH6CA6PwkVdn3nFRibUKP3sFT2byG -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=redis://192.168.54.112:6379/1 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-redis-2.conf b/source/test/test-integration/src/test/resources/ledger-binding-redis-2.conf deleted file mode 100644 index d5a8ce58..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-redis-2.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=2 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=c.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNmdpT4DiTwLUP9jRQhwdRBRiXeHno456vy -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=redis://192.168.54.112:6379/2 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-redis-3.conf b/source/test/test-integration/src/test/resources/ledger-binding-redis-3.conf deleted file mode 100644 index 68ef1bd3..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-redis-3.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=3 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=d.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNekdXMHqyz9Qxc2jDSBnkvvZLbty6pRDdP -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=redis://192.168.54.112:6379/3 -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-0.conf b/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-0.conf deleted file mode 100644 index 73ac4731..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-0.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=0 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=a.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeP3fY7jJbNwL8CiL2wU21AF9unDWQjVEW5w -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=rocksdb -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-1.conf b/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-1.conf deleted file mode 100644 index 9af1f941..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-1.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=1 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=b.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNnz88dH6CA6PwkVdn3nFRibUKP3sFT2byG -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=rocksdb -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-2.conf b/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-2.conf deleted file mode 100644 index 087955da..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-2.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=2 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=c.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNmdpT4DiTwLUP9jRQhwdRBRiXeHno456vy -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=rocksdb -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-3.conf b/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-3.conf deleted file mode 100644 index 2e27c865..00000000 --- a/source/test/test-integration/src/test/resources/ledger-binding-rocksdb-3.conf +++ /dev/null @@ -1,23 +0,0 @@ -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ - - -#第 1 个账本[6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ]的配置; -#账本的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.name=myledger -#账本的当前共识参与方的ID; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.id=3 -#账本的当前共识参与方的名字; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.name=d.com -#账本的当前共识参与方的私钥文件的保存路径; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk-path= -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pk=177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY -#账本的当前共识参与方地址 -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.parti.address=LdeNekdXMHqyz9Qxc2jDSBnkvvZLbty6pRDdP -#账本的存储数据库的连接字符串; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.uri=rocksdb -#账本的存储数据库的连接口令; -binding.6BCg5vgU57ykY6g2CpyUnt5ZMgdxfD1b3qXxQrRyfiXTQ.db.pwd= \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/ledger.init b/source/test/test-integration/src/test/resources/ledger.init deleted file mode 100644 index 48e74994..00000000 --- a/source/test/test-integration/src/test/resources/ledger.init +++ /dev/null @@ -1,96 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name= - -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=true -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=true - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=classpath:keys/parti2.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey= -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=true - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/test/resources/ledger_init_test.init b/source/test/test-integration/src/test/resources/ledger_init_test.init deleted file mode 100644 index 4253311e..00000000 --- a/source/test/test-integration/src/test/resources/ledger_init_test.init +++ /dev/null @@ -1,162 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name=TEST-LEDGER - -#声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - -#----------------------------------------------- -# 初始的角色名称列表;可选项; -# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; -# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; -# -# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; -# -security.roles=DEFAULT, ADMIN, MANAGER, GUEST - -# 赋予角色的账本权限清单;可选项; -# 可选的权限如下; -# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, -# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, -# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -# APPROVE_TX, CONSENSUS_TX -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT - -# 赋予角色的交易权限清单;可选项; -# 可选的权限如下; -# DIRECT_OPERATION, CONTRACT_OPERATION -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 其它角色的配置示例; -# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; -security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER -security.role.ADMIN.tx-privileges=DIRECT_OPERATION - -# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; -security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; -security.role.GUEST.ledger-privileges= -security.role.GUEST.tx-privileges=CONTRACT_OPERATION - - - -#----------------------------------------------- -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - -#从存储中加载账本数据时,是否校验哈希;可选; -crypto.verify-hash=true - -#哈希算法; -crypto.hash-algorithm=SHA256 - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的角色清单;可选项; -cons_parti.0.roles=ADMIN, MANAGER -#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.0.roles-policy=UNION -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=false -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的角色清单;可选项; -cons_parti.1.roles=MANAGER -#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.1.roles-policy=UNION -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的角色清单;可选项; -cons_parti.2.roles=MANAGER -#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.2.roles-policy=UNION -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的角色清单;可选项; -cons_parti.3.roles=GUEST -#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.3.roles-policy=INTERSECT -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/test/resources/ledger_init_test_integration.init b/source/test/test-integration/src/test/resources/ledger_init_test_integration.init deleted file mode 100644 index 24499052..00000000 --- a/source/test/test-integration/src/test/resources/ledger_init_test_integration.init +++ /dev/null @@ -1,88 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name= - -#声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=false -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=10100 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=10110 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=10120 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=10130 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/test/resources/ledger_init_test_web1.init b/source/test/test-integration/src/test/resources/ledger_init_test_web1.init deleted file mode 100644 index 09274151..00000000 --- a/source/test/test-integration/src/test/resources/ledger_init_test_web1.init +++ /dev/null @@ -1,88 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name= - -#声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=false -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=7800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=7810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=7820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=7830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/test/resources/ledger_init_test_web2-role.init b/source/test/test-integration/src/test/resources/ledger_init_test_web2-role.init deleted file mode 100644 index 634a27ca..00000000 --- a/source/test/test-integration/src/test/resources/ledger_init_test_web2-role.init +++ /dev/null @@ -1,133 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name==myledger - -#声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - -#----------------------------------------------- -# 初始的角色名称列表;可选项; -# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; -# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; -# -# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; -# -security.roles=DEFAULT, ADMIN, MANAGER, GUEST - -# 赋予角色的账本权限清单;可选项; -# 可选的权限如下; -# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, -# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, -# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -# APPROVE_TX, CONSENSUS_TX -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT - -# 赋予角色的交易权限清单;可选项; -# 可选的权限如下; -# DIRECT_OPERATION, CONTRACT_OPERATION -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 其它角色的配置示例; -# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; -security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER, APPROVE_TX,REGISTER_DATA_ACCOUNT,WRITE_DATA_ACCOUNT -security.role.ADMIN.tx-privileges=DIRECT_OPERATION - -# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; -security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, APPROVE_TX,REGISTER_PARTICIPANT -security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; -security.role.GUEST.ledger-privileges=APPROVE_TX,REGISTER_DATA_ACCOUNT,CONFIGURE_ROLES -security.role.GUEST.tx-privileges=CONTRACT_OPERATION,DIRECT_OPERATION - - - -#----------------------------------------------- - -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的角色清单;可选项; -cons_parti.0.roles=ADMIN, MANAGER -#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.0.roles-policy=INTERSECT -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=9800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的角色清单;可选项; -cons_parti.1.roles=MANAGER -#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.1.roles-policy=UNION -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=9810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的角色清单;可选项; -cons_parti.2.roles=MANAGER -#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.2.roles-policy=UNION -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=9820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的角色清单;可选项; -cons_parti.3.roles=GUEST -#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.3.roles-policy=INTERSECT -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=9830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/test/resources/ledger_init_test_web2.init b/source/test/test-integration/src/test/resources/ledger_init_test_web2.init deleted file mode 100644 index 5be0e69d..00000000 --- a/source/test/test-integration/src/test/resources/ledger_init_test_web2.init +++ /dev/null @@ -1,74 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name==myledger - -#声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=9800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=9810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=9820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=9830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-integration/src/test/resources/log4j2.xml b/source/test/test-integration/src/test/resources/log4j2.xml deleted file mode 100644 index 8e40da20..00000000 --- a/source/test/test-integration/src/test/resources/log4j2.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/test/test-integration/src/test/resources/mq.config b/source/test/test-integration/src/test/resources/mq.config deleted file mode 100644 index 9bd3238e..00000000 --- a/source/test/test-integration/src/test/resources/mq.config +++ /dev/null @@ -1,12 +0,0 @@ -system.msg.queue.server=rabbit://192.168.151.40:5672 -system.msg.queue.topic.tx=tx-topic-3 -system.msg.queue.topic.bl=bl-topic-3 -system.msg.queue.topic.msg=msg-topic-3 -system.msg.queue.block.txsize=1000 -system.msg.queue.block.maxdelay=2000 - -system.servers.num=4 -system.server.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -system.server.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -system.server.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -system.server.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk diff --git a/source/test/test-integration/src/test/resources/system.config b/source/test/test-integration/src/test/resources/system.config deleted file mode 100644 index ada42b49..00000000 --- a/source/test/test-integration/src/test/resources/system.config +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage diff --git a/source/test/test-ledger/src/main/java/test/perf/com/jd/blockchain/ledger/MerkleDatasetPerformanceTester.java b/source/test/test-ledger/src/main/java/test/perf/com/jd/blockchain/ledger/MerkleDatasetPerformanceTester.java deleted file mode 100644 index a71efcee..00000000 --- a/source/test/test-ledger/src/main/java/test/perf/com/jd/blockchain/ledger/MerkleDatasetPerformanceTester.java +++ /dev/null @@ -1,185 +0,0 @@ -package test.perf.com.jd.blockchain.ledger; - -import java.io.IOException; -import java.util.Random; - -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.MerkleDataSet; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.ExPolicyKVStorage; -import com.jd.blockchain.storage.service.VersioningKVStorage; -import com.jd.blockchain.storage.service.impl.redis.RedisConnectionFactory; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.utils.Bytes; - -public class MerkleDatasetPerformanceTester { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName() }; - - private static final String MKL_KEY_PREFIX = ""; - - public static void main(String[] args) { - testPerformanceInMemory(); - - // testPerformanceWithRedis(); - } - - public static void testPerformanceInMemory() { - testInsertPerformanceInMermory(1000, 1); - testInsertPerformanceInMermory(10000, 1); - testInsertPerformanceInMermory(20000, 1); - testInsertPerformanceInMermory(40000, 1); - // testInsertPerformance(80000, 1); - // testInsertPerformance(100000, 1); - // testInsertPerformance(1000000, 1); - - System.out.println("============================================================"); - - testInsertPerformanceInMermory(500, 4); - testInsertPerformanceInMermory(1000, 4); - testInsertPerformanceInMermory(10000, 4); - testInsertPerformanceInMermory(20000, 4); - // testInsertPerformance(40000, 4); - // testInsertPerformance(80000, 4); - System.out.println("============================================================"); - testInsertPerformanceInMermory(100, 10); - testInsertPerformanceInMermory(1000, 10); - testInsertPerformanceInMermory(2000, 10); - testInsertPerformanceInMermory(4000, 10); - testInsertPerformanceInMermory(2000, 20); - testInsertPerformanceInMermory(200, 20); - testInsertPerformanceInMermory(4000, 20); - testInsertPerformanceInMermory(400, 20); - // testInsertPerformance(8000, 10); - System.out.println("============================================================"); - testInsertPerformanceInMermory(100, 100); - testInsertPerformanceInMermory(100, 1000); - testInsertPerformanceInMermory(100, 10000); - System.out.println("============================================================"); - testInsertPerformanceInMermory(20, 4); - testInsertPerformanceInMermory(20, 8); - testInsertPerformanceInMermory(20, 10); - testInsertPerformanceInMermory(20, 20); - testInsertPerformanceInMermory(20, 40); - testInsertPerformanceInMermory(20, 100); - testInsertPerformanceInMermory(20, 400); - testInsertPerformanceInMermory(20, 1000); - } - - public static void testPerformanceWithRedis() { - String redisUri = "redis://127.0.0.1:6379/0"; - RedisConnectionFactory connFact = new RedisConnectionFactory(); - try (DbConnection conn = connFact.connect(redisUri)) { - ExPolicyKVStorage exStorage = conn.getStorageService().getExPolicyKVStorage(); - VersioningKVStorage verStorage = conn.getStorageService().getVersioningKVStorage(); - - testInsertPerformance(1000, 1, exStorage, verStorage); - testInsertPerformance(10000, 1, exStorage, verStorage); - testInsertPerformance(20000, 1, exStorage, verStorage); - testInsertPerformance(40000, 1, exStorage, verStorage); - // testInsertPerformance(80000, 1,exStorage, verStorage); - // testInsertPerformance(100000, 1,exStorage, verStorage); - // testInsertPerformance(1000000, 1,exStorage, verStorage); - - System.out.println("============================================================"); - - testInsertPerformance(500, 4, exStorage, verStorage); - testInsertPerformance(1000, 4, exStorage, verStorage); - testInsertPerformance(10000, 4, exStorage, verStorage); - testInsertPerformance(20000, 4, exStorage, verStorage); - // testInsertPerformance(40000, 4,exStorage, verStorage); - // testInsertPerformance(80000, 4,exStorage, verStorage); - System.out.println("============================================================"); - testInsertPerformance(100, 10, exStorage, verStorage); - testInsertPerformance(1000, 10, exStorage, verStorage); - testInsertPerformance(2000, 10, exStorage, verStorage); - testInsertPerformance(4000, 10, exStorage, verStorage); - testInsertPerformance(2000, 20, exStorage, verStorage); - testInsertPerformance(200, 20, exStorage, verStorage); - testInsertPerformance(4000, 20, exStorage, verStorage); - testInsertPerformance(400, 20, exStorage, verStorage); - // testInsertPerformance(8000, 10,exStorage, verStorage); - System.out.println("============================================================"); - testInsertPerformance(100, 100, exStorage, verStorage); - testInsertPerformance(100, 1000, exStorage, verStorage); - testInsertPerformance(100, 10000, exStorage, verStorage); - System.out.println("============================================================"); - testInsertPerformance(20, 4, exStorage, verStorage); - testInsertPerformance(20, 8, exStorage, verStorage); - testInsertPerformance(20, 10, exStorage, verStorage); - testInsertPerformance(20, 20, exStorage, verStorage); - testInsertPerformance(20, 40, exStorage, verStorage); - testInsertPerformance(20, 100, exStorage, verStorage); - testInsertPerformance(20, 400, exStorage, verStorage); - testInsertPerformance(20, 1000, exStorage, verStorage); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public static void testInsertPerformanceInMermory(int round, int batchCount) { - // Map storageMap1 = new HashMap<>(); - // ExPolicyKVStorage exStorage = new ExistancePolicyKVStorageMap(storageMap1); - // Map storageMap2 = new HashMap<>(); - // VersioningKVStorage verStorage = new VersioningKVStorageMap(storageMap2); - MemoryKVStorage memoryKVStorage = new MemoryKVStorage(); - testInsertPerformance(round, batchCount, memoryKVStorage, memoryKVStorage); - } - - public static void testInsertPerformance(int round, int batchCount, ExPolicyKVStorage exStorage, - VersioningKVStorage verStorage) { - Random rand = new Random(); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(supportedProviders); - cryptoConfig.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); - cryptoConfig.setAutoVerifyHash(true); - - // generate base data sample; - String key; - byte[] data = new byte[64]; - rand.nextBytes(data); - - long startTs = System.currentTimeMillis(); - HashDigest rootHash; - int randomId = rand.nextInt(1000); - MerkleDataSet mds = new MerkleDataSet(cryptoConfig, MKL_KEY_PREFIX, exStorage, verStorage); - for (int i = 0; i < round; i++) { - for (int j = 0; j < batchCount; j++) { - key = "data_" + startTs + "_" + randomId + "_" + (i * batchCount + j); - long v = mds.getVersion(Bytes.fromString(key)); - mds.setValue(Bytes.fromString(key), data, v); - } - mds.commit(); - rootHash = mds.getRootHash(); - mds = new MerkleDataSet(rootHash, cryptoConfig, Bytes.fromString(MKL_KEY_PREFIX), exStorage, verStorage, false); - } - - long elapsedTs = System.currentTimeMillis() - startTs; - - System.out.println(String.format( - "Inserted %s keys[round=%s, batchCount=%s], takes %s ms! -- TPS=%.2f, KPS=%.2f;", round * batchCount, - round, batchCount, elapsedTs, round * 1000.0D / elapsedTs, round * batchCount * 1000.0D / elapsedTs)); - - // int exKeys = storageMap1.size(); - // int verKeys = storageMap2.size(); - // System.out.println(String.format( - // "Inserted %s keys[round=%s, batchCount=%s], takes %s ms! -- TPS=%.2f, - // KPS=%.2f, " - // + "Total Storage Keys=%s [ex.count=%s, ver.count=%s];", - // round * batchCount, round, batchCount, elapsedTs, round * 1000.0D / - // elapsedTs, - // round * batchCount * 1000.0D / elapsedTs, exKeys + verKeys, exKeys, - // verKeys)); - } -} diff --git a/source/test/test-ledger/src/main/resources/MerkleDataset_Performance_Result_20180922.txt b/source/test/test-ledger/src/main/resources/MerkleDataset_Performance_Result_20180922.txt deleted file mode 100644 index 5a0e3450..00000000 --- a/source/test/test-ledger/src/main/resources/MerkleDataset_Performance_Result_20180922.txt +++ /dev/null @@ -1,119 +0,0 @@ - -Environment:Mac Book Pro(IDE + Redis Server 3.2.9); - - -============================================================================================== -======================================= In Memory : 1 ======================================== -============================================================================================== - -Inserted 1000 keys[round=1000, batchCount=1], takes 311 ms! -- TPS=3215.43, KPS=3215.43; -Inserted 10000 keys[round=10000, batchCount=1], takes 894 ms! -- TPS=11185.68, KPS=11185.68; -Inserted 20000 keys[round=20000, batchCount=1], takes 1367 ms! -- TPS=14630.58, KPS=14630.58; -Inserted 40000 keys[round=40000, batchCount=1], takes 2706 ms! -- TPS=14781.97, KPS=14781.97; -============================================================ -Inserted 2000 keys[round=500, batchCount=4], takes 34 ms! -- TPS=14705.88, KPS=58823.53; -Inserted 4000 keys[round=1000, batchCount=4], takes 72 ms! -- TPS=13888.89, KPS=55555.56; -Inserted 40000 keys[round=10000, batchCount=4], takes 811 ms! -- TPS=12330.46, KPS=49321.82; -Inserted 80000 keys[round=20000, batchCount=4], takes 1957 ms! -- TPS=10219.72, KPS=40878.90; -============================================================ -Inserted 1000 keys[round=100, batchCount=10], takes 12 ms! -- TPS=8333.33, KPS=83333.33; -Inserted 10000 keys[round=1000, batchCount=10], takes 118 ms! -- TPS=8474.58, KPS=84745.76; -Inserted 20000 keys[round=2000, batchCount=10], takes 226 ms! -- TPS=8849.56, KPS=88495.58; -Inserted 40000 keys[round=4000, batchCount=10], takes 468 ms! -- TPS=8547.01, KPS=85470.09; -Inserted 40000 keys[round=2000, batchCount=20], takes 384 ms! -- TPS=5208.33, KPS=104166.67; -Inserted 4000 keys[round=200, batchCount=20], takes 31 ms! -- TPS=6451.61, KPS=129032.26; -Inserted 80000 keys[round=4000, batchCount=20], takes 723 ms! -- TPS=5532.50, KPS=110650.07; -Inserted 8000 keys[round=400, batchCount=20], takes 65 ms! -- TPS=6153.85, KPS=123076.92; -============================================================ -Inserted 10000 keys[round=100, batchCount=100], takes 73 ms! -- TPS=1369.86, KPS=136986.30; -Inserted 100000 keys[round=100, batchCount=1000], takes 711 ms! -- TPS=140.65, KPS=140646.98; -Inserted 1000000 keys[round=100, batchCount=10000], takes 9096 ms! -- TPS=10.99, KPS=109938.43; -============================================================ -Inserted 80 keys[round=20, batchCount=4], takes 1 ms! -- TPS=20000.00, KPS=80000.00; -Inserted 160 keys[round=20, batchCount=8], takes 1 ms! -- TPS=20000.00, KPS=160000.00; -Inserted 200 keys[round=20, batchCount=10], takes 1 ms! -- TPS=20000.00, KPS=200000.00; -Inserted 400 keys[round=20, batchCount=20], takes 3 ms! -- TPS=6666.67, KPS=133333.33; -Inserted 800 keys[round=20, batchCount=40], takes 6 ms! -- TPS=3333.33, KPS=133333.33; -Inserted 2000 keys[round=20, batchCount=100], takes 13 ms! -- TPS=1538.46, KPS=153846.15; -Inserted 8000 keys[round=20, batchCount=400], takes 55 ms! -- TPS=363.64, KPS=145454.55; -Inserted 20000 keys[round=20, batchCount=1000], takes 164 ms! -- TPS=121.95, KPS=121951.22; - - -============================================================================================== -======================= In Redis : 1 [存量记录数:0][最终记录数:5161945] ======================== -============================================================================================== - -Inserted 1000 keys[round=1000, batchCount=1], takes 897 ms! -- TPS=1114.83, KPS=1114.83; -Inserted 10000 keys[round=10000, batchCount=1], takes 6293 ms! -- TPS=1589.07, KPS=1589.07; -Inserted 20000 keys[round=20000, batchCount=1], takes 12515 ms! -- TPS=1598.08, KPS=1598.08; -Inserted 40000 keys[round=40000, batchCount=1], takes 26683 ms! -- TPS=1499.08, KPS=1499.08; -============================================================ -Inserted 2000 keys[round=500, batchCount=4], takes 633 ms! -- TPS=789.89, KPS=3159.56; -Inserted 4000 keys[round=1000, batchCount=4], takes 1251 ms! -- TPS=799.36, KPS=3197.44; -Inserted 40000 keys[round=10000, batchCount=4], takes 13840 ms! -- TPS=722.54, KPS=2890.17; -Inserted 80000 keys[round=20000, batchCount=4], takes 27632 ms! -- TPS=723.80, KPS=2895.19; -============================================================ -Inserted 1000 keys[round=100, batchCount=10], takes 277 ms! -- TPS=361.01, KPS=3610.11; -Inserted 10000 keys[round=1000, batchCount=10], takes 2787 ms! -- TPS=358.81, KPS=3588.09; -Inserted 20000 keys[round=2000, batchCount=10], takes 5596 ms! -- TPS=357.40, KPS=3573.98; -Inserted 40000 keys[round=4000, batchCount=10], takes 11133 ms! -- TPS=359.29, KPS=3592.92; -Inserted 40000 keys[round=2000, batchCount=20], takes 10680 ms! -- TPS=187.27, KPS=3745.32; -Inserted 4000 keys[round=200, batchCount=20], takes 1036 ms! -- TPS=193.05, KPS=3861.00; -Inserted 80000 keys[round=4000, batchCount=20], takes 21045 ms! -- TPS=190.07, KPS=3801.38; -Inserted 8000 keys[round=400, batchCount=20], takes 2125 ms! -- TPS=188.24, KPS=3764.71; -============================================================ -Inserted 10000 keys[round=100, batchCount=100], takes 2614 ms! -- TPS=38.26, KPS=3825.55; -Inserted 100000 keys[round=100, batchCount=1000], takes 25076 ms! -- TPS=3.99, KPS=3987.88; -Inserted 1000000 keys[round=100, batchCount=10000], takes 250569 ms! -- TPS=0.40, KPS=3990.92; -============================================================ -Inserted 80 keys[round=20, batchCount=4], takes 25 ms! -- TPS=800.00, KPS=3200.00; -Inserted 160 keys[round=20, batchCount=8], takes 45 ms! -- TPS=444.44, KPS=3555.56; -Inserted 200 keys[round=20, batchCount=10], takes 58 ms! -- TPS=344.83, KPS=3448.28; -Inserted 400 keys[round=20, batchCount=20], takes 125 ms! -- TPS=160.00, KPS=3200.00; -Inserted 800 keys[round=20, batchCount=40], takes 227 ms! -- TPS=88.11, KPS=3524.23; -Inserted 2000 keys[round=20, batchCount=100], takes 537 ms! -- TPS=37.24, KPS=3724.39; -Inserted 8000 keys[round=20, batchCount=400], takes 2054 ms! -- TPS=9.74, KPS=3894.84; -Inserted 20000 keys[round=20, batchCount=1000], takes 5252 ms! -- TPS=3.81, KPS=3808.07; - - -============================================================================================== -======================= In Redis : 2 [存量记录数:3246278][最终记录数:8408223] ================== -============================================================================================== - -Inserted 1000 keys[round=1000, batchCount=1], takes 1084 ms! -- TPS=922.51, KPS=922.51; -Inserted 10000 keys[round=10000, batchCount=1], takes 6716 ms! -- TPS=1488.98, KPS=1488.98; -Inserted 20000 keys[round=20000, batchCount=1], takes 13520 ms! -- TPS=1479.29, KPS=1479.29; -Inserted 40000 keys[round=40000, batchCount=1], takes 26724 ms! -- TPS=1496.78, KPS=1496.78; -============================================================ -Inserted 2000 keys[round=500, batchCount=4], takes 689 ms! -- TPS=725.69, KPS=2902.76; -Inserted 4000 keys[round=1000, batchCount=4], takes 1441 ms! -- TPS=693.96, KPS=2775.85; -Inserted 40000 keys[round=10000, batchCount=4], takes 14211 ms! -- TPS=703.68, KPS=2814.72; -Inserted 80000 keys[round=20000, batchCount=4], takes 29281 ms! -- TPS=683.04, KPS=2732.15; -============================================================ -Inserted 1000 keys[round=100, batchCount=10], takes 304 ms! -- TPS=328.95, KPS=3289.47; -Inserted 10000 keys[round=1000, batchCount=10], takes 3001 ms! -- TPS=333.22, KPS=3332.22; -Inserted 20000 keys[round=2000, batchCount=10], takes 5910 ms! -- TPS=338.41, KPS=3384.09; -Inserted 40000 keys[round=4000, batchCount=10], takes 12445 ms! -- TPS=321.41, KPS=3214.14; -Inserted 40000 keys[round=2000, batchCount=20], takes 10792 ms! -- TPS=185.32, KPS=3706.45; -Inserted 4000 keys[round=200, batchCount=20], takes 1102 ms! -- TPS=181.49, KPS=3629.76; -Inserted 80000 keys[round=4000, batchCount=20], takes 21885 ms! -- TPS=182.77, KPS=3655.47; -Inserted 8000 keys[round=400, batchCount=20], takes 2081 ms! -- TPS=192.22, KPS=3844.31; -============================================================ -Inserted 10000 keys[round=100, batchCount=100], takes 2484 ms! -- TPS=40.26, KPS=4025.76; -Inserted 100000 keys[round=100, batchCount=1000], takes 24897 ms! -- TPS=4.02, KPS=4016.55; -Inserted 1000000 keys[round=100, batchCount=10000], takes 252557 ms! -- TPS=0.40, KPS=3959.50; -============================================================ -Inserted 80 keys[round=20, batchCount=4], takes 26 ms! -- TPS=769.23, KPS=3076.92; -Inserted 160 keys[round=20, batchCount=8], takes 49 ms! -- TPS=408.16, KPS=3265.31; -Inserted 200 keys[round=20, batchCount=10], takes 62 ms! -- TPS=322.58, KPS=3225.81; -Inserted 400 keys[round=20, batchCount=20], takes 127 ms! -- TPS=157.48, KPS=3149.61; -Inserted 800 keys[round=20, batchCount=40], takes 227 ms! -- TPS=88.11, KPS=3524.23; -Inserted 2000 keys[round=20, batchCount=100], takes 560 ms! -- TPS=35.71, KPS=3571.43; -Inserted 8000 keys[round=20, batchCount=400], takes 2100 ms! -- TPS=9.52, KPS=3809.52; -Inserted 20000 keys[round=20, batchCount=1000], takes 5161 ms! -- TPS=3.88, KPS=3875.22; - - - - - - diff --git a/source/test/test-ledger/src/test/java/test/com/jd/blockchain/test/ledger/RolesAuthorizationTest.java b/source/test/test-ledger/src/test/java/test/com/jd/blockchain/test/ledger/RolesAuthorizationTest.java deleted file mode 100644 index 87b3acc6..00000000 --- a/source/test/test-ledger/src/test/java/test/com/jd/blockchain/test/ledger/RolesAuthorizationTest.java +++ /dev/null @@ -1,374 +0,0 @@ -package test.com.jd.blockchain.test.ledger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.DataAccountRegisterOperation; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.RolePrivilegeSettings; -import com.jd.blockchain.ledger.RolePrivileges; -import com.jd.blockchain.ledger.RolesConfigureOperation; -import com.jd.blockchain.ledger.RolesPolicy; -import com.jd.blockchain.ledger.TransactionBuilder; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionRequestBuilder; -import com.jd.blockchain.ledger.TransactionResponse; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.UserAuthorizeOperation; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.UserRoles; -import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.LedgerInitializer; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.TransactionBatchProcessor; -import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.service.TransactionBatchResult; -import com.jd.blockchain.service.TransactionBatchResultHandle; -import com.jd.blockchain.storage.service.KVStorageService; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.RuntimeIOException; - -public class RolesAuthorizationTest { - - private static final OperationHandleRegisteration HANDLE_REG = new DefaultOperationHandleRegisteration(); - - public static final String PASSWORD = "abc"; - - public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; - - public static final String[] PRIV_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - - public static final BlockchainKeypair[] KEYS; - - private static final BlockchainKeypair ADMIN_USER; - private static final BlockchainKeypair MANAGER_USER; - private static final BlockchainKeypair DEFAULT_USER; - private static final BlockchainKeypair GUEST_USER; - - // 预置的新普通用户; - private static final BlockchainKeypair NEW_USER = BlockchainKeyGenerator.getInstance().generate(); - // 预置的数据账户; - private static final BlockchainIdentity DATA_ACCOUNT_ID = BlockchainKeyGenerator.getInstance().generate() - .getIdentity(); - - static { - KEYS = new BlockchainKeypair[PRIV_KEYS.length]; - for (int i = 0; i < PRIV_KEYS.length; i++) { - PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[i], PASSWORD); - PubKey pubKey = KeyGenUtils.decodePubKey(PUB_KEYS[i]); - KEYS[i] = new BlockchainKeypair(pubKey, privKey); - } - ADMIN_USER = KEYS[0]; - MANAGER_USER = KEYS[1]; - DEFAULT_USER = KEYS[2]; - GUEST_USER = KEYS[3]; - - // ---------- - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(RolesConfigureOperation.class); - DataContractRegistry.register(UserAuthorizeOperation.class); - } - - @Test - public void test() { - MemoryKVStorage storage = new MemoryKVStorage(); - LedgerBlock genesisBlock = initLedger(storage); - final HashDigest ledgerHash = genesisBlock.getHash(); - - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledger = ledgerManager.register(ledgerHash, storage); - - // 验证角色和用户的权限配置; - assertUserRolesPermissions(ledger); - - // 预置数据:准备一个新用户和数据账户; - TransactionRequest predefinedTx = buildRequest(ledger.getHash(), ADMIN_USER, ADMIN_USER, - new TransactionDefiner() { - @Override - public void define(TransactionBuilder txBuilder) { - txBuilder.security().roles().configure("NORMAL") - .enable(LedgerPermission.REGISTER_DATA_ACCOUNT) - .disable(LedgerPermission.REGISTER_USER) - .enable(TransactionPermission.CONTRACT_OPERATION); - - txBuilder.users().register(NEW_USER.getIdentity()); - - txBuilder.security().authorziations().forUser(NEW_USER.getAddress()).authorize("NORMAL"); - - txBuilder.dataAccounts().register(DATA_ACCOUNT_ID); - } - }); - - TransactionBatchResult procResult = executeTransactions(ledger, predefinedTx); - - //断言预定义数据的交易和区块成功; - assertBlock(1, procResult); - assertTransactionAllSuccess(procResult); - - //断言预定义的数据符合预期; - assertPredefineData(ledgerHash, storage); - - // 用不具备“注册用户”权限的用户,注册另一个新用户,预期交易失败; - BlockchainKeypair tempUser = BlockchainKeyGenerator.getInstance().generate(); - TransactionRequest tx = buildRequest(ledger.getHash(), NEW_USER, ADMIN_USER, new TransactionDefiner() { - @Override - public void define(TransactionBuilder txBuilder) { - txBuilder.users().register(tempUser.getIdentity()); - } - }); - - procResult = executeTransactions(ledger, tx); - assertBlock(2, procResult); - - assertTransactionAllFail(procResult, TransactionState.REJECTED_BY_SECURITY_POLICY); - } - - /** - * 断言区块高度; - * - * @param blockHeight - * @param procResult - */ - private void assertBlock(long blockHeight, TransactionBatchResult procResult) { - assertEquals(blockHeight, procResult.getBlock().getHeight()); - } - - /** - * 断言全部交易结果都是成功的; - * - * @param procResult - */ - private void assertTransactionAllSuccess(TransactionBatchResult procResult) { - - Iterator responses = procResult.getResponses(); - while (responses.hasNext()) { - TransactionResponse transactionResponse = (TransactionResponse) responses.next(); - - assertEquals(true, transactionResponse.isSuccess()); - assertEquals(TransactionState.SUCCESS, transactionResponse.getExecutionState()); - assertEquals(procResult.getBlock().getHash(), transactionResponse.getBlockHash()); - assertEquals(procResult.getBlock().getHeight(), transactionResponse.getBlockHeight()); - } - } - - /** - * 断言全部交易结果都是失败的; - * - * @param procResult - */ - private void assertTransactionAllFail(TransactionBatchResult procResult, TransactionState txState) { - Iterator responses = procResult.getResponses(); - while (responses.hasNext()) { - TransactionResponse transactionResponse = (TransactionResponse) responses.next(); - - assertEquals(false, transactionResponse.isSuccess()); - assertEquals(txState, transactionResponse.getExecutionState()); - } - } - - /** - * 断言预定义的数据符合预期; - * - * @param ledgerHash - * @param storage - */ - private void assertPredefineData(HashDigest ledgerHash, MemoryKVStorage storage) { - LedgerManager ledgerManager = new LedgerManager(); - LedgerRepository ledger = ledgerManager.register(ledgerHash, storage); - UserAccount newUser = ledger.getUserAccountSet().getAccount(NEW_USER.getAddress()); - assertNotNull(newUser); - DataAccount dataAccount = ledger.getDataAccountSet().getAccount(DATA_ACCOUNT_ID.getAddress()); - assertNotNull(dataAccount); - - UserRoles userRoles = ledger.getAdminSettings().getAuthorizations().getUserRoles(NEW_USER.getAddress()); - assertNotNull(userRoles); - assertEquals(1, userRoles.getRoleCount()); - assertEquals("NORMAL", userRoles.getRoles()[0]); - - RolePrivileges normalRole = ledger.getAdminSettings().getRolePrivileges().getRolePrivilege("NORMAL"); - assertNotNull(normalRole); - assertEquals(true, normalRole.getLedgerPrivilege().isEnable(LedgerPermission.REGISTER_DATA_ACCOUNT)); - assertEquals(false, normalRole.getLedgerPrivilege().isEnable(LedgerPermission.REGISTER_USER)); - assertEquals(true, normalRole.getTransactionPrivilege().isEnable(TransactionPermission.CONTRACT_OPERATION)); - assertEquals(false, normalRole.getTransactionPrivilege().isEnable(TransactionPermission.DIRECT_OPERATION)); - } - - private TransactionBatchResult executeTransactions(LedgerRepository ledger, TransactionRequest... transactions) { - TransactionBatchProcessor txProcessor = new TransactionBatchProcessor(ledger, HANDLE_REG); - - for (TransactionRequest request : transactions) { - txProcessor.schedule(request); - } - - TransactionBatchResultHandle procResult = txProcessor.prepare(); - procResult.commit(); - - return procResult; - } - - private TransactionRequest buildRequest(HashDigest ledgerHash, BlockchainKeypair endpoint, BlockchainKeypair node, - TransactionDefiner definer) { - TransactionBuilder txBuilder = new TxBuilder(ledgerHash); - definer.define(txBuilder); - TransactionRequestBuilder reqBuilder = txBuilder.prepareRequest(); - reqBuilder.signAsEndpoint(endpoint); - if (node != null) { - reqBuilder.signAsNode(node); - } - return reqBuilder.buildRequest(); - } - - private void assertUserRolesPermissions(LedgerQuery ledger) { - // 验证角色-权限; - assertRolePermissions(ledger, "DEFAULT", - new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, - new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, - TransactionPermission.CONTRACT_OPERATION }); - - assertRolePermissions(ledger, "ADMIN", - new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.AUTHORIZE_USER_ROLES, - LedgerPermission.SET_CONSENSUS, LedgerPermission.SET_CRYPTO, - LedgerPermission.REGISTER_PARTICIPANT, LedgerPermission.REGISTER_USER }, - new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION }); - - assertRolePermissions(ledger, "MANAGER", - new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.AUTHORIZE_USER_ROLES, - LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT, - LedgerPermission.REGISTER_CONTRACT, LedgerPermission.UPGRADE_CONTRACT, - LedgerPermission.SET_USER_ATTRIBUTES, LedgerPermission.WRITE_DATA_ACCOUNT, - LedgerPermission.APPROVE_TX }, - new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, - TransactionPermission.CONTRACT_OPERATION }); - - assertRolePermissions(ledger, "GUEST", new LedgerPermission[] {}, - new TransactionPermission[] { TransactionPermission.CONTRACT_OPERATION }); - - // 验证用户-角色; - assertUserRoles(ledger, ADMIN_USER, RolesPolicy.UNION, "ADMIN", "MANAGER"); - assertUserRoles(ledger, MANAGER_USER, RolesPolicy.UNION, "MANAGER"); - assertUserRoles(ledger, DEFAULT_USER, RolesPolicy.UNION); - assertUserRoles(ledger, DEFAULT_USER, RolesPolicy.UNION); - } - - private void assertUserRoles(LedgerQuery ledger, BlockchainKeypair userKey, RolesPolicy policy, String... roles) { - assertUserRoles(ledger, userKey.getAddress(), policy, roles); - } - - private void assertUserRoles(LedgerQuery ledger, Bytes address, RolesPolicy policy, String[] roles) { - if (roles == null) { - roles = new String[0]; - } - UserRoles userRoles = ledger.getAdminSettings().getAuthorizations().getUserRoles(address); - assertNotNull(userRoles); - assertEquals(policy, userRoles.getPolicy()); - - Set expectedRoles = new HashSet(Arrays.asList(roles)); - Set actualRoles = userRoles.getRoleSet(); - assertEquals(expectedRoles.size(), actualRoles.size()); - for (String r : actualRoles) { - assertTrue(expectedRoles.contains(r)); - } - } - - private void assertRolePermissions(LedgerQuery ledger, String roleName, LedgerPermission[] ledgerPermissions, - TransactionPermission[] txPermissions) { - RolePrivilegeSettings roles = ledger.getAdminSettings().getRolePrivileges(); - assertTrue(roles.contains(roleName)); - RolePrivileges privileges = roles.getRolePrivilege(roleName); - assertEquals(ledgerPermissions.length, privileges.getLedgerPrivilege().getPermissionCount()); - assertEquals(txPermissions.length, privileges.getTransactionPrivilege().getPermissionCount()); - - Set expectedLedgerPermissions = new HashSet( - Arrays.asList(ledgerPermissions)); - for (LedgerPermission p : LedgerPermission.values()) { - if (expectedLedgerPermissions.contains(p)) { - assertTrue(privileges.getLedgerPrivilege().isEnable(p)); - } else { - assertFalse(privileges.getLedgerPrivilege().isEnable(p)); - } - } - - Set expectedTxPermissions = new HashSet( - Arrays.asList(txPermissions)); - for (TransactionPermission p : TransactionPermission.values()) { - if (expectedTxPermissions.contains(p)) { - assertTrue(privileges.getTransactionPrivilege().isEnable(p)); - } else { - assertFalse(privileges.getTransactionPrivilege().isEnable(p)); - } - } - } - - private LedgerBlock initLedger(KVStorageService storage) { - LedgerInitProperties initProps = loadInitProperties(); - LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(initProps); - LedgerInitializer initializer = LedgerInitializer.create(initConfig.getLedgerSettings(), - initConfig.getSecuritySettings()); - - DigitalSignature sign0 = initializer.signTransaction(KEYS[0]); - DigitalSignature sign1 = initializer.signTransaction(KEYS[1]); - DigitalSignature sign2 = initializer.signTransaction(KEYS[2]); - DigitalSignature sign3 = initializer.signTransaction(KEYS[3]); - - LedgerBlock genesisBlock = initializer.prepareLedger(storage, sign0, sign1, sign2, sign3); - initializer.commit(); - return genesisBlock; - } - - private LedgerInitProperties loadInitProperties() { - try { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger.init"); - InputStream in = ledgerInitSettingResource.getInputStream(); - return LedgerInitProperties.resolve(in); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - private static interface TransactionDefiner { - - void define(TransactionBuilder txBuilder); - - } -} diff --git a/source/test/test-ledger/src/test/resources/bftsmart.config b/source/test/test-ledger/src/test/resources/bftsmart.config deleted file mode 100644 index df69caf5..00000000 --- a/source/test/test-ledger/src/test/resources/bftsmart.config +++ /dev/null @@ -1,144 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#Configuration of all node servers; -#PubKey of node server with specified ID, with base58 encoding. -system.server.0.pubkey= -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=8900 -system.server.0.network.secure=false - -system.server.1.pubkey= -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=8910 -system.server.1.network.secure=false - -system.server.2.pubkey= -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=8920 -system.server.2.network.secure=false - -system.server.3.pubkey= -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=8920 -system.server.3.network.secure=false diff --git a/source/test/test-ledger/src/test/resources/keys/parti2.pub b/source/test/test-ledger/src/test/resources/keys/parti2.pub deleted file mode 100644 index dde44b8e..00000000 --- a/source/test/test-ledger/src/test/resources/keys/parti2.pub +++ /dev/null @@ -1 +0,0 @@ -3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x \ No newline at end of file diff --git a/source/test/test-ledger/src/test/resources/ledger.init b/source/test/test-ledger/src/test/resources/ledger.init deleted file mode 100644 index a503c96a..00000000 --- a/source/test/test-ledger/src/test/resources/ledger.init +++ /dev/null @@ -1,165 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name=test - -#声明账本的创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - - -#----------------------------------------------- -# 初始的角色名称列表;可选项; -# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; -# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; -# -# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; -# -security.roles=DEFAULT, ADMIN, MANAGER, GUEST - -# 赋予角色的账本权限清单;可选项; -# 可选的权限如下; -# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, -# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, -# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -# APPROVE_TX, CONSENSUS_TX -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT - -# 赋予角色的交易权限清单;可选项; -# 可选的权限如下; -# DIRECT_OPERATION, CONTRACT_OPERATION -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 其它角色的配置示例; -# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; -security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER -security.role.ADMIN.tx-privileges=DIRECT_OPERATION - -# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; -security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, \ -REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, APPROVE_TX -security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; -security.role.GUEST.ledger-privileges= -security.role.GUEST.tx-privileges=CONTRACT_OPERATION - - - -#----------------------------------------------- -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - -#从存储中加载账本数据时,是否校验哈希;可选; -crypto.verify-hash=true - -#哈希算法; -crypto.hash-algorithm=SHA256 - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的角色清单;可选项; -cons_parti.0.roles=ADMIN, MANAGER -#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.0.roles-policy=UNION -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=true -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=true - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的角色清单;可选项; -cons_parti.1.roles=MANAGER -#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.1.roles-policy=UNION -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=classpath:keys/parti2.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey= -#第2个参与方的角色清单;可选项; -cons_parti.2.roles= -#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.2.roles-policy= -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=true - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的角色清单;可选项; -cons_parti.3.roles=GUEST -#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.3.roles-policy=INTERSECT -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/test/test-ledger/src/test/resources/logback-test.xml b/source/test/test-ledger/src/test/resources/logback-test.xml deleted file mode 100644 index 29013782..00000000 --- a/source/test/test-ledger/src/test/resources/logback-test.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/CapabilityBooter.java b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/CapabilityBooter.java deleted file mode 100644 index 9f7f92a4..00000000 --- a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/CapabilityBooter.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.capability.CapabilityBooter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/3 下午5:35 - * Description: - */ -package com.jd.blockchain.capability; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * - * @author shaozhuguang - * @create 2019/1/3 - * @since 1.0.0 - */ -@SpringBootApplication -public class CapabilityBooter { - - public static void main(String[] args) { - SpringApplication.run(CapabilityBooter.class, args); - } -} \ No newline at end of file diff --git a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/CapabilityEngine.java b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/CapabilityEngine.java deleted file mode 100644 index d6eeeb19..00000000 --- a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/CapabilityEngine.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.capability.CapabilityEngine - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/27 上午10:16 - * Description: - */ -package com.jd.blockchain.capability; - -import org.springframework.boot.CommandLineRunner; -import org.springframework.stereotype.Component; - -import com.jd.blockchain.capability.service.RemoteTransactionService; -import com.jd.blockchain.capability.service.SettingsInit; -import com.jd.blockchain.capability.settings.CapabilitySettings; -import com.jd.blockchain.utils.ArgumentSet; - -/** - * - * @author shaozhuguang - * @create 2018/12/27 - * @since 1.0.0 - */ -@Component -public class CapabilityEngine implements CommandLineRunner { - - public static final String MQURL_ARG = "-s"; - - public static final String CONF_ARG = "-c"; - - public static final String TOPIC_ARG = "-t"; - - public static final String UR_AEG = "-ur"; - - public static final String DR_AEG = "-dr"; - - public static final String UR_DR_AEG = "-udr"; - - public static final String DR_KV_AEG = "-drw"; - - public static final String KV_AEG = "-kv"; - - public static void engine(String[] args) { - ArgumentSet arguments = ArgumentSet.resolve(args, - ArgumentSet.setting() - .prefix(MQURL_ARG) - .prefix(CONF_ARG) - .prefix(TOPIC_ARG) - .option(UR_AEG) - .option(DR_AEG) - .option(UR_DR_AEG) - .option(KV_AEG) - .option(DR_KV_AEG)); - try { - ArgumentSet.ArgEntry mqArg = arguments.getArg(MQURL_ARG); - if (mqArg != null) { - String mqUrl = mqArg.getValue(); - CapabilitySettings.MSG_QUEUE_URL = mqUrl; - } - - ArgumentSet.ArgEntry confArg = arguments.getArg(CONF_ARG); - if (confArg != null) { - String conf = confArg.getValue(); - SettingsInit.init(conf); - } else { - SettingsInit.init(CapabilitySettings.settingsConf); - } - - ArgumentSet.ArgEntry topicArg = arguments.getArg(TOPIC_ARG); - if (topicArg != null) { - String topic = topicArg.getValue(); - CapabilitySettings.TX_TOPIC = topic; - } - - RemoteTransactionService service = new RemoteTransactionService(); - - if (arguments.hasOption(UR_AEG)) { - // 单纯注册1亿个用户 - service.userRegister(CapabilitySettings.TX_TOTAL_SIZE); - } else if (arguments.hasOption(DR_AEG)) { - // 单纯注册1亿数据账户 - service.dataAccountRegister(CapabilitySettings.TX_TOTAL_SIZE); - } else if (arguments.hasOption(UR_DR_AEG)) { - // 先注册5千万用户再注册5千万数据账户 - service.userAndDataAccountRegister(CapabilitySettings.TX_HALF_SIZE, - CapabilitySettings.TX_HALF_SIZE); - } else if (arguments.hasOption(DR_KV_AEG)) { - // 先注册1万数据账户,再对每个数据账户写入1万个kv - service.dataAccountRegisterAndKvStorage(CapabilitySettings.DR_SIZE, - CapabilitySettings.KV_SIZE); - } else if (arguments.hasOption(KV_AEG)) { - // 单纯向其中某个数据账户写入KV - service.kvStorage(CapabilitySettings.KV_TOTAL_SIZE); - } else { - // 单纯向其中某个数据账户写入KV - service.kvStorage(CapabilitySettings.KV_TOTAL_SIZE); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void run(String... args) throws Exception { - engine(args); - } -} \ No newline at end of file diff --git a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/RemoteTransactionService.java b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/RemoteTransactionService.java deleted file mode 100644 index 6ddd5b0f..00000000 --- a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/RemoteTransactionService.java +++ /dev/null @@ -1,364 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.capability.service.RemoteTransactionService - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/26 下午5:22 - * Description: - */ -package com.jd.blockchain.capability.service; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; - -import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.capability.settings.CapabilitySettings; -import com.jd.blockchain.consensus.mq.factory.MsgQueueFactory; -import com.jd.blockchain.consensus.mq.producer.MsgQueueProducer; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionRequestBuilder; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * - * @author shaozhuguang - * @create 2018/12/26 - * @since 1.0.0 - */ - -public class RemoteTransactionService { - - private MsgQueueProducer txProducer; - - private final ExecutorService instanceFactory = Executors.newSingleThreadExecutor(); - - private final ArrayBlockingQueue> txBlockingQueue = new ArrayBlockingQueue(1); - - private final LinkedList dataAccountAddress = new LinkedList<>(); - - private Bytes defaultDataAccount; - - private static final AtomicLong keyPrefix = new AtomicLong(); - - public void userRegister(int count) throws Exception { - initTxProducer(); - int loop = 0; - if (count <= 0) { - userCreate(); - } else { - loop = count / CapabilitySettings.TX_SIZE_PER_SEND; - userCreate(loop); - } - // 从队列中获取数据 - if (count <= 0) { - for (;;) { - txRequestSend(); - } - } else { - for (int i = 0; i < loop; i++) { - txRequestSend(); - } - } - closeTxProducer(); - } - - public void dataAccountRegister(int count) throws Exception { - initTxProducer(); - int loop = 0; - if (count <= 0) { - dataAccountCreate(); - } else { - loop = count / CapabilitySettings.TX_SIZE_PER_SEND; - dataAccountCreate(loop); - } - // 从队列中获取数据 - if (count <= 0) { - for (;;) { - txRequestSend(); - } - } else { - for (int i = 0; i < loop; i++) { - txRequestSend(); - } - } - closeTxProducer(); - } - - public void userAndDataAccountRegister(int userCount, int dataAccountCount) throws Exception { - if (userCount <= 0 || dataAccountCount <= 0) { - throw new IllegalArgumentException("userCount and dataAccountCount can not be 0!!!"); - } - initTxProducer(); - int userLoop = userCount / CapabilitySettings.TX_SIZE_PER_SEND; - int dataAccountLoop = dataAccountCount / CapabilitySettings.TX_SIZE_PER_SEND; - userCreate(userLoop); - dataAccountCreate(dataAccountLoop); - for (int i = 0, totalLoop = userLoop + dataAccountCount; i < totalLoop; i++) { - txRequestSend(); - } - closeTxProducer(); - } - - public void dataAccountRegisterAndKvStorage(int dataAccountCount, int kvCount) throws Exception { - if (kvCount <= 0 || dataAccountCount <= 0) { - throw new IllegalArgumentException("userCount and dataAccountCount can not be 0!!!"); - } - initTxProducer(); - int dataAccountLoop = dataAccountCount / CapabilitySettings.TX_SIZE_PER_SEND; - dataAccountCreate(dataAccountLoop); - // 首先将数据账户写入 - for (int i = 0; i < dataAccountLoop; i++) { - txRequestSend(); - } - int kvLoop = kvCount / CapabilitySettings.TX_SIZE_PER_SEND; - // 然后将每个数据账户都写入指定数量的kv - Iterator iterator = dataAccountAddress.iterator(); - while (iterator.hasNext()) { - Bytes address = iterator.next(); - kvStorageCreate(kvCount, address); - } - for (int i = 0, loop = kvLoop * dataAccountCount; i < loop; i++) { - txRequestSend(); - } - - closeTxProducer(); - } - - public void kvStorage(int kvCount) throws Exception { - initTxProducer(); - - dataAccountDefaultCreate(); - try { - txRequestSend(); - // 确认结块成功 - Thread.sleep(10000); - } catch (Exception e) { - throw e; - } - int kvLoop = kvCount / CapabilitySettings.TX_SIZE_PER_SEND; - // 然后将每个数据账户都写入指定数量的kv - Bytes address = defaultDataAccount; - kvStorageCreate(kvLoop, address); - for (int i = 0; i < kvLoop; i++) { - txRequestSend(); - } - - closeTxProducer(); - } - - private void txRequestSend() throws Exception { - List txRequests = txBlockingQueue.take(); - if (txRequests != null && !txRequests.isEmpty()) { - Iterator iterator = txRequests.iterator(); - while (iterator.hasNext()) { - byte[] txRequest = iterator.next(); - try { - txProducer.publish(txRequest); - } catch (Exception e) { - e.printStackTrace(); - } - } - ConsoleUtils.info("[*] Transaction Request send success!!!"); - } - } - - private void initTxProducer() throws Exception { - txProducer = MsgQueueFactory.newProducer(CapabilitySettings.MSG_QUEUE_URL, CapabilitySettings.TX_TOPIC); - txProducer.connect(); - ConsoleUtils.info("[*] Transaction Producer start success!!!"); - } - - private void closeTxProducer() throws Exception { - txProducer.close(); - } - - private void userCreate(int loop) { - instanceFactory.execute(() -> { - for (int index = 0; index < loop; index++) { - // 每次生产10000个,然后放入队列中 - try { - LinkedList txSerializeBytes = userActiveCreate(); - txBlockingQueue.put(txSerializeBytes); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - - private void userCreate() { - // 一直在生产用户 - instanceFactory.execute(() -> { - for (;;) { - // 每次生产10000个,然后放入队列中 - try { - LinkedList txSerializeBytes = userActiveCreate(); - txBlockingQueue.put(txSerializeBytes); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - - private void dataAccountCreate(int loop) { - dataAccountCreate(loop, false); - } - - private void dataAccountCreate(int loop, final boolean isSave) { - instanceFactory.execute(() -> { - for (int index = 0; index < loop; index++) { - // 每次生产10000个,然后放入队列中 - try { - LinkedList txSerializeBytes = dataAccountActiveCreate(isSave); - txBlockingQueue.put(txSerializeBytes); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - - private void dataAccountDefaultCreate() { - instanceFactory.execute(() -> { - List currentBytes = new ArrayList<>(); - TransactionRequest txRequest = dataAccountRegisterRequest(CapabilitySettings.ledgerHash, - CapabilitySettings.adminKey); - byte[] serializeBytes = BinaryProtocol.encode(txRequest, TransactionRequest.class); - currentBytes.add(serializeBytes); - try { - txBlockingQueue.put(currentBytes); - } catch (Exception e) { - throw new RuntimeException(e); - } - }); - } - - private void dataAccountCreate() { - // 一直在生产用户 - instanceFactory.execute(() -> { - for (;;) { - // 每次生产10000个,然后放入队列中 - try { - LinkedList txSerializeBytes = dataAccountActiveCreate(); - txBlockingQueue.put(txSerializeBytes); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - - private void kvStorageCreate(int loop, Bytes address) { - // 一直在生产用户 - instanceFactory.execute(() -> { - for (int index = 0; index < loop; index++) { - // 每次生产10000个,然后放入队列中 - try { - LinkedList txSerializeBytes = kvActiveCreate(address); - txBlockingQueue.put(txSerializeBytes); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - - private LinkedList userActiveCreate() { - // 每次生产10000个,然后放入队列中 - LinkedList txSerializeBytes = new LinkedList<>(); - for (int i = 0; i < CapabilitySettings.TX_SIZE_PER_SEND; i++) { - TransactionRequest txRequest = userRegisterRequest(CapabilitySettings.ledgerHash, - CapabilitySettings.adminKey); - byte[] serializeBytes = BinaryProtocol.encode(txRequest, TransactionRequest.class); - txSerializeBytes.addFirst(serializeBytes); - } - return txSerializeBytes; - } - - private LinkedList dataAccountActiveCreate() { - return dataAccountActiveCreate(false); - } - - private LinkedList dataAccountActiveCreate(boolean isSave) { - // 每次生产10000个,然后放入队列中 - LinkedList txSerializeBytes = new LinkedList<>(); - for (int i = 0; i < CapabilitySettings.TX_SIZE_PER_SEND; i++) { - TransactionRequest txRequest = dataAccountRegisterRequest(CapabilitySettings.ledgerHash, - CapabilitySettings.adminKey, isSave); - byte[] serializeBytes = BinaryProtocol.encode(txRequest, TransactionRequest.class); - txSerializeBytes.addFirst(serializeBytes); - } - return txSerializeBytes; - } - - private LinkedList kvActiveCreate(Bytes address) { - // 每次生产10000个,然后放入队列中 - LinkedList txSerializeBytes = new LinkedList<>(); - for (int i = 0; i < CapabilitySettings.TX_SIZE_PER_SEND; i++) { - TransactionRequest txRequest = kvStorageRequest(address, CapabilitySettings.ledgerHash, - CapabilitySettings.adminKey); - byte[] serializeBytes = BinaryProtocol.encode(txRequest, TransactionRequest.class); - txSerializeBytes.addFirst(serializeBytes); - } - return txSerializeBytes; - } - - private TransactionRequest userRegisterRequest(HashDigest ledgerHash, AsymmetricKeypair adminKey) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate(); - txbuilder.users().register(userKey.getIdentity()); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - return reqBuilder.buildRequest(); - } - - private TransactionRequest dataAccountRegisterRequest(HashDigest ledgerHash, AsymmetricKeypair adminKey, - boolean isSave) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - BlockchainKeypair dataAccountKey = BlockchainKeyGenerator.getInstance().generate(); - BlockchainIdentity identity = dataAccountKey.getIdentity(); - txbuilder.dataAccounts().register(identity); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - if (isSave) { - dataAccountAddress.addFirst(identity.getAddress()); - } - return reqBuilder.buildRequest(); - } - - private TransactionRequest dataAccountRegisterRequest(HashDigest ledgerHash, AsymmetricKeypair adminKey) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - BlockchainKeypair dataAccountKey = BlockchainKeyGenerator.getInstance().generate(); - BlockchainIdentity identity = dataAccountKey.getIdentity(); - txbuilder.dataAccounts().register(identity); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - defaultDataAccount = identity.getAddress(); - return reqBuilder.buildRequest(); - } - - private TransactionRequest kvStorageRequest(Bytes address, HashDigest ledgerHash, AsymmetricKeypair adminKey) { - TxBuilder txbuilder = new TxBuilder(ledgerHash); - long currValue = keyPrefix.getAndIncrement(); - txbuilder.dataAccount(address).setText("key-" + currValue + "-" + System.currentTimeMillis(), - "value-" + currValue, -1L); - TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest(); - reqBuilder.signAsEndpoint(adminKey); - return reqBuilder.buildRequest(); - } -} \ No newline at end of file diff --git a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java deleted file mode 100644 index 0c0e6db9..00000000 --- a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.capability.service.SettingsInit - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/27 下午2:26 - * Description: - */ -package com.jd.blockchain.capability.service; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.capability.settings.CapabilitySettings; -import com.jd.blockchain.consensus.action.ActionResponse; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; -import com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings; -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.utils.codec.Base58Utils; - -/** - * - * @author shaozhuguang - * @create 2018/12/27 - * @since 1.0.0 - */ - -public class SettingsInit { - - static { - DataContractRegistry.register(LedgerBlock.class); - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class); - - DataContractRegistry.register(Operation.class); - DataContractRegistry.register(ContractCodeDeployOperation.class); - DataContractRegistry.register(ContractEventSendOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - - DataContractRegistry.register(ActionResponse.class); - - DataContractRegistry.register(BftsmartConsensusSettings.class); - DataContractRegistry.register(BftsmartNodeSettings.class); - - } - - public static final void init(String settingsFile) throws Exception { - - Settings settings = new Settings(); -// settings.ledgerHash = "6B3aa543AkotypMaLCeuWDTXFLuG9UKyZCSdJBPStJzEe"; - settings.ledgerHash = "6CB4tTkKyfshafJB1xk8deeZ8FxnjJsSnQLExi5Bq6Mum"; - settings.privKey = "177gjsj5PHeCpbAtJE7qnbmhuZMHAEKuMsd45zHkv8F8AWBvTBbff8yRKdCyT3kwrmAjSnY"; - settings.pubKey = "endPsK36koyFr1D245Sa9j83vt6pZUdFBJoJRB3xAsWM6cwhRbna"; - settings.pwd = "abc"; - init(settings); - -// File confFile = new File(settingsFile); -// if (settingsFile == null || settingsFile.length() == 0 || !confFile.exists()) { -// ClassPathResource resource = new ClassPathResource(CapabilitySettings.settingsConf); -// confFile = resource.getFile(); -// } -// if (!confFile.exists()) { -// Settings settings = new Settings(); -// settings.ledgerHash = "6B3aa543AkotypMaLCeuWDTXFLuG9UKyZCSdJBPStJzEe"; -// settings.privKey = "177gjsj5PHeCpbAtJE7qnbmhuZMHAEKuMsd45zHkv8F8AWBvTBbff8yRKdCyT3kwrmAjSnY"; -// settings.pubKey = "endPsK36koyFr1D245Sa9j83vt6pZUdFBJoJRB3xAsWM6cwhRbna"; -// settings.pwd = "abc"; -// init(settings); -// } else { -// List readLines = FileUtils.readLines(confFile); -// if (readLines != null && !readLines.isEmpty()) { -// Settings settings = new Settings(); -// for (String readLine : readLines) { -// if (readLine.startsWith("ledgerHash")) { -// settings.ledgerHash = readLine.split("=")[1]; -// } else if (readLine.startsWith("privKey")) { -// settings.privKey = readLine.split("=")[1]; -// } else if (readLine.startsWith("pubKey")) { -// settings.pubKey = readLine.split("=")[1]; -// } else if (readLine.startsWith("pwd")) { -// settings.pwd = readLine.split("=")[1]; -// } -// } -// init(settings); -// } else { -// throw new IllegalArgumentException("file is not exist !!!"); -// } -// } - } - - private static void init(Settings settings) { - // 处理ledgerHash - HashDigest hash = new HashDigest(Base58Utils.decode(settings.getLedgerHash())); - CapabilitySettings.ledgerHash = hash; - - // 处理用户 - PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(settings.getPrivKey(), settings.getPwd()); - PubKey pubKey = KeyGenUtils.decodePubKey(settings.getPubKey()); - CapabilitySettings.adminKey = new AsymmetricKeypair(pubKey, privKey); - } - - private static class Settings { - String ledgerHash; - - String privKey; - - String pubKey; - - String pwd; - - public String getLedgerHash() { - return ledgerHash; - } - - public String getPrivKey() { - return privKey; - } - - public String getPubKey() { - return pubKey; - } - - public String getPwd() { - return pwd; - } - } -} \ No newline at end of file diff --git a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/settings/CapabilitySettings.java b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/settings/CapabilitySettings.java deleted file mode 100644 index 081fe6dd..00000000 --- a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/settings/CapabilitySettings.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.capability.CapabilitySettings - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/26 下午5:38 - * Description: - */ -package com.jd.blockchain.capability.settings; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.HashDigest; - -/** - * - * @author shaozhuguang - * @create 2018/12/26 - * @since 1.0.0 - */ - -public class CapabilitySettings { - - public static final int TX_TOTAL_SIZE = 100 * 1000 * 1000; -// public static final int TX_TOTAL_SIZE = 100 * 1000; - - public static final int TX_HALF_SIZE = 50 * 1000 * 1000; - - public static final int DR_SIZE = 10000; - - public static final int KV_SIZE = 10000; - - public static final int KV_TOTAL_SIZE = 100 * 1000 * 1000; - -// public static String MSG_QUEUE_URL = "nats://127.0.0.1:4222"; - public static String MSG_QUEUE_URL = "rabbit://127.0.0.1:5672"; - -// public static String TX_TOPIC = "tx-topic"; - public static String TX_TOPIC = "tx-two-topic"; - - public static final int TX_SIZE_PER_SEND = 10000; - - public static HashDigest ledgerHash; - - public static AsymmetricKeypair adminKey; - - public static final String settingsConf = "settings.conf"; -} \ No newline at end of file diff --git a/source/tools/tools-capability/src/main/resources/META-INF/MANIFEST.MF b/source/tools/tools-capability/src/main/resources/META-INF/MANIFEST.MF deleted file mode 100644 index b08cf0d7..00000000 --- a/source/tools/tools-capability/src/main/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,10 +0,0 @@ -Manifest-Version: 1.0 -Created-By: 1.8.0 -Built-By: shaozhuguang@jd.com -Extension-Name: JDChain -Specification-Title: JDChain -Specification-Vendor: JD Software Foundation -Implementation-Vendor: JD Software Foundation -Implementation-URL: http://ledger.jd.com -Build-Jdk: 1.8.0 - diff --git a/source/tools/tools-capability/src/main/resources/settings.conf b/source/tools/tools-capability/src/main/resources/settings.conf deleted file mode 100644 index 216cc7cb..00000000 --- a/source/tools/tools-capability/src/main/resources/settings.conf +++ /dev/null @@ -1,4 +0,0 @@ -ledgerHash=6B3aa543AkotypMaLCeuWDTXFLuG9UKyZCSdJBPStJzEe -privKey=177gjsj5PHeCpbAtJE7qnbmhuZMHAEKuMsd45zHkv8F8AWBvTBbff8yRKdCyT3kwrmAjSnY -pubKey=endPsK36koyFr1D245Sa9j83vt6pZUdFBJoJRB3xAsWM6cwhRbna -pwd=abc \ No newline at end of file diff --git a/source/tools/tools-initializer-booter/ledger.init b/source/tools/tools-initializer-booter/ledger.init deleted file mode 100644 index 6cc31468..00000000 --- a/source/tools/tools-initializer-booter/ledger.init +++ /dev/null @@ -1,85 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name= - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=endPsK36koyFr1D245Sa9j83vt6pZUdFBJoJRB3xAsWM6cwhRbna -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=true -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=true - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=endPsK36sC5JdPCDPDAXUwZtS3sxEmqEhFcC4whayAsTTh8Z6eoZ -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=keys/bt-com.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=endPsK36jEG281HMHeh6oSqzqLkT95DTnCM6REDURjdb2c67uR3R -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=true - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=endPsK36nse1dck4uF19zPvAMijCV336Y3zWdgb4rQG8QoRj5ktR -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/tools/tools-initializer-booter/local.conf b/source/tools/tools-initializer-booter/local.conf deleted file mode 100644 index ee8254fc..00000000 --- a/source/tools/tools-initializer-booter/local.conf +++ /dev/null @@ -1,22 +0,0 @@ - -#当前参与方的 id; -local.parti.id=0 - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsj5PHeCpbAtJE7qnbmhuZMHAEKuMsd45zHkv8F8AWBvTBbff8yRKdCyT3kwrmAjSnY - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=./ - -#账本数据库的连接字符串; -ledger.db.uri=redis://127.0.0.1/0 - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识系统的参数配置;可选参数; -consensus.conf= - diff --git a/source/tools/tools-initializer-booter/src/main/java/com/jd/blockchain/tools/initializer/boot/LedgerInitCommandBooter.java b/source/tools/tools-initializer-booter/src/main/java/com/jd/blockchain/tools/initializer/boot/LedgerInitCommandBooter.java deleted file mode 100644 index 1a25ac34..00000000 --- a/source/tools/tools-initializer-booter/src/main/java/com/jd/blockchain/tools/initializer/boot/LedgerInitCommandBooter.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jd.blockchain.tools.initializer.boot; - -import com.jd.blockchain.tools.initializer.LedgerInitCommand; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; - -public class LedgerInitCommandBooter { - - private static final String[] JAR_DIRS = new String[]{"libs", "system"}; - - public static void main(String[] args) { - // 加载当前包及../system包下的所有class - load(); - LedgerInitCommand.main(args); - } - - private static void load() { - List jarPaths = loadPaths(); - try { - if (jarPaths != null && !jarPaths.isEmpty()) { - loadJars(jarPaths); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static void loadJars(List jarPaths) throws Exception { - Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); - boolean accessible = method.isAccessible(); - try { - if (!accessible) { - method.setAccessible(true); - } - // 获取系统类加载器 - URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); - for (File file : jarPaths) { - URL url = file.toURI().toURL(); - try { - method.invoke(classLoader, url); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - } finally { - method.setAccessible(accessible); - } - } - - private static List loadPaths() { - List loadJarFiles = new ArrayList<>(); - URL url = LedgerInitCommandBooter.class - .getProtectionDomain() - .getCodeSource() - .getLocation(); - try { - String currPath = java.net.URLDecoder.decode(url.getPath(), "utf-8"); - if (currPath.endsWith(".jar")) { - currPath = currPath.substring(0, currPath.lastIndexOf("/") + 1); - } - File file = new File(currPath); - loadJarFiles.addAll(dirJars(file)); - - for (String jarDir : JAR_DIRS) { - // 获取上级路径 - String jarPath = file.getParent() + File.separator + jarDir; - loadJarFiles.addAll(dirJars(new File(jarPath))); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - return loadJarFiles; - } - - private static List dirJars(File dir) { - List jars = new ArrayList<>(); - if (dir.exists() && dir.isDirectory()) { - File[] jarArray = dir.listFiles(); - if (jarArray != null) { - for (File jar : jarArray) { - if (jar.getAbsolutePath().endsWith(".jar")) { - jars.add(jar); - } - } - } - } - return jars; - } -} diff --git a/source/tools/tools-initializer-booter/src/main/resources/META-INF/MANIFEST.MF b/source/tools/tools-initializer-booter/src/main/resources/META-INF/MANIFEST.MF deleted file mode 100644 index b08cf0d7..00000000 --- a/source/tools/tools-initializer-booter/src/main/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,10 +0,0 @@ -Manifest-Version: 1.0 -Created-By: 1.8.0 -Built-By: shaozhuguang@jd.com -Extension-Name: JDChain -Specification-Title: JDChain -Specification-Vendor: JD Software Foundation -Implementation-Vendor: JD Software Foundation -Implementation-URL: http://ledger.jd.com -Build-Jdk: 1.8.0 - diff --git a/source/tools/tools-initializer/.gitignore b/source/tools/tools-initializer/.gitignore deleted file mode 100644 index da7560e0..00000000 --- a/source/tools/tools-initializer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.apt_generated_tests/ diff --git a/source/tools/tools-initializer/bftsmart.config b/source/tools/tools-initializer/bftsmart.config deleted file mode 100644 index df69caf5..00000000 --- a/source/tools/tools-initializer/bftsmart.config +++ /dev/null @@ -1,144 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#Configuration of all node servers; -#PubKey of node server with specified ID, with base58 encoding. -system.server.0.pubkey= -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=8900 -system.server.0.network.secure=false - -system.server.1.pubkey= -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=8910 -system.server.1.network.secure=false - -system.server.2.pubkey= -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=8920 -system.server.2.network.secure=false - -system.server.3.pubkey= -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=8920 -system.server.3.network.secure=false diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/ConsolePrompter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/ConsolePrompter.java deleted file mode 100644 index 01083537..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/ConsolePrompter.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import com.jd.blockchain.utils.ConsoleUtils; - -public class ConsolePrompter implements Prompter { - - private boolean debug = true; - - @Override - public void info(String format, Object... args) { - ConsoleUtils.info(format, args); - } - - @Override - public void error(String format, Object... args) { - ConsoleUtils.error(format, args); - } - - @Override - public void error(Exception error, String format, Object... args) { - if (debug) { - error.printStackTrace(); - } - } - - @Override - public String confirm(String format, Object... args) { - return confirm("", format, args); - } - - @Override - public String confirm(String tag, String format, Object... args) { - String msg = String.format(format, args); - return ConsoleUtils.confirm("[%s] %s", tag, msg); - } - - public boolean isDebug() { - return debug; - } - - public void setDebug(boolean debug) { - this.debug = debug; - } - -} \ No newline at end of file diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/DBConnectionConfig.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/DBConnectionConfig.java deleted file mode 100644 index 8ca98ffc..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/DBConnectionConfig.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -public class DBConnectionConfig { - - private String connectionUri; - - private String password; - - public DBConnectionConfig() { - } - public DBConnectionConfig(String uri) { - this.connectionUri = uri; - } - - public String getUri() { - return connectionUri; - } - - public void setConnectionUri(String connectionUri) { - this.connectionUri = connectionUri; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - -} \ No newline at end of file diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializerConfiguration.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializerConfiguration.java deleted file mode 100644 index 5129433f..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializerConfiguration.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import org.springframework.context.annotation.Configuration; - -/** - * Spring Boot 项目的配置类; - * - * @author huanghaiquan - * - */ -@Configuration -public interface InitializerConfiguration { -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializingStep.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializingStep.java deleted file mode 100644 index 50fe9984..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializingStep.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -public enum InitializingStep { - - PERMISSION_READY, - - LEDGER_INIT_COMPLETED - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerBindingConfig.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerBindingConfig.java deleted file mode 100644 index 25fc6519..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerBindingConfig.java +++ /dev/null @@ -1,401 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.io.RuntimeIOException; - -public class LedgerBindingConfig { - - public static final String CHARSET = "UTF-8"; - - public static final String LEDGER_HASH_SEPERATOR = ","; - - public static final String ATTR_SEPERATOR = "."; - - // Binding List; - public static final String LEDGER_BINDINS = "ledger.bindings"; - - // Binding Config Key Prefix; - public static final String BINDING_PREFIX = "binding"; - - // Participant Config Key Prefix; - public static final String PARTI_PREFIX = "parti."; - - // Participant Attribute Key; - public static final String PARTI_ADDRESS = PARTI_PREFIX + "address"; - // 参与方名称 - public static final String PARTI_NAME = PARTI_PREFIX + "name"; - public static final String PARTI_PK_PATH = PARTI_PREFIX + "pk-path"; - public static final String PARTI_PK = PARTI_PREFIX + "pk"; - public static final String PARTI_PASSWORD = PARTI_PREFIX + "pwd"; - - - // DB Connection Config Key Prefix; - public static final String DB_PREFIX = "db."; - - // DB Connction Attribute Key; - public static final String DB_CONN = DB_PREFIX + "uri"; - public static final String DB_PASSWORD = DB_PREFIX + "pwd"; - - // 账本名字 - public static final String LEDGER_NAME = "name"; - - // ------------------------------ - - private Map bindings = new LinkedHashMap<>(); - - public HashDigest[] getLedgerHashs() { - return bindings.keySet().toArray(new HashDigest[bindings.size()]); - } - - public BindingConfig getLedger(HashDigest hash) { - return bindings.get(hash); - } - - public void addLedgerBinding(HashDigest ledgerHash, BindingConfig binding) { - bindings.put(ledgerHash, binding); - } - - public void removeLedgerBinding(HashDigest ledgerHash) { - bindings.remove(ledgerHash); - } - - public void store(File file) { - try (FileOutputStream out = new FileOutputStream(file, false)) { - store(out); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public void store(OutputStream out) { - FileUtils.writeText(toPropertiesString(), out, CHARSET); - } - - private String toPropertiesString() { - StringBuilder builder = new StringBuilder(); - - HashDigest[] hashs = this.getLedgerHashs(); - writeLedgerHashs(builder, hashs); - writeLine(builder); - - for (int i = 0; i < hashs.length; i++) { - writeLine(builder, "#第 %s 个账本[%s]的配置;", i + 1, hashs[i].toBase58()); - BindingConfig binding = getLedger(hashs[i]); - writeLedger(builder, hashs[i], binding); - writeParticipant(builder, hashs[i], binding); - writeDB(builder, hashs[i], binding); - writeLine(builder); - } - return builder.toString(); - } - - private void writeLedgerHashs(StringBuilder builder, HashDigest[] hashs) { - writeLine(builder, "#绑定的账本的hash列表;以逗号分隔;"); - - String[] base58Hashs = new String[hashs.length]; - for (int i = 0; i < base58Hashs.length; i++) { - base58Hashs[i] = hashs[i].toBase58(); - } - String base58HashList = String.join(", \\\r\n", base58Hashs); - writeLine(builder, "%s=%s", LEDGER_BINDINS, base58HashList); - writeLine(builder); - } - - private void writeParticipant(StringBuilder builder, HashDigest ledgerHash, BindingConfig binding) { - String ledgerPrefix = String.join(ATTR_SEPERATOR, BINDING_PREFIX, ledgerHash.toBase58()); - // 参与方配置; - String partiAddressKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_ADDRESS); - String partiPkPathKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_PK_PATH); - String partiNameKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_NAME); - String partiPKKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_PK); - String partiPwdKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_PASSWORD); - - writeLine(builder, "#账本的当前共识参与方的节点地址 Address;"); - writeLine(builder, "%s=%s", partiAddressKey, stringOf(binding.getParticipant().getAddress())); - writeLine(builder, "#账本的当前共识参与方的节点名称 NodeName;"); - writeLine(builder, "%s=%s", partiNameKey, stringOf(binding.getParticipant().getName())); - writeLine(builder, "#账本的当前共识参与方的私钥文件的保存路径;"); - writeLine(builder, "%s=%s", partiPkPathKey, stringOf(binding.getParticipant().getPkPath())); - writeLine(builder, "#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性;"); - writeLine(builder, "%s=%s", partiPKKey, stringOf(binding.getParticipant().getPk())); - writeLine(builder, "#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入;"); - writeLine(builder, "%s=%s", partiPwdKey, stringOf(binding.getParticipant().getPassword())); - writeLine(builder); - } - - private void writeDB(StringBuilder builder, HashDigest ledgerHash, BindingConfig binding) { - String ledgerPrefix = String.join(ATTR_SEPERATOR, BINDING_PREFIX, ledgerHash.toBase58()); - // 数据库存储配置; - String dbConnKey = String.join(ATTR_SEPERATOR, ledgerPrefix, DB_CONN); - String dbPwdKey = String.join(ATTR_SEPERATOR, ledgerPrefix, DB_PASSWORD); - - writeLine(builder, "#账本的存储数据库的连接字符串;"); - writeLine(builder, "%s=%s", dbConnKey, stringOf(binding.getDbConnection().getUri())); - writeLine(builder, "#账本的存储数据库的连接口令;"); - writeLine(builder, "%s=%s", dbPwdKey, stringOf(binding.getDbConnection().getPassword())); - writeLine(builder); - } - - private void writeLedger(StringBuilder builder, HashDigest ledgerHash, BindingConfig binding) { - String ledgerPrefix = String.join(ATTR_SEPERATOR, BINDING_PREFIX, ledgerHash.toBase58()); - // 账本相关信息配置; - String ledgerNameKey = String.join(ATTR_SEPERATOR, ledgerPrefix, LEDGER_NAME); - - writeLine(builder, "#账本的名称;"); - writeLine(builder, "%s=%s", ledgerNameKey, stringOf(binding.getLedgerName())); - writeLine(builder); - } - - private static String stringOf(Object obj) { - if (obj == null) { - return ""; - } - return obj.toString(); - } - - private static void writeLine(StringBuilder content, String format, Object... args) { - content.append(String.format(format, args)); - content.append("\r\n"); - } - - private static void writeLine(StringBuilder content) { - content.append("\r\n"); - } - - /** - * 解析配置; - * - * @param file - * @return - */ - public static LedgerBindingConfig resolve(File file) { - Properties props = FileUtils.readProperties(file, CHARSET); - return resolve(props); - } - - /** - * 解析配置; - * - * @param in - * @return - */ - public static LedgerBindingConfig resolve(InputStream in) { - Properties props = FileUtils.readProperties(in, CHARSET); - return resolve(props); - } - - /** - * 解析配置; - * - * @param props - * @return - */ - public static LedgerBindingConfig resolve(Properties props) { - LedgerBindingConfig conf = new LedgerBindingConfig(); - - // 解析哈希列表; - String ledgerHashListString = getProperty(props, LEDGER_BINDINS, true); - String[] base58Hashs = split(ledgerHashListString, LEDGER_HASH_SEPERATOR); - if (base58Hashs.length == 0) { - return conf; - } - HashDigest[] hashs = new HashDigest[base58Hashs.length]; - for (int i = 0; i < base58Hashs.length; i++) { - byte[] hashBytes = Base58Utils.decode(base58Hashs[i]); - hashs[i] = new HashDigest(hashBytes); - - BindingConfig bindingConf = resolveBinding(props, base58Hashs[i]); - conf.bindings.put(hashs[i], bindingConf); - } - - return conf; - } - - /** - * 解析 Binding 配置; - * - * @param props - * @param ledgerHash - * @return - */ - private static BindingConfig resolveBinding(Properties props, String ledgerHash) { - BindingConfig binding = new BindingConfig(); - - String ledgerPrefix = String.join(ATTR_SEPERATOR, BINDING_PREFIX, ledgerHash); - // 参与方配置; - String partiAddrKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_ADDRESS); - String partiPkPathKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_PK_PATH); - String partiNameKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_NAME); - String partiPKKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_PK); - String partiPwdKey = String.join(ATTR_SEPERATOR, ledgerPrefix, PARTI_PASSWORD); - - binding.participant.address = getProperty(props, partiAddrKey, true); - binding.participant.name = getProperty(props, partiNameKey, true); - binding.participant.pkPath = getProperty(props, partiPkPathKey, false); - binding.participant.pk = getProperty(props, partiPKKey, false); - binding.participant.password = getProperty(props, partiPwdKey, false); -// if (binding.participant.address < 0) { -// throw new IllegalArgumentException( -// String.format("Participant id less than 0 in ledger binding[%s]!", ledgerHash)); -// } - if (binding.participant.pkPath == null && binding.participant.pk == null) { - throw new IllegalArgumentException( - String.format("No priv key config of participant of ledger binding[%s]!", ledgerHash)); - } - - // 数据库存储配置; - String dbConnKey = String.join(ATTR_SEPERATOR, ledgerPrefix, DB_CONN); - String dbPwdKey = String.join(ATTR_SEPERATOR, ledgerPrefix, DB_PASSWORD); - - binding.dbConnection.setConnectionUri(getProperty(props, dbConnKey, true)); - binding.dbConnection.setPassword(getProperty(props, dbPwdKey, false)); - if (binding.dbConnection.getUri() == null) { - throw new IllegalArgumentException( - String.format("No db connection config of participant of ledger binding[%s]!", ledgerHash)); - } - - // 设置账本名称 - String ledgerNameKey = String.join(ATTR_SEPERATOR, ledgerPrefix, LEDGER_NAME); - binding.ledgerName = getProperty(props, ledgerNameKey, true); - - return binding; - } - - private static String[] split(String str, String seperator) { - String[] items = str.split(seperator); - List validItems = new ArrayList<>(); - for (int i = 0; i < items.length; i++) { - items[i] = items[i].trim(); - if (items[i].length() > 0) { - validItems.add(items[i]); - } - } - return validItems.toArray(new String[validItems.size()]); - } - - /** - * 返回指定属性的值; - * - *
- * 当值不存在时,如果是必需参数,则抛出异常 {@link IllegalArgumentException},否则返回 null; - * - * @param props - * 属性表; - * @param key - * 属性的键; - * @param required - * 是否为必需参数; - * @return 长度大于 0 的字符串,或者 null; - */ - private static String getProperty(Properties props, String key, boolean required) { - String value = props.getProperty(key); - if (value == null) { - if (required) { - throw new IllegalArgumentException("Miss property[" + key + "]!"); - } - return null; - } - value = value.trim(); - if (value.length() == 0) { - if (required) { - throw new IllegalArgumentException("Miss property[" + key + "]!"); - } - return null; - } - return value; - } - - public static class BindingConfig { - - private String ledgerName; - - // 账本名字 - private ParticipantBindingConfig participant = new ParticipantBindingConfig(); - - private DBConnectionConfig dbConnection = new DBConnectionConfig(); - - public ParticipantBindingConfig getParticipant() { - return participant; - } - - public DBConnectionConfig getDbConnection() { - return dbConnection; - } - - public void setLedgerName(String ledgerName) { - this.ledgerName = ledgerName; - } - - public String getLedgerName() { - return ledgerName; - } - } - - public static class ParticipantBindingConfig { - - private String address; - - private String name; - - private String pkPath; - - private String pk; - - private String password; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getPkPath() { - return pkPath; - } - - public void setPkPath(String pkPath) { - this.pkPath = pkPath; - } - - public String getPk() { - return pk; - } - - public void setPk(String pk) { - this.pk = pk; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - } - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java deleted file mode 100644 index 0073a346..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java +++ /dev/null @@ -1,254 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import java.io.File; - -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig.BindingConfig; -import com.jd.blockchain.utils.ArgumentSet; -import com.jd.blockchain.utils.ArgumentSet.ArgEntry; -import com.jd.blockchain.utils.ArgumentSet.Setting; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * 账本初始化器; - * - * @author huanghaiquan - * - */ -@SpringBootApplication -@EnableAutoConfiguration -@EnableConfigurationProperties -public class LedgerInitCommand { - - private static final String LEDGER_BINDING_FILE_NAME = "ledger-binding.conf"; - - // 当前参与方的本地配置文件的路径(local.conf); - private static final String LOCAL_ARG = "-l"; - - // 账本的初始化配置文件的路径(ledger.init); - private static final String INI_ARG = "-i"; - - // 是否输出调试信息; - private static final String DEBUG_OPT = "-debug"; - - private static final String MONITOR_OPT = "-monitor"; - - private static final Prompter DEFAULT_PROMPTER = new ConsolePrompter(); - - private static final Prompter ANSWER_PROMPTER = new PresetAnswerPrompter("Y"); - - private static final Prompter LOG_PROMPTER = new LogPrompter(); - - /** - * 入口; - * - * @param args - */ - public static void main(String[] args) { - Prompter prompter = DEFAULT_PROMPTER; - - Setting argSetting = ArgumentSet.setting().prefix(LOCAL_ARG, INI_ARG).option(DEBUG_OPT).option(MONITOR_OPT); - ArgumentSet argSet = ArgumentSet.resolve(args, argSetting); - - try { - if (argSet.hasOption(MONITOR_OPT)) { - prompter = LOG_PROMPTER; - } - - ArgEntry localArg = argSet.getArg(LOCAL_ARG); - if (localArg == null) { - prompter.info("Miss local config file which can be specified with arg [%s]!!!", LOCAL_ARG); - - } - LocalConfig localConf = LocalConfig.resolve(localArg.getValue()); - - ArgEntry iniArg = argSet.getArg(INI_ARG); - if (iniArg == null) { - prompter.info("Miss ledger initializing config file which can be specified with arg [%s]!!!", INI_ARG); - return; - } - - // load ledger init setting; - LedgerInitProperties ledgerInitProperties = LedgerInitProperties.resolve(iniArg.getValue()); - String localNodePubKeyString = localConf.getLocal().getPubKeyString(); - PubKey localNodePubKey = KeyGenUtils.decodePubKey(localNodePubKeyString); - // 地址根据公钥生成 - String localNodeAddress = AddressEncoding.generateAddress(localNodePubKey).toBase58(); - - // 加载全部公钥; - int currId = -1; - for (int i = 0; i < ledgerInitProperties.getConsensusParticipantCount(); i++) { - ParticipantProperties partiConf = ledgerInitProperties.getConsensusParticipant(i); -// String partiAddress = partiConf.getAddress(); -// if (partiAddress == null) { -// if (partiConf.getPubKeyPath() != null) { -// PubKey pubKey = KeyGenUtils.readPubKey(partiConf.getPubKeyPath()); -// partiConf.setPubKey(pubKey); -// partiAddress = partiConf.getAddress(); -// } -// } - if (localNodeAddress.equals(partiConf.getAddress().toBase58())) { - currId = i; - } - } - if (currId == -1) { - throw new IllegalStateException( - "The current node specified in local.conf is not found in ledger.init!"); - } - - // 加载当前节点的私钥; - String base58Pwd = localConf.getLocal().getPassword(); - if (base58Pwd == null) { - base58Pwd = KeyGenUtils.readPasswordString(); - } - PrivKey privKey = KeyGenUtils.decodePrivKey(localConf.getLocal().getPrivKeyString(), base58Pwd); - - // Output ledger binding config of peer; - if (!FileUtils.existDirectory(localConf.getBindingOutDir())) { - FileUtils.makeDirectory(localConf.getBindingOutDir()); - } - File ledgerBindingFile = new File(localConf.getBindingOutDir(), LEDGER_BINDING_FILE_NAME); - LedgerBindingConfig conf; - if (ledgerBindingFile.exists()) { - conf = LedgerBindingConfig.resolve(ledgerBindingFile); - } else { - conf = new LedgerBindingConfig(); - } - - // 启动初始化; - LedgerInitCommand initCommand = new LedgerInitCommand(); - HashDigest newLedgerHash = initCommand.startInit(currId, privKey, base58Pwd, ledgerInitProperties, - localConf.getStoragedDb(), prompter, conf); - - if (newLedgerHash != null) { - // success; - // so save ledger binding config to file system; - conf.store(ledgerBindingFile); - prompter.info("\r\n------ Update Ledger binding configuration success! ------[%s]", - ledgerBindingFile.getAbsolutePath()); - } - - } catch (Exception e) { - prompter.error("\r\nError!! -- %s\r\n", e.getMessage()); - if (argSet.hasOption(DEBUG_OPT)) { - e.printStackTrace(); - } - - prompter.error("\r\n Ledger init process has been broken by error!"); - } - prompter.confirm(InitializingStep.LEDGER_INIT_COMPLETED.toString(), "\r\n\r\n Press any key to quit. :>"); - - if (argSet.hasOption(MONITOR_OPT)) { - // 管理工具启动的方式下,需自动退出 - System.exit(0); - } - } - - private LedgerManager ledgerManager; - - public LedgerManager getLedgerManager() { - return ledgerManager; - } - - public LedgerInitCommand() { - } - - public HashDigest startInit(int currId, PrivKey privKey, String base58Pwd, - LedgerInitProperties ledgerInitProperties, DBConnectionConfig dbConnConfig, Prompter prompter, - LedgerBindingConfig conf, Object... extBeans) { - if (currId < 0 || currId >= ledgerInitProperties.getConsensusParticipantCount()) { - prompter.info( - "Your participant id is illegal which is less than 1 or great than the total participants count[%s]!!!", - ledgerInitProperties.getConsensusParticipantCount()); - return null; - } - - // generate binding config; - BindingConfig bindingConf = new BindingConfig(); - - // 设置账本名称 - bindingConf.setLedgerName(ledgerInitProperties.getLedgerName()); - - bindingConf.getParticipant() - .setAddress(ledgerInitProperties.getConsensusParticipant(currId).getAddress().toBase58()); - // 设置参与方名称 - bindingConf.getParticipant().setName(ledgerInitProperties.getConsensusParticipant(currId).getName()); - - String encodedPrivKey = KeyGenUtils.encodePrivKey(privKey, base58Pwd); - bindingConf.getParticipant().setPk(encodedPrivKey); - bindingConf.getParticipant().setPassword(base58Pwd); - - bindingConf.getDbConnection().setConnectionUri(dbConnConfig.getUri()); - bindingConf.getDbConnection().setPassword(dbConnConfig.getPassword()); - - // confirm continue; - prompter.info("\r\n\r\n This is participant [%s], the ledger initialization is ready to start!\r\n", currId); -// ConsoleUtils.confirm("Press any key to continue... "); -// prompter.confirm("Press any key to continue... "); - - // start the web controller of Ledger Initializer; - NetworkAddress serverAddress = ledgerInitProperties.getConsensusParticipant(currId).getInitializerAddress(); - String argServerAddress = String.format("--server.address=%s", serverAddress.getHost()); - String argServerPort = String.format("--server.port=%s", serverAddress.getPort()); - String[] innerArgs = { argServerAddress, argServerPort }; - - SpringApplication app = new SpringApplication(LedgerInitCommand.class); - if (extBeans != null && extBeans.length > 0) { - app.addInitializers((ApplicationContextInitializer) applicationContext -> { - ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); - for (Object bean : extBeans) { - beanFactory.registerSingleton(bean.toString(), bean); - } - }); - } - ConfigurableApplicationContext ctx = app.run(innerArgs); - this.ledgerManager = ctx.getBean(LedgerManager.class); - - prompter.info("\r\n------ Web controller of Ledger Initializer[%s:%s] was started. ------\r\n", - serverAddress.getHost(), serverAddress.getPort()); - - try { - LedgerInitProcess initProc = ctx.getBean(LedgerInitProcess.class); - HashDigest ledgerHash = initProc.initialize(currId, privKey, ledgerInitProperties, - bindingConf.getDbConnection(), prompter); - - if (ledgerHash == null) { - // ledger init fail; - prompter.error("\r\n------ Ledger initialize fail! ------\r\n"); - return null; - } else { - prompter.info("\r\n------ Ledger initialize success! ------"); - prompter.info("New Ledger Hash is :[%s]", ledgerHash.toBase58()); - - if (conf == null) { - conf = new LedgerBindingConfig(); - } - conf.addLedgerBinding(ledgerHash, bindingConf); - - return ledgerHash; - - } - } finally { - ctx.close(); - prompter.info("\r\n------ Web listener[%s:%s] was closed. ------\r\n", serverAddress.getHost(), - serverAddress.getPort()); - } - } - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java deleted file mode 100644 index 71cc6816..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; - -/** - * - * @author huanghaiquan - * - */ -public interface LedgerInitProcess { - - /** - * Init a new ledger; - * - * @param currentId Id of current participant. - * @param privKey Private key of current participant. - * @param ledgerInitProps The settings about this initialization. - * @param dbConnConfig The configuration of DB Connection. - * @param prompter Prompter for interaction. - * @return - */ - HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, - DBConnectionConfig dbConnConfig, Prompter prompter); - - /** - * @param currentId - * @param privKey - * @param ledgerInitConfig - * @param dbConnConfig - * @param prompter - * @param cryptoSetting - * @return - */ - HashDigest initialize(int currentId, PrivKey privKey, LedgerInitConfiguration ledgerInitConfig, - DBConnectionConfig dbConnConfig, Prompter prompter); - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LocalConfig.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LocalConfig.java deleted file mode 100644 index 08b00bd7..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LocalConfig.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import java.io.File; -import java.io.InputStream; -import java.util.Properties; - -import com.jd.blockchain.utils.PathUtils; -import com.jd.blockchain.utils.PropertiesUtils; -import com.jd.blockchain.utils.io.FileUtils; - -public class LocalConfig { - - // 当前参与方的 id; - public static final String LOCAL_PARTI_PUBKEY = "local.parti.pubkey"; - - // 当前参与方的私钥(密文编码); - public static final String LOCAL_PARTI_PRIVKEY = "local.parti.privkey"; - - // 当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; - public static final String LOCAL_PARTI_PWD = "local.parti.pwd"; - - // 账本初始化完成后生成的"账本绑定配置文件"的输出目录; - public static final String LEDGER_BINDING_OUT = "ledger.binding.out"; - - // 账本数据库的连接字符串; - public static final String LEDGER_DB_URI = "ledger.db.uri"; - - // 账本数据库的连接口令; - public static final String LEDGER_DB_PWD = "ledger.db.pwd"; - -// // 共识系统的参数配置;必须参数; -// public static final String CONSENSUS_CONF = "consensus.conf"; -// -// // 共识系统的参数配置;必须参数; -// public static final String CONSENSUS_SERVICE_PROVIDER = "consensus.service-provider"; - - private LocalParticipantConfig local = new LocalParticipantConfig(); - - private String bindingOutDir; - - private DBConnectionConfig storagedDb = new DBConnectionConfig(); - - -// private String consensusConfig; -// private String consensusProvider; - - public LocalParticipantConfig getLocal() { - return local; - } - - public void setLocal(LocalParticipantConfig local) { - this.local = local; - } - - public String getBindingOutDir() { - return bindingOutDir; - } - - public void setBindingOutDir(String bindingOutDir) { - this.bindingOutDir = bindingOutDir; - } - - public DBConnectionConfig getStoragedDb() { - return storagedDb; - } - - public void setStoragedDb(DBConnectionConfig storagedDb) { - this.storagedDb = storagedDb; - } - - public static LocalConfig resolve(String initSettingFile) { - Properties props = FileUtils.readProperties(initSettingFile, "UTF-8"); - return resolve(props, initSettingFile); - } - - public static LocalConfig resolve(InputStream in) { - Properties props = FileUtils.readProperties(in, "UTF-8"); - return resolve(props, null); - } - - public static LocalConfig resolve(Properties props, String initSettingFile) { - - LocalConfig conf = new LocalConfig(); - - String pubKeyString = PropertiesUtils.getRequiredProperty(props, LOCAL_PARTI_PUBKEY); - conf.local.pubKeyString = pubKeyString; - - conf.local.privKeyString = PropertiesUtils.getRequiredProperty(props, LOCAL_PARTI_PRIVKEY); - conf.local.password = PropertiesUtils.getProperty(props, LOCAL_PARTI_PWD, false); - - conf.storagedDb.setConnectionUri(PropertiesUtils.getRequiredProperty(props, LEDGER_DB_URI)); - conf.storagedDb.setPassword(PropertiesUtils.getProperty(props, LEDGER_DB_PWD, false)); - - if (initSettingFile == null) { - conf.bindingOutDir = PropertiesUtils.getRequiredProperty(props, LEDGER_BINDING_OUT); - } else { - String bindingOutDir = PropertiesUtils.getRequiredProperty(props, LEDGER_BINDING_OUT); - String initSettingDir = PathUtils.concatPaths(initSettingFile, "../"); - conf.bindingOutDir = absolutePath(initSettingDir, bindingOutDir); - } - - return conf; - } - - private static String absolutePath(String currPath, String settingPath) { - String absolutePath = settingPath; - File settingFile = new File(settingPath); - if (!settingFile.isAbsolute()) { - absolutePath = PathUtils.concatPaths(currPath, settingPath); - } - return absolutePath; - } - - /** - * 当前参与方的本地配置信息; - * - * @author huanghaiquan - * - */ - public static class LocalParticipantConfig { - private String pubKeyString; - - private String privKeyString; - - private String password; - - public String getPubKeyString() { - return pubKeyString; - } - - public void setId(String pubKeyString) { - this.pubKeyString = pubKeyString; - } - - public String getPrivKeyString() { - return privKeyString; - } - - public void setPrivKeyString(String privKeyString) { - this.privKeyString = privKeyString; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - } - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LogPrompter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LogPrompter.java deleted file mode 100644 index ccc6a850..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LogPrompter.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LogPrompter implements Prompter { - - private static final Logger LOGGER = LoggerFactory.getLogger(LogPrompter.class); - - private static final String ANSWER_DEFAULT = "Yes"; - - private boolean debug = true; - - @Override - public void info(String format, Object... args) { - LOGGER.info(format, args); - } - - @Override - public void error(String format, Object... args) { - LOGGER.error(format, args); - } - - @Override - public void error(Exception error, String format, Object... args) { - if (debug) { - error.printStackTrace(); - LOGGER.error(error.toString()); - } - } - - @Override - public String confirm(String format, Object... args) { - return confirm("", format, args); - } - - @Override - public String confirm(String tag, String format, Object... args) { - String msg = String.format(format, args); - LOGGER.info(msg); - return ANSWER_DEFAULT; - } - - public boolean isDebug() { - return debug; - } - - public void setDebug(boolean debug) { - this.debug = debug; - } - -} \ No newline at end of file diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/PresetAnswerPrompter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/PresetAnswerPrompter.java deleted file mode 100644 index dbd06917..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/PresetAnswerPrompter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -import java.util.Properties; - -public class PresetAnswerPrompter extends ConsolePrompter { - - private Properties answers = new Properties(); - - private String defaultAnswer; - - public PresetAnswerPrompter(String defaultAnswer) { - this.defaultAnswer = defaultAnswer; - } - - public void setAnswer(String tag, String answer) { - answers.setProperty(tag, answer); - } - - public void setDefaultAnswer(String defaultAnswer) { - this.defaultAnswer = defaultAnswer; - } - - @Override - public String confirm(String tag, String format, Object... args) { - System.out.print(String.format(format, args)); - String answer = answers.getProperty(tag, defaultAnswer); - System.out.println(String.format("\r\n [Default answer:%s]", answer)); - return answer; - } -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/Prompter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/Prompter.java deleted file mode 100644 index b1f589dd..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/Prompter.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jd.blockchain.tools.initializer; - -public interface Prompter { - - //定义一些常用的问答常量; - - /** - * 询问是或否; - */ - public static final String QUESTION_YESNO = "YES/NO"; - - /** - * 提示按任意键继续; - */ - public static final String PROMPT_ANYKEY_TO_CONTINUE = "ANYKEY"; - - /** - * - */ - public static final String ANSWER_YES = "Y"; - - public static final String ANSWER_NO = "N"; - - - - - void info(String format, Object... args); - - void error(String format, Object... args); - - void error(Exception error, String format, Object... args); - - String confirm(String format, Object... args); - - String confirm(String tag, String format, Object... args); - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DataCodes.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DataCodes.java deleted file mode 100644 index 184745cb..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DataCodes.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -public interface DataCodes { - public static final int PERMISSION = 0x0010; -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/HttpInitConsensServiceFactory.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/HttpInitConsensServiceFactory.java deleted file mode 100644 index cc1f87ad..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/HttpInitConsensServiceFactory.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -import com.jd.blockchain.utils.http.agent.HttpServiceAgent; -import com.jd.blockchain.utils.http.agent.ServiceEndpoint; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class HttpInitConsensServiceFactory implements InitConsensusServiceFactory { - - @Override - public LedgerInitConsensusService connect(NetworkAddress endpointAddress) { - ServiceEndpoint endpoint = new ServiceEndpoint(endpointAddress); - LedgerInitConsensusService initConsensus = HttpServiceAgent.createService(LedgerInitConsensusService.class, - endpoint); - return initConsensus; - } - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitConsensusServiceFactory.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitConsensusServiceFactory.java deleted file mode 100644 index c6c4dad7..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitConsensusServiceFactory.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -import com.jd.blockchain.utils.net.NetworkAddress; - -public interface InitConsensusServiceFactory { - - public LedgerInitConsensusService connect(NetworkAddress endpointAddress); - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConfiguration.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConfiguration.java deleted file mode 100644 index d453cc26..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConfiguration.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerInitException; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.LedgerInitProperties.CryptoProperties; -import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; -import com.jd.blockchain.ledger.LedgerPermission; -import com.jd.blockchain.ledger.SecurityInitData; -import com.jd.blockchain.ledger.TransactionPermission; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerSecurityManager; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.utils.StringUtils; - -public class LedgerInitConfiguration { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private static final String DEFAULT_HASH_ALGORITHM = "SHA256"; - - private ParticipantProperties[] participants; - - private ConsensusConfig consensusConfiguration; - - private CryptoConfig cryptoConfig; - - private ConsensusConfig consensusConfig; - - private LedgerInitData ledgerSettings; - - private SecurityInitData securitySettings; - - public ParticipantProperties[] getParticipants() { - return participants; - } - - public int getParticipantCount() { - return participants.length; - } - - /** - * @param id - * @return - */ - public ParticipantProperties getParticipant(int id) { - // 注:解析的过程确保了参与方列表是升序排列,且列表中第一个参与方的 id 为 0, id 以 1 递增; - return participants[id]; - } - - public ConsensusConfig getConsensusConfiguration() { - return consensusConfiguration; - } - - public CryptoConfig getCryptoConfig() { - return cryptoConfig; - } - - public ConsensusConfig getConsensusConfig() { - return consensusConfig; - } - - public LedgerInitData getLedgerSettings() { - return ledgerSettings; - } - - public SecurityInitData getSecuritySettings() { - return securitySettings; - } - - private LedgerInitConfiguration() { - } - - public void setConsensusSettings(ConsensusProvider consensusProvider, ConsensusSettings consensusSettings) { - byte[] consensusSettingBytes = encodeConsensusSettings(consensusProvider, consensusSettings); - ledgerSettings.setConsensusProvider(consensusProvider.getName()); - ledgerSettings.setConsensusSettings(consensusSettingBytes); - } - - public static LedgerInitConfiguration create(LedgerInitProperties ledgerInitProps) { - LedgerInitConfiguration ledgerConfig = new LedgerInitConfiguration(); - - CryptoConfig cryptoConfig = createCryptoConfig(ledgerInitProps.getCryptoProperties()); - ledgerConfig.cryptoConfig = cryptoConfig; - - ConsensusConfig consensusConfig = createConsensusConfig(ledgerInitProps); - ledgerConfig.consensusConfig = consensusConfig; - - ParticipantProperties[] participants = resolveParticipants(ledgerInitProps); - ledgerConfig.participants = participants; - - LedgerInitData ledgerSettings = createLedgerInitSettings(ledgerInitProps, cryptoConfig, consensusConfig, - participants); - ledgerConfig.ledgerSettings = ledgerSettings; - - SecurityInitData securitySettings = createSecurityInitSettings(ledgerInitProps, participants); - ledgerConfig.securitySettings = securitySettings; - - return ledgerConfig; - } - - private static ConsensusConfig createConsensusConfig(LedgerInitProperties initProps) { - ConsensusProvider consensusProvider = ConsensusProviders.getProvider(initProps.getConsensusProvider()); - - Properties csProps = initProps.getConsensusConfig(); - ConsensusSettings protocolSettings = consensusProvider.getSettingsFactory().getConsensusSettingsBuilder() - .createSettings(csProps, initProps.getConsensusParticipantNodes()); - - ConsensusConfig config = new ConsensusConfig(); - config.setProvider(consensusProvider); - config.setProtocolSettings(protocolSettings); - - return config; - } - - private static CryptoConfig createCryptoConfig(CryptoProperties cryptoProperties) { - // 总是包含默认的提供者; - Set cryptoProviderNames = new LinkedHashSet(); - for (String providerName : SUPPORTED_PROVIDERS) { - cryptoProviderNames.add(providerName); - } - if (cryptoProperties.getProviders() != null) { - for (String providerName : cryptoProperties.getProviders()) { - cryptoProviderNames.add(providerName); - } - } - CryptoProvider[] cryptoProviders = new CryptoProvider[cryptoProviderNames.size()]; - int i = 0; - for (String providerName : cryptoProviderNames) { - cryptoProviders[i] = Crypto.getProvider(providerName); - i++; - } - - String hashAlgorithmName = StringUtils.trim(cryptoProperties.getHashAlgorithm()); - hashAlgorithmName = hashAlgorithmName.length() == 0 ? DEFAULT_HASH_ALGORITHM : hashAlgorithmName; - CryptoAlgorithm hashAlgorithm = Crypto.getAlgorithm(hashAlgorithmName); - - CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setSupportedProviders(cryptoProviders); - cryptoConfig.setAutoVerifyHash(cryptoProperties.isVerifyHash()); - cryptoConfig.setHashAlgorithm(hashAlgorithm); - - return cryptoConfig; - } - - private static SecurityInitData createSecurityInitSettings(LedgerInitProperties ledgerInitProps, - ParticipantProperties[] participants) { - // 设置角色; - SecurityInitData securityInitData = new SecurityInitData(); - securityInitData.setRoles(ledgerInitProps.getRoles()); - // 如果没有默认角色,则创建“默认”角色; - if (securityInitData.getRolesCount() == 0) { - securityInitData.addRole(LedgerSecurityManager.DEFAULT_ROLE, LedgerPermission.values(), - TransactionPermission.values()); - } else if (!securityInitData.containsRole(LedgerSecurityManager.DEFAULT_ROLE)) { - // 如果定义了角色,则必须显式地定义“默认”角色; - throw new LedgerInitException("Miss definition of role[DEFAULT]!"); - } - - // 设置授权; - for (ParticipantProperties partiProps : participants) { - String[] roles = partiProps.getRoles(); - for (String role : roles) { - if (!securityInitData.containsRole(role)) { - throw new LedgerInitException( - String.format("The role[%s] authenticated to participant[%s-%s] is not defined!", role, - partiProps.getId(), partiProps.getName())); - } - } - //去掉对默认角色的授权; - - securityInitData.addUserAuthencation(partiProps.getAddress(), roles, partiProps.getRolesPolicy()); - } - - return securityInitData; - } - - private static LedgerInitData createLedgerInitSettings(LedgerInitProperties ledgerProps, - CryptoSetting cryptoSetting, ConsensusConfig consensusConfig, ParticipantProperties[] participants) { - // 创建初始化配置; - LedgerInitData initSetting = new LedgerInitData(); - initSetting.setLedgerSeed(ledgerProps.getLedgerSeed()); - initSetting.setCryptoSetting(cryptoSetting); - - initSetting.setConsensusParticipants(participants); - - initSetting.setCreatedTime(ledgerProps.getCreatedTime()); - - // 创建共识配置; - try { - byte[] consensusSettingsBytes = encodeConsensusSettings(consensusConfig.getProvider(), - consensusConfig.protocolSettings); - initSetting.setConsensusProvider(consensusConfig.getProvider().getName()); - initSetting.setConsensusSettings(consensusSettingsBytes); - } catch (Exception e) { - throw new LedgerInitException("Create default consensus config failed! --" + e.getMessage(), e); - } - - return initSetting; - } - - public static byte[] encodeConsensusSettings(ConsensusProvider consensusProvider, - ConsensusSettings consensusSettings) { - return consensusProvider.getSettingsFactory().getConsensusSettingsEncoder().encode(consensusSettings); - } - - /** - * 解析参与方列表; - * - * @param ledgerInitProps - * @return - */ - private static ParticipantProperties[] resolveParticipants(LedgerInitProperties ledgerInitProps) { - List partiList = ledgerInitProps.getConsensusParticipants(); - ParticipantProperties[] parties = new ParticipantProperties[partiList.size()]; - parties = partiList.toArray(parties); - ParticipantProperties[] orderedParties = sortAndVerify(parties); - - return orderedParties; - } - - /** - * 对参与者列表按照 id 进行升序排列,并校验id是否从 1 开始且没有跳跃; - * - * @param parties - * @return - */ - private static ParticipantProperties[] sortAndVerify(ParticipantProperties[] parties) { - Arrays.sort(parties, new Comparator() { - @Override - public int compare(ParticipantProperties o1, ParticipantProperties o2) { - return o1.getId() - o2.getId(); - } - }); - for (int i = 0; i < parties.length; i++) { - if (parties[i].getId() != i) { - throw new LedgerInitException( - "The ids of participants are not match their positions in the participant-list!"); - } - } - return parties; - } - - public static class ConsensusConfig { - - private ConsensusProvider provider; - - private ConsensusSettings protocolSettings; - - public ConsensusSettings getProtocolSettings() { - return protocolSettings; - } - - public void setProtocolSettings(ConsensusSettings protocolSettings) { - this.protocolSettings = protocolSettings; - } - - public ConsensusProvider getProvider() { - return provider; - } - - public void setProvider(ConsensusProvider provider) { - this.provider = provider; - } - } -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConsensusService.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConsensusService.java deleted file mode 100644 index 46ae01b5..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConsensusService.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.utils.http.HttpAction; -import com.jd.blockchain.utils.http.HttpMethod; -import com.jd.blockchain.utils.http.HttpService; -import com.jd.blockchain.utils.http.PathParam; -import com.jd.blockchain.utils.http.RequestBody; - -@HttpService -public interface LedgerInitConsensusService { - - /** - * 请求账本的初始化许可; - * - * @param requesterId - * 发起请求的参与者 id; - * @param signature - * 请求者的私钥对 “id” + “账本种子” 做出的签名;只有签名合法且参与者是初始化配置中的参与方才能获得有效返回,否则将被拒绝; - */ - @HttpAction(path = "/legerinit/permission/{requesterId}", method = HttpMethod.POST, contentType = LedgerInitMessageConverter.CONTENT_TYPE_VALUE, responseConverter = PermissionResponseConverter.class) - LedgerInitProposal requestPermission(@PathParam(name = "requesterId") int requesterId, - @RequestBody(converter = SignatureDigestRequestBodyConverter.class) SignatureDigest signature); - - /** - * 同步账本初始化决议; - * - * @param initDecision - * 调用者的账本初始化决议; - * @return 目标参与方的账本初始化决议;如果目标参与者尚未准备就绪, 则返回 null; - */ - @HttpAction(path = "/legerinit/decision", method = HttpMethod.POST, contentType = LedgerInitMessageConverter.CONTENT_TYPE_VALUE, responseConverter = DecisionResponseConverter.class) - LedgerInitDecision synchronizeDecision(@RequestBody(converter = DecisionRequestBodyConverter.class) LedgerInitDecision initDecision); - -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitDecisionData.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitDecisionData.java deleted file mode 100644 index 702d4a48..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitDecisionData.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.ledger.core.LedgerInitDecision; - -public class LedgerInitDecisionData implements LedgerInitDecision { - - private int participantId; - - private HashDigest ledgerHash; - - private SignatureDigest signature; - - @Override - public int getParticipantId() { - return participantId; - } - - @Override - public HashDigest getLedgerHash() { - return ledgerHash; - } - - @Override - public SignatureDigest getSignature() { - return signature; - } - - public void setParticipantId(int participantId) { - this.participantId = participantId; - } - - public void setLedgerHash(HashDigest ledgerHash) { - this.ledgerHash = ledgerHash; - } - - public void setSignature(SignatureDigest signature) { - this.signature = signature; - } - - } \ No newline at end of file diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitResponse.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitResponse.java deleted file mode 100644 index 1f803963..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitResponse.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.Serializable; - -import com.jd.blockchain.utils.io.ByteArray; -import com.jd.blockchain.utils.io.BytesEncoding; -import com.jd.blockchain.utils.io.BytesSerializable; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.NumberMask; - -public class LedgerInitResponse implements BytesSerializable, Serializable { - - private static final long serialVersionUID = -475554045260920722L; - - private boolean error; - - private String errorMessage; - - private byte[] data; - - public boolean isError() { - return error; - } - - public String getErrorMessage() { - return errorMessage; - } - - public byte[] getData() { - return data; - } - - private LedgerInitResponse() { - } - - public static LedgerInitResponse error(String messageFormat, Object... args) { - LedgerInitResponse resp = new LedgerInitResponse(); - resp.error = true; - resp.errorMessage = String.format(messageFormat, args); - return resp; - } - - public static LedgerInitResponse success(byte[] data) { - LedgerInitResponse resp = new LedgerInitResponse(); - resp.error = false; - resp.data = data; - return resp; - } - - public static LedgerInitResponse resolve(InputStream in) { - LedgerInitResponse resp = new LedgerInitResponse(); - long uid = BytesUtils.readLong(in); - if (uid != serialVersionUID) { - throw new IllegalArgumentException("Illegal bytes of " + LedgerInitResponse.class.getName() + "!"); - } - resp.error = BytesUtils.readByte(in) == 1; - if (resp.error) { - byte[] errorMsgBytes = BytesEncoding.read(NumberMask.SHORT, in); - resp.errorMessage = BytesUtils.toString(errorMsgBytes, "UTF-8"); - } - resp.data = BytesEncoding.read(NumberMask.NORMAL, in); - return resp; - } - - public static LedgerInitResponse resolve(byte[] bytes) { - ByteArrayInputStream in = new ByteArrayInputStream(bytes); - return resolve(in); - } - - @Override - public byte[] toBytes() { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BytesUtils.writeLong(serialVersionUID, out); - BytesUtils.writeByte(error ? (byte) 1 : (byte) 0, out); - if (error) { - byte[] errorBytes = ByteArray.fromString(errorMessage, "UTF-8"); - BytesEncoding.write(errorBytes, NumberMask.SHORT, out); - } - BytesEncoding.write(data, NumberMask.NORMAL, out); - return out.toByteArray(); - } -} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java deleted file mode 100644 index 0d4216ea..00000000 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java +++ /dev/null @@ -1,727 +0,0 @@ -package com.jd.blockchain.tools.initializer.web; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.LedgerInitException; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerInitProposalData; -import com.jd.blockchain.ledger.core.LedgerInitializer; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.InitializingStep; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.transaction.DigitalSignatureBlob; -import com.jd.blockchain.transaction.SignatureUtils; -import com.jd.blockchain.utils.concurrent.InvocationResult; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -/** - * 账本初始化控制器; - * - * @author huanghaiquan - * - */ -@RestController -public class LedgerInitializeWebController implements LedgerInitProcess, LedgerInitConsensusService { - - static { - DataContractRegistry.register(TransactionRequest.class); - } - - private static final String DEFAULT_SIGN_ALGORITHM = "ED25519"; - - /** - * 决定值列表并发处理,必须等待Local释放 - * - */ - private final CountDownLatch decisionsCountDownLatch = new CountDownLatch(1); - - private final SignatureFunction SIGN_FUNC; - - private volatile LedgerInitConfiguration ledgerInitConfig; - - private volatile LedgerInitializer initializer; - - private volatile LedgerInitProposal localPermission; - - private volatile int currentId = -1; - - private volatile LedgerInitProposal[] permissions; - - private volatile NetworkAddress[] initializerAddresses; - - private volatile Prompter prompter; - - private volatile LedgerInitDecision localDecision; - - private volatile DecisionResultHandle[] decisions; - - private volatile DbConnection dbConn; - - @Autowired - private DbConnectionFactory dbConnFactory; - - @Autowired - private InitConsensusServiceFactory initCsServiceFactory; - - public LedgerInitializeWebController() { - this.SIGN_FUNC = Crypto.getSignatureFunction(DEFAULT_SIGN_ALGORITHM); - } - - public LedgerInitializeWebController(DbConnectionFactory dbConnFactory, - InitConsensusServiceFactory initCsServiceFactory) { - this.SIGN_FUNC = Crypto.getSignatureFunction(DEFAULT_SIGN_ALGORITHM); - - this.dbConnFactory = dbConnFactory; - this.initCsServiceFactory = initCsServiceFactory; - } - - public int getId() { - return currentId; - } - - public TransactionContent getInitTxContent() { - return initializer.getTransactionContent(); - } - - public LedgerInitProposal getLocalPermission() { - return localPermission; - } - - public LedgerInitDecision getLocalDecision() { - return localDecision; - } - - public void setPrompter(Prompter prompter) { - this.prompter = prompter; - } - - @Override - public HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, - DBConnectionConfig dbConnConfig, Prompter prompter) { - LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(ledgerInitProps); - return initialize(currentId, privKey, initConfig, dbConnConfig, prompter); - } - - @Override - public HashDigest initialize(int currentId, PrivKey privKey, LedgerInitConfiguration initConfig, - DBConnectionConfig dbConnConfig, Prompter prompter) { - if (initConfig == null) { - throw new IllegalArgumentException("Ledger init configuration is null"); - } - if (this.ledgerInitConfig != null) { - throw new IllegalStateException("ledger init process has already started."); - } - - setPrompter(prompter); - -// Properties csProps = ledgerInitProps.getConsensusConfig(); -// ConsensusProvider csProvider = ConsensusProviders.getProvider(ledgerInitProps.getConsensusProvider()); -// ConsensusSettings csSettings = csProvider.getSettingsFactory().getConsensusSettingsBuilder() -// .createSettings(csProps, ledgerInitProps.getConsensusParticipantNodes()); -// setConsensusProvider(csProvider); - - prompter.info("Init settings and sign permision..."); - - this.ledgerInitConfig = initConfig; - - prepareLocalPermission(currentId, privKey, ledgerInitConfig); - - prompter.confirm(InitializingStep.PERMISSION_READY.toString(), - "Ledger init permission has already prepared! Any key to continue..."); - - prompter.info("Start consensus with each other participant..."); - - // 从其它参与者获得许可; - boolean allPermitted = consensusPermissions(currentId, privKey); - - if (allPermitted) { - prompter.info("All participants permitted!"); - } else { - prompter.error("Initialization is broken because of not all participants permitting!"); - return null; - } - - try { - // 连接数据库; - connectDb(dbConnConfig); - - // 生成账本; - makeLocalDecision(privKey); - - // 获取其它参与方的账本生成结果; - return consensusDecisions(privKey); - } finally { - closeDb(); - } - } - - public boolean consensusPermisions(PrivKey privKey) { - return consensusPermissions(currentId, privKey); - } - - public DbConnection connectDb(DBConnectionConfig dbConnConfig) { - this.dbConn = dbConnFactory.connect(dbConnConfig.getUri(), dbConnConfig.getPassword()); - return dbConn; - } - - public LedgerInitDecision makeLocalDecision(PrivKey privKey) { - - try { - // 生成账本; - initializer.prepareLedger(dbConn.getStorageService(), getNodesSignatures()); - - // 生成签名决定; - this.localDecision = makeDecision(currentId, initializer.getLedgerHash(), privKey); - this.decisions = new DecisionResultHandle[ledgerInitConfig.getParticipantCount()]; - for (int i = 0; i < decisions.length; i++) { - // 参与者的 id 是依次递增的; - this.decisions[i] = new DecisionResultHandle(i); - } - // 预置当前参与方的“决定”到列表,避免向自己发起请求; - this.decisions[currentId].setValue(localDecision); - } finally { - // 释放,以便于其他节点接收 - this.decisionsCountDownLatch.countDown(); - } - - return localDecision; - } - - private DigitalSignature[] getNodesSignatures() { - ParticipantNode[] parties = this.ledgerInitConfig.getParticipants(); - DigitalSignature[] signatures = new DigitalSignature[parties.length]; - for (int i = 0; i < parties.length; i++) { - PubKey pubKey = parties[i].getPubKey(); - SignatureDigest signDigest = this.permissions[i].getTransactionSignature(); - signatures[i] = new DigitalSignatureBlob(pubKey, signDigest); - } - - return signatures; - } - - public HashDigest consensusDecisions(PrivKey privKey) { - // 获取其它参与方的账本生成结果; - boolean allDecided = startRequestDecisions(privKey, prompter); - if (!allDecided) { - prompter.error( - "Rollback ledger initialization because of not all nodes make same decision! --[Current Participant=%s]", - currentId); - initializer.cancel(); - return null; - } - - // 执行提交提交; - initializer.commit(); - return initializer.getLedgerHash(); - } - - public void closeDb() { - if (dbConn != null) { - DbConnection connection = dbConn; - dbConn = null; - try { - connection.close(); - } catch (IOException e) { - prompter.error(e, "Error occurred on closing db connection! --" + e.getMessage()); - } - } - } - - /** - * 在所有参与者之间进行第一阶段的共识:账本创建许可; - * - * @param privKey - * @return - */ - private boolean consensusPermissions(int currentId, PrivKey privKey) { - // 从其它参与者获得许可; - boolean allPermitted = false; - int retry = 0; - do { - allPermitted = startRequestPermissions(currentId, privKey); - if (!allPermitted) { - if (retry < 16) { - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore interrupted exception; - } - } else { - String r = prompter.confirm( - "\r\n Some permissions were rejected! Do you retry again? Press 'Y' to retry, any others to quit. :>"); - if (!"Y".equalsIgnoreCase(r)) { - throw new LedgerInitException("Ledger init process has broken!"); - } - retry = 0; - } - - retry++; - prompter.info("Retry requesting permissions...[%s]", retry); - } - } while (!allPermitted); - - return allPermitted; - } - -// public CryptoSetting createDefaultCryptoSetting() { -// CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; -// for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { -// supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); -// } -// CryptoConfig defCryptoSetting = new CryptoConfig(); -// defCryptoSetting.setSupportedProviders(supportedProviders); -// defCryptoSetting.setAutoVerifyHash(true); -// defCryptoSetting.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); -// -// return defCryptoSetting; -// } -// - public LedgerInitProposal prepareLocalPermission(int currentId, PrivKey privKey, - LedgerInitProperties ledgerInitProps) { - LedgerInitConfiguration ledgerInitConfiguration = LedgerInitConfiguration.create(ledgerInitProps); - return prepareLocalPermission(currentId, privKey, ledgerInitConfiguration); - } - - public LedgerInitProposal prepareLocalPermission(int currentId, PrivKey privKey, - LedgerInitConfiguration ledgerInitConfig) { - // 创建初始化配置; - ParticipantProperties[] participants = ledgerInitConfig.getParticipants(); - if (currentId < 0 || currentId >= participants.length) { - throw new LedgerInitException("Your id is out of bound of participant list!"); - } - this.currentId = currentId; - - // 校验当前的公钥、私钥是否匹配; - byte[] testBytes = BytesUtils.toBytes(currentId); - SignatureDigest testSign = SIGN_FUNC.sign(privKey, testBytes); - PubKey myPubKey = participants[currentId].getPubKey(); - if (!SIGN_FUNC.verify(testSign, myPubKey, testBytes)) { - throw new LedgerInitException("Your pub-key specified in the init-settings isn't match your priv-key!"); - } - this.initializerAddresses = new NetworkAddress[participants.length]; - // 记录每个参与方的账本初始化服务地址; - for (int i = 0; i < participants.length; i++) { - initializerAddresses[i] = participants[i].getInitializerAddress(); - } - - // 初始化账本; - this.initializer = LedgerInitializer.create(ledgerInitConfig.getLedgerSettings(), - ledgerInitConfig.getSecuritySettings()); - - // 对初始交易签名,生成当前参与者的账本初始化许可; - SignatureDigest permissionSign = initializer.signTransaction(privKey); - LedgerInitProposalData permission = new LedgerInitProposalData(currentId, permissionSign); - - this.currentId = currentId; - this.permissions = new LedgerInitProposal[ledgerInitConfig.getParticipantCount()]; - this.permissions[currentId] = permission; - this.localPermission = permission; - - return permission; - } - - private LedgerInitDecision makeDecision(int participantId, HashDigest ledgerHash, PrivKey privKey) { - byte[] dataBytes = getDecisionBytes(participantId, ledgerHash); - SignatureFunction signFunc = Crypto.getSignatureFunction(privKey.getAlgorithm()); - SignatureDigest signature = signFunc.sign(privKey, dataBytes); - - LedgerInitDecisionData decision = new LedgerInitDecisionData(); - decision.setParticipantId(participantId); - decision.setLedgerHash(ledgerHash); - decision.setSignature(signature); - return decision; - } - - /** - * 请求所有其它参与方的账本创建许可; - * - * @param privKey - * @return - */ - private boolean startRequestPermissions(int currentId, PrivKey privKey) { - SignatureDigest reqAuthSign = signPermissionRequest(currentId, privKey); - - ParticipantNode[] participants = ledgerInitConfig.getParticipants(); - - // 异步请求结果列表;不包括已经获得许可的参与方; - InvocationResult[] results = new InvocationResult[participants.length]; - int unpermittedCount = 0; - for (int i = 0; i < participants.length; i++) { - if (this.permissions[i] == null) { - unpermittedCount++; - } - } - - // 发起请求; - CountDownLatch latch = new CountDownLatch(unpermittedCount); - for (int i = 0; i < participants.length; i++) { - if (this.permissions[i] == null) { - results[i] = doRequestPermission(participants[i].getId(), reqAuthSign, latch); - } - } - - // 等待结果; - try { - while (!latch.await(5000, TimeUnit.MILLISECONDS)) { - List waitingIds = new ArrayList<>(); - for (int i = 0; i < results.length; i++) { - if (results[i] != null) { - if (results[i].getValue() == null) { - waitingIds.add("" + (i + 1)); - } - } - } - - prompter.info("\r\nWaiting for permissions of participants[%s] ...", String.join(",", waitingIds)); - } - } catch (InterruptedException e) { - throw new LedgerInitException( - "Process of requesting participant permissions was interrupted! --" + e.getMessage(), e); - } - - // 校验接入许可; - boolean allPermitted = true; - for (int i = 0; i < results.length; i++) { - if (results[i] == null) {// 忽略自己; - continue; - } - if (results[i].getError() != null) { - prompter.error(results[i].getError(), - "Error occurred on requesting permission from participant[Id=%s, name=%s]!", - participants[i].getAddress(), participants[i].getName()); - allPermitted = false; - continue; - } - PubKey pubKey = participants[i].getPubKey(); - LedgerInitProposal permission = (LedgerInitProposal) results[i].getValue(); - if (permission.getParticipantId() != participants[i].getId()) { - prompter.error("\r\nThe id of received permission isn't equal to it's participant ! --[Id=%s][name=%s]", - participants[i].getAddress(), participants[i].getName()); - allPermitted = false; - continue; - } - - if (!SignatureUtils.verifySignature(initializer.getTransactionContent(), - permission.getTransactionSignature(), pubKey)) { - prompter.error("Invalid permission from participant! --[Id=%s][name=%s]", participants[i].getAddress(), - participants[i].getName()); - allPermitted = false; - continue; - } - this.permissions[i] = permission; - } - return allPermitted; - } - - private byte[] getDecisionBytes(int participantId, HashDigest ledgerHash) { - return BytesUtils.concat(BytesUtils.toBytes(participantId), ledgerHash.toBytes()); - } - - private LedgerInitConsensusService connectToParticipant(int participantId) { - return initCsServiceFactory.connect(this.initializerAddresses[participantId]); - } - - public SignatureDigest signPermissionRequest(int requesterId, PrivKey privKey) { - byte[] reqAuthBytes = BytesUtils.concat(BytesUtils.toBytes(requesterId), - ledgerInitConfig.getLedgerSettings().getLedgerSeed()); - SignatureDigest reqAuthSign = SIGN_FUNC.sign(privKey, reqAuthBytes); - return reqAuthSign; - } - - /** - * 向指定的参与方请求其对于账本初始化参数的许可签名; - * - * @param targetId - * @param reqAuthSign - * @param latch - * @return - */ - private InvocationResult doRequestPermission(int targetId, SignatureDigest reqAuthSign, - CountDownLatch latch) { - InvocationResult result = new InvocationResult<>(); - try { - LedgerInitConsensusService initConsensus = connectToParticipant(targetId); - Thread thrd = new Thread(new Runnable() { - @Override - public void run() { - try { - LedgerInitProposal permission = initConsensus.requestPermission(currentId, reqAuthSign); - result.setValue(permission); - } catch (Exception e) { - result.setError(e); - } finally { - latch.countDown(); - } - } - }); - thrd.start(); - } catch (Exception e) { - result.setError(e); - } - return result; - } - - @RequestMapping(path = "/legerinit/permission/{requesterId}", method = RequestMethod.POST, produces = LedgerInitMessageConverter.CONTENT_TYPE_VALUE, consumes = LedgerInitMessageConverter.CONTENT_TYPE_VALUE) - @Override - public LedgerInitProposal requestPermission(@PathVariable(name = "requesterId") int requesterId, - @RequestBody SignatureDigest signature) { - if (requesterId == currentId) { - throw new LedgerInitException("There is a id conflict!"); - } - int retry = 0; - while (currentId == -1 || ledgerInitConfig == null || localPermission == null) { - // 本地尚未完成初始化; - if (retry < 30) { - try { - Thread.sleep(800); - } catch (InterruptedException e) { - // ignore interrupted exception; - } - } else { - return null; - } - retry++; - } - - ParticipantNode[] participants = ledgerInitConfig.getParticipants(); - if (requesterId < 0 || requesterId >= participants.length) { - throw new LedgerInitException("The id of requester is out of the bound of participant list!"); - } - byte[] requestCodeBytes = BytesUtils.concat(BytesUtils.toBytes(requesterId), - ledgerInitConfig.getLedgerSettings().getLedgerSeed()); - PubKey requesterPubKey = participants[requesterId].getPubKey(); - if (!SIGN_FUNC.verify(signature, requesterPubKey, requestCodeBytes)) { - throw new LedgerInitException("The requester signature is invalid!"); - } - return localPermission; - } - - /** - * 开始请求所有成员的账本创建决定; - */ - private boolean startRequestDecisions(PrivKey privKey, Prompter prompter) { - // 进行随机化选择请求的目标列表的顺序; - Random rand = new Random(); - DecisionResultHandle[] randDecHdls = Arrays.copyOf(this.decisions, this.decisions.length); - DecisionResultHandle temp; - for (int i = 0; i < randDecHdls.length; i++) { - int a = rand.nextInt(randDecHdls.length); - int b = rand.nextInt(randDecHdls.length); - temp = randDecHdls[a]; - randDecHdls[a] = randDecHdls[b]; - randDecHdls[b] = temp; - } - - // 请求; - boolean allDecided = false; - while (!allDecided) { - allDecided = true; - for (int i = 0; i < randDecHdls.length; i++) { - if (randDecHdls[i].getValue() != null) { - // 忽略当前参与方自己(在初始化“决定”时已经置为非空),以及已经收到主动提交“决定”的参与方; - continue; - } - boolean decided = doSynchronizeDecision(randDecHdls[i].PARTICIPANT_ID, privKey, randDecHdls[i], - prompter); - allDecided = allDecided & decided; - } - if (!allDecided) { - String r = prompter.confirm( - "\r\nSome decisions were rejected! Do you retry again? Press 'Y' to retry, any others to quit. :>"); - if (!"Y".equalsIgnoreCase(r)) { - return false; - } - } - } - - return allDecided; - } - - /** - * 与指定的参与方同步“账本初始化决定({@link LedgerInitDecision})”; - * - * @param targetId - * @param privKey - * @param resultHandle - * @param prompter - * @return - */ - private boolean doSynchronizeDecision(int targetId, PrivKey privKey, DecisionResultHandle resultHandle, - Prompter prompter) { - try { - LedgerInitConsensusService initConsensus = connectToParticipant(targetId); - LedgerInitDecision targetDecision = null; - int retry = 0; - do { - prompter.info("Start synchronizling decision from participant[%s] to participant[%s] ......", currentId, - targetId); - try { - targetDecision = initConsensus.synchronizeDecision(localDecision); - } catch (Exception e1) { - prompter.info("Error occurred on synchronizing decision . --[%s] %s", e1.getClass().getName(), - e1.getMessage()); - } - if (targetDecision == null) { - if (resultHandle.getValue() != null) { - // 已经验证过; - return true; - } - // 对方的账本初始化尚未就绪;隔5秒重试;重试超过3后提示确认是否继续重试; - if (retry == 16) { - String r = prompter.confirm( - "Target participant[%s] isn't ready to do decision! Do you want to retry again?\r\n" - + " Press 'Y' to retry, and any others to break this participant and to continue synchronizing with others. :>", - targetId); - if (!"Y".equalsIgnoreCase(r)) { - return false; - } - retry = 0; - } - prompter.info( - "Target participant[%s] isn't ready to do decision! Waiting 5 seconds and retry again...", - targetId); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore InterruptedException; - } - retry++; - } - } while (targetDecision == null); - - if (targetDecision.getParticipantId() != targetId && resultHandle.getValue() == null) { - prompter.error( - "The received id of participant isn't equal to id of request target participant! --[Id=%s]", - targetId); - return false; - } - - return validateAndRecordDecision(targetDecision, resultHandle); - } catch (Exception e) { - prompter.error(e, "Error occurred on synchronizing decision from participant[%s] to participant[%s] ! --%s", - currentId, targetId, e.getMessage()); - return false; - } - } - - /** - * 校验并记录指定的参与方做出的决定; - *

- * 注:对 {@link DecisionResultHandle#setValue(LedgerInitDecision)} - * 方法的调用不是线程安全的,但由于是在满足有效性校验之后才调用,具有幂等性,所以不必对该方法的多处调用进行同步; - * - * @param targetDecision - * @param resultHandle - * @param hashAlgorithm - * @return - */ - private synchronized boolean validateAndRecordDecision(LedgerInitDecision targetDecision, - DecisionResultHandle resultHandle) { - if ((!localDecision.getLedgerHash().equals(targetDecision.getLedgerHash())) - && resultHandle.getValue() == null) { - // 如果结果已经被 - prompter.error( - "The received ledger hash of participant isn't equal to ledger hash of current participant! --[Id=%s]", - targetDecision.getParticipantId()); - return false; - } - - // 检查签名; - PubKey targetPubKey = ledgerInitConfig.getParticipant(targetDecision.getParticipantId()).getPubKey(); - byte[] deciBytes = getDecisionBytes(targetDecision.getParticipantId(), targetDecision.getLedgerHash()); - if ((!SIGN_FUNC.verify(targetDecision.getSignature(), targetPubKey, deciBytes)) - && resultHandle.getValue() == null) { - prompter.error("The signature of received decision is invalid! --[Id=%s]", - targetDecision.getParticipantId()); - return false; - } - - resultHandle.setValue(targetDecision); - return true; - } - - @RequestMapping(path = "/legerinit/decision", method = RequestMethod.POST, produces = LedgerInitMessageConverter.CONTENT_TYPE_VALUE, consumes = LedgerInitMessageConverter.CONTENT_TYPE_VALUE) - @Override - public LedgerInitDecision synchronizeDecision(@RequestBody LedgerInitDecision initDecision) { - int remoteId = initDecision.getParticipantId(); - if (remoteId == currentId) { - prompter.error("Reject decision because of self-synchronization! --[Id=%s]", remoteId); - throw new LedgerInitException( - String.format("Reject decision because of self-synchronization! --[Id=%s]", remoteId)); - } - - if (this.initializer == null) { - // 当前参与者尚未准备就绪,返回 null; - prompter.info("Not ready for genesis block! --[RemoteId=%s][CurrentId=%s]", remoteId, currentId); - return null; - } - - prompter.info("Received request of synchronizing decision! --[RemoteId=%s][CurrentId=%s]", remoteId, currentId); - - try { - - // 必须等待本地处理完成,此处线程阻塞 - this.decisionsCountDownLatch.await(); - - DecisionResultHandle resultHandle = this.decisions[remoteId]; - if (!validateAndRecordDecision(initDecision, resultHandle)) { - // 签名无效; - prompter.error("Reject decision because of invalid signature! --[RemoteId=%s][CurrentId=%s]", remoteId, - currentId); - throw new LedgerInitException( - String.format("Reject decision because of invalid signature! --[RemoteId=%s][CurrentId=%s]", - remoteId, currentId)); - } - return localDecision; - } catch (Exception e) { - prompter.error(e, - "Error occurred while receiving the request of synchronizing decision! --[RemoteId=%s][CurrentId=%s] %s", - remoteId, currentId, e.getMessage()); - throw new LedgerInitException( - "Error occurred while receiving the request of synchronizing decision! --" + e.getMessage(), e); - } - } - - private static class DecisionResultHandle extends InvocationResult { - - private final int PARTICIPANT_ID; - - public DecisionResultHandle(int participantId) { - this.PARTICIPANT_ID = participantId; - } - - } - -} diff --git a/source/tools/tools-initializer/src/main/resources/banner.txt b/source/tools/tools-initializer/src/main/resources/banner.txt deleted file mode 100644 index c39618bd..00000000 --- a/source/tools/tools-initializer/src/main/resources/banner.txt +++ /dev/null @@ -1,13 +0,0 @@ - - ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄ -▐░░░░░░░░░░░▌▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░▌ ▐░▌ - ▀▀▀▀▀█░█▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░▌░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ - ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ - ▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▐░▌ -▐░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░░▌ - ▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀ - diff --git a/source/tools/tools-initializer/src/main/resources/local.conf b/source/tools/tools-initializer/src/main/resources/local.conf deleted file mode 100644 index dc7c7347..00000000 --- a/source/tools/tools-initializer/src/main/resources/local.conf +++ /dev/null @@ -1,18 +0,0 @@ - -#当前参与方的公钥; -local.parti.pubkey=endPsK36sC5JdPCDPDAXUwZtS3sxEmqEhFcC4whayAsTTh8Z6eoZ - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsj5PHeCpbAtJE7qnbmhuZMHAEKuMsd45zHkv8F8AWBvTBbff8yRKdCyT3kwrmAjSnY - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=./ - -#账本数据库的连接字符串; -ledger.db.uri=redis://127.0.0.1/0 - -#账本数据库的连接口令; -ledger.db.pwd= diff --git a/source/tools/tools-initializer/src/main/resources/log4j2-init.xml b/source/tools/tools-initializer/src/main/resources/log4j2-init.xml deleted file mode 100644 index fe98c0c1..00000000 --- a/source/tools/tools-initializer/src/main/resources/log4j2-init.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/tools/tools-initializer/src/main/resources/mq.config b/source/tools/tools-initializer/src/main/resources/mq.config deleted file mode 100644 index 9795a9de..00000000 --- a/source/tools/tools-initializer/src/main/resources/mq.config +++ /dev/null @@ -1,6 +0,0 @@ -system.msg.queue.server=nats://127.0.0.1:4222 -system.msg.queue.topic.tx=tx-topic -system.msg.queue.topic.bl=bl-topic -system.msg.queue.topic.msg=msg-topic -system.msg.queue.block.txsize=1000 -system.msg.queue.block.maxdelay=2000 \ No newline at end of file diff --git a/source/tools/tools-initializer/src/main/resources/system.config b/source/tools/tools-initializer/src/main/resources/system.config deleted file mode 100644 index 2f2c9185..00000000 --- a/source/tools/tools-initializer/src/main/resources/system.config +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#Unique ID of node. -server.1.address= -server.1.pubkey= diff --git a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/ConsensusSettingTest.java b/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/ConsensusSettingTest.java deleted file mode 100644 index 0500d122..00000000 --- a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/ConsensusSettingTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package test.com.jd.blockchain.tools.initializer; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import java.io.*; - -/** - * Created by zhangshuang3 on 2018/9/11. - */ -public class ConsensusSettingTest { - - @Test - public void systemFileToBytes() throws Exception { - - ClassPathResource systemConfigResource = new ClassPathResource("bftsmart.config"); - InputStream fis = systemConfigResource.getInputStream(); - ByteArrayOutputStream bos = null; - FileOutputStream fos = null; - byte[] buffer = null; - - try { - bos = new ByteArrayOutputStream(1000); - byte[] b = new byte[1000]; - int n; - while ((n = fis.read(b)) != -1) { - bos.write(b, 0, n); - } - //file to bytes - buffer = bos.toByteArray(); - //bytes to file - File file = new File("bftsmart.config"); - fos = new FileOutputStream(file); - fos.write(buffer); - } catch (FileNotFoundException e) { - throw new Exception(e.getMessage(), e); - } catch (IOException e) { - throw new Exception(e.getMessage(), e); - } finally { - if (fis != null) { - fis.close(); - } - if (bos != null) { - bos.close(); - } - if (fos != null) { - fos.close(); - } - } - return; - } -} \ No newline at end of file diff --git a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerBindingConfigTest.java b/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerBindingConfigTest.java deleted file mode 100644 index dab50f75..00000000 --- a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerBindingConfigTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package test.com.jd.blockchain.tools.initializer; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig.BindingConfig; -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -public class LedgerBindingConfigTest { - - @Test - public void testResolveAndStore() throws IOException { - ClassPathResource ledgerBindingConfigFile = new ClassPathResource("ledger-binding.conf"); - InputStream in = ledgerBindingConfigFile.getInputStream(); - try { - LedgerBindingConfig conf = LedgerBindingConfig.resolve(in); - assertLedgerBindingConfig(conf); - - conf.store(System.out); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - conf.store(out); - - ByteArrayInputStream newIn = new ByteArrayInputStream(out.toByteArray()); - LedgerBindingConfig newConf = LedgerBindingConfig.resolve(newIn); - - assertLedgerBindingConfig(newConf); - } finally { - in.close(); - } - } - -// @Test -// public void testLedgerBindingRegister() throws IOException { -// LedgerManager ledgerManager = new LedgerManager(); -// ClassPathResource ledgerBindingConfigFile = new ClassPathResource("ledger-binding-1.conf"); -// InputStream in = ledgerBindingConfigFile.getInputStream(); -// Exception ex = null; -// try { -// LedgerBindingConfig conf = LedgerBindingConfig.resolve(in); -//// assertLedgerBindingConfig(conf); -// -// HashDigest[] existingLedgerHashs = ledgerManager.getLedgerHashs(); -// for (HashDigest lh : existingLedgerHashs) { -// ledgerManager.unregister(lh); -// } -// HashDigest[] ledgerHashs = conf.getLedgerHashs(); -// for (HashDigest ledgerHash : ledgerHashs) { -//// setConfig(conf,ledgerHash); -// LedgerBindingConfig.BindingConfig bindingConfig = conf.getLedger(ledgerHash); -// } -// } catch (Exception e) { -// ex =e; -// } finally { -// in.close(); -// } -// -// assertNull(ex); -// } - - /** - * 判断指定的对象跟测试模板是否一致; - * - * @param conf - */ - private void assertLedgerBindingConfig(LedgerBindingConfig conf) { - String[] expectedHashs = { "j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk", - "j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf" }; - HashDigest[] hashs = conf.getLedgerHashs(); - for (int i = 0; i < hashs.length; i++) { - assertEquals(expectedHashs[i], hashs[i].toBase58()); - } - - BindingConfig bindingConf_0 = conf.getLedger(hashs[0]); - assertEquals("1", bindingConf_0.getParticipant().getAddress()); - assertEquals("keys/jd-com.priv", bindingConf_0.getParticipant().getPkPath()); - assertEquals("AdSXsf5QJpy", bindingConf_0.getParticipant().getPk()); - assertNull(bindingConf_0.getParticipant().getPassword()); - - assertEquals("redis://ip:port/1", bindingConf_0.getDbConnection().getUri()); - assertEquals("kksfweffj", bindingConf_0.getDbConnection().getPassword()); - - BindingConfig bindingConf_1 = conf.getLedger(hashs[1]); - assertEquals("2", bindingConf_1.getParticipant().getAddress()); - assertEquals("keys/jd-com-1.priv", bindingConf_1.getParticipant().getPkPath()); - assertNull(bindingConf_1.getParticipant().getPk()); - assertEquals("kksafe", bindingConf_1.getParticipant().getPassword()); - - assertEquals("redis://ip:port/2", bindingConf_1.getDbConnection().getUri()); - assertNull(bindingConf_1.getDbConnection().getPassword()); - } - -} diff --git a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/TestConsts.java b/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/TestConsts.java deleted file mode 100644 index 50078db2..00000000 --- a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/TestConsts.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.intgr.perf.IntegrationBase - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/12/25 下午3:40 - * Description: - */ -package test.com.jd.blockchain.tools.initializer; - -import java.util.concurrent.atomic.AtomicLong; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.LedgerInitOperation; -import com.jd.blockchain.ledger.UserRegisterOperation; - -public class TestConsts { - - static { - DataContractRegistry.register(LedgerInitOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - } - - public static final String PASSWORD = "abc"; - - public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; - - public static final String[] PRIV_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - -} \ No newline at end of file diff --git a/source/tools/tools-initializer/src/test/resources/bftsmart.config b/source/tools/tools-initializer/src/test/resources/bftsmart.config deleted file mode 100644 index df69caf5..00000000 --- a/source/tools/tools-initializer/src/test/resources/bftsmart.config +++ /dev/null @@ -1,144 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage - - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#Configuration of all node servers; -#PubKey of node server with specified ID, with base58 encoding. -system.server.0.pubkey= -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=8900 -system.server.0.network.secure=false - -system.server.1.pubkey= -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=8910 -system.server.1.network.secure=false - -system.server.2.pubkey= -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=8920 -system.server.2.network.secure=false - -system.server.3.pubkey= -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=8920 -system.server.3.network.secure=false diff --git a/source/tools/tools-initializer/src/test/resources/keys/parti2.pub b/source/tools/tools-initializer/src/test/resources/keys/parti2.pub deleted file mode 100644 index dde44b8e..00000000 --- a/source/tools/tools-initializer/src/test/resources/keys/parti2.pub +++ /dev/null @@ -1 +0,0 @@ -3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x \ No newline at end of file diff --git a/source/tools/tools-initializer/src/test/resources/ledger-binding.conf b/source/tools/tools-initializer/src/test/resources/ledger-binding.conf deleted file mode 100644 index 82b1ba3d..00000000 --- a/source/tools/tools-initializer/src/test/resources/ledger-binding.conf +++ /dev/null @@ -1,38 +0,0 @@ - - -#绑定的账本的hash列表;以逗号分隔; -ledger.bindings=j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk, \ -j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf - -#第1个账本[j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk]的配置; -#账本的当前共识参与方的ID; -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.name= PRODUCT-INFO -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.address=1 -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.name=PARTI-01 -#账本的当前共识参与方的私钥文件的保存路径; -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.pk-path=keys/jd-com.priv -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.pk=AdSXsf5QJpy -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.pwd= -#账本的存储数据库的连接字符串; -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.db.uri=redis://ip:port/1 -#账本的存储数据库的连接口令; -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.db.pwd=kksfweffj - - -#第2个账本[j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf]的配置; -#账本的当前共识参与方的ID; -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.name= BASIC-INFO -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.address=2 -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.name=PARTI-02 -#账本的当前共识参与方的私钥文件的保存路径; -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.pk-path=keys/jd-com-1.priv -#账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.pk= -#账本的当前共识参与方的私钥文件的读取口令;可为空;如果为空时,节点的启动过程中需要手动从控制台输入; -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.pwd=kksafe -#账本的存储数据库的连接字符串; -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.db.uri=redis://ip:port/2 -#账本的存储数据库的连接口令; -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.db.pwd= \ No newline at end of file diff --git a/source/tools/tools-initializer/src/test/resources/ledger.init b/source/tools/tools-initializer/src/test/resources/ledger.init deleted file mode 100644 index ebbd8872..00000000 --- a/source/tools/tools-initializer/src/test/resources/ledger.init +++ /dev/null @@ -1,158 +0,0 @@ - -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name=test - -#声明账本的创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 -created-time=2019-08-01 14:26:58.069+0800 - - -#----------------------------------------------- -# 初始的角色名称列表;可选项; -# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; -# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; -# -# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; -# -security.roles=DEFAULT, ADMIN, MANAGER, GUEST - -# 赋予角色的账本权限清单;可选项; -# 可选的权限如下; -# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, -# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, -# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -# APPROVE_TX, CONSENSUS_TX -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT - -# 赋予角色的交易权限清单;可选项; -# 可选的权限如下; -# DIRECT_OPERATION, CONTRACT_OPERATION -# 多项权限之间用逗点“,”分隔; -# -security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 其它角色的配置示例; -# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; -security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER -security.role.ADMIN.tx-privileges=DIRECT_OPERATION - -# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; -security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, -security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION - -# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; -security.role.GUEST.ledger-privileges= -security.role.GUEST.tx-privileges=CONTRACT_OPERATION - - - -#----------------------------------------------- -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path=keys/jd-com.pub -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的角色清单;可选项; -cons_parti.0.roles=ADMIN, MANAGER -#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.0.roles-policy=UNION -#第0个参与方的共识服务的主机地址; -cons_parti.0.consensus.host=127.0.0.1 -#第0个参与方的共识服务的端口; -cons_parti.0.consensus.port=8900 -#第0个参与方的共识服务是否开启安全连接; -cons_parti.0.consensus.secure=true -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=8800 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=true - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path=keys/at-com.pub -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的角色清单;可选项; -cons_parti.1.roles=MANAGER -#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.1.roles-policy=UNION -#第1个参与方的共识服务的主机地址; -cons_parti.1.consensus.host=127.0.0.1 -#第1个参与方的共识服务的端口; -cons_parti.1.consensus.port=8910 -#第1个参与方的共识服务是否开启安全连接; -cons_parti.1.consensus.secure=false -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=8810 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path=classpath:keys/parti2.pub -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey= -#第2个参与方的角色清单;可选项; -cons_parti.2.roles=MANAGER -#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.2.roles-policy=UNION -#第2个参与方的共识服务的主机地址; -cons_parti.2.consensus.host=127.0.0.1 -#第2个参与方的共识服务的端口; -cons_parti.2.consensus.port=8920 -#第2个参与方的共识服务是否开启安全连接; -cons_parti.2.consensus.secure=false -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=8820 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=true - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path=keys/xt-com.pub -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的角色清单;可选项; -cons_parti.3.roles=GUEST -#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; -cons_parti.3.roles-policy=INTERSECT -#第3个参与方的共识服务的主机地址; -cons_parti.3.consensus.host=127.0.0.1 -#第3个参与方的共识服务的端口; -cons_parti.3.consensus.port=8930 -#第3个参与方的共识服务是否开启安全连接; -cons_parti.3.consensus.secure=false -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=8830 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false diff --git a/source/tools/tools-initializer/src/test/resources/local.conf b/source/tools/tools-initializer/src/test/resources/local.conf deleted file mode 100644 index 9df0303c..00000000 --- a/source/tools/tools-initializer/src/test/resources/local.conf +++ /dev/null @@ -1,25 +0,0 @@ - -#当前参与方的公钥; -local.parti.pubkey=endPsK36sC5JdPCDPDAXUwZtS3sxEmqEhFcC4whayAsTTh8Z6eoZ - -#当前参与方的私钥(密文编码); -local.parti.privkey=177gjsj5PHeCpbAtJE7qnbmhuZMHAEKuMsd45zHkv8F8AWBvTBbff8yRKdCyT3kwrmAjSnY - -#当前参与方的私钥解密密钥(原始口令的一次哈希,Base58格式),如果不设置,则启动过程中需要从控制台输入; -local.parti.pwd=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY - -#账本初始化完成后生成的"账本绑定配置文件"的输出目录; -ledger.binding.out=./ - -#账本数据库的连接字符串; -ledger.db.uri=redis://127.0.0.1/0 - -#账本数据库的连接口令; -ledger.db.pwd= - -#共识协议的参数配置;必须参数; -consensus.conf=mq.config - -#共识协议的实现类型;必须参数; -consensus.service-provider=com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider - diff --git a/source/tools/tools-initializer/src/test/resources/mq.config b/source/tools/tools-initializer/src/test/resources/mq.config deleted file mode 100644 index 9795a9de..00000000 --- a/source/tools/tools-initializer/src/test/resources/mq.config +++ /dev/null @@ -1,6 +0,0 @@ -system.msg.queue.server=nats://127.0.0.1:4222 -system.msg.queue.topic.tx=tx-topic -system.msg.queue.topic.bl=bl-topic -system.msg.queue.topic.msg=msg-topic -system.msg.queue.block.txsize=1000 -system.msg.queue.block.maxdelay=2000 \ No newline at end of file diff --git a/source/tools/tools-initializer/src/test/resources/system.config b/source/tools/tools-initializer/src/test/resources/system.config deleted file mode 100644 index ada42b49..00000000 --- a/source/tools/tools-initializer/src/test/resources/system.config +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 400 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage diff --git a/source/tools/tools-joiner/src/test/java/com/jd/blockchain/AppTest.java b/source/tools/tools-joiner/src/test/java/com/jd/blockchain/AppTest.java deleted file mode 100644 index 941b907f..00000000 --- a/source/tools/tools-joiner/src/test/java/com/jd/blockchain/AppTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -/** - * Unit test for simple App. - */ -public class AppTest -{ - /** - * Rigorous Test :-) - */ - @Test - public void shouldAnswerWithTrue() - { - assertTrue( true ); - } -} diff --git a/source/tools/tools-keygen-booter/src/main/java/com/jd/blockchain/tools/keygen/boot/KeyGenBooter.java b/source/tools/tools-keygen-booter/src/main/java/com/jd/blockchain/tools/keygen/boot/KeyGenBooter.java deleted file mode 100644 index c0ce182c..00000000 --- a/source/tools/tools-keygen-booter/src/main/java/com/jd/blockchain/tools/keygen/boot/KeyGenBooter.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jd.blockchain.tools.keygen.boot; - -import com.jd.blockchain.tools.keygen.KeyGenCommand; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; - -public class KeyGenBooter { - - private static final String charSet = "UTF-8"; - - private static final String jarSuffix = ".jar"; - - public static void main(String[] args) { - load(); - KeyGenCommand.main(args); - } - - - private static void load() { - List jarPaths = loadPaths(); - try { - if (!jarPaths.isEmpty()) { - loadJars(jarPaths); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static void loadJars(List jarPaths) throws Exception { - Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); - boolean accessible = method.isAccessible(); - try { - if (accessible == false) { - method.setAccessible(true); - } - // 获取系统类加载器 - URLClassLoader classLoader = (URLClassLoader) Thread - .currentThread() - .getContextClassLoader(); - for (File file : jarPaths) { - URL url = file.toURI().toURL(); - try { - method.invoke(classLoader, url); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - } finally { - method.setAccessible(accessible); - } - } - - private static List loadPaths() { - List loadJarFiles = new ArrayList<>(); - URL url = KeyGenBooter.class - .getProtectionDomain() - .getCodeSource() - .getLocation(); - try { - String currPath = java.net.URLDecoder.decode(url.getPath(), charSet); - if (currPath.endsWith(jarSuffix)) { - currPath = currPath.substring(0, currPath.lastIndexOf("/") + 1); - } - File file = new File(currPath); - loadJarFiles.addAll(dirJars(file)); - // 获取上级路径 - String systemPath = file.getParent() + File.separator + "system"; - loadJarFiles.addAll(dirJars(new File(systemPath))); - } catch (Exception e) { - throw new RuntimeException(e); - } - return loadJarFiles; - } - - private static List dirJars(File dir) { - List jars = new ArrayList<>(); - if (dir.exists() && dir.isDirectory()) { - File[] jarArray = dir.listFiles(); - if (jarArray != null) { - for (File jar : jarArray) { - if (jar.getAbsolutePath().endsWith(jarSuffix)) { - jars.add(jar); - } - } - } - } - return jars; - } -} diff --git a/source/tools/tools-keygen-booter/src/main/resources/META-INF/MANIFEST.MF b/source/tools/tools-keygen-booter/src/main/resources/META-INF/MANIFEST.MF deleted file mode 100644 index bdb5fd98..00000000 --- a/source/tools/tools-keygen-booter/src/main/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Created-By: 1.8.0 -Built-By: shaozhuguang@jd.com -Extension-Name: JDChain -Specification-Title: JDChain -Specification-Vendor: JD Software Foundation -Implementation-Vendor: JD Software Foundation -Implementation-URL: http://ledger.jd.com -Build-Jdk: 1.8.0 diff --git a/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java b/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java deleted file mode 100644 index cd2df93c..00000000 --- a/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java +++ /dev/null @@ -1,218 +0,0 @@ - -package com.jd.blockchain.tools.keygen; - -import static com.jd.blockchain.crypto.KeyGenUtils.decodePubKey; -import static com.jd.blockchain.crypto.KeyGenUtils.decryptedPrivKeyBytes; -import static com.jd.blockchain.crypto.KeyGenUtils.encodePrivKey; -import static com.jd.blockchain.crypto.KeyGenUtils.encodePubKey; -import static com.jd.blockchain.crypto.KeyGenUtils.readPassword; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import com.jd.blockchain.crypto.AsymmetricKeypair; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.utils.ArgumentSet; -import com.jd.blockchain.utils.ArgumentSet.ArgEntry; -import com.jd.blockchain.utils.ArgumentSet.Setting; -import com.jd.blockchain.utils.ConsoleUtils; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.security.DecryptionException; - -public class KeyGenCommand { - - // 指定 -r 参数时为“读取模式”,显示密钥文件; -r 参数之后紧跟着指定要读取的公钥或者私钥文件的路径; - private static final String READ_ARG = "-r"; - - // 在“读取模式”下指定 -d 参数时要求输入密码,并显示解密后的私钥明文; - private static final String OPT_DECRYPTING = "-d"; - - // 未指定 -r 参数时为“生成模式”,输出密钥文件;通过 -o - // 参数指定文件的输出目录;并通过第一个名称参数指定密钥名称,密钥的保存文件以指定的名称命名; - private static final String OUT_DIR_ARG = "-o"; - - private static final String NAME_ARG = "-n"; - - // 指定local.conf的路径,以方便直接修改local.conf配置文件 - private static final String LOCAL_CONF_ARG = "-l"; - - // 是否输出调试信息; - private static final String OPT_DEBUG = "-debug"; - - /** - * 入口; - * - * @param args - */ - public static void main(String[] args) { - Setting setting = ArgumentSet.setting().prefix(READ_ARG, NAME_ARG, OUT_DIR_ARG, LOCAL_CONF_ARG) - .option(OPT_DECRYPTING, OPT_DEBUG); - ArgumentSet argSet = ArgumentSet.resolve(args, setting); - try { - ArgEntry[] argEntries = argSet.getArgs(); - if (argEntries.length == 0) { - ConsoleUtils.info("Miss argument!\r\n" - + "-r : Run in reading mode if set this option, or in generating mode if not set.\r\n" - + "-d : Decrypt priv key in reading mode, optional.\r\n" + "-n : name of key.\r\n" - + "-o : output dir of key under generating mode.\r\n"); - return; - } - - if (argSet.getArg(READ_ARG) != null) { - readKey(argSet.getArg(READ_ARG).getValue(), argSet.hasOption(OPT_DECRYPTING)); - } else { - ArgEntry name = argSet.getArg(NAME_ARG); - if (name == null) { - ConsoleUtils.info("Miss name of key!"); - return; - } - String outputDir = null; - ArgEntry dirArg = argSet.getArg(OUT_DIR_ARG); - if (dirArg == null || dirArg.getValue() == null) { - // 在当前目录生成; - outputDir = "." + File.separatorChar; - - // ConsoleUtils.info("Miss storage dir of keys!"); - // return; - } else { - outputDir = dirArg.getValue(); - } - if (!FileUtils.existDirectory(outputDir)) { - // 创建目录; - ConsoleUtils.info( - "The storage dir[" + outputDir + "] doesn't exist, it will be created automatically!"); - FileUtils.makeDirectory(outputDir); -// return; - } - ArgEntry localConfArg = argSet.getArg(LOCAL_CONF_ARG); - String localConfPath = localConfArg == null ? null : localConfArg.getValue(); - - generateKeyPair(name.getValue(), outputDir, localConfPath); - } - - } catch (Exception e) { - ConsoleUtils.info("Error!!! %s", e.getMessage()); - if (argSet.hasOption(OPT_DEBUG)) { - e.printStackTrace(); - } - } - - } - - /** - * 生成密钥,要求输入密码用于保护私钥文件; - * - * @param name - * @param outputDir - */ - private static void generateKeyPair(String name, String outputDir, String localConfPath) { - AsymmetricKeypair kp = Crypto.getSignatureFunction("ED25519").generateKeypair(); - - String base58PubKey = encodePubKey(kp.getPubKey()); - - byte[] pwdBytes = readPassword(); - String base58PrivKey = encodePrivKey(kp.getPrivKey(), pwdBytes); - - File pubKeyFile = new File(outputDir, String.format("%s.pub", name)); - File privKeyFile = new File(outputDir, String.format("%s.priv", name)); - FileUtils.writeText(base58PubKey, pubKeyFile); - FileUtils.writeText(base58PrivKey, privKeyFile); - - String base58PwdKey = null; - String savePwdStr = ConsoleUtils - .confirm("Do you want to save encode password to file? Please input y or n ..."); - if (savePwdStr.equalsIgnoreCase("y") || savePwdStr.equalsIgnoreCase("yes")) { - base58PwdKey = Base58Utils.encode(pwdBytes); - File pwdFile = new File(outputDir, String.format("%s.pwd", name)); - FileUtils.writeText(base58PwdKey, pwdFile); - } else if (savePwdStr.equalsIgnoreCase("n") || savePwdStr.equalsIgnoreCase("no")) { - // do nothing - } else { - savePwdStr = ConsoleUtils.confirm("Please input y or n ..."); - if (savePwdStr.equalsIgnoreCase("y") || savePwdStr.equalsIgnoreCase("yes")) { - base58PwdKey = Base58Utils.encode(pwdBytes); - File pwdFile = new File(outputDir, String.format("%s.pwd", name)); - FileUtils.writeText(base58PwdKey, pwdFile); - } else { - // do nothing - } - } - if (localConfPath != null) { - File localConf = new File(localConfPath); - if (localConf.exists()) { - try { - List configs = org.apache.commons.io.FileUtils.readLines(localConf); - List modifyConfigs = new ArrayList<>(); - if (configs != null && !configs.isEmpty()) { - for (String configLine : configs) { - if (configLine.startsWith("local.parti.pubkey")) { - modifyConfigs.add("local.parti.pubkey=" + base58PubKey); - } else if (configLine.startsWith("local.parti.privkey")) { - modifyConfigs.add("local.parti.privkey=" + base58PrivKey); - } else if (configLine.startsWith("local.parti.pwd")) { - modifyConfigs.add("local.parti.pwd=" + base58PwdKey); - } else { - modifyConfigs.add(configLine); - } - } - } - org.apache.commons.io.FileUtils.writeLines(localConf, modifyConfigs, false); - } catch (Exception e) { - System.err.println("Error!!! --[" + e.getClass().getName() + "] " + e.getMessage()); - } - } - } - } - - /** - * 读取密钥;
- * 如果是私钥,则需要输入密码; - * - * @param keyFile - */ - public static void readKey(String keyFile, boolean decrypting) { - String base58KeyString = FileUtils.readText(keyFile); - byte[] keyBytes = Base58Utils.decode(base58KeyString); - if (KeyGenUtils.isPubKeyBytes(keyBytes)) { - if (decrypting) { - // Try reading pubKey; - PubKey pubKey = decodePubKey(keyBytes); - ConsoleUtils.info( - "======================== pub key ========================\r\n" + "[%s]\r\n" - + "Raw:[%s][%s]\r\n", - base58KeyString, pubKey.getAlgorithm(), Base58Utils.encode(pubKey.toBytes())); - } else { - ConsoleUtils.info("======================== pub key ========================\r\n" + "[%s]\r\n", - base58KeyString); - } - return; - } else if (KeyGenUtils.isPrivKeyBytes(keyBytes)) { - // Try reading privKye; - try { - if (decrypting) { - byte[] pwdBytes = readPassword(); - PrivKey privKey = decryptedPrivKeyBytes(keyBytes, pwdBytes); - ConsoleUtils.info( - "======================== priv key ========================\r\n" + "[%s]\r\n" - + "Raw:[%s][%s]\r\n", - base58KeyString, privKey.getAlgorithm(), Base58Utils.encode(privKey.toBytes())); - } else { - ConsoleUtils.info("======================== priv key ========================\r\n[%s]\r\n", - base58KeyString); - } - } catch (DecryptionException e) { - ConsoleUtils.error("Invalid password!"); - } - return; - } else { - ConsoleUtils.error("Unknow key!!"); - return; - } - } - -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerLedgerInitializer.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerLedgerInitializer.java deleted file mode 100644 index 938e12bd..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerLedgerInitializer.java +++ /dev/null @@ -1,339 +0,0 @@ -package com.jd.blockchain.mocker; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Random; - -import org.springframework.web.bind.annotation.RequestBody; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.LedgerInitException; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerInitProposalData; -import com.jd.blockchain.ledger.core.LedgerInitializer; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; -import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.initializer.web.LedgerInitDecisionData; -import com.jd.blockchain.transaction.DigitalSignatureBlob; -import com.jd.blockchain.transaction.LedgerInitData; -import com.jd.blockchain.transaction.SignatureUtils; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.concurrent.InvocationResult; -import com.jd.blockchain.utils.io.BytesUtils; - -/** - * 账本初始化控制器; - * - * @author huanghaiquan - * - */ -public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitConsensusService { - - static { - DataContractRegistry.register(TransactionRequest.class); - } - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private static final String DEFAULT_SIGN_ALGORITHM = "ED25519"; - - private final SignatureFunction SIGN_FUNC; - - private volatile LedgerInitProposal localPermission; - - private volatile LedgerInitializer initializer; - - private volatile int currentId = -1; - - private volatile LedgerInitConfiguration ledgerInitConfig; - -// private volatile LedgerInitPermission[] permissions; -// private volatile LedgerInitPermission permission; - - private volatile Prompter prompter; - - private volatile ConsensusProvider consensusProvider; - - private volatile LedgerInitDecision localDecision; - - private volatile DecisionResultHandle[] decisions; - - private volatile DbConnection dbConn; - - private LedgerManager ledgerManager; - - private DbConnectionFactory dbConnFactory; - - public MockerLedgerInitializer() { - this.SIGN_FUNC = Crypto.getSignatureFunction(DEFAULT_SIGN_ALGORITHM); - } - - public MockerLedgerInitializer(DbConnectionFactory dbConnFactory, LedgerManager ledgerManager) { - this.SIGN_FUNC = Crypto.getSignatureFunction(DEFAULT_SIGN_ALGORITHM); - this.dbConnFactory = dbConnFactory; - this.ledgerManager = ledgerManager; - } - - public int getId() { - return currentId; - } - - public TransactionContent getInitTxContent() { - return initializer.getTransactionContent(); - } - - public LedgerInitProposal getLocalPermission() { - return localPermission; - } - - public LedgerInitDecision getLocalDecision() { - return localDecision; - } - - public void setPrompter(Prompter prompter) { - this.prompter = prompter; - } - - private void setConsensusProvider(ConsensusProvider consensusProvider) { - this.consensusProvider = consensusProvider; - } - - @Override - public HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, - DBConnectionConfig dbConnConfig, Prompter prompter) { - LedgerInitConfiguration ledgerInitConfig = LedgerInitConfiguration.create(ledgerInitProps); - return initialize(currentId, privKey, ledgerInitConfig, dbConnConfig, prompter); - } - - @Override - public synchronized HashDigest initialize(int currentId, PrivKey privKey, LedgerInitConfiguration ledgerInitProps, - DBConnectionConfig dbConnConfig, Prompter prompter) { - if (this.ledgerInitConfig != null) { - throw new IllegalStateException("ledger init process has already started."); - } - - setPrompter(prompter); - - prompter.info("Init settings and sign permision..."); - - prepareLocalProposal(currentId, privKey, ledgerInitProps); - - try { - // 连接数据库; - connectDb(dbConnConfig); - - // 生成账本; - makeLocalDecision(privKey); - - // 获取其它参与方的账本生成结果; - return consensusDecisions(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - closeDb(); - } - } - - public DbConnection connectDb(DBConnectionConfig dbConnConfig) { - this.dbConn = dbConnFactory.connect(dbConnConfig.getUri(), dbConnConfig.getPassword()); - return dbConn; - } - - public LedgerInitDecision makeLocalDecision(PrivKey privKey) { - // 生成账本; -// this.ledgerEditor = ledgerManager.newLedger(this.ledgerInitSetting, dbConn.getStorageService()); -// this.genesisBlock = initLedgerDataset(ledgerEditor); - initializer.prepareLedger(dbConn.getStorageService(), getNodeSignatures()); - - // 生成签名决定; - this.localDecision = makeDecision(currentId, initializer.getLedgerHash(), privKey); - this.decisions = new DecisionResultHandle[this.ledgerInitConfig.getParticipantCount()]; - for (int i = 0; i < decisions.length; i++) { - // 参与者的 id 是依次递增的; - this.decisions[i] = new DecisionResultHandle(i); - } - // 预置当前参与方的“决定”到列表,避免向自己发起请求; - this.decisions[currentId].setValue(localDecision); - return localDecision; - } - - private DigitalSignature getNodeSignatures() { - ParticipantNode parti = this.ledgerInitConfig.getParticipant(currentId); - PubKey pubKey = parti.getPubKey(); - SignatureDigest signDigest = this.localPermission.getTransactionSignature(); - DigitalSignatureBlob digitalSignature = new DigitalSignatureBlob(pubKey, signDigest); - - return digitalSignature; - } - - public HashDigest consensusDecisions() { - // 执行提交提交; - initializer.commit(); - return initializer.getLedgerHash(); - } - - public void closeDb() { - if (dbConn != null) { - DbConnection connection = dbConn; - dbConn = null; - try { - connection.close(); - } catch (IOException e) { - prompter.error(e, "Error occurred on closing db connection! --" + e.getMessage()); - } - } - } - - public CryptoSetting createDefaultCryptoSetting() { - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig defCryptoSetting = new CryptoConfig(); - defCryptoSetting.setSupportedProviders(supportedProviders); - defCryptoSetting.setAutoVerifyHash(true); - defCryptoSetting.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); - - return defCryptoSetting; - } - - public LedgerInitProposal prepareLocalProposal(int currentId, PrivKey privKey, - LedgerInitConfiguration ledgerInitConfig) { - - if (currentId < 0 || currentId >= ledgerInitConfig.getParticipantCount()) { - throw new LedgerInitException("Your id is out of bound of participant list!"); - } - this.currentId = currentId; - - // 校验当前的公钥、私钥是否匹配; - byte[] testBytes = BytesUtils.toBytes(currentId); - SignatureDigest testSign = SIGN_FUNC.sign(privKey, testBytes); - PubKey myPubKey = ledgerInitConfig.getParticipant(currentId).getPubKey(); - if (!SIGN_FUNC.verify(testSign, myPubKey, testBytes)) { - throw new LedgerInitException("Your pub-key specified in the init-settings isn't match your priv-key!"); - } - // 初始化; - this.initializer = LedgerInitializer.create(ledgerInitConfig.getLedgerSettings(), - ledgerInitConfig.getSecuritySettings()); - - // 对初始交易签名,生成当前参与者的账本初始化许可; - SignatureDigest permissionSign = SignatureUtils.sign(initializer.getTransactionContent(), privKey); - localPermission = new LedgerInitProposalData(currentId, permissionSign); - - this.currentId = currentId; - return localPermission; - } - - private LedgerInitDecision makeDecision(int participantId, HashDigest ledgerHash, PrivKey privKey) { - byte[] dataBytes = getDecisionBytes(participantId, ledgerHash); - SignatureFunction signFunc = Crypto.getSignatureFunction(privKey.getAlgorithm()); - SignatureDigest signature = signFunc.sign(privKey, dataBytes); - - LedgerInitDecisionData decision = new LedgerInitDecisionData(); - decision.setParticipantId(participantId); - decision.setLedgerHash(ledgerHash); - decision.setSignature(signature); - return decision; - } - -// private LedgerBlock initLedgerDataset(LedgerEditor ledgerEditor) { -// // 初始化时,自动将参与方注册为账本的用户; -// TxRequestBuilder txReqBuilder = new TxRequestBuilder(this.initTxContent); -//// ParticipantNode[] parties = this.ledgerInitSetting.getConsensusParticipants(); -// ParticipantNode parti = this.ledgerInitSetting.getConsensusParticipants()[currentId]; -// -// PubKey pubKey = parti.getPubKey(); -// SignatureDigest signDigest = this.localPermission.getTransactionSignature(); -// DigitalSignatureBlob digitalSignature = new DigitalSignatureBlob(pubKey, signDigest); -// txReqBuilder.addNodeSignature(digitalSignature); -// -// TransactionRequest txRequest = txReqBuilder.buildRequest(); -// -// LedgerTransactionContext txCtx = ledgerEditor.newTransaction(txRequest); -// Operation[] ops = txRequest.getTransactionContent().getOperations(); -// // 注册用户; 注:第一个操作是 LedgerInitOperation; -// // TODO:暂时只支持注册用户的初始化操作; -// for (int i = 1; i < ops.length; i++) { -// UserRegisterOperation userRegOP = (UserRegisterOperation) ops[i]; -// txCtx.getDataset().getUserAccountSet().register(userRegOP.getUserID().getAddress(), -// userRegOP.getUserID().getPubKey()); -// } -// -// txCtx.commit(TransactionState.SUCCESS, null); -// -// return ledgerEditor.prepare(); -// } - - private byte[] getDecisionBytes(int participantId, HashDigest ledgerHash) { - return BytesUtils.concat(BytesUtils.toBytes(participantId), ledgerHash.toBytes()); - } - - @Override - public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { - return localPermission; - } - - @Override - public LedgerInitDecision synchronizeDecision(@RequestBody LedgerInitDecision initDecision) { - return localDecision; - } - - /** - * 对参与者列表按照 id 进行升序排列,并校验id是否从 1 开始且没有跳跃; - * - * @param parties - * @return - */ - private ParticipantProperties[] sortAndVerify(ParticipantProperties[] parties) { - Arrays.sort(parties, (o1, o2) -> o1.getId() - o2.getId()); - for (int i = 0; i < parties.length; i++) { - if (parties[i].getId() != i) { - throw new LedgerInitException( - "The ids of participants are not match their positions in the participant-list!"); - } - } - return parties; - } - - private static class DecisionResultHandle extends InvocationResult { - - private final int PARTICIPANT_ID; - - public DecisionResultHandle(int participantId) { - this.PARTICIPANT_ID = participantId; - } - - } - -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerNodeContext.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerNodeContext.java deleted file mode 100644 index 266f7973..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerNodeContext.java +++ /dev/null @@ -1,512 +0,0 @@ -package com.jd.blockchain.mocker; - -import static java.lang.reflect.Proxy.newProxyInstance; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import com.jd.blockchain.ledger.*; -import org.mockito.Mockito; - -import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ClientIdentification; -import com.jd.blockchain.consensus.ClientIdentifications; -import com.jd.blockchain.consensus.action.ActionRequest; -import com.jd.blockchain.consensus.action.ActionResponse; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.LedgerDataQuery; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQueryService; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerSecurityManager; -import com.jd.blockchain.ledger.core.SecurityPolicy; -import com.jd.blockchain.ledger.core.TransactionBatchProcessor; -import com.jd.blockchain.mocker.config.MockerConstant; -import com.jd.blockchain.mocker.config.PresetAnswerPrompter; -import com.jd.blockchain.mocker.handler.MockerContractExeHandle; -import com.jd.blockchain.mocker.proxy.ContractProxy; -import com.jd.blockchain.service.TransactionBatchResultHandle; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; -import com.jd.blockchain.transaction.BlockchainQueryService; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.web.serializes.ByteArrayObjectUtil; - -public class MockerNodeContext implements BlockchainQueryService { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private static final DBConnectionConfig dbConnectionConfig = new DBConnectionConfig("memory://local/0"); - - private DbConnectionFactory dbConnFactory = new MemoryDBConnFactory(); - - private DefaultOperationHandleRegisteration opHandler = new DefaultOperationHandleRegisteration(); - - private MockerContractExeHandle contractExeHandle = new MockerContractExeHandle(); - - private Map participants = new HashMap<>(); - - private LedgerManager ledgerManager = new LedgerManager(); - - private BlockchainKeypair defaultKeypair; - - private LedgerRepository ledgerRepository; - - private LedgerQueryService queryService; - - private HashDigest ledgerHash; - - private String ledgerSeed; - - static { - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); - - DataContractRegistry.register(Operation.class); - DataContractRegistry.register(ContractCodeDeployOperation.class); - DataContractRegistry.register(ContractEventSendOperation.class); - DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(UserRegisterOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.class); - DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - - DataContractRegistry.register(ActionRequest.class); - DataContractRegistry.register(ActionResponse.class); - DataContractRegistry.register(ClientIdentifications.class); - DataContractRegistry.register(ClientIdentification.class); - -// DataContractRegistry.register(LedgerAdminInfo.class); - - ByteArrayObjectUtil.init(); - } - - public MockerNodeContext() { - } - - public MockerNodeContext(String ledgerSeed) { - this.ledgerSeed = ledgerSeed; - } - - public MockerNodeContext participants(String name, BlockchainKeypair partiKey) { - participants.put(name, partiKey); - return this; - } - - public MockerNodeContext participants(BlockchainKeypair partiKey) { - participants.put(partiKey.getPubKey().toBase58(), partiKey); - return this; - } - - public MockerNodeContext build() { - if (ledgerSeed == null || ledgerSeed.length() == 0) { - ledgerSeed = MockerConstant.DEFAULT_LEDGER_SEED; - } - if (participants.size() < 4) { - // 缺少的需要补充,使用常量中的内容进行补充 - for (int i = 0; i < MockerConstant.PUBLIC_KEYS.length; i++) { - String pubKeyString = MockerConstant.PUBLIC_KEYS[i]; - boolean isExist = false; - // 通过公钥进行判断 - for (Map.Entry entry : participants.entrySet()) { - String existPubKey = KeyGenUtils.encodePubKey(entry.getValue().getPubKey()); - if (pubKeyString.equals(existPubKey)) { - isExist = true; - } - } - if (!isExist) { - // 加入系统中 - PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(MockerConstant.PRIVATE_KEYS[i], - MockerConstant.PASSWORD); - PubKey pubKey = KeyGenUtils.decodePubKey(MockerConstant.PUBLIC_KEYS[i]); - participants(new BlockchainKeypair(pubKey, privKey)); - } - if (participants.size() >= 4) { - break; - } - } - } - - LedgerInitProperties ledgerInitProperties = loadInitSetting(); - - MockerLedgerInitializer mockLedgerInitializer = new MockerLedgerInitializer(dbConnFactory, ledgerManager); - - LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(ledgerInitProperties); - initConfig.getLedgerSettings().setCryptoSetting(cryptoConfig()); - - ledgerHash = mockLedgerInitializer.initialize(0, defaultKeypair.getPrivKey(), initConfig, dbConnectionConfig, - new PresetAnswerPrompter("N")); - - ledgerRepository = registerLedger(ledgerHash, dbConnectionConfig); - - queryService = new LedgerQueryService(ledgerRepository); - - contractExeHandle.initLedger(ledgerManager, ledgerHash); - - opHandler.registerHandle(contractExeHandle); - - return this; - } - - public String registerUser(BlockchainKeypair user) { - TxBuilder txBuilder = txBuilder(); - txBuilder.users().register(user.getIdentity()); - txProcess(txRequest(txBuilder)); - return user.getAddress().toBase58(); - } - - public String registerDataAccount(BlockchainKeypair dataAccount) { - TxBuilder txBuilder = txBuilder(); - txBuilder.dataAccounts().register(dataAccount.getIdentity()); - txProcess(txRequest(txBuilder)); - return dataAccount.getAddress().toBase58(); - } - - public String registerDataAccount() { - return registerDataAccount(BlockchainKeyGenerator.getInstance().generate()); - } - - public void writeKv(String address, String key, String value, long version) { - TxBuilder txBuilder = txBuilder(); - txBuilder.dataAccount(address).setText(key, value, version); - txProcess(txRequest(txBuilder)); - } - - public void writeKv(String address, String key, long value, long version) { - TxBuilder txBuilder = txBuilder(); - txBuilder.dataAccount(address).setInt64(key, value, version); - txProcess(txRequest(txBuilder)); - } - - public void writeKv(String address, String key, byte[] value, long version) { - TxBuilder txBuilder = txBuilder(); - txBuilder.dataAccount(address).setBytes(key, value, version); - txProcess(txRequest(txBuilder)); - } - - public void writeKv(String address, String key, Bytes value, long version) { - TxBuilder txBuilder = txBuilder(); - txBuilder.dataAccount(address).setBytes(key, value, version); - txProcess(txRequest(txBuilder)); - } - - public T deployContract(T contract) { - // 首先发布合约 - BlockchainIdentity identity = deployContract2Ledger(contract); - // 生成代理对象 - ContractProxy contractProxy = new ContractProxy<>(identity, this, contract, contractExeHandle); - - T proxy = (T) newProxyInstance(contract.getClass().getClassLoader(), contract.getClass().getInterfaces(), - contractProxy); - - return proxy; - } - - private BlockchainIdentity deployContract2Ledger(Object contract) { - BlockchainIdentity contractIdentity = BlockchainKeyGenerator.getInstance().generate().getIdentity(); - // 合约发布 - // 注意此处只是将其放入内存中,而不需要真正编译为字节码 - TxBuilder txBuilder = txBuilder(); - txBuilder.contracts().deploy(contractIdentity, BytesUtils.toBytes(contract.getClass().getName())); - // 执行 - txProcess(txRequest(txBuilder)); - return contractIdentity; - } - - public String getLedgerSeed() { - return ledgerSeed; - } - - public HashDigest getLedgerHash() { - return ledgerHash; - } - - @Override - public HashDigest[] getLedgerHashs() { - return queryService.getLedgerHashs(); - } - - @Override - public LedgerInfo getLedger(HashDigest ledgerHash) { - return queryService.getLedger(ledgerHash); - } - - @Override - public LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash) { - return queryService.getLedgerAdminInfo(ledgerHash); - } - - @Override - public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { - return queryService.getConsensusParticipants(ledgerHash); - } - - @Override - public LedgerMetadata getLedgerMetadata(HashDigest ledgerHash) { - return queryService.getLedgerMetadata(ledgerHash); - } - - @Override - public LedgerBlock getBlock(HashDigest ledgerHash, long height) { - return queryService.getBlock(ledgerHash, height); - } - - @Override - public LedgerBlock getBlock(HashDigest ledgerHash, HashDigest blockHash) { - return queryService.getBlock(ledgerHash, blockHash); - } - - @Override - public long getTransactionCount(HashDigest ledgerHash, long height) { - return queryService.getTransactionCount(ledgerHash, height); - } - - @Override - public long getTransactionCount(HashDigest ledgerHash, HashDigest blockHash) { - return queryService.getTransactionCount(ledgerHash, blockHash); - } - - @Override - public long getTransactionTotalCount(HashDigest ledgerHash) { - return queryService.getTransactionTotalCount(ledgerHash); - } - - @Override - public long getDataAccountCount(HashDigest ledgerHash, long height) { - return queryService.getDataAccountCount(ledgerHash, height); - } - - @Override - public long getDataAccountCount(HashDigest ledgerHash, HashDigest blockHash) { - return queryService.getDataAccountCount(ledgerHash, blockHash); - } - - @Override - public long getDataAccountTotalCount(HashDigest ledgerHash) { - return queryService.getDataAccountTotalCount(ledgerHash); - } - - @Override - public long getUserCount(HashDigest ledgerHash, long height) { - return queryService.getUserCount(ledgerHash, height); - } - - @Override - public long getUserCount(HashDigest ledgerHash, HashDigest blockHash) { - return queryService.getUserCount(ledgerHash, blockHash); - } - - @Override - public long getUserTotalCount(HashDigest ledgerHash) { - return queryService.getUserTotalCount(ledgerHash); - } - - @Override - public long getContractCount(HashDigest ledgerHash, long height) { - return queryService.getContractCount(ledgerHash, height); - } - - @Override - public long getContractCount(HashDigest ledgerHash, HashDigest blockHash) { - return queryService.getContractCount(ledgerHash, blockHash); - } - - @Override - public long getContractTotalCount(HashDigest ledgerHash) { - return queryService.getContractTotalCount(ledgerHash); - } - - @Override - public LedgerTransaction[] getTransactions(HashDigest ledgerHash, long height, int fromIndex, int count) { - return queryService.getTransactions(ledgerHash, height, fromIndex, count); - } - - @Override - public LedgerTransaction[] getTransactions(HashDigest ledgerHash, HashDigest blockHash, int fromIndex, int count) { - return queryService.getTransactions(ledgerHash, blockHash, fromIndex, count); - } - - @Override - public LedgerTransaction getTransactionByContentHash(HashDigest ledgerHash, HashDigest contentHash) { - return queryService.getTransactionByContentHash(ledgerHash, contentHash); - } - - @Override - public TransactionState getTransactionStateByContentHash(HashDigest ledgerHash, HashDigest contentHash) { - return queryService.getTransactionStateByContentHash(ledgerHash, contentHash); - } - - @Override - public UserInfo getUser(HashDigest ledgerHash, String address) { - return queryService.getUser(ledgerHash, address); - } - - @Override - public AccountHeader getDataAccount(HashDigest ledgerHash, String address) { - return queryService.getDataAccount(ledgerHash, address); - } - - @Override - public KVDataEntry[] getDataEntries(HashDigest ledgerHash, String address, String... keys) { - return queryService.getDataEntries(ledgerHash, address, keys); - } - - @Override - public KVDataEntry[] getDataEntries(HashDigest ledgerHash, String address, KVInfoVO kvInfoVO) { - return queryService.getDataEntries(ledgerHash, address, kvInfoVO); - } - - @Override - public long getDataEntriesTotalCount(HashDigest ledgerHash, String address) { - return queryService.getDataEntriesTotalCount(ledgerHash, address); - } - - @Override - public KVDataEntry[] getDataEntries(HashDigest ledgerHash, String address, int fromIndex, int count) { - return queryService.getDataEntries(ledgerHash, address, fromIndex, count); - } - - @Override - public ContractInfo getContract(HashDigest ledgerHash, String address) { - return queryService.getContract(ledgerHash, address); - } - - @Override - public AccountHeader[] getUsers(HashDigest ledgerHash, int fromIndex, int count) { - return queryService.getUsers(ledgerHash, fromIndex, count); - } - - @Override - public AccountHeader[] getDataAccounts(HashDigest ledgerHash, int fromIndex, int count) { - return queryService.getDataAccounts(ledgerHash, fromIndex, count); - } - - @Override - public AccountHeader[] getContractAccounts(HashDigest ledgerHash, int fromIndex, int count) { - return queryService.getContractAccounts(ledgerHash, fromIndex, count); - } - - public TxBuilder txBuilder() { - return new TxBuilder(ledgerHash); - } - - public TransactionRequest txRequest(TxBuilder txBuilder) { - TransactionRequestBuilder reqBuilder = txBuilder.prepareRequest(); - reqBuilder.signAsEndpoint(defaultKeypair); - return reqBuilder.buildRequest(); - } - - private static LedgerSecurityManager getSecurityManager() { - LedgerSecurityManager securityManager = Mockito.mock(LedgerSecurityManager.class); - - SecurityPolicy securityPolicy = Mockito.mock(SecurityPolicy.class); - when(securityPolicy.isEndpointEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isEndpointEnable(any(TransactionPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(LedgerPermission.class), any())).thenReturn(true); - when(securityPolicy.isNodeEnable(any(TransactionPermission.class), any())).thenReturn(true); - - when(securityManager.createSecurityPolicy(any(), any())).thenReturn(securityPolicy); - - return securityManager; - } - - public OperationResult[] txProcess(TransactionRequest txRequest) { - LedgerEditor newEditor = ledgerRepository.createNextBlock(); - LedgerBlock latestBlock = ledgerRepository.getLatestBlock(); - LedgerDataQuery previousDataSet = ledgerRepository.getLedgerData(latestBlock); - TransactionBatchProcessor txProc = new TransactionBatchProcessor(getSecurityManager(), newEditor, - ledgerRepository, opHandler); - TransactionResponse txResp = txProc.schedule(txRequest); - TransactionBatchResultHandle handle = txProc.prepare(); - handle.commit(); - return txResp.getOperationResults(); - } - - private LedgerRepository registerLedger(HashDigest ledgerHash, DBConnectionConfig dbConnConf) { - return ledgerManager.register(ledgerHash, dbConnFactory.connect(dbConnConf.getUri()).getStorageService()); - } - - private CryptoConfig cryptoConfig() { - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig cryptoSetting = new CryptoConfig(); - cryptoSetting.setSupportedProviders(supportedProviders); - cryptoSetting.setAutoVerifyHash(false); - cryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - return cryptoSetting; - } - - private LedgerInitProperties loadInitSetting() { - - Properties ledgerProp = new Properties(); - - ledgerProp.put(LedgerInitProperties.LEDGER_SEED, ledgerSeed); - - Date now = new Date(); - SimpleDateFormat format = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); - ledgerProp.put(LedgerInitProperties.CREATED_TIME, format.format(now)); - - ledgerProp.put("ledger.name", MockerConstant.LEDGER_NAME); - - ledgerProp.put(LedgerInitProperties.CONSENSUS_SERVICE_PROVIDER, - "com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"); - - ledgerProp.put(LedgerInitProperties.CONSENSUS_CONFIG, "classpath:bftsmart.config"); - - ledgerProp.put(LedgerInitProperties.CRYPTO_SERVICE_PROVIDERS, - "com.jd.blockchain.crypto.service.classic.ClassicCryptoService," - + "com.jd.blockchain.crypto.service.sm.SMCryptoService"); - - ledgerProp.put(LedgerInitProperties.PART_COUNT, String.valueOf(participants.size())); - - int partiIndex = 0; - for (Map.Entry entry : participants.entrySet()) { - String name = entry.getKey(); - BlockchainKeypair keypair = entry.getValue(); - if (partiIndex == 0) { - defaultKeypair = keypair; - } - String partiPrefix = String.format(LedgerInitProperties.PART_ID_PATTERN, partiIndex) + "."; - ledgerProp.put(partiPrefix + LedgerInitProperties.PART_NAME, name); - ledgerProp.put(partiPrefix + LedgerInitProperties.PART_PUBKEY_PATH, ""); - ledgerProp.put(partiPrefix + LedgerInitProperties.PART_PUBKEY, - KeyGenUtils.encodePubKey(keypair.getPubKey())); - ledgerProp.put(partiPrefix + LedgerInitProperties.PART_INITIALIZER_HOST, MockerConstant.LOCAL_ADDRESS); - ledgerProp.put(partiPrefix + LedgerInitProperties.PART_INITIALIZER_PORT, - String.valueOf(MockerConstant.LEDGER_INIT_PORT_START + partiIndex * 10)); - ledgerProp.put(partiPrefix + LedgerInitProperties.PART_INITIALIZER_SECURE, String.valueOf(false)); - partiIndex++; - } - - return LedgerInitProperties.resolve(ledgerProp); - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/LedgerInitWebConfiguration.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/LedgerInitWebConfiguration.java deleted file mode 100644 index 11f6a762..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/LedgerInitWebConfiguration.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.mocker.config; - -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import com.jd.blockchain.tools.initializer.web.InitWebSecurityConfiguration; -import com.jd.blockchain.tools.initializer.web.InitWebServerConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@SpringBootApplication -@Configuration -@EnableConfigurationProperties -@Import(value = { InitWebServerConfiguration.class, InitWebSecurityConfiguration.class }) -public class LedgerInitWebConfiguration { - - @Bean - public CompositeConnectionFactory getCompositeConnectionFactory() { - return new CompositeConnectionFactory(); - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/MockerConstant.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/MockerConstant.java deleted file mode 100644 index e52f02bd..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/MockerConstant.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jd.blockchain.mocker.config; - -public class MockerConstant { - - public static final String DEFAULT_LEDGER_SEED = "932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffa"; - - public static final int PEER_PORT_START = 12000; - - public static final int LEDGER_INIT_PORT_START = 1600; - - public static final int GATEWAY_PORT = 11000; - - public static final String LOCAL_ADDRESS = "127.0.0.1"; - - public static final String LEDGER_NAME = "JDChain"; - - public static final String LEDGER_INIT_FORMATTER = "ledger%s.init"; - - public static final String[] CONSENSUS_PROVIDERS = new String[] {"com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider"}; - - public static final String PASSWORD = "abc"; - - public static final String PASSWORD_ENCODE = "DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY"; - - public static final String[] PUBLIC_KEYS = { - "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", - "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", - "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", - "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk", - "3snPdw7i7PXPRMp3EAjsxJkHe7aZJRLNzdW8kEHBWeQsSgcPAiHP2J", - "3snPdw7i7PmmQoPgUpUmmAUj6nakHj8wMSQmiMi1RaiZp4YU1D4AXk", - "3snPdw7i7PiJKsa94q3EcLT1y6GRJ7LeFGe799hdzRRHmf6LNodyiM", - "3snPdw7i7Pm2wJwEnKn8kK8eGTkN36C2BZRRjVTr9FPB2rqtcgTq7h" - }; - - public static final String[] ADDRESS_ARRAY = { - "LdeP3fY7jJbNwL8CiL2wU21AF9unDWQjVEW5w", - "LdeNnz88dH6CA6PwkVdn3nFRibUKP3sFT2byG", - "LdeNmdpT4DiTwLUP9jRQhwdRBRiXeHno456vy", - "LdeNekdXMHqyz9Qxc2jDSBnkvvZLbty6pRDdP", - "LdeNryu2DK96tDvtLJfBz7ArWynAWPJAep38n", - "LdeNkoQpXffVF9qjsa4A7wZVgT9W2vnhpEEm5", - "LdeNzfFrsJT7Ni1L7k1EP3NuxUfK8QGAxMGpt", - "LdeNuLhR5AoyhQoVeS15haJvvGC5ByoPezrGq" - }; - - public static final String[] PRIVATE_KEYS = { - "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", - "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", - "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", - "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns", - "177gjwyHzfmsD4g3MVB655seYWXua2KBdQEqTf9kHgeMc6gdRZADKb6cL13L5koqMsBtkGX", - "177gk2C9V7gwPhAGgawL53W8idDpSo63jnbg8finbZkk4zermr5aqgTeKspN45fbymey8t6", - "177gjtz29TXa2E3FFBpCNr5LpU5zYxkNPAgcAJZW7tCGUgWQr4gcVv8PHmoVVPeSVVnyZV5", - "177gjzpHnqGEuSKyi3pW69WhpEPmeFPxLNVmUfXQb4DDV2EfnMgY7T4NFsyRsThjJFsau7X"}; - - public static final String[] DB_MEMS = { - "memory://127.0.0.1/0", - "memory://127.0.0.1/1", - "memory://127.0.0.1/2", - "memory://127.0.0.1/3", - "memory://127.0.0.1/4", - "memory://127.0.0.1/5", - "memory://127.0.0.1/6", - "memory://127.0.0.1/7" - }; -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/PresetAnswerPrompter.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/PresetAnswerPrompter.java deleted file mode 100644 index bb93d7e1..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/config/PresetAnswerPrompter.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jd.blockchain.mocker.config; - -import com.jd.blockchain.tools.initializer.ConsolePrompter; - -import java.util.Properties; - -public class PresetAnswerPrompter extends ConsolePrompter { - - private Properties answers = new Properties(); - - private String defaultAnswer; - - public PresetAnswerPrompter(String defaultAnswer) { - this.defaultAnswer = defaultAnswer; - } - - public void setAnswer(String tag, String answer) { - answers.setProperty(tag, answer); - } - - public void setDefaultAnswer(String defaultAnswer) { - this.defaultAnswer = defaultAnswer; - } - - @Override - public String confirm(String tag, String format, Object... args) { - System.out.print(String.format(format, args)); - String answer = answers.getProperty(tag, defaultAnswer); - System.out.println(String.format("\r\n [Mocked answer:%s]", answer)); - return answer; - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/AccountContract.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/AccountContract.java deleted file mode 100644 index d42d6458..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/AccountContract.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jd.blockchain.mocker.contracts; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEvent; - -@Contract -public interface AccountContract { - - @ContractEvent(name = "create") - void create(String address, String account, long money); - - @ContractEvent(name = "transfer") - void transfer(String address, String from, String to, long money); - - @ContractEvent(name = "print") - void print(String address, String from, String to); -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/AccountContractImpl.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/AccountContractImpl.java deleted file mode 100644 index e414e2df..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/AccountContractImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.jd.blockchain.mocker.contracts; - -import com.jd.blockchain.contract.ContractEventContext; -import com.jd.blockchain.contract.ContractException; -import com.jd.blockchain.contract.EventProcessingAware; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.KVDataEntry; - -public class AccountContractImpl implements EventProcessingAware, AccountContract { - - private ContractEventContext eventContext; - - private HashDigest ledgerHash; - - @Override - public void create(String address, String account, long money) { - // 暂不处理该账户已经存在的问题 - eventContext.getLedger().dataAccount(address).setInt64(account, money, -1); - } - - @Override - public void transfer(String address, String from, String to, long money) { - // 首先分别查询from与to的结果 - KVDataEntry[] dataEntries = eventContext.getLedger().getDataEntries(ledgerHash, address, from, to); - long currentFromMoney = 0L, currentToMoney = 0L, currentFromVer = -1L, currentToVer = -1L; - if (dataEntries != null && dataEntries.length > 0) { - for (KVDataEntry dataEntry : dataEntries) { - String key = dataEntry.getKey(); - Object value = dataEntry.getValue(); - long version = dataEntry.getVersion(); - if (key.equals(from)) { - currentFromMoney = (long) value; - currentFromVer = version; - } - if (key.equals(to)) { - currentToMoney = (long) value; - currentToVer = version; - } - } - } - currentFromMoney -= money; - currentToMoney += money; - // 重新设置结果 - eventContext.getLedger().dataAccount(address).setInt64(from, currentFromMoney, currentFromVer) - .setInt64(to, currentToMoney, currentToVer); - } - - @Override - public void print(String address, String from, String to) { - KVDataEntry[] dataEntries = eventContext.getLedger().getDataEntries(ledgerHash, address, from, to); - if (dataEntries != null && dataEntries.length > 0) { - for (KVDataEntry dataEntry : dataEntries) { - String key = dataEntry.getKey(); - Object value = dataEntry.getValue(); - long version = dataEntry.getVersion(); - System.out.printf("Key = %s Value = %s Version = %s \r\n", key, value, version); - } - } - } - - @Override - public void beforeEvent(ContractEventContext eventContext) { - this.eventContext = eventContext; - this.ledgerHash = this.eventContext.getCurrentLedgerHash(); - } - - @Override - public void postEvent(ContractEventContext eventContext, Exception error) { - - } - -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/WriteContract.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/WriteContract.java deleted file mode 100644 index 9662dd68..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/WriteContract.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.mocker.contracts; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEvent; - -@Contract -public interface WriteContract { - - @ContractEvent(name = "print") - void print(String name); - - @ContractEvent(name = "writeKv") - String writeKv(String address, String key, String value); -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/WriteContractImpl.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/WriteContractImpl.java deleted file mode 100644 index 83f5521d..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/contracts/WriteContractImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jd.blockchain.mocker.contracts; - -import com.jd.blockchain.contract.ContractEventContext; -import com.jd.blockchain.contract.ContractException; -import com.jd.blockchain.contract.EventProcessingAware; - -public class WriteContractImpl implements EventProcessingAware, WriteContract { - - private ContractEventContext eventContext; - - @Override - public void print(String name) { - System.out.printf("My Name is %s \r\n", name); - System.out.printf("My Ledger Hash is %s \r\n", eventContext.getCurrentLedgerHash().toBase58()); - } - - @Override - public String writeKv(String address, String key, String value) { - eventContext.getLedger().dataAccount(address).setText(key, value, -1); - return String.format("address = %s, key = %s, value = %s, version = %s", address, key, value, 0); - } - - @Override - public void beforeEvent(ContractEventContext eventContext) { - this.eventContext = eventContext; - } - - @Override - public void postEvent(ContractEventContext eventContext, Exception error) { - System.out.println("----- postEvent1 -----"); - } - -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/data/KvData.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/data/KvData.java deleted file mode 100644 index ec6cce3d..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/data/KvData.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jd.blockchain.mocker.data; - -public class KvData { - - private String dataAccount; - - private String key; - - private byte[] value; - - private long version; - - public KvData() { - } - - public KvData(String dataAccount, String key, byte[] value, long version) { - this.dataAccount = dataAccount; - this.key = key; - this.value = value; - this.version = version; - } - - public String getDataAccount() { - return dataAccount; - } - - public String getKey() { - return key; - } - - public byte[] getValue() { - return value; - } - - public long getVersion() { - return version; - } - - public void setDataAccount(String dataAccount) { - this.dataAccount = dataAccount; - } - - public void setKey(String key) { - this.key = key; - } - - public void setValue(byte[] value) { - this.value = value; - } - - public void setVersion(long version) { - this.version = version; - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/data/ResponseData.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/data/ResponseData.java deleted file mode 100644 index 61cf6893..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/data/ResponseData.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jd.blockchain.mocker.data; - -import com.jd.blockchain.ledger.TransactionResponse; - -public class ResponseData { - - private TransactionResponse txResponse; - - private T data; - - public ResponseData() { - } - - public ResponseData(TransactionResponse txResponse) { - this.txResponse = txResponse; - } - - public ResponseData(TransactionResponse txResponse, T data) { - this.txResponse = txResponse; - this.data = data; - } - - public TransactionResponse getTxResponse() { - return txResponse; - } - - public T getData() { - return data; - } - - public void setTxResponse(TransactionResponse txResponse) { - this.txResponse = txResponse; - } - - public void setData(T data) { - this.data = data; - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerContractExeHandle.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerContractExeHandle.java deleted file mode 100644 index dee8fe18..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerContractExeHandle.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.jd.blockchain.mocker.handler; - -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import com.jd.blockchain.contract.ContractEventContext; -import com.jd.blockchain.contract.ContractException; -import com.jd.blockchain.contract.EventProcessingAware; -import com.jd.blockchain.contract.LedgerContext; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.BytesValueEncoding; -import com.jd.blockchain.ledger.BytesValueList; -import com.jd.blockchain.ledger.ContractEventSendOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.core.LedgerDataset; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.ledger.core.LedgerQueryService; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.OperationHandleContext; -import com.jd.blockchain.ledger.core.TransactionRequestExtension; -import com.jd.blockchain.ledger.core.handles.ContractLedgerContext; -import com.jd.blockchain.mocker.proxy.ExecutorProxy; - -public class MockerContractExeHandle implements OperationHandle { - - private Map executorProxyMap = new ConcurrentHashMap<>(); - - private LedgerManager ledgerManager; - - private HashDigest ledgerHash; - - @Override - public BytesValue process(Operation op, LedgerDataset dataset, TransactionRequestExtension request, - LedgerQuery ledger, OperationHandleContext opHandleContext) { - ContractEventSendOperation contractOP = (ContractEventSendOperation) op; - - HashDigest txHash = request.getTransactionContent().getHash(); - - ExecutorProxy executorProxy = executorProxyMap.get(txHash); - - Object result = null; - if (executorProxy != null) { - LedgerQueryService queryService = new LedgerQueryService(ledger); - ContractLedgerContext ledgerContext = new ContractLedgerContext(queryService, opHandleContext); - - MockerContractEventContext contractEventContext = new MockerContractEventContext(ledgerHash, - contractOP.getEvent(), request, ledgerContext); - - Object instance = executorProxy.getInstance(); - EventProcessingAware awire = null; - - if (instance instanceof EventProcessingAware) { - awire = (EventProcessingAware) instance; - awire.beforeEvent(contractEventContext); - } - - try { - result = executorProxy.invoke(); - if (awire != null) { - // After处理过程 - awire.postEvent(contractEventContext, null); - } - } catch (Exception e) { - if (awire != null) { - awire.postEvent(contractEventContext, new ContractException(e.getMessage())); - } - } finally { - removeExecutorProxy(txHash); - } - } - - // No return value; - return BytesValueEncoding.encodeSingle(result, null); - } - - @Override - public Class getOperationType() { - return ContractEventSendOperation.class; - } - - public void initLedger(LedgerManager ledgerManager, HashDigest ledgerHash) { - this.ledgerManager = ledgerManager; - this.ledgerHash = ledgerHash; - } - - public void registerExecutorProxy(HashDigest hashDigest, ExecutorProxy executorProxy) { - executorProxyMap.put(hashDigest, executorProxy); - } - - public ExecutorProxy removeExecutorProxy(HashDigest hashDigest) { - return executorProxyMap.remove(hashDigest); - } - - public static class MockerContractEventContext implements ContractEventContext { - - private HashDigest ledgeHash; - - private String event; - - private TransactionRequest transactionRequest; - - private LedgerContext ledgerContext; - - public MockerContractEventContext(HashDigest ledgeHash, String event, TransactionRequest transactionRequest, - LedgerContext ledgerContext) { - this.ledgeHash = ledgeHash; - this.event = event; - this.transactionRequest = transactionRequest; - this.ledgerContext = ledgerContext; - } - - @Override - public HashDigest getCurrentLedgerHash() { - return ledgeHash; - } - - @Override - public TransactionRequest getTransactionRequest() { - return transactionRequest; - } - - @Override - public Set getTxSigners() { - return null; - } - - @Override - public String getEvent() { - return event; - } - - @Override - public BytesValueList getArgs() { - return null; - } - - @Override - public LedgerContext getLedger() { - return ledgerContext; - } - - @Override - public Set getContracOwners() { - return null; - } - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerNodeHandler.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerNodeHandler.java deleted file mode 100644 index b4d355fc..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerNodeHandler.java +++ /dev/null @@ -1,189 +0,0 @@ -package com.jd.blockchain.mocker.handler; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.gateway.GatewayConfigProperties; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.mocker.config.MockerConstant; -import com.jd.blockchain.mocker.config.PresetAnswerPrompter; -import com.jd.blockchain.mocker.node.GatewayNodeRunner; -import com.jd.blockchain.mocker.node.NodeWebContext; -import com.jd.blockchain.mocker.node.PeerNodeRunner; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.net.NetworkAddress; -import org.springframework.util.ResourceUtils; - -import java.io.File; -import java.io.FileInputStream; -import java.util.*; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static com.jd.blockchain.mocker.config.MockerConstant.*; - -public class MockerNodeHandler { - - private static final String LEDGER_BINDING_FORMAT = "binding.%s."; - - private static final String PARTI_FORMAT = LEDGER_BINDING_FORMAT + "parti."; - - private static final String BINDING_ID_FORMAT = PARTI_FORMAT + "id"; - - private static final String BINDING_PK_PATH_FORMAT = PARTI_FORMAT + "pk-path"; - - private static final String BINDING_PK_FORMAT = PARTI_FORMAT + "pk"; - - private static final String BINDING_PWD_FORMAT = PARTI_FORMAT + "pwd"; - - private static final String BINDING_ADDRESS_FORMAT = PARTI_FORMAT + "address"; - - private static final String DB_FORMAT = LEDGER_BINDING_FORMAT + "db."; - - private static final String BINDING_DB_URI_FORMAT = DB_FORMAT + "uri"; - - private static final String BINDING_DB_PWD_FORMAT = DB_FORMAT + "pwd"; - - private PeerNodeRunner[] peerNodes; - - private GatewayNodeRunner gatewayNodeRunner; - - public void start(int nodeSize) throws Exception { - - HashDigest ledgerHash = ledgerInit(nodeSize); - - // 启动Peer节点 - peerNodes = peerNodeStart(nodeSize, ledgerHash); - - // 启动网关节点 - gatewayNodeRunner = gatewayNodeStart(peerNodes[0].getServiceAddress()); - } - - public LedgerInitProperties initLedgerProperties(int nodeSize) throws Exception { - - File ledgerInitFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + - String.format(MockerConstant.LEDGER_INIT_FORMATTER, nodeSize)); - - final LedgerInitProperties ledgerInitProperties = LedgerInitProperties.resolve(new FileInputStream(ledgerInitFile)); - - return ledgerInitProperties; - } - - private HashDigest ledgerInit(int nodeSize) throws Exception { - - System.out.println("----------- is daemon=" + Thread.currentThread().isDaemon()); - - Prompter consolePrompter = new PresetAnswerPrompter("N"); // new ConsolePrompter(); - - LedgerInitProperties initSetting = initLedgerProperties(nodeSize); - - Set hashDigestSet = new HashSet<>(); - - CountDownLatch quitLatch = new CountDownLatch(nodeSize); - - ExecutorService peerThreads = Executors.newFixedThreadPool(nodeSize); - - for (int i = 0; i < nodeSize; i++) { - final int nodeIndex = i; - peerThreads.execute(() -> { - // 启动服务器; - NetworkAddress initAddr = initSetting.getConsensusParticipant(nodeIndex).getInitializerAddress(); - NodeWebContext node = new NodeWebContext(nodeIndex, initAddr); - PrivKey privkey = KeyGenUtils.decodePrivKeyWithRawPassword(PRIVATE_KEYS[nodeIndex], PASSWORD); - DBConnectionConfig dbConn = new DBConnectionConfig(); - dbConn.setConnectionUri(MockerConstant.DB_MEMS[nodeIndex]); - ThreadInvoker.AsyncCallback nodeCallback = node.startInit(privkey, initSetting, dbConn, consolePrompter, - quitLatch); - hashDigestSet.add(nodeCallback.waitReturn()); - }); - } - - quitLatch.await(); - - if (hashDigestSet.size() != 1) { - throw new IllegalStateException(String.format("%s Node Ledger Init Fail !!!", nodeSize)); - } - return hashDigestSet.toArray(new HashDigest[hashDigestSet.size()])[0]; - } - - - public PeerNodeRunner[] peerNodeStart(int nodeSize, HashDigest ledgerHash) { - - int portStart = PEER_PORT_START; - - List> threadInvokers = new ArrayList<>(); - - final PeerNodeRunner[] peerNodeRunners = new PeerNodeRunner[nodeSize]; - - for (int i = 0; i < nodeSize; i++) { - NetworkAddress peerSrvAddr = new NetworkAddress(LOCAL_ADDRESS, portStart); - LedgerBindingConfig bindingConfig = loadBindingConfig(i, ledgerHash); - PeerNodeRunner peerNodeRunner = new PeerNodeRunner(peerSrvAddr, bindingConfig); - peerNodeRunners[i] = peerNodeRunner; - portStart += 10; - threadInvokers.add(peerNodeRunner.start()); - } - - // 等待结果 - for (ThreadInvoker.AsyncCallback threadInvoker : threadInvokers) { - threadInvoker.waitReturn(); - } - - return peerNodeRunners; - } - - public GatewayNodeRunner gatewayNodeStart(NetworkAddress peerAddress) { - GatewayConfigProperties.KeyPairConfig gwKeyPair = new GatewayConfigProperties.KeyPairConfig(); - gwKeyPair.setPubKeyValue(PUBLIC_KEYS[0]); - gwKeyPair.setPrivKeyValue(PRIVATE_KEYS[0]); - gwKeyPair.setPrivKeyPassword(PASSWORD_ENCODE); - GatewayNodeRunner gateway = new GatewayNodeRunner(LOCAL_ADDRESS, GATEWAY_PORT, gwKeyPair, - peerAddress, CONSENSUS_PROVIDERS,null); - - ThreadInvoker.AsyncCallback gwStarting = gateway.start(); - - gwStarting.waitReturn(); - - return gateway; - } - - public void stop() { - if (peerNodes != null) { - for (PeerNodeRunner peerNodeRunner : peerNodes) { - peerNodeRunner.stop(); - } - } - if (gatewayNodeRunner != null) { - gatewayNodeRunner.stop(); - } - } - - private LedgerBindingConfig loadBindingConfig(int nodeIndex, HashDigest ledgerHash) { - - Properties properties = new Properties(); - - String ledgerHashBase58 = ledgerHash.toBase58(); - - properties.put("ledger.bindings", ledgerHashBase58); - - properties.put(String.format(BINDING_ID_FORMAT, ledgerHashBase58), nodeIndex); - - properties.put(String.format(BINDING_PK_PATH_FORMAT, ledgerHashBase58), ""); - - properties.put(String.format(BINDING_PK_FORMAT, ledgerHashBase58), PUBLIC_KEYS[nodeIndex]); - - properties.put(String.format(BINDING_PWD_FORMAT, ledgerHashBase58), PASSWORD_ENCODE); - - properties.put(String.format(BINDING_ADDRESS_FORMAT, ledgerHashBase58), ADDRESS_ARRAY[nodeIndex]); - - properties.put(String.format(BINDING_DB_URI_FORMAT, ledgerHashBase58), DB_MEMS[nodeIndex]); - - properties.put(String.format(BINDING_DB_PWD_FORMAT, ledgerHashBase58), ""); - - return LedgerBindingConfig.resolve(properties); - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerOperationHandleRegister.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerOperationHandleRegister.java deleted file mode 100644 index d22c6174..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerOperationHandleRegister.java +++ /dev/null @@ -1,54 +0,0 @@ -//package com.jd.blockchain.mocker.handler; -// -//import java.util.ArrayList; -//import java.util.List; -// -//import com.jd.blockchain.ledger.LedgerException; -//import com.jd.blockchain.ledger.core.OperationHandle; -//import com.jd.blockchain.ledger.core.OperationHandleRegisteration; -//import com.jd.blockchain.ledger.core.handles.ContractCodeDeployOperationHandle; -//import com.jd.blockchain.ledger.core.handles.DataAccountKVSetOperationHandle; -//import com.jd.blockchain.ledger.core.handles.DataAccountRegisterOperationHandle; -//import com.jd.blockchain.ledger.core.handles.UserRegisterOperationHandle; -// -//public class MockerOperationHandleRegister implements OperationHandleRegisteration { -// -// private List opHandles = new ArrayList<>(); -// -// public MockerOperationHandleRegister() { -// initDefaultHandles(); -// } -// -// /** -// * 针对不采用bean依赖注入的方式来处理; -// */ -// private void initDefaultHandles(){ -// opHandles.add(new DataAccountKVSetOperationHandle()); -// opHandles.add(new DataAccountRegisterOperationHandle()); -// opHandles.add(new UserRegisterOperationHandle()); -// opHandles.add(new ContractCodeDeployOperationHandle()); -//// opHandles.add(new ContractEventSendOperationHandle()); -// } -// -// public List getOpHandles() { -// return opHandles; -// } -// -// public void registerHandler(OperationHandle operationHandle) { -// opHandles.add(operationHandle); -// } -// -// public void removeHandler(OperationHandle operationHandle) { -// opHandles.remove(operationHandle); -// } -// -// @Override -// public OperationHandle getHandle(Class operationType) { -// for (OperationHandle handle : opHandles) { -// if (handle.support(operationType)) { -// return handle; -// } -// } -// throw new LedgerException("Unsupported operation type[" + operationType.getName() + "]!"); -// } -//} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerServiceHandler.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerServiceHandler.java deleted file mode 100644 index d7f1f43b..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerServiceHandler.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.jd.blockchain.mocker.handler; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.KeyGenUtils; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.mocker.config.MockerConstant; -import com.jd.blockchain.mocker.data.KvData; -import com.jd.blockchain.mocker.data.ResponseData; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; - -public class MockerServiceHandler { - - private BlockchainKeypair defaultParticipant; - - private BlockchainKeypair defaultUser; - - private BlockchainKeypair defaultDataAccount; - - private String gatewayHost; - - private int gatewayPort; - - private GatewayServiceFactory gatewayServiceFactory; - - private BlockchainService blockchainService; - - private HashDigest ledgerHash; - - public MockerServiceHandler(String gatewayHost, int gatewayPort) { - this.gatewayHost = gatewayHost; - this.gatewayPort = gatewayPort; - init(); - } - - public BlockchainKeypair getDefaultParticipant() { - return defaultParticipant; - } - - public BlockchainKeypair getDefaultUser() { - return defaultUser; - } - - public BlockchainKeypair getDefaultDataAccount() { - return defaultDataAccount; - } - - public String getDefaultDataAccountAddress() { - return defaultDataAccount.getAddress().toBase58(); - } - - public String getGatewayHost() { - return gatewayHost; - } - - public int getGatewayPort() { - return gatewayPort; - } - - public GatewayServiceFactory getGatewayServiceFactory() { - return gatewayServiceFactory; - } - - public BlockchainService getBlockchainService() { - return blockchainService; - } - - public HashDigest getLedgerHash() { - return ledgerHash; - } - - private void init() { - - defaultParticipant = defaultParticipant(); - - gatewayServiceFactory = GatewayServiceFactory.connect(gatewayHost, gatewayPort, - false, defaultParticipant); - - blockchainService = gatewayServiceFactory.getBlockchainService(); - - HashDigest[] ledgerHashs = blockchainService.getLedgerHashs(); - - ledgerHash = ledgerHashs[0]; - - // 默认注册部分内容 - // 注册一个用户和一个数据账户 - TransactionTemplate txTemplate = blockchainService.newTransaction(ledgerHash); - - defaultUser = newKeypair(); - - defaultDataAccount = newKeypair(); - - // 注册用户 - txTemplate.users().register(defaultUser.getIdentity()); - - // 注册数据账户 - txTemplate.dataAccounts().register(defaultDataAccount.getIdentity()); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemplate.prepare(); - - // 使用私钥进行签名; - prepTx.sign(defaultParticipant); - - // 提交交易; - TransactionResponse txResponse = prepTx.commit(); - - System.out.printf("Commit Transaction Result = %s \r\n", txResponse.isSuccess()); - } - - public BlockchainKeypair newKeypair() { - return BlockchainKeyGenerator.getInstance().generate(); - } - - private BlockchainKeypair defaultParticipant() { - PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(MockerConstant.PRIVATE_KEYS[0], MockerConstant.PASSWORD); - PubKey pubKey = KeyGenUtils.decodePubKey(MockerConstant.PUBLIC_KEYS[0]); - return new BlockchainKeypair(pubKey, privKey); - } - - public ResponseData writeKv(String key, byte[] value) { - return writeKv(key, value, -1); - } - - public ResponseData writeKv(String key, byte[] value, long version) { - return writeKv(getDefaultDataAccountAddress(), key, value, version); - } - - public ResponseData writeKv(String dataAccount, String key, byte[] value) { - return writeKv(dataAccount, key, value, -1); - } - - public ResponseData writeKv(String dataAccount, String key, byte[] value, long version) { - - TransactionTemplate txTemplate = newTxTemplate(); - - txTemplate.dataAccount(dataAccount).setBytes(key, value, version); - - TransactionResponse txResponse = txPrepareAndCommit(txTemplate); - - long saveVersion = version; - - if (txResponse.isSuccess()) { - saveVersion = version + 1; - } - - KvData kvData = new KvData(dataAccount, key, value, saveVersion); - - return new ResponseData(txResponse, kvData); - } - - public ResponseData registerUser() { - - BlockchainKeypair newUser = BlockchainKeyGenerator.getInstance().generate(); - - return registerUser(newUser); - } - - public ResponseData registerUser(BlockchainKeypair user) { - - TransactionTemplate txTemplate = newTxTemplate(); - - // 注册 - txTemplate.users().register(user.getIdentity()); - - TransactionResponse txResponse = txPrepareAndCommit(txTemplate); - - return new ResponseData(txResponse, user); - } - - public ResponseData registerDataAccount() { - - BlockchainKeypair newDataAccount = BlockchainKeyGenerator.getInstance().generate(); - - return registerDataAccount(newDataAccount); - } - - public ResponseData registerDataAccount(BlockchainKeypair dataAccount) { - - TransactionTemplate txTemplate = newTxTemplate(); - - // 注册 - txTemplate.dataAccounts().register(dataAccount.getIdentity()); - - TransactionResponse txResponse = txPrepareAndCommit(txTemplate); - - return new ResponseData(txResponse, dataAccount); - } - - public ResponseData deployContract() { - return null; - } - - public ResponseData executeContract() { - return null; - } - - private TransactionTemplate newTxTemplate() { - return blockchainService.newTransaction(ledgerHash); - } - - private TransactionResponse txPrepareAndCommit(TransactionTemplate txTemplate) { - // TX 准备就绪; - PreparedTransaction prepTx = txTemplate.prepare(); - - // 使用私钥进行签名; - prepTx.sign(defaultParticipant); - - // 提交交易; - TransactionResponse txResponse = prepTx.commit(); - - return txResponse; - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/GatewayNodeRunner.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/GatewayNodeRunner.java deleted file mode 100644 index 61520c4b..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/GatewayNodeRunner.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jd.blockchain.mocker.node; - -import com.jd.blockchain.gateway.GatewayConfigProperties; -import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.gateway.GatewayServerBooter; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; -import org.springframework.core.io.ClassPathResource; -import org.springframework.util.CollectionUtils; - -import java.util.Map; - -public class GatewayNodeRunner { - - private NetworkAddress serviceAddress; - - private GatewayServerBooter gatewayServer; - - public GatewayNodeRunner(String host, int port, KeyPairConfig gatewayDefaultKey, NetworkAddress masterPeerAddres) { - this(host, port, gatewayDefaultKey, masterPeerAddres, null,null); - } - - public GatewayNodeRunner(String host, int port, KeyPairConfig gatewayDefaultKey, NetworkAddress masterPeerAddres, String[] providers, - Map otherMap) { - this.serviceAddress = new NetworkAddress(host, port); - GatewayConfigProperties config = new GatewayConfigProperties(); - - config.http().setHost(host); - config.http().setPort(port); - - if (providers != null) { - for (String provider : providers) { - config.providerConfig().add(provider); - } - } - - config.setMasterPeerAddress(masterPeerAddres); - - config.keys().getDefault().setPubKeyValue(gatewayDefaultKey.getPubKeyValue()); - config.keys().getDefault().setPrivKeyValue(gatewayDefaultKey.getPrivKeyValue()); - config.keys().getDefault().setPrivKeyPassword(gatewayDefaultKey.getPrivKeyPassword()); - - if(!CollectionUtils.isEmpty(otherMap)){ - config.setDataRetrievalUrl(otherMap.get("DATA_RETRIEVAL_URL").toString()); - } - - - //get the springConfigLocation; - ClassPathResource configResource = new ClassPathResource("application-gw.properties"); - String springConfigLocation = "classPath:"+configResource.getPath(); - - this.gatewayServer = new GatewayServerBooter(config,springConfigLocation); - } - - public AsyncCallback start() { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected Object invoke() throws Exception { - gatewayServer.start(); - return null; - } - }; - - return invoker.start(); - } - - public void stop() { - gatewayServer.close(); - } - - public NetworkAddress getServiceAddress() { - return serviceAddress; - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/NodeWebContext.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/NodeWebContext.java deleted file mode 100644 index 24a6ee53..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/NodeWebContext.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.jd.blockchain.mocker.node; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.PrivKey; -import com.jd.blockchain.ledger.LedgerInitProperties; -import com.jd.blockchain.ledger.TransactionContent; -import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitProposal; -import com.jd.blockchain.ledger.core.LedgerManager; -import com.jd.blockchain.ledger.core.LedgerQuery; -import com.jd.blockchain.mocker.config.LedgerInitWebConfiguration; -import com.jd.blockchain.storage.service.DbConnection; -import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; -import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.net.NetworkAddress; -import org.springframework.boot.SpringApplication; -import org.springframework.context.ConfigurableApplicationContext; - -import java.util.concurrent.CountDownLatch; - -public class NodeWebContext { - - private NetworkAddress serverAddress; - - private DBConnectionConfig dbConnConfig; - - private volatile ConfigurableApplicationContext ctx; - - private volatile LedgerInitProcess initProcess; - - private volatile LedgerInitializeWebController controller; - - private volatile LedgerManager ledgerManager; - - private volatile CompositeConnectionFactory db; - - private int id; - - public int getId() { - return controller.getId(); - } - - public TransactionContent getInitTxContent() { - return controller.getInitTxContent(); - } - - public LedgerInitProposal getLocalPermission() { - return controller.getLocalPermission(); - } - - public LedgerInitDecision getLocalDecision() { - return controller.getLocalDecision(); - } - - public NodeWebContext(int id, NetworkAddress serverAddress) { - this.id = id; - this.serverAddress = serverAddress; - } - - public LedgerQuery registLedger(HashDigest ledgerHash) { - DbConnection conn = db.connect(dbConnConfig.getUri()); - LedgerQuery ledgerRepo = ledgerManager.register(ledgerHash, conn.getStorageService()); - return ledgerRepo; - } - - public ThreadInvoker.AsyncCallback startInit(PrivKey privKey, LedgerInitProperties setting, - DBConnectionConfig dbConnConfig, Prompter prompter, CountDownLatch quitLatch) { - - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected HashDigest invoke() throws Exception { - doStartServer(); - - NodeWebContext.this.dbConnConfig = dbConnConfig; - HashDigest ledgerHash = NodeWebContext.this.initProcess.initialize(id, privKey, setting, - dbConnConfig, prompter); - - System.out.printf("ledgerHash = %s \r\n", ledgerHash.toBase58()); - - quitLatch.countDown(); - return ledgerHash; - } - }; - - return invoker.start(); - } - - public void doStartServer() { - String argServerAddress = String.format("--server.address=%s", serverAddress.getHost()); - String argServerPort = String.format("--server.port=%s", serverAddress.getPort()); - String nodebug = "--debug=false"; - String[] innerArgs = { argServerAddress, argServerPort, nodebug }; - - ctx = SpringApplication.run(LedgerInitWebConfiguration.class, innerArgs); - - ctx.setId("Node-" + id); - controller = ctx.getBean(LedgerInitializeWebController.class); - ledgerManager = ctx.getBean(LedgerManager.class); - db = ctx.getBean(CompositeConnectionFactory.class); - initProcess = ctx.getBean(LedgerInitProcess.class); - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/PeerNodeRunner.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/PeerNodeRunner.java deleted file mode 100644 index ba90d280..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/PeerNodeRunner.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jd.blockchain.mocker.node; - -import com.jd.blockchain.peer.PeerServerBooter; -import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.utils.concurrent.ThreadInvoker; -import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class PeerNodeRunner { - - private NetworkAddress serviceAddress; - - private volatile PeerServerBooter peerServer; - - private LedgerBindingConfig ledgerBindingConfig; - - public DbConnectionFactory getDBConnectionFactory() { - return peerServer.getDBConnectionFactory(); - } - - public NetworkAddress getServiceAddress() { - return serviceAddress; - } - - public LedgerBindingConfig getLedgerBindingConfig() { - return ledgerBindingConfig; - } - - public PeerNodeRunner(NetworkAddress serviceAddress, LedgerBindingConfig ledgerBindingConfig) { - this(serviceAddress, ledgerBindingConfig, null); - } - - public PeerNodeRunner(NetworkAddress serviceAddress, LedgerBindingConfig ledgerBindingConfig, - DbConnectionFactory dbConnectionFactory) { - this.serviceAddress = serviceAddress; - this.ledgerBindingConfig = ledgerBindingConfig; - if (dbConnectionFactory == null) { - this.peerServer = new PeerServerBooter(ledgerBindingConfig, serviceAddress.getHost(), serviceAddress.getPort(),null); - }else { - this.peerServer = new PeerServerBooter(ledgerBindingConfig, serviceAddress.getHost(), serviceAddress.getPort(),null, - dbConnectionFactory); - } - } - - public AsyncCallback start() { - ThreadInvoker invoker = new ThreadInvoker() { - @Override - protected Object invoke() throws Exception { - peerServer.start(); - - return null; - } - }; - - return invoker.start(); - } - - public void stop() { - peerServer.close(); - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/proxy/ContractProxy.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/proxy/ContractProxy.java deleted file mode 100644 index b2e23766..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/proxy/ContractProxy.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jd.blockchain.mocker.proxy; - -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -import com.jd.blockchain.contract.Contract; -import com.jd.blockchain.contract.ContractEvent; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValueEncoding; -import com.jd.blockchain.ledger.OperationResult; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.mocker.MockerNodeContext; -import com.jd.blockchain.mocker.handler.MockerContractExeHandle; -import com.jd.blockchain.transaction.TxBuilder; - -public class ContractProxy implements InvocationHandler { - - private BlockchainIdentity identity; - - private MockerNodeContext mockerNodeContext; - - private T instance; - - private MockerContractExeHandle operationHandle; - - public ContractProxy(BlockchainIdentity identity, MockerNodeContext mockerNodeContext, T instance, - MockerContractExeHandle operationHandle) { - this.identity = identity; - this.mockerNodeContext = mockerNodeContext; - this.instance = instance; - this.operationHandle = operationHandle; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - // 实际执行时,首先判断执行的是否是添加注解的方法 - if (!isExecuteContractMethod(method)) { - return method.invoke(instance, args); - } - - // 首先发送一次执行的请求 - TxBuilder txBuilder = mockerNodeContext.txBuilder(); - - Class contractInft = null; - - Class[] instanceInfts = instance.getClass().getInterfaces(); - - for (Class instanceInft : instanceInfts) { - if (instanceInft.isAnnotationPresent(Contract.class)) { - contractInft = instanceInft; - break; - } - } - - if (contractInft == null) { - throw new IllegalStateException( - "This object does not implement the interface for the @Contract annotation !!!"); - } - - // 生成代理类 - Object proxyInstance = txBuilder.contract(identity.getAddress().toBase58(), contractInft); - // 代理方式执行一次 - method.invoke(proxyInstance, args); - - TransactionRequest txRequest = mockerNodeContext.txRequest(txBuilder); - - // 放入到Map中 - HashDigest txHash = txRequest.getTransactionContent().getHash(); - operationHandle.registerExecutorProxy(txHash, new ExecutorProxy(instance, method, args)); - - // 提交该请求至整个区块链系统 - OperationResult[] operationResults = mockerNodeContext.txProcess(txRequest); - if (operationResults == null || operationResults.length == 0) { - return null; - } - OperationResult opResult = operationResults[0]; - - // 处理返回值 - return BytesValueEncoding.decode(opResult.getResult(), method.getReturnType()); - } - - private boolean isExecuteContractMethod(Method method) { - Annotation annotation = method.getAnnotation(ContractEvent.class); - return annotation != null; - } -} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/proxy/ExecutorProxy.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/proxy/ExecutorProxy.java deleted file mode 100644 index 04873be5..00000000 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/proxy/ExecutorProxy.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jd.blockchain.mocker.proxy; - -import java.lang.reflect.Method; - -public class ExecutorProxy { - - private Object instance; - - private Method method; - - private Object[] args; - - public ExecutorProxy(Object instance, Method method, Object[] args) { - this.instance = instance; - this.method = method; - this.args = args; - } - - public Object getInstance() { - return instance; - } - - public Method getMethod() { - return method; - } - - public Object[] getArgs() { - return args; - } - - public Object invoke() throws Exception { - return method.invoke(instance, args); - } -} diff --git a/source/tools/tools-mocker/src/main/resources/bftsmart.config b/source/tools/tools-mocker/src/main/resources/bftsmart.config deleted file mode 100644 index 870fcde2..00000000 --- a/source/tools/tools-mocker/src/main/resources/bftsmart.config +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=500 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=5000 - -############################################ -###### #Consensus Participant0 ###### -############################################ - -system.server.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=16000 -system.server.0.network.secure=false - -############################################ -###### #Consensus Participant1 ###### -############################################ - -system.server.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=16100 -system.server.1.network.secure=false - -############################################ -###### #Consensus Participant2 ###### -############################################ - -system.server.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=16200 -system.server.2.network.secure=false - -############################################ -###### #Consensus Participant3 ###### -############################################ - -system.server.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=16300 -system.server.3.network.secure=false - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 500 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage \ No newline at end of file diff --git a/source/tools/tools-mocker/src/main/resources/bftsmart4.config b/source/tools/tools-mocker/src/main/resources/bftsmart4.config deleted file mode 100644 index 870fcde2..00000000 --- a/source/tools/tools-mocker/src/main/resources/bftsmart4.config +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=500 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=5000 - -############################################ -###### #Consensus Participant0 ###### -############################################ - -system.server.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=16000 -system.server.0.network.secure=false - -############################################ -###### #Consensus Participant1 ###### -############################################ - -system.server.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=16100 -system.server.1.network.secure=false - -############################################ -###### #Consensus Participant2 ###### -############################################ - -system.server.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=16200 -system.server.2.network.secure=false - -############################################ -###### #Consensus Participant3 ###### -############################################ - -system.server.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=16300 -system.server.3.network.secure=false - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 4 - -#Maximum number of faulty replicas -system.servers.f = 1 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 500 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage \ No newline at end of file diff --git a/source/tools/tools-mocker/src/main/resources/bftsmart8.config b/source/tools/tools-mocker/src/main/resources/bftsmart8.config deleted file mode 100644 index 814a6c3d..00000000 --- a/source/tools/tools-mocker/src/main/resources/bftsmart8.config +++ /dev/null @@ -1,208 +0,0 @@ -# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -############################################ -###### Consensus Commit Block Parameters: transaction count ###### -############################################ -system.block.txsize=500 - -############################################ -###### Consensus Commit Block Parameters: delay time ###### -############################################ -system.block.maxdelay=5000 - -############################################ -###### #Consensus Participant0 ###### -############################################ - -system.server.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -system.server.0.network.host=127.0.0.1 -system.server.0.network.port=16000 -system.server.0.network.secure=false - -############################################ -###### #Consensus Participant1 ###### -############################################ - -system.server.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -system.server.1.network.host=127.0.0.1 -system.server.1.network.port=16100 -system.server.1.network.secure=false - -############################################ -###### #Consensus Participant2 ###### -############################################ - -system.server.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -system.server.2.network.host=127.0.0.1 -system.server.2.network.port=16200 -system.server.2.network.secure=false - -############################################ -###### #Consensus Participant3 ###### -############################################ - -system.server.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -system.server.3.network.host=127.0.0.1 -system.server.3.network.port=16300 -system.server.3.network.secure=false - - -############################################ -###### #Consensus Participant4 ###### -############################################ - -system.server.4.pubkey=3snPdw7i7PXPRMp3EAjsxJkHe7aZJRLNzdW8kEHBWeQsSgcPAiHP2J -system.server.4.network.host=127.0.0.1 -system.server.4.network.port=16400 -system.server.4.network.secure=false - - -############################################ -###### #Consensus Participant5 ###### -############################################ - -system.server.5.pubkey=3snPdw7i7PmmQoPgUpUmmAUj6nakHj8wMSQmiMi1RaiZp4YU1D4AXk -system.server.5.network.host=127.0.0.1 -system.server.5.network.port=16500 -system.server.5.network.secure=false - - -############################################ -###### #Consensus Participant6 ###### -############################################ - -system.server.6.pubkey=3snPdw7i7PiJKsa94q3EcLT1y6GRJ7LeFGe799hdzRRHmf6LNodyiM -system.server.6.network.host=127.0.0.1 -system.server.6.network.port=16600 -system.server.6.network.secure=false - - -############################################ -###### #Consensus Participant7 ###### -############################################ - -system.server.7.pubkey=3snPdw7i7Pm2wJwEnKn8kK8eGTkN36C2BZRRjVTr9FPB2rqtcgTq7h -system.server.7.network.host=127.0.0.1 -system.server.7.network.port=16700 -system.server.7.network.secure=false - - -############################################ -####### Communication Configurations ####### -############################################ - -#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value) -#This parameter is not currently being used -#system.authentication.hmacAlgorithm = HmacSHA1 - -#Specify if the communication system should use a thread to send data (true or false) -system.communication.useSenderThread = true - -#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments -#and benchmarks, but must not be used in production systems. -system.communication.defaultkeys = true - -############################################ -### Replication Algorithm Configurations ### -############################################ - -#Number of servers in the group -system.servers.num = 8 - -#Maximum number of faulty replicas -system.servers.f = 2 - -#Timeout to asking for a client request -system.totalordermulticast.timeout = 2000 - -#Maximum batch size (in number of messages) -system.totalordermulticast.maxbatchsize = 500 - -#Number of nonces (for non-determinism actions) generated -system.totalordermulticast.nonces = 10 - -#if verification of leader-generated timestamps are increasing -#it can only be used on systems in which the network clocks -#are synchronized -system.totalordermulticast.verifyTimestamps = false - -#Quantity of messages that can be stored in the receive queue of the communication system -system.communication.inQueueSize = 500000 - -# Quantity of messages that can be stored in the send queue of each replica -system.communication.outQueueSize = 500000 - -#Set to 1 if SMaRt should use signatures, set to 0 if otherwise -system.communication.useSignatures = 0 - -#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise -system.communication.useMACs = 1 - -#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise -system.debug = 0 - -#Print information about the replica when it is shutdown -system.shutdownhook = true - -############################################ -###### State Transfer Configurations ####### -############################################ - -#Activate the state transfer protocol ('true' to activate, 'false' to de-activate) -system.totalordermulticast.state_transfer = true - -#Maximum ahead-of-time message not discarded -system.totalordermulticast.highMark = 10000 - -#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered) -system.totalordermulticast.revival_highMark = 10 - -#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs -system.totalordermulticast.timeout_highMark = 200 - -############################################ -###### Log and Checkpoint Configurations ### -############################################ - -system.totalordermulticast.log = true -system.totalordermulticast.log_parallel = false -system.totalordermulticast.log_to_disk = false -system.totalordermulticast.sync_log = false - -#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol) -system.totalordermulticast.checkpoint_period = 1000 -system.totalordermulticast.global_checkpoint_period = 120000 - -system.totalordermulticast.checkpoint_to_disk = false -system.totalordermulticast.sync_ckp = false - - -############################################ -###### Reconfiguration Configurations ###### -############################################ - -#Replicas ID for the initial view, separated by a comma. -# The number of replicas in this parameter should be equal to that specified in 'system.servers.num' -system.initial.view = 0,1,2,3,4,5,6,7 - -#The ID of the trust third party (TTP) -system.ttp.id = 7002 - -#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults -system.bft = true - -#Custom View Storage; -#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage \ No newline at end of file diff --git a/source/tools/tools-mocker/src/main/resources/ledger4.init b/source/tools/tools-mocker/src/main/resources/ledger4.init deleted file mode 100644 index 4ed4cd06..00000000 --- a/source/tools/tools-mocker/src/main/resources/ledger4.init +++ /dev/null @@ -1,72 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffa - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name=JDChain - - -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart4.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=4 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path= -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=1601 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path= -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=1611 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path= -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=1621 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path= -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=1631 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false \ No newline at end of file diff --git a/source/tools/tools-mocker/src/main/resources/ledger8.init b/source/tools/tools-mocker/src/main/resources/ledger8.init deleted file mode 100644 index dacbfeca..00000000 --- a/source/tools/tools-mocker/src/main/resources/ledger8.init +++ /dev/null @@ -1,125 +0,0 @@ -#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; -ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe - -#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name=JDChain - - -#共识服务提供者;必须; -consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider - -#共识服务的参数配置;必须; -consensus.conf=classpath:bftsmart8.config - -#密码服务提供者列表,以英文逗点“,”分隔;必须; -crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ -com.jd.blockchain.crypto.service.sm.SMCryptoService - - -#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; -cons_parti.count=8 - -#第0个参与方的名称; -cons_parti.0.name=jd.com -#第0个参与方的公钥文件路径; -cons_parti.0.pubkey-path= -#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 -#第0个参与方的账本初始服务的主机; -cons_parti.0.initializer.host=127.0.0.1 -#第0个参与方的账本初始服务的端口; -cons_parti.0.initializer.port=1601 -#第0个参与方的账本初始服务是否开启安全连接; -cons_parti.0.initializer.secure=false - -#第1个参与方的名称; -cons_parti.1.name=at.com -#第1个参与方的公钥文件路径; -cons_parti.1.pubkey-path= -#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX -#第1个参与方的账本初始服务的主机; -cons_parti.1.initializer.host=127.0.0.1 -#第1个参与方的账本初始服务的端口; -cons_parti.1.initializer.port=1611 -#第1个参与方的账本初始服务是否开启安全连接; -cons_parti.1.initializer.secure=false - -#第2个参与方的名称; -cons_parti.2.name=bt.com -#第2个参与方的公钥文件路径; -cons_parti.2.pubkey-path= -#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x -#第2个参与方的账本初始服务的主机; -cons_parti.2.initializer.host=127.0.0.1 -#第2个参与方的账本初始服务的端口; -cons_parti.2.initializer.port=1621 -#第2个参与方的账本初始服务是否开启安全连接; -cons_parti.2.initializer.secure=false - -#第3个参与方的名称; -cons_parti.3.name=xt.com -#第3个参与方的公钥文件路径; -cons_parti.3.pubkey-path= -#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk -#第3个参与方的账本初始服务的主机; -cons_parti.3.initializer.host=127.0.0.1 -#第3个参与方的账本初始服务的端口; -cons_parti.3.initializer.port=1631 -#第3个参与方的账本初始服务是否开启安全连接; -cons_parti.3.initializer.secure=false - - -#第4个参与方的名称; -cons_parti.4.name=mt.com -#第4个参与方的公钥文件路径; -cons_parti.4.pubkey-path= -#第4个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.4.pubkey=3snPdw7i7PXPRMp3EAjsxJkHe7aZJRLNzdW8kEHBWeQsSgcPAiHP2J -#第4个参与方的账本初始服务的主机; -cons_parti.4.initializer.host=127.0.0.1 -#第4个参与方的账本初始服务的端口; -cons_parti.4.initializer.port=1641 -#第4个参与方的账本初始服务是否开启安全连接; -cons_parti.4.initializer.secure=false - -#第5个参与方的名称; -cons_parti.5.name=nt.com -#第5个参与方的公钥文件路径; -cons_parti.5.pubkey-path= -#第5个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.5.pubkey=3snPdw7i7PmmQoPgUpUmmAUj6nakHj8wMSQmiMi1RaiZp4YU1D4AXk -#第5个参与方的账本初始服务的主机; -cons_parti.5.initializer.host=127.0.0.1 -#第5个参与方的账本初始服务的端口; -cons_parti.5.initializer.port=1651 -#第5个参与方的账本初始服务是否开启安全连接; -cons_parti.5.initializer.secure=false - -#第6个参与方的名称; -cons_parti.6.name=yt.com -#第6个参与方的公钥文件路径; -cons_parti.6.pubkey-path= -#第6个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.6.pubkey=3snPdw7i7PiJKsa94q3EcLT1y6GRJ7LeFGe799hdzRRHmf6LNodyiM -#第6个参与方的账本初始服务的主机; -cons_parti.6.initializer.host=127.0.0.1 -#第6个参与方的账本初始服务的端口; -cons_parti.6.initializer.port=1661 -#第6个参与方的账本初始服务是否开启安全连接; -cons_parti.6.initializer.secure=false - -#第7个参与方的名称; -cons_parti.7.name=zt.com -#第7个参与方的公钥文件路径; -cons_parti.7.pubkey-path= -#第7个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; -cons_parti.7.pubkey=3snPdw7i7Pm2wJwEnKn8kK8eGTkN36C2BZRRjVTr9FPB2rqtcgTq7h -#第7个参与方的账本初始服务的主机; -cons_parti.7.initializer.host=127.0.0.1 -#第7个参与方的账本初始服务的端口; -cons_parti.7.initializer.port=1671 -#第7个参与方的账本初始服务是否开启安全连接; -cons_parti.7.initializer.secure=false \ No newline at end of file diff --git a/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/AccountMockerTest.java b/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/AccountMockerTest.java deleted file mode 100644 index 5058ebdc..00000000 --- a/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/AccountMockerTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package test.com.jd.blockchain.contract; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.mocker.MockerNodeContext; -import com.jd.blockchain.mocker.contracts.AccountContract; -import com.jd.blockchain.mocker.contracts.AccountContractImpl; -import org.junit.Before; -import org.junit.Test; - -public class AccountMockerTest { - - String accountFrom = "zhangsan"; - - String accountTo = "lisi"; - - MockerNodeContext mockerNodeContext = null; - - HashDigest ledgerHash = null; - - @Before - public void init() { - mockerNodeContext = new MockerNodeContext().build(); - ledgerHash = mockerNodeContext.getLedgerHash(); - } - - @Test - public void test() { - // 首先创建一个数据账户 - String address = mockerNodeContext.registerDataAccount(); - - // 处理合约 - AccountContract accountContract = new AccountContractImpl(); - - // 发布合约 - accountContract = mockerNodeContext.deployContract(accountContract); - - //首先创建账户 - accountContract.create(address, accountFrom, 1000L); - - accountContract.create(address, accountTo, 1000L); - -// accountContract.print(address, accountFrom, accountTo); - - // 开始转账 - accountContract.transfer(address, accountFrom, accountTo, 500); - - // 打印转账后结果 - accountContract.print(address, accountFrom, accountTo); - } -} diff --git a/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/MockTest.java b/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/MockTest.java deleted file mode 100644 index b9362607..00000000 --- a/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/MockTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package test.com.jd.blockchain.contract; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.KVDataEntry; -import com.jd.blockchain.mocker.MockerNodeContext; -import com.jd.blockchain.mocker.config.MockerConstant; -import com.jd.blockchain.mocker.contracts.WriteContract; -import com.jd.blockchain.mocker.contracts.WriteContractImpl; -import org.junit.Test; - -public class MockTest { - - @Test - public void test() { - // 准备环境 - BlockchainKeypair blockchainKeypair = BlockchainKeyGenerator.getInstance().generate(); - MockerNodeContext mockerNodeContext = - new MockerNodeContext(MockerConstant.DEFAULT_LEDGER_SEED) - .participants("zhangsan", blockchainKeypair) - .build(); - HashDigest ledgerHash = mockerNodeContext.getLedgerHash(); - - System.out.printf("LedgerHash = %s \r\n", ledgerHash.toBase58()); - System.out.printf("LedgerSeed = %s \r\n", mockerNodeContext.getLedgerSeed()); - - // 注册用户 - String userAddress = mockerNodeContext.registerUser(BlockchainKeyGenerator.getInstance().generate()); - System.out.printf("----- 注册用户地址 {%s} -----\r\n", userAddress); - - // 注册数据账户 - String dataAccountAddress = mockerNodeContext.registerDataAccount(BlockchainKeyGenerator.getInstance().generate()); - System.out.printf("----- 注册数据账户地址 {%s} -----\r\n", dataAccountAddress); - - WriteContract writeContract = new WriteContractImpl(); - - // 发布合约 - writeContract = mockerNodeContext.deployContract(writeContract); - - writeContract.print("张三"); - - String key = "Hello", value = "World"; - - writeContract.writeKv(dataAccountAddress, key, value); - - // 查询 - KVDataEntry[] kvDataEntries = mockerNodeContext.getDataEntries(ledgerHash, dataAccountAddress, key); - - for (KVDataEntry kvDataEntry : kvDataEntries) { - System.out.printf("Key = %s, Value = %s \r\n", kvDataEntry.getKey(), kvDataEntry.getValue()); - } - } -} diff --git a/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/SampleTest.java b/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/SampleTest.java deleted file mode 100644 index 19cd34df..00000000 --- a/source/tools/tools-mocker/src/test/java/test/com/jd/blockchain/contract/SampleTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package test.com.jd.blockchain.contract; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.KVDataEntry; -import com.jd.blockchain.mocker.MockerNodeContext; -import com.jd.blockchain.mocker.contracts.WriteContract; -import com.jd.blockchain.mocker.contracts.WriteContractImpl; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class SampleTest { - - MockerNodeContext mockerNodeContext = null; - - HashDigest ledgerHash = null; - - @Before - public void init() { - mockerNodeContext = new MockerNodeContext().build(); - ledgerHash = mockerNodeContext.getLedgerHash(); - } - - @Test - public void writeTest() { - - String key = "MyKey-" + System.currentTimeMillis(), value = "JDChain"; - - WriteContract writeContract = new WriteContractImpl(); - - String dataAccountAddress = mockerNodeContext.registerDataAccount(); - - writeContract = mockerNodeContext.deployContract(writeContract); - - String result = writeContract.writeKv(dataAccountAddress, key, value); - - System.out.println(result); - - // 查询结果 - KVDataEntry[] dataEntries = mockerNodeContext.getDataEntries(ledgerHash, dataAccountAddress, key); - - for (KVDataEntry kvDataEntry : dataEntries) { - assertEquals(key, kvDataEntry.getKey()); - assertEquals(value, kvDataEntry.getValue()); - System.out.printf("Key = %s, Value = %s \r\n", kvDataEntry.getKey(), kvDataEntry.getValue()); - } - } -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ArgumentSet.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ArgumentSet.java deleted file mode 100644 index 7b604f54..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ArgumentSet.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.jd.blockchain.utils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class ArgumentSet { - -// private static Pattern ARG_PATTERN = Pattern.compile("\\-.+\\={1}.*"); - - private ArgEntry[] args; - - private Map prefixArgs = new HashMap<>(); - - private Set options = new HashSet<>(); - - private ArgumentSet(ArgEntry[] args) { - this.args = args; - for (ArgEntry arg : args) { - if (arg.prefix != null) { - prefixArgs.put(arg.prefix, arg); - } - if (arg.option != null) { - options.add(arg.option); - } - } - } - - public static boolean hasOption(String[] args, String option) { - boolean contains = false; - if (args != null) { - for (String a : args) { - if (option.equalsIgnoreCase(a)) { - contains = true; - break; - } - } - } - return contains; - } - - public static Setting setting() { - return new Setting(); - } - - public static ArgumentSet resolve(String[] args, Setting setting) { - if (args == null) { - return new ArgumentSet(new ArgEntry[0]); - } - List argEntries = new ArrayList<>(); - for (int i = 0; i < args.length; i++) { - if (setting.prefixes.contains(args[i])) { - ArgEntry ae = new ArgEntry(); - ae.prefix = args[i]; - if (i+1 >= args.length) { - throw new IllegalArgumentException(String.format("缺少 %s 参数!", args[i])); - } - i++; - ae.value = args[i]; - argEntries.add(ae); - continue; - } - - if(setting.options.contains(args[i])){ - ArgEntry ae = new ArgEntry(); - ae.option = args[i]; - argEntries.add(ae); - continue; - } - } - return new ArgumentSet(argEntries.toArray(new ArgEntry[argEntries.size()])); - } - - /** - * 按照原始顺序排列的参数列表; - * - * @return ArgEntry[] - */ - public ArgEntry[] getArgs() { - return args; - } - - public ArgEntry getArg(String prefix) { - return prefixArgs.get(prefix); - } - - public boolean hasOption(String option) { - return options.contains(option); - } - - /** - * @author huanghaiquan - * - */ - public static class ArgEntry { - - private String prefix; - - private String value; - - private String option; - - /** - * 前缀;
- * 如果不是前缀参数,则为 null; - * - * @return String - */ - public String getPrefix() { - return prefix; - } - - /** - * 参数值;
- * - * 如果只是选项参数,则返回 null; - * - * @return String - */ - public String getValue() { - return value; - } - - /** - * 选项; - * - * @return String - */ - public String getOption() { - return option; - } - - } - - public static class Setting { - - private Set prefixes = new HashSet<>(); - - private Set options = new HashSet<>(); - - private Setting() { - } - - - public Setting prefix(String... prefixes) { - this.prefixes.addAll(Arrays.asList(prefixes)); - return this; - } - - public Setting option(String... options) { - this.options.addAll(Arrays.asList(options)); - return this; - } - - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Bytes.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Bytes.java deleted file mode 100644 index dd87b2ff..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Bytes.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.jd.blockchain.utils; - -import java.io.IOException; -import java.io.OutputStream; - -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesSerializable; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.io.RuntimeIOException; - -/** - * Bytes 被设计为不可变对象; - * - * @author huanghaiquan - * - */ -public class Bytes implements BytesSerializable { - - public static final Bytes EMPTY = new Bytes(BytesUtils.EMPTY_BYTES); - - private static final int MAX_CACHE = 256; - - private static Bytes[] INT_BYTES; - - private static Bytes[] LONG_BYTES; - - static { - INT_BYTES = new Bytes[MAX_CACHE]; - LONG_BYTES = new Bytes[MAX_CACHE]; - for (int i = 0; i < MAX_CACHE; i++) { - INT_BYTES[i] = new Bytes(BytesUtils.toBytes((int) i)); - LONG_BYTES[i] = new Bytes(BytesUtils.toBytes((long) i)); - } - } - - private final Bytes prefix; - - private final byte[] data; - - private final int hashCode; - - public int size() { - return prefix == null ? data.length : prefix.size() + data.length; - } - - public Bytes() { - prefix = null; - data = null; - hashCode = hashCode(1); - } - - public Bytes(byte[] data) { - if (data == null) { - throw new IllegalArgumentException("data is null!"); - } - this.prefix = null; - this.data = data; - hashCode = hashCode(1); - } - - public Bytes(Bytes prefix, byte[] data) { - if (data == null) { - throw new IllegalArgumentException("data is null!"); - } - this.prefix = prefix; - this.data = data; - // setPrefix(prefix); - hashCode = hashCode(1); - } - - public Bytes(Bytes prefix, Bytes data) { - // setData(data.toBytes()); - // setPrefix(prefix); - if (data == null) { - throw new IllegalArgumentException("data is null!"); - } - this.prefix = prefix; - this.data = data.toBytes(); - - hashCode = hashCode(1); - } - - // private void setData(byte[] data) { - // if (data == null) { - // throw new IllegalArgumentException("data is null!"); - // } - // this.data = data; - // } - - /** - * 返回当前的字节数组(不包含前缀对象); - * - * @return byte[] - */ - protected byte[] getDirectBytes() { - return data; - } - - public static Bytes fromString(String str) { - return new Bytes(BytesUtils.toBytes(str)); - } - - public static Bytes fromBase58(String str) { - return new Bytes(Base58Utils.decode(str)); - } - - // /** - // * 连接指定的前缀后面;此操作并不会更改“prefix”参数; - // * - // * @param prefix - // * @return - // */ - // private Bytes setPrefix(Bytes prefix) { - // this.prefix = prefix; - // return this; - // } - - public Bytes concat(Bytes key) { - return new Bytes(this, key); - } - - public Bytes concat(byte[] key) { - return new Bytes(this, key); - } - - public int writeTo(OutputStream out) { - int size = 0; - if (prefix != null) { - size = prefix.writeTo(out); - } - try { - out.write(data); - size += data.length; - return size; - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - private int hashCode(int result) { - if (prefix != null) { - result = prefix.hashCode(result); - } - for (byte element : data) { - result = 31 * result + element; - } - - return result; - } - - // private static int hashCode(byte a[], int offset, int len) { - // if (a == null) - // return 0; - // - // int result = 1; - // for (int i = 0; i < len; i++) { - // result = 31 * result + a[offset + i]; - // } - // - // return result; - // } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (!(obj instanceof Bytes)) { - return false; - } - Bytes oth = (Bytes) obj; - if (this.hashCode != oth.hashCode) { - return false; - } - boolean prefixIsEqual = false; - if (this.prefix == null && oth.prefix == null) { - prefixIsEqual = true; - } else if (this.prefix == null) { - prefixIsEqual = false; - } else { - prefixIsEqual = this.prefix.equals(oth.prefix); - } - if (!prefixIsEqual) { - return false; - } - return BytesUtils.equals(this.data, oth.data); - } - - public int copyTo(byte[] buffer, int offset, int len) { - if (len < 0) { - throw new IllegalArgumentException("Argument len is negative!"); - } - if (len == 0) { - return 0; - } - int s = 0; - if (prefix != null) { - s = prefix.copyTo(buffer, offset, len); - } - if (s < len) { - int l = len - s; - l = l < data.length ? l : data.length; - System.arraycopy(data, 0, buffer, offset + s, l); - s += l; - } - return s; - } - - @Override - public byte[] toBytes() { - if (prefix == null || prefix.size() == 0) { - return data; - } - int size = size(); - byte[] buffer = new byte[size]; - copyTo(buffer, 0, size); - return buffer; - } - - public String toBase58() { - return Base58Utils.encode(toBytes()); - } - - public static Bytes fromInt(int value) { - if (value > -1 && value < MAX_CACHE) { - return INT_BYTES[value]; - } - return new Bytes(BytesUtils.toBytes(value)); - } - - public String toUTF8String() { - return BytesUtils.toString(toBytes()); - } - - public static Bytes fromLong(long value) { - if (value > -1 && value < MAX_CACHE) { - return LONG_BYTES[(int) value]; - } - return new Bytes(BytesUtils.toBytes(value)); - } - - /** - * 返回 Base58 编码的字符; - */ - @Override - public String toString() { - return toBase58(); - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ConsoleUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ConsoleUtils.java deleted file mode 100644 index 7811faa5..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ConsoleUtils.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jd.blockchain.utils; - -import java.io.Console; - -import com.jd.blockchain.utils.io.ByteArray; - -public class ConsoleUtils { - - public static byte[] readPassword() { - Console cs = getConsole(); - char[] pwdChars; - do { - pwdChars = cs.readPassword("\r\nInput password:"); - } while (pwdChars.length == 0); - String pwd = new String(pwdChars); - return ByteArray.fromString(pwd, "UTF-8"); - } - - public static void info(String format, Object... args) { - System.out.println(String.format(format, args)); - } - - public static void error(String format, Object... args) { - System.err.println(String.format(format, args)); - } - - public static String confirm(String fmt, Object...args) { - Console cs = getConsole(); - return cs.readLine(fmt, args); - } - - public static Console getConsole() { - Console cs = System.console(); - if (cs == null) { - throw new IllegalStateException("You are not running in console!"); - } - return cs; - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/DataIterator.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/DataIterator.java deleted file mode 100644 index 13a8a0d0..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/DataIterator.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.utils; - -/** - * 数据迭代器; - * - * @author huanghaiquan - * - * @param - * @param - */ -public interface DataIterator { - - void skip(long count); - - DataEntry next(); - - DataEntry[] next(int count); - - boolean hasNext(); - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Dataset.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Dataset.java deleted file mode 100644 index 2a82bd19..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Dataset.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jd.blockchain.utils; - -/** - * Key-Value data set; - * - * @author huanghaiquan - * - * @param - * @param - */ -public interface Dataset { - - /** - * Total count of data entries; - * - * @return - */ - long getDataCount(); - - /** - * Create or update the value associated the specified key if the version - * checking is passed.
- * - * The value of the key will be updated only if it's latest version equals the - * specified version argument.
- * If the key doesn't exist, it will be created when the version arg was -1. - *

- * If updating is performed, the version of the key increase by 1.
- * If creating is performed, the version of the key initialize by 0.
- * - * @param key The key of data; - * @param value The value of data; - * @param version The expected latest version of the key. - * @return The new version of the key.
- * If the key is new created success, then return 0;
- * If the key is updated success, then return the new version;
- * If this operation fail by version checking or other reason, then - * return -1; - */ - long setValue(K key, V value, long version); - - /** - * Return the specified version's value;
- * - * If the key with the specified version doesn't exist, then return null;
- * If the version is specified to -1, then return the latest version's value; - * - * @param key - * @param version - */ - V getValue(K key, long version); - - /** - * Return the value of the latest version; - * - * @param key - * @return return null if not exist; - */ - V getValue(K key); - - /** - * Return the latest version number of the specified key; - * - * @param key - * @return The version number of the specified key; If the key doesn't exist, - * then return -1; - */ - long getVersion(K key); - - /** - * Return the data entry with the specified key; - * - * @param key - * @return Null if the key doesn't exist! - */ - DataEntry getDataEntry(K key); - - /** - * Return the data entry with the specified key and version; - * - * @param key - * @param version - * @return Null if the key doesn't exist! - */ - DataEntry getDataEntry(K key, long version); - - /** - * Ascending iterator; - * - * @return - */ - DataIterator iterator(); - - /** - * Descending iterator; - * - * @return - */ - DataIterator iteratorDesc(); - -} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/DatasetHelper.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/DatasetHelper.java deleted file mode 100644 index acbdce51..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/DatasetHelper.java +++ /dev/null @@ -1,382 +0,0 @@ -package com.jd.blockchain.utils; - -/** - * Helper for {@link Dataset}; - * - * @author huanghaiquan - * - */ -public class DatasetHelper { - - public static final TypeMapper UTF8_STRING_BYTES_MAPPER = new TypeMapper() { - - @Override - public Bytes encode(String t2) { - return Bytes.fromString(t2); - } - - @Override - public String decode(Bytes t1) { - return t1.toUTF8String(); - } - }; - - public static final TypeMapper BYTES_UTF8_STRING_MAPPER = new TypeMapper() { - - @Override - public String encode(Bytes t1) { - return t1.toUTF8String(); - } - - @Override - public Bytes decode(String t2) { - return Bytes.fromString(t2); - } - }; - - /** - * 适配两个不同类型参数的数据集; - * - * @param 适配输入的 键 类型; - * @param 适配输出的 键 类型; - * @param 适配输入的 值 类型; - * @param 适配输出的 值 类型; - * @param dataset 数据集; - * @param keyMapper 键的映射配置; - * @param valueMapper 值的映射配置; - * @return - */ - public static Dataset map(Dataset dataset) { - return new TypeAdapter(dataset, UTF8_STRING_BYTES_MAPPER, new EmptyMapper()); - } - - /** - * 适配两个不同类型参数的数据集; - * - * @param 适配输入的 键 类型; - * @param 适配输出的 键 类型; - * @param 适配输入的 值 类型; - * @param 适配输出的 值 类型; - * @param dataset 数据集; - * @param keyMapper 键的映射配置; - * @param valueMapper 值的映射配置; - * @return - */ - public static Dataset map(Dataset dataset, TypeMapper valueMapper) { - return new TypeAdapter(dataset, UTF8_STRING_BYTES_MAPPER, valueMapper); - } - - /** - * 适配两个不同类型参数的数据集; - * - * @param 适配输入的 键 类型; - * @param 适配输出的 键 类型; - * @param 适配输入的 值 类型; - * @param 适配输出的 值 类型; - * @param dataset 数据集; - * @param keyMapper 键的映射配置; - * @param valueMapper 值的映射配置; - * @return - */ - public static Dataset map(Dataset dataset, TypeMapper keyMapper, - TypeMapper valueMapper) { - return new TypeAdapter(dataset, keyMapper, valueMapper); - } - - /** - * 监听对数据集的变更; - * - * @param 键 类型; - * @param 值 类型; - * @param dataset 要监听的数据集; - * @param listener 要植入的监听器; - * @return 植入监听器的数据集实例; - */ - public static Dataset listen(Dataset dataset, DataChangedListener listener) { - return new DatasetUpdatingMonitor(dataset, listener); - } - - /** - * 数据修改监听器; - * - * @author huanghaiquan - * - * @param - * @param - */ - public static interface DataChangedListener { - - void onChanged(K key, V value, long expectedVersion, long newVersion); - - } - - /** - * 类型映射接口; - * - * @author huanghaiquan - * - * @param - * @param - */ - public static interface TypeMapper { - - T1 encode(T2 t2); - - T2 decode(T1 t1); - - } - - private static class EmptyMapper implements TypeMapper { - - @Override - public T encode(T t) { - return t; - } - - @Override - public T decode(T t) { - return t; - } - - } - - private static class DatasetUpdatingMonitor implements Dataset { - - private Dataset dataset; - - private DataChangedListener listener; - - public DatasetUpdatingMonitor(Dataset dataset, DataChangedListener listener) { - this.dataset = dataset; - this.listener = listener; - } - - @Override - public long getDataCount() { - return dataset.getDataCount(); - } - - @Override - public long setValue(K key, V value, long version) { - long newVersion = dataset.setValue(key, value, version); - if (newVersion > -1) { - listener.onChanged(key, value, version, newVersion); - } - return newVersion; - } - - @Override - public V getValue(K key, long version) { - return dataset.getValue(key, version); - } - - @Override - public V getValue(K key) { - return dataset.getValue(key); - } - - @Override - public long getVersion(K key) { - return dataset.getVersion(key); - } - - @Override - public DataEntry getDataEntry(K key) { - return dataset.getDataEntry(key); - } - - @Override - public DataEntry getDataEntry(K key, long version) { - return dataset.getDataEntry(key, version); - } - - @Override - public DataIterator iterator() { - return dataset.iterator(); - } - - @Override - public DataIterator iteratorDesc() { - return dataset.iteratorDesc(); - } - - } - - /** - * 类型适配器; - * - * @author huanghaiquan - * - * @param - * @param - * @param - * @param - */ - private static class TypeAdapter implements Dataset { - private Dataset dataset; - private TypeMapper keyMapper; - private TypeMapper valueMapper; - - public TypeAdapter(Dataset dataset, TypeMapper keyMapper, TypeMapper valueMapper) { - this.dataset = dataset; - this.keyMapper = keyMapper; - this.valueMapper = valueMapper; - } - - @Override - public long getDataCount() { - return dataset.getDataCount(); - } - - @Override - public long setValue(K2 key, V2 value, long version) { - K1 key1 = keyMapper.encode(key); - V1 value1 = valueMapper.encode(value); - return dataset.setValue(key1, value1, version); - } - - @Override - public V2 getValue(K2 key, long version) { - K1 k = keyMapper.encode(key); - V1 v = dataset.getValue(k, version); - if (v == null) { - return null; - } - return valueMapper.decode(v); - } - - @Override - public V2 getValue(K2 key) { - K1 k = keyMapper.encode(key); - V1 v = dataset.getValue(k); - if (v == null) { - return null; - } - return valueMapper.decode(v); - } - - @Override - public long getVersion(K2 key) { - K1 k = keyMapper.encode(key); - return dataset.getVersion(k); - } - - @Override - public DataEntry getDataEntry(K2 key) { - K1 k = keyMapper.encode(key); - DataEntry entry = dataset.getDataEntry(k); - if (entry == null) { - return null; - } - V2 v = valueMapper.decode(entry.getValue()); - return new KeyValueEntry(key, v, entry.getVersion()); - } - - @Override - public DataEntry getDataEntry(K2 key, long version) { - K1 k = keyMapper.encode(key); - DataEntry entry = dataset.getDataEntry(k, version); - if (entry == null) { - return null; - } - V2 v = valueMapper.decode(entry.getValue()); - return new KeyValueEntry(key, v, entry.getVersion()); - } - - @Override - public DataIterator iterator() { - DataIterator it = dataset.iterator(); - return new DataIteratorAdapter(it, keyMapper, valueMapper); - } - - @Override - public DataIterator iteratorDesc() { - DataIterator it = dataset.iteratorDesc(); - return new DataIteratorAdapter(it, keyMapper, valueMapper); - } - - } - - private static class DataIteratorAdapter implements DataIterator { - - private DataIterator iterator; - - private TypeMapper keyMapper; - private TypeMapper valueMapper; - - public DataIteratorAdapter(DataIterator iterator, TypeMapper keyMapper, - TypeMapper valueMapper) { - this.iterator = iterator; - this.keyMapper = keyMapper; - this.valueMapper = valueMapper; - } - - @Override - public void skip(long count) { - iterator.skip(count); - } - - @Override - public DataEntry next() { - DataEntry entry = iterator.next(); - return cast(entry); - } - - private DataEntry cast(DataEntry entry) { - if (entry == null) { - return null; - } - - K2 k = keyMapper.decode(entry.getKey()); - V2 v = valueMapper.decode(entry.getValue()); - return new KeyValueEntry(k, v, entry.getVersion()); - } - - @SuppressWarnings("unchecked") - @Override - public DataEntry[] next(int count) { - DataEntry[] entries = iterator.next(count); - if (entries == null) { - return null; - } - if (entries.length == 0) { - return (DataEntry[]) entries; - } - return ArrayUtils.castTo(entries, DataEntry.class, e -> cast(e)); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - } - - private static class KeyValueEntry implements DataEntry { - - private K key; - - private V value; - - private long version; - - public KeyValueEntry(K key, V value, long version) { - this.key = key; - this.value = value; - this.version = version; - } - - public K getKey() { - return key; - } - - public long getVersion() { - return version; - } - - public V getValue() { - return value; - } - - } -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Int8Code.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Int8Code.java deleted file mode 100644 index 339c9c07..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Int8Code.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.jd.blockchain.utils; - -public interface Int8Code { - - byte getCode(); - - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Property.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Property.java deleted file mode 100644 index 802d68ee..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Property.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jd.blockchain.utils; - -import java.io.ByteArrayInputStream; - -import com.jd.blockchain.utils.io.BytesEncoding; -import com.jd.blockchain.utils.io.BytesSerializable; -import com.jd.blockchain.utils.io.BytesUtils; - -public class Property implements BytesSerializable { - - private String name; - - private String value; - - public Property() { - } - - public Property(String name, String value) { - this.name = name; - this.value = value; - } - - public Property(byte[] nameValueBytes) { - decode(nameValueBytes); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - public byte[] toBytes() { - byte[] nameBytes = BytesUtils.toBytes(name); - byte[] valueBytes = value == null ? BytesUtils.EMPTY_BYTES : BytesUtils.toBytes(value); - int totalSize = BytesEncoding.getOutputSizeInNormal(nameBytes.length) - + BytesEncoding.getOutputSizeInNormal(valueBytes.length); - byte[] totalBytes = new byte[totalSize]; - int offset = 0; - offset += BytesEncoding.writeInNormal(nameBytes, totalBytes, offset); - offset += BytesEncoding.writeInNormal(valueBytes, totalBytes, offset); - return totalBytes; - } - - private void decode(byte[] nameValueBytes) { - ByteArrayInputStream in = new ByteArrayInputStream(nameValueBytes); - byte[] nameBytes = BytesEncoding.readInNormal(in); - byte[] valueBytes = BytesEncoding.readInNormal(in); - this.name = BytesUtils.toString(nameBytes); - this.value = valueBytes.length == 0 ? "" : BytesUtils.toString(valueBytes); - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/QueryUtil.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/QueryUtil.java deleted file mode 100644 index 16021427..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/QueryUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jd.blockchain.utils; - -import static com.jd.blockchain.utils.BaseConstant.QUERY_LIST_MAX; - -/** - * @author zhaogw - * date 2019/2/22 17:00 - */ -public class QueryUtil { - - /** - * confirm the fromIndex and count by 3 factors; - * @param fromIndex fromIndex - * @param count count - * @param maxNum maxNum - * @return int[] - */ - public static int[] calFromIndexAndCount(int fromIndex, int count, int maxNum){ - int [] rtn = new int[2]; - if (fromIndex < 0 || fromIndex >= maxNum) { - fromIndex = 0; - } - - //must < maxNum; - if(count > maxNum){ - count = maxNum; - } - //must < threshold; - if(count > QUERY_LIST_MAX){ - count = QUERY_LIST_MAX; - } - //if count is empty, get the small; - if (count == -1) { - fromIndex = 0; - //count must <=100; - count = maxNum > QUERY_LIST_MAX ? QUERY_LIST_MAX : maxNum; - } - //count is ok, then calculate the plus condition; - if (fromIndex + count >= maxNum) { - count = maxNum - fromIndex; - } - //now if count<-1, then deduce: make trouble;so set count=0; - if(count < -1){ - count = 0; - } - rtn[0] = fromIndex; - rtn[1] = count; - return rtn; - } - - /** - * cal the data by descend; - * @param fromIndex - * @param count - * @param maxNum - * @return - */ - public static int[] calFromIndexAndCountDescend(int fromIndex, int count, int maxNum){ - int rtn[] = new int[2]; - int results[] = calFromIndexAndCount(fromIndex,count,maxNum); - - //now use descend; first show the latest record; - rtn[0] = maxNum - results[0] - results[1]; - rtn[1] = results[1]; - return rtn; - } -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/StringUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/StringUtils.java deleted file mode 100644 index 480d1335..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/StringUtils.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jd.blockchain.utils; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; -import java.util.regex.Pattern; - -/** - * @Author zhaogw date 2018/11/26 20:46 - */ -public class StringUtils { - - public static final String[] EMPTY_ARRAY = {}; - - public static boolean isEmpty(Object str) { - return str == null || "".equals(str); - } - - /* - * 判断是否为整数 - * - * @param str 传入的字符串 - * - * @return 是整数返回true,否则返回false - */ - - public static boolean isNumber(String str) { - Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); - return pattern.matcher(str).matches(); - } - - /** - * 按照指定的分隔符把字符串分解为字符数组,同时截掉每一个元素两端的空白字符,并忽略掉空字符元素; - * - * @param str 要被截断的字符串; - * @param delimiter 分隔符; - * @return - */ - public static String[] splitToArray(String str, String delimiter) { - return splitToArray(str, delimiter, true, true); - } - - /** - * 按照指定的分隔符把字符串分解为字符数组 - * - * @param str 要被截断的字符串; - * @param delimiter 分隔符; - * @param trimElement 是否截断元素两端的空白字符; - * @param ignoreEmptyElement 是否忽略空字符元素; - * @return - */ - public static String[] splitToArray(String str, String delimiter, boolean trimElement, boolean ignoreEmptyElement) { - if (str == null) { - return EMPTY_ARRAY; - } - if (trimElement) { - str = str.trim(); - } - if (str.length() == 0) { - return EMPTY_ARRAY; - } - StringTokenizer tokenizer = new StringTokenizer(str, delimiter); - List tokens = new ArrayList<>(); - while (tokenizer.hasMoreTokens()) { - String token = tokenizer.nextToken(); - if (trimElement) { - token = token.trim(); - } - if ((!ignoreEmptyElement) || token.length() > 0) { - tokens.add(token); - } - } - return tokens.toArray(new String[tokens.size()]); - } - - public static String trim(String str) { - return str == null ? "" : str.trim(); - } -} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Transactional.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Transactional.java deleted file mode 100644 index fc2a85a9..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/Transactional.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jd.blockchain.utils; - -/** - * {@link Transactional} 表示一种事务特性,即对一个对象的状态的更改是临时性的,直到成功地调用 {@link #commit()} - * 方法提交变更,或者调用 {@link #cancel()} 方法取消变更; - * - * @author huanghaiquan - * - */ -public interface Transactional { - - /** - * 是否发生了变更;
- * - * 自上一次调用 {@link #commit()} 或 {@link #cancel()} 之后,对象的状态如果发生了变更,则返回 true,否则返回 - * false; - * - * @return boolean - */ - boolean isUpdated(); - - /** - * 提交所有变更;
- * - * 如果执行前 {@link #isUpdated()} 返回 true,则提交之后 {@link #isUpdated()} 返回 false; - */ - void commit(); - - /** - * 取消所有变更;
- * - * 如果执行前 {@link #isUpdated()} 返回 true,则取消之后 {@link #isUpdated()} 返回 false; - */ - void cancel(); - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/AsyncHandle.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/AsyncHandle.java deleted file mode 100644 index cda5bd57..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/AsyncHandle.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jd.blockchain.utils.concurrent; - -import java.util.function.BiConsumer; - -public interface AsyncHandle extends BiConsumer { - - void complete(T returnValue, Throwable error); - - - @Override - default void accept(T t, Throwable u) { - complete(t, u); - } -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/AsyncResult.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/AsyncResult.java deleted file mode 100644 index 2d4ebcda..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/AsyncResult.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jd.blockchain.utils.concurrent; -//package my.utils.concurrent; -// -//public interface AsyncResult { -// -// public T getResult(); -// -// /** -// * 操作是否已完成; -// * -// * 当操作成功返回或者异常返回时,都表示为已完成; -// * -// * @return -// */ -// public boolean isDone(); -// -// /** -// * 操作是否已成功; -// * -// * @return -// */ -// public boolean isSuccess(); -// -// public String getErrorCode(); -// -// /** -// * 返回操作异常; -// * -// * 当未完成(isDone方法返回false)或操作正常结束时,返回 null; -// * -// * @return -// */ -// public Throwable getException(); -// -// /** -// * 等待异步操作完成后返回; -// * -// * 等待过程不触发中断; -// */ -// public void awaitUninterruptibly(); -// -// /** -// * 等待异步操作完成后返回; -// * -// * 等待过程不触发中断; -// * -// * @param timeoutMillis -// * 超时毫秒数; -// * @return true 表示操作已完成; false 表示超时返回; -// */ -// public boolean awaitUninterruptibly(long timeoutMillis); -// -// /** -// * 注册监听器; -// * -// * @param listener -// */ -// public void addListener(AsyncCallback callback); -// -//} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/InvocationResult.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/InvocationResult.java deleted file mode 100644 index 27a7e68f..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/InvocationResult.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jd.blockchain.utils.concurrent; - -public class InvocationResult { - - private volatile T value; - - private volatile Exception error; - - public T getValue() { - return value; - } - - public void setValue(T value) { - this.value = value; - } - - public Exception getError() { - return error; - } - - public void setError(Exception error) { - this.error = error; - } - -} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/ThreadInvoker.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/ThreadInvoker.java deleted file mode 100644 index fcd83083..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/concurrent/ThreadInvoker.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.jd.blockchain.utils.concurrent; - -/** - * 在新线程执行调用的工具类;
- * - * 注意:一个实例只能调用一次,并且不应在多线程间共享; - * - * @author huanghaiquan - * - * @param class - */ -public abstract class ThreadInvoker { - - private volatile T retn; - - private volatile Exception error; - - private volatile boolean started = false; - - public Exception getError() { - return error; - } - - public T getRetn() { - return retn; - } - - protected abstract T invoke() throws Exception; - - /** - * Start invoke in new thread, and wait for the invoking thread to die; - * - * @return t - */ - public T startAndWait() { - Thread thrd = doStart(); - try { - thrd.join(); - } catch (InterruptedException e) { - throw new IllegalStateException(e.getMessage(), e); - } - if (error != null) { - throw new IllegalStateException(error.getMessage(), error); - } - return retn; - } - - /** - * Start invoke in new thread; - * - * @return AsyncCallback t; - */ - public AsyncCallback start() { - Thread thrd = doStart(); - return new AsyncCallback(thrd, this); - } - - public synchronized void reset() { - if (started) { - throw new IllegalStateException("Cann't reset when this invoking is running."); - } - retn = null; - error = null; - } - - private synchronized Thread doStart() { - if (started) { - throw new IllegalStateException("Invoker thread has started. Cann't start again until it's over."); - } - if (retn != null || error != null) { - throw new IllegalStateException("Cann't start again until the result of last invoking is reseted."); - } - started = true; - Thread thrd = new Thread(new Runnable() { - @Override - public void run() { - try { - retn = invoke(); - } catch (Exception e) { - error = e; - } finally { - started = false; - } - } - }); - thrd.start(); - return thrd; - } - - public static class AsyncCallback { - private Thread thrd; - - private ThreadInvoker invoker; - - public AsyncCallback(Thread thrd, ThreadInvoker invoker) { - this.thrd = thrd; - this.invoker = invoker; - } - - /** - * 等待调用返回; - * @return class t; - */ - public T waitReturn() { - try { - thrd.join(); - } catch (InterruptedException e) { - throw new IllegalStateException(e.getMessage(), e); - } - if (invoker.error != null) { - throw new IllegalStateException(invoker.error.getMessage(), invoker.error); - } - return invoker.retn; - } - } -} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/decompiler/loads/BytesTypeLoader.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/decompiler/loads/BytesTypeLoader.java deleted file mode 100644 index 379aab08..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/decompiler/loads/BytesTypeLoader.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.jd.blockchain.utils.decompiler.loads; - -import com.strobel.assembler.ir.ConstantPool; -import com.strobel.assembler.metadata.Buffer; -import com.strobel.assembler.metadata.ClasspathTypeLoader; -import com.strobel.assembler.metadata.ITypeLoader; -import com.strobel.core.StringUtilities; -import com.strobel.core.VerifyArgument; - -import java.io.ByteArrayInputStream; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class BytesTypeLoader implements ITypeLoader { - - private final static Logger LOG = Logger.getLogger(BytesTypeLoader.class.getSimpleName()); - - private final ITypeLoader defaultTypeLoader; - private final Map> packageLocations; - private final Map knownBytes; - - private String name; - - public BytesTypeLoader(byte[] bytes) { - this(new ClasspathTypeLoader(), bytes); - } - - public BytesTypeLoader(final ITypeLoader defaultTypeLoader, byte[] bytes) { - this.defaultTypeLoader = VerifyArgument.notNull(defaultTypeLoader, "defaultTypeLoader"); - this.packageLocations = new LinkedHashMap<>(); - this.knownBytes = new LinkedHashMap<>(); - Buffer innerNameBuffer = new Buffer(); - if (tryLoadTypeFromBytes(bytes, innerNameBuffer)) { - this.name = getInternalNameFromClassFile(innerNameBuffer); - this.knownBytes.put(this.name, bytes); - } else { - throw new IllegalStateException("Input Class Bytes Exception !!!"); - } - } - - @Override - public boolean tryLoadType(final String typeNameOrPath, final Buffer buffer) { - VerifyArgument.notNull(typeNameOrPath, "typeNameOrPath"); - VerifyArgument.notNull(buffer, "buffer"); - - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("Attempting to load type: " + typeNameOrPath + "..."); - } - - final boolean hasExtension = StringUtilities.endsWithIgnoreCase(typeNameOrPath, ".class"); - - if (hasExtension) { - return false; - } - - String internalName = typeNameOrPath; - - if (tryLoadTypeFromName(internalName, buffer)) { - return true; - } - - for (int lastDelimiter = internalName.lastIndexOf('/'); - lastDelimiter != -1; - lastDelimiter = internalName.lastIndexOf('/')) { - - internalName = internalName.substring(0, lastDelimiter) + "$" + - internalName.substring(lastDelimiter + 1); - - if (tryLoadTypeFromName(internalName, buffer)) { - return true; - } - } - - if (LOG.isLoggable(Level.FINER)) { - LOG.finer("Failed to load type: " + typeNameOrPath + "."); - } - - return false; - } - - private boolean tryLoadTypeFromName(final String internalName, final Buffer buffer) { - if (tryLoadFromKnownLocation(internalName, buffer)) { - return true; - } - - if (defaultTypeLoader.tryLoadType(internalName, buffer)) { - return true; - } - - return false; - } - - private boolean tryLoadFromKnownLocation(final String internalName, final Buffer buffer) { - final byte[] knownFile = knownBytes.get(internalName); - - if (tryLoadBytes(knownFile, buffer)) { - return true; - } - - final int packageEnd = internalName.lastIndexOf('/'); - - String head; - String tail; - - if (packageEnd < 0 || packageEnd >= internalName.length()) { - head = StringUtilities.EMPTY; - tail = internalName; - } - else { - head = internalName.substring(0, packageEnd); - tail = internalName.substring(packageEnd + 1); - } - - while (true) { - final LinkedHashSet directories = packageLocations.get(head); - - if (directories != null) { - for (final byte[] directory : directories) { - if (tryLoadBytes(internalName, directory, buffer, true)) { - return true; - } - } - } - - final int split = head.lastIndexOf('/'); - - if (split <= 0) { - break; - } - - tail = head.substring(split + 1) + '/' + tail; - head = head.substring(0, split); - } - - return false; - } - - private boolean tryLoadBytes(final byte[] bytes, final Buffer buffer) { - - if (bytes == null || bytes.length == 0) { - return false; - } - - int length = bytes.length; - buffer.position(0); - buffer.reset(length); - new ByteArrayInputStream(bytes).read(buffer.array(), 0, length); - buffer.position(0); - - return true; - } - - private boolean tryLoadBytes(final String internalName, final byte[] bytes, final Buffer buffer, final boolean trustName) { - if (!tryLoadBytes(bytes, buffer)) { - return false; - } - - final String actualName = getInternalNameFromClassFile(buffer); - - final String name = trustName ? (internalName != null ? internalName : actualName) - : actualName; - - if (name == null) { - return false; - } - - final boolean nameMatches = StringUtilities.equals(actualName, internalName); - - final boolean result = internalName == null || nameMatches; - - if (result) { - final int packageEnd = name.lastIndexOf('/'); - final String packageName; - - if (packageEnd < 0 || packageEnd >= name.length()) { - packageName = StringUtilities.EMPTY; - } - else { - packageName = name.substring(0, packageEnd); - } - - registerKnownPath(packageName, bytes); - - knownBytes.put(actualName, bytes); - - } - else { - buffer.reset(0); - } - - return result; - } - - private void registerKnownPath(final String packageName, final byte[] directory) { - if (directory == null || directory.length == 0) { - return; - } - - LinkedHashSet directories = packageLocations.get(packageName); - - if (directories == null) { - packageLocations.put(packageName, directories = new LinkedHashSet<>()); - } - - if (!directories.add(directory)) { - return; - } - } - - private static String getInternalNameFromClassFile(final Buffer b) { - final long magic = b.readInt() & 0xFFFFFFFFL; - - if (magic != 0xCAFEBABEL) { - return null; - } - - b.readUnsignedShort(); // minor version - b.readUnsignedShort(); // major version - - final ConstantPool constantPool = ConstantPool.read(b); - - b.readUnsignedShort(); // access flags - - final ConstantPool.TypeInfoEntry thisClass = constantPool.getEntry(b.readUnsignedShort()); - - b.position(0); - - return thisClass.getName(); - } - - public String getName() { - return name; - } - - private boolean tryLoadTypeFromBytes(byte[] bytes, Buffer buffer) { - if (bytes == null || bytes.length == 0 || buffer == null) { - return false; - } - int length = bytes.length; - buffer.position(0); - buffer.reset(length); - new ByteArrayInputStream(bytes).read(buffer.array(), 0, length); - buffer.position(0); - return true; - } -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesDeserializable.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesDeserializable.java deleted file mode 100644 index dff8ade1..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesDeserializable.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.utils.io; - -public interface BytesDeserializable { - - /** - * 以字节数组形式获取字节块的副本; - * @param bytes butes - */ - void fromBytes(byte[] bytes); - -} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesEncoder.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesEncoder.java deleted file mode 100644 index d4e6613c..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesEncoder.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.jd.blockchain.utils.io; - -public interface BytesEncoder { - - byte[] encode(T data); - - T decode(byte[] bytes); -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesInputStream.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesInputStream.java deleted file mode 100644 index e492c9d8..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesInputStream.java +++ /dev/null @@ -1,240 +0,0 @@ -package com.jd.blockchain.utils.io; - -import java.io.IOException; -import java.io.InputStream; - -public class BytesInputStream extends InputStream { - - private byte[] bytes; - - private int posistion; - - private int tail; - - public BytesInputStream(byte[] bytes, int offset, int size) { - this.bytes = bytes; - this.posistion = offset; - this.tail = offset + size; - } - - protected int getPosition() { - return posistion; - } - - protected byte[] getOriginBytes() { - return bytes; - } - - /** - * 返回剩余的字节数; - * - * @return int - */ - public int getSize() { - return tail - posistion; - } - - /** - * 读取接下来的 1 个字节并返回; - * - * @return byte - */ - public byte readByte() { - int off = this.posistion; - checkBoundary(off, 1); - posistion++; - return bytes[off]; - } - - /** - * 读取接下来的 2 个字节并返回16位字符; - * - * @return char - */ - public char readChar() { - int off = posistion; - checkBoundary(off, 2); - char ch = BytesUtils.toChar(bytes, off); - posistion += 2; - return ch; - } - - /** - * 读取接下来的 2 个字节并返回16位整数; - * - * @return short - */ - public short readShort() { - int off = posistion; - checkBoundary(off, 2); - short n = BytesUtils.toShort(bytes, off); - posistion += 2; - return n; - } - - /** - * 读取接下来的 4 个字节并返回32位整数; - * - * @return int - */ - public int readInt() { - int off = posistion; - checkBoundary(off, 4); - int n = BytesUtils.toInt(bytes, off); - posistion += 4; - return n; - } - - /** - * 读取接下来的 8 个字节并返回64位整数; - * - * @return long - */ - public long readLong() { - int off = posistion; - checkBoundary(off, 8); - long n = BytesUtils.toLong(bytes, off); - posistion += 8; - return n; - } - - /** - * 读取指定数量的字节并返回对应的字符串; - * - * @param size size - * @return String - */ - public String readString(int size) { - int off = posistion; - checkBoundary(off, size); - String s = BytesUtils.toString(bytes, off, size); - posistion += size; - return s; - } - - /** - * 读取指定数量的字节并返回对应的字符串; - * @param size size - * @param charset charset - * @return String - */ - public String readString(int size, String charset) { - int off = posistion; - checkBoundary(off, size); - String s = BytesUtils.toString(bytes, off, size, charset); - posistion += size; - return s; - } - - /** - * 读取指定数量的字节并返回; - * - * @param size size - * @return 返回指定数量的字节拷贝; - */ - public byte[] readBytes(int size) { - byte[] copy = new byte[size]; - readBytes(copy, 0, size); - return copy; - } - - public int readBytes(byte[] buffer, int offset, int size) { - int off = posistion; - int s = tail - posistion; - s = s < size ? s : size; - checkBoundary(off, s); - System.arraycopy(bytes, off, buffer, offset, s); - posistion += s; - return s; - } - - /** - * 从当前位置开始读取, 返回剩余字节的片段;; - * 注:此操作不影响游标位置; - * @return BytesSlice - */ - public BytesSlice getSlice() { - if (tail == posistion) { - return BytesSlice.EMPTY; - } - return getSlice(tail - posistion); - } - - /** - * 从当前位置开始读取, 返回指定数量的字节片段; - * - *
- * 注:此操作不影响游标位置; - * - * @param size size - * @return byteSlice - */ - public BytesSlice getSlice(int size) { - int off = posistion; - checkBoundary(off, size); - BytesSlice copy = new BytesSlice(bytes, off, size); - return copy; - } - - /** - * 从当前位置开始读取, 返回指定数量的字节片段;
- * - * 注:此操作将数据游标位置向后移动指定数量的字节;; - * - * @param size size - * @return byteSlice - */ - public BytesSlice readSlice(int size) { - BytesSlice copy = getSlice(size); - posistion += size; - return copy; - } - - public void skip(int size) { - checkBoundary(posistion, size); - posistion += size; - } - - private void checkBoundary(int off, int len) { - // assert off >= posistion && off + len <= tail : "The accessing index is out of - // BytesInputStream's bounds!"; - if (off < posistion || off + len > tail) { - throw new IndexOutOfBoundsException("The accessing index is out of BytesInputStream's bounds!"); - } - } - - /** - * 注:遵循 JDK 接口要求,读取一个字节以 int 类型返回; - */ - @Override - public int read() throws IOException { - return readByte() & 0xFF; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - return readBytes(b, off, len); - } - - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - - @Override - public int available() throws IOException { - return getSize(); - } - - @Override - public long skip(long n) throws IOException { - if (n < 0) { - throw new IllegalArgumentException("Specified a negative number of bytes to be skipped!"); - } - if (n >= Integer.MAX_VALUE) { - throw new IllegalArgumentException("The number of bytes to be skipped is out of max value!"); - } - skip((int) n); - return n; - } -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesMap.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesMap.java deleted file mode 100644 index 21bf2afc..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesMap.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jd.blockchain.utils.io; - -import java.util.Set; - -public interface BytesMap { - - Set keySet(); - - byte[] getValue(T key); -} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesOutputBuffer.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesOutputBuffer.java deleted file mode 100644 index 6a9065ab..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesOutputBuffer.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.jd.blockchain.utils.io; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * 字节输出缓冲区;
- * - * 提供一种避免字节数组在内存复制的缓冲写入的实现;
- * - * BytesOutputBuffer 是线程安全的; - * - * @author huanghaiquan - * - */ -public class BytesOutputBuffer { - - private static final int DEFAULT_CAPACITY = 8; - - private volatile int size = 0; - - private int capacity = 0; - - private int cursor = 0; - - private byte[][] buffers; - - public int getSize() { - return size; - } - - public BytesOutputBuffer() { - this(DEFAULT_CAPACITY); - } - - public BytesOutputBuffer(int initCapacity) { - if (initCapacity < 0) { - throw new IllegalArgumentException("Init capacity is negative!"); - } - this.capacity = initCapacity; - buffers = new byte[initCapacity][]; - } - - /** - * 直接写入;
- * - * 此方法直接引用参数指定的数组作为缓冲区的组成部分,调用者需要避免在执行之后对参数引用的字节数组再做任何更改;
- * - * 设计此方法的目的是提供一种通过避免字节数组复制操作来提升写入性能的方法; - * - * @param data data - */ - public synchronized void write(byte[] data) { - if (data == null) { - throw new IllegalArgumentException("data is null!"); - } - int idx = cursor; - if (idx == capacity) { - growCapacity(); - } - buffers[idx] = data; - cursor++; - size += data.length; - } - - private void growCapacity() { - int newCapacity = capacity + capacity / 2; - if (newCapacity == capacity) { - newCapacity++; - } - byte[][] newBuffers = new byte[newCapacity][]; - System.arraycopy(buffers, 0, newBuffers, 0, capacity); - buffers = newBuffers; - capacity = newCapacity; - } - - /** - * @param buffer buffer - */ - public void write(BytesOutputBuffer buffer) { - byte[][] fromBuffers = buffer.buffers; - for (int i = 0; i < buffer.cursor; i++) { - write(fromBuffers[i]); - } - } - - /** - * 复制写入;
- * - * 此方法复制参数指定的数组的一个副本作为写入缓冲区的组成部分; - * - * @param data data - */ - public void writeCopy(byte[] data) { - int len = data.length; - byte[] copy = new byte[len]; - System.arraycopy(data, 0, copy, 0, len); - write(copy); - } - - /** - * * 复制写入;
- * - * 此方法复制参数指定的数组的一个副本作为写入缓冲区的组成部分; - * @param data data - * @param offset offset - * @param len len - */ - public void writeCopy(byte[] data, int offset, int len) { - byte[] copy = new byte[len]; - System.arraycopy(data, offset, copy, 0, len); - write(copy); - } - - /** - * 把结果输出到指定的缓冲区,并返回写入的长度; - *

- * 如果指定的缓冲区的空间足够,则将写入全部数据,返回值等于 {@link #getSize()} ;
- * 如果指定的缓冲区的空间足够,则写满为止,返回实际写入的数据大小;
- * - * 调用者可以把返回值与 {@link #getSize()} 比较,以判断是否完成写入; - * - * @param outBuffer outBuffer - * @param offset offset - * @return int - */ - public synchronized int writeTo(byte[] outBuffer, int offset) { - int len = Math.min(size, outBuffer.length - offset); - int t = len; - int s; - for (int i = 0; i < cursor & t > 0; i++) { - s = Math.min(buffers[i].length, t); - System.arraycopy(buffers[i], 0, outBuffer, offset, s); - offset += s; - t -= s; - } - return len; - } - - public synchronized int writeTo(OutputStream out) { - try { - for (int i = 0; i < cursor; i++) { - out.write(buffers[i]); - } - return size; - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - /** - * 返回所有内容的副本; - * - * @return byte array; - */ - public byte[] toBytes() { - byte[] data =new byte[size]; - writeTo(data, 0); - return data; - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSerializable.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSerializable.java deleted file mode 100644 index 8b2f656e..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSerializable.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jd.blockchain.utils.io; - -public interface BytesSerializable { - - /** - * 以字节数组形式获取字节块的副本; - * @return byte[] - */ - byte[] toBytes(); - -} \ No newline at end of file diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSlice.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSlice.java deleted file mode 100644 index 24ef4191..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSlice.java +++ /dev/null @@ -1,193 +0,0 @@ -package com.jd.blockchain.utils.io; - -/** - * @author huanghaiquan - * - */ -public class BytesSlice implements BytesSerializable { - - public static final BytesSlice EMPTY = new BytesSlice(new byte[0], 0, 0); - - private byte[] bytes; - - private int dataOffset; - - private int size; - - public BytesSlice() { - } - - public BytesSlice(byte[] bytes) { - this(bytes, 0, bytes.length); - } - - public BytesSlice(byte[] bytes, int offset) { - this(bytes, offset, bytes.length - offset); - } - - public BytesSlice(byte[] bytes, int offset, int size) { - if (offset + size > bytes.length) { - throw new IndexOutOfBoundsException(); - } - this.bytes = bytes; - this.dataOffset = offset; - this.size = size; - } - - public boolean isEmpty() { - return size == 0; - } - - public int getSize() { - return size; - } - - /** - * 返回首个字节; - * - * @return byte - */ - public byte getByte() { - return getByte(0); - } - - /** - * 返回首个字节; - * @param offset offset - * @return byte - */ - public byte getByte(int offset) { - int off = this.dataOffset + offset; - checkBoundary(off, 1); - return bytes[off]; - } - - public char getChar() { - return getChar(0); - } - - public char getChar(int offset) { - int off = this.dataOffset + offset; - checkBoundary(off, 2); - return BytesUtils.toChar(bytes, off); - } - - public short getShort() { - return getShort(0); - } - - public short getShort(int offset) { - int off = this.dataOffset + offset; - checkBoundary(off, 2); - return BytesUtils.toShort(bytes, off); - } - - public int getInt() { - return getInt(0); - } - - /** - * 从指定的偏移量开始,读取连续 4 个字节,转换为 int 类型的数值返回; - * - * @param offset offset - * @return int - */ - public int getInt(int offset) { - int off = this.dataOffset + offset; - checkBoundary(off, 4); - return BytesUtils.toInt(bytes, off); - } - - public long getLong() { - return getLong(0); - } - - /** - * 从指定的偏移量开始,读取连续 8 个字节,转换为 long 类型的数值返回; - * - * @param offset offset - * @return long - */ - public long getLong(int offset) { - int off = this.dataOffset + offset; - checkBoundary(off, 8); - return BytesUtils.toLong(bytes, off); - } - - public String getString() { - return BytesUtils.toString(bytes, dataOffset, size); - } - - public BytesInputStream getInputStream() { - return getInputStream(0); - } - - public BytesInputStream getInputStream(int offset) { - int off = this.dataOffset + offset; - int s = size; - checkBoundary(off, s); - return new BytesInputStream(bytes, off, s); - } - - // public InputStream asInputStream() { - // return new ByteArrayInputStream(bytes, dataOffset, size); - // } - - public byte[] getBytesCopy() { - if (size == 0) { - return BytesUtils.EMPTY_BYTES; - } - byte[] copy = new byte[size]; - System.arraycopy(bytes, dataOffset, copy, 0, size); - return copy; - } - - public byte[] getBytesCopy(int offset) { - return getBytesCopy(offset, getSize() - offset) ; - } - - public byte[] getBytesCopy(int offset, int size) { - int newOffset = dataOffset + offset; - checkBoundary(newOffset, size); - - if (size == 0) { - return BytesUtils.EMPTY_BYTES; - } - byte[] copy = new byte[size]; - System.arraycopy(bytes, newOffset, copy, 0, size); - return copy; - } - - protected byte[] getOriginBytes() { - return bytes; - } - - protected int getOriginOffset() { - return dataOffset; - } - - protected void checkBoundary(int offset, int len) { - // assert offset >= dataOffset - // && offset + len <= dataOffset + this.size : "The accessing index is out of - // BytesSlice's bounds!"; - if (offset < dataOffset || offset + len > dataOffset + this.size) { - throw new IndexOutOfBoundsException("The accessing index is out of BytesSlice's bounds!"); - } - } - - public BytesSlice getSlice(int offset) { - return getSlice(offset, getSize() - offset); - } - - public BytesSlice getSlice(int offset, int size) { - int newOffset = dataOffset + offset; - checkBoundary(newOffset, size); - return new BytesSlice(bytes, newOffset, size); - } - - @Override - public byte[] toBytes() { - return getBytesCopy(); - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSliceArrayWrapper.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSliceArrayWrapper.java deleted file mode 100644 index 0774c6d2..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSliceArrayWrapper.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jd.blockchain.utils.io; - -public class BytesSliceArrayWrapper implements BytesSlices { - - private BytesSlice slice; - - /** - * @param dataBytes - * 数据; - * @param offset - * 初始的偏移量; - * @param dataOffset - * 数据的起始偏移量; - * @param count - * 数据片段的总数; - * @param size - * 单个数据片段的大小; - */ - private BytesSliceArrayWrapper(BytesSlice slice) { - this.slice = slice; - } - - @Override - public int getTotalSize() { - return slice.getSize(); - } - - @Override - public int getCount() { - return 1; - } - - @Override - public BytesSlice getDataSlice(int id) { - if (id != 0) { - throw new IndexOutOfBoundsException("The specified idx is out of bound!"); - } - return slice; - } - - public static BytesSlices wrap(BytesSlice slice) { - if (slice instanceof BytesSlices) { - return (BytesSlices)slice; - } - return new BytesSliceArrayWrapper(slice); - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSlices.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSlices.java deleted file mode 100644 index 2ac975ec..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesSlices.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jd.blockchain.utils.io; - -public interface BytesSlices { - - /** - * 总的字节数;包含各个子数据片段之间间隔的头部字节; - * @return int - */ - int getTotalSize(); - - /** - * 包含的子片段的数量; - * - * @return int - */ - int getCount(); - - /** - * 返回一个子数据片段; - * @param idx 子数据片段的编号;大于等于 0 ,小于总数 {@link #getCount()}; - * @return bytesSlice - */ - BytesSlice getDataSlice(int idx); - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/DynamicBytesSliceArray.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/DynamicBytesSliceArray.java deleted file mode 100644 index a1580616..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/DynamicBytesSliceArray.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.jd.blockchain.utils.io; - -public class DynamicBytesSliceArray implements BytesSlices { - - private byte[] dataBytes; - - private int totalSize; - - private int[] offsets; - - private int[] sizes; - - private DynamicBytesSliceArray(byte[] dataBytes, int totalSize, int[] offsets, int[] sizes) { - this.dataBytes = dataBytes; - this.totalSize = totalSize; - this.offsets = offsets; - this.sizes = sizes; - } - - @Override - public int getTotalSize() { - return totalSize; - } - - @Override - public int getCount() { - return sizes.length; - } - - @Override - public BytesSlice getDataSlice(int idx) { - return new BytesSlice(dataBytes, offsets[idx], sizes[idx]); - } - -// public static DynamicBytesSliceArray resolve(byte[] dataBytes, int offset) { -// return resolve(new BytesSlice(dataBytes, 0, dataBytes.length), 0); -// } - - public static DynamicBytesSliceArray resolve(BytesInputStream bytesStream) { - int p1 = bytesStream.getPosition(); - int count = NumberMask.NORMAL.resolveMaskedNumber(bytesStream); - - int[] offsets = new int[count]; - int[] sizes = new int[count]; - - int size; - for (int i = 0; i < count; i++) { - size = NumberMask.NORMAL.resolveMaskedNumber(bytesStream); - sizes[i] = size; - offsets[i] = bytesStream.getPosition(); - bytesStream.skip(size); - } - int totalSize = bytesStream.getPosition() - p1; - return new DynamicBytesSliceArray(bytesStream.getOriginBytes(), totalSize, offsets, sizes); - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/FileUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/FileUtils.java deleted file mode 100644 index 17ed444f..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/FileUtils.java +++ /dev/null @@ -1,508 +0,0 @@ -package com.jd.blockchain.utils.io; - -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Properties; - -import com.jd.blockchain.utils.PathUtils; -import org.springframework.util.ResourceUtils; - -/** - * @author haiq - * - */ -public class FileUtils { - - public static final String DEFAULT_CHARSET = "UTF-8"; - - public static boolean existFile(String filePath) { - File file = new File(filePath); - return file.isFile(); - } - - public static boolean existDirectory(String dir) { - File file = new File(dir); - return file.isDirectory(); - } - - public static boolean makeDirectory(String dir) { - File file = new File(dir); - return file.mkdirs(); - } - - /** - * 返回完整的绝对路径; - * - * @param path path - * @return String - */ - public static String getFullPath(String path) { - try { - File file = new File(path); - return file.getCanonicalPath(); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - /** - * 返回父目录的路径; - * - * @param path path - * @return String - */ - public static String getParent(String path) { - File file = new File(path); - return file.getParent(); - } - - /** - * 以默认字符集(UTF-8)读取指定文件的首行; - * - * @param file file - * @return String - * @throws IOException exception - */ - public static String readFirstLine(File file) throws IOException { - return readFirstLine(file, DEFAULT_CHARSET); - } - - /** - * 读取指定文件的首行; - * - * @param file file - * @param charset 字符集; - * @return 返回首行非空行;返回结果不会自动截取两头的空字符串; - * @throws IOException exception - */ - public static String readFirstLine(File file, String charset) throws IOException { - FileInputStream in = new FileInputStream(file); - try { - InputStreamReader reader = new InputStreamReader(in, charset); - return getFirstLine(reader); - } finally { - in.close(); - } - } - - public static String[] readLines(File file) { - return readLines(file, DEFAULT_CHARSET); - } - - /** - * 返回指定文件的所有行; - * - * @param file file - * @param charset 字符集; - * @return 返回首行非空行;返回结果不会自动截取两头的空字符串; - */ - public static String[] readLines(File file, String charset) { - try (FileInputStream in = new FileInputStream(file); - InputStreamReader reader = new InputStreamReader(in, charset);) { - return getLines(reader); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static void writeLines(String[] lines, File file) { - writeLines(lines, file, DEFAULT_CHARSET); - } - - public static void writeLines(String[] lines, File file, String charset) { - try (FileOutputStream out = new FileOutputStream(file, false); - OutputStreamWriter writer = new OutputStreamWriter(out, charset); - BufferedWriter bfw = new BufferedWriter(writer);) { - for (String line : lines) { - writer.write(line); - writer.write("\r\n"); - } - - bfw.flush(); - writer.flush(); - out.flush(); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static String getFirstLine(Reader reader) throws IOException { - BufferedReader bfr = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - try { - String line = null; - while ((line = bfr.readLine()) != null) { - return line; - } - return null; - } finally { - bfr.close(); - } - } - - public static String[] getLines(Reader reader) throws IOException { - BufferedReader bfr = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - try { - ArrayList lines = new ArrayList(); - String line = null; - while ((line = bfr.readLine()) != null) { - lines.add(line); - } - return lines.toArray(new String[lines.size()]); - } finally { - bfr.close(); - } - } - - /** - * 以默认字符集(UTF-8)将指定的文本保存到指定的文件中; - * - * @param file 要保存的文件; - * @param text 文本内容; - */ - public static void writeText(String text, File file) { - writeText(text, file, DEFAULT_CHARSET); - } - - /** - * 将指定的文本保存到指定的文件中; - * - * @param text 文本内容; - * @param file 要保存的文件; - * @param charset 字符集; - */ - public static void writeText(String text, File file, String charset) { - try (FileOutputStream out = new FileOutputStream(file, false)) { - writeText(text, out, charset); - out.flush(); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static void writeBytes(byte[] content, File file) { - try (FileOutputStream out = new FileOutputStream(file, false)) { - out.write(content); - out.flush(); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static void appendBytes(byte[] content, File file) { - try (FileOutputStream out = new FileOutputStream(file, true)) { - out.write(content); - out.flush(); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static void writeText(String text, OutputStream out, String charset) { - try (OutputStreamWriter writer = new OutputStreamWriter(out, charset);) { - writer.write(text); - writer.flush(); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static void writeProperties(Properties props, OutputStream out) { - writeProperties(props, out, DEFAULT_CHARSET); - } - - public static void writeProperties(Properties props, OutputStream out, String charset) { - try (OutputStreamWriter writer = new OutputStreamWriter(out, charset);) { - props.store(writer, null); - writer.flush(); - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - /** - * 以默认字符集(UTF-8)从文件读取文本; - * - * @param file file - * @return String - */ - public static String readText(String filePath) { - try { - File file = ResourceUtils.getFile(filePath); - return readText(file, DEFAULT_CHARSET); - } catch (FileNotFoundException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - /** - * 从文件读取文本; - * - * @param file file - * @param charset charset - * @return String - */ - public static String readText(String file, String charset) { - return readText(new File(file), charset); - } - - /** - * 以默认字符集(UTF-8)从文件读取文本; - * - * @param file file - * @return String - */ - public static String readText(File file) { - return readText(file, DEFAULT_CHARSET); - } - - /** - * 从文件读取文本; - * - * @param file file - * @param charset charset - * @return String - */ - public static String readText(File file, String charset) { - try { - FileInputStream in = new FileInputStream(file); - try { - return readText(in, charset); - } finally { - in.close(); - } - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static String readText(InputStream in) throws IOException { - return readText(in, DEFAULT_CHARSET); - } - - /** - * 从流读取文本; - * - * @param in in - * @param charset charset - * @return String - * @throws IOException exception - */ - public static String readText(InputStream in, String charset) throws IOException { - InputStreamReader reader = new InputStreamReader(in, charset); - try { - StringBuilder content = new StringBuilder(); - char[] buffer = new char[64]; - int len = 0; - while ((len = reader.read(buffer)) > 0) { - content.append(buffer, 0, len); - } - return content.toString(); - } finally { - reader.close(); - } - } - - public static byte[] readBytes(String file) { - try { - FileInputStream in = new FileInputStream(file); - try { - return BytesUtils.copyToBytes(in); - } finally { - in.close(); - } - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static byte[] readBytes(File file) { - try { - FileInputStream in = new FileInputStream(file); - try { - return BytesUtils.copyToBytes(in); - } finally { - in.close(); - } - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static Properties readProperties(String file) { - return readProperties(file, DEFAULT_CHARSET); - } - - public static Properties readProperties(File file) { - return readProperties(file, DEFAULT_CHARSET); - } - - public static Properties readProperties(String file, String charset) { - try { - FileInputStream in = new FileInputStream(file); - try { - return readProperties(in, charset); - } finally { - in.close(); - } - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static Properties readProperties(File file, String charset) { - try { - FileInputStream in = new FileInputStream(file); - try { - return readProperties(in, charset); - } finally { - in.close(); - } - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - public static Properties readProperties(InputStream in) { - return readProperties(in, DEFAULT_CHARSET); - } - - public static Properties readProperties(InputStream in, String charset) { - try { - InputStreamReader reader = new InputStreamReader(in, charset); - try { - Properties props = new Properties(); - props.load(reader); - return props; - } finally { - reader.close(); - } - } catch (IOException e) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - /** - * 根据byte数组,生成文件 filePath 文件路径 fileName 文件名称(需要带后缀,如*.jar) - */ - public static File getFile(byte[] bfile, String filePath, String fileName) { - BufferedOutputStream bos = null; - FileOutputStream fos = null; - File file = null; - try { - File dir = new File(filePath); - if (!dir.exists()) {// 判断文件目录是否存在 - dir.mkdirs(); - } - file = new File(filePath + File.separator + fileName); - fos = new FileOutputStream(file); - bos = new BufferedOutputStream(fos); - bos.write(bfile); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (bos != null) { - try { - bos.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - } - if (fos != null) { - try { - fos.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - } - } - return file; - } - - public static String getCurrentDir() { - try { - return new File("./").getCanonicalPath(); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static void deleteFile(String dir) { - deleteFile(dir, false); - } - - public static void deleteFile(File file) { - deletePath(file, false); - } - - public static void deleteFile(String dir, boolean silent) { - File directory = new File(dir); - deletePath(directory, silent); - } - - /** - * 删除文件;
- * - * @param path 如果指定的路径是单个文件,则删除该文件;如果指定路径是目录,则删除该目录及其下的全部文件; - * @param silent 是否静默删除;如果为 true ,则吞噬删除过程中的异常, 意味着方法即便正常返回时也有可能删除不完全; - * @return 如果删除成功,则返回 true; 否则返回 false,或者抛出 {@link RuntimeIOException}; - */ - public static boolean deletePath(File path, boolean silent) { - if (path.isFile()) { - try { - path.delete(); - return true; - } catch (Exception e) { - if (!silent) { - throw new RuntimeIOException(e.getMessage(), e); - } - } - - return false; - } - - // delete dir; - File[] files = path.listFiles(); - if (files == null) { - return false; - } - - for (File f : files) { - deletePath(f, silent); - } - return path.delete(); - } - - /** - * 获取指定路径和位置的文件信息 - * - * @param dir - * 指定路径,不要以"/"结尾 - * @param resourceLocation - * 文件位置信息,可支持绝对路径、相对路径(相对dir)、classpath:前缀 - * @return - * - * @throws FileNotFoundException - */ - public static File getFile(String dir, String resourceLocation) throws FileNotFoundException { - if (resourceLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { - return ResourceUtils.getFile(resourceLocation); - } - if (resourceLocation.startsWith(PathUtils.PATH_SEPERATOR)) { - return new File(resourceLocation); - } - String totalPath = PathUtils.concatPaths(dir, resourceLocation); - return new File(totalPath); - } -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/FixedBytesSliceArray.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/FixedBytesSliceArray.java deleted file mode 100644 index 68983284..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/FixedBytesSliceArray.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jd.blockchain.utils.io; - -public class FixedBytesSliceArray implements BytesSlices { - - private byte[] dataBytes; - - private int totalSize; - - private int dataOffset; - - private int itemCount; - - private int itemSize; - - /** - * @param dataBytes - * 数据; - * @param totalSize - * 初始的偏移量; - * @param dataOffset - * 数据的起始偏移量; - * @param itemCount - * 数据片段的总数; - * @param itemSize - * 单个数据片段的大小; - */ - private FixedBytesSliceArray(byte[] dataBytes, int totalSize, int dataOffset, int itemCount, int itemSize) { - if ((dataOffset + itemCount * itemSize) > dataBytes.length) { - throw new IllegalArgumentException("The tail index of all slices is out of bound of data bytes!"); - } - this.dataBytes = dataBytes; - // this.length = (dataOffset + count * size) - totalSize; - this.totalSize = totalSize; - this.dataOffset = dataOffset; - this.itemCount = itemCount; - this.itemSize = itemSize; - } - - @Override - public int getTotalSize() { - return totalSize; - } - - @Override - public int getCount() { - return itemCount; - } - - @Override - public BytesSlice getDataSlice(int idx) { - if (idx < 0 || idx >= itemCount) { - throw new IllegalArgumentException("The specified idx is out of bound!"); - } - return new BytesSlice(dataBytes, dataOffset + idx * itemSize, itemSize); - } - - public static FixedBytesSliceArray resolve(BytesInputStream bytesStream, int itemSize) { - int p1 = bytesStream.getPosition(); - - int itemCount = NumberMask.NORMAL.resolveMaskedNumber(bytesStream); - - int dataOffset = bytesStream.getPosition(); - - bytesStream.skip(itemCount * itemSize); - int totalSize = bytesStream.getPosition() - p1; - - return new FixedBytesSliceArray(bytesStream.getOriginBytes(), totalSize, dataOffset, itemCount, itemSize); - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/SingleBytesSliceArray.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/SingleBytesSliceArray.java deleted file mode 100644 index 152fdbd7..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/SingleBytesSliceArray.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jd.blockchain.utils.io; - -public class SingleBytesSliceArray extends BytesSlice implements BytesSlices { - - private int totalSize; - - /** - * @param dataBytes - * 数据; - * @param offset - * 初始的偏移量; - * @param dataOffset - * 数据的起始偏移量; - * @param count - * 数据片段的总数; - * @param size - * 单个数据片段的大小; - */ - /** - * @param dataBytes - * @param offset - * @param dataOffset - * @param dataSize - */ - private SingleBytesSliceArray(byte[] dataBytes, int totalSize, int dataOffset, int dataSize) { - super(dataBytes, dataOffset, dataSize); - this.totalSize = totalSize; - } - - @Override - public int getTotalSize() { - return totalSize; - } - - @Override - public int getCount() { - return 1; - } - - @Override - public BytesSlice getDataSlice(int idx) { - if (idx != 0) { - throw new IllegalArgumentException("The specified idx is out of bound!"); - } - return this; - } - - public static SingleBytesSliceArray resolveDynamic(BytesInputStream bytesStream) { - int p1 = bytesStream.getPosition(); - int size = NumberMask.NORMAL.resolveMaskedNumber(bytesStream); - int dataOffset = bytesStream.getPosition(); - bytesStream.skip(size); - int totalSize = bytesStream.getPosition() - p1; - return new SingleBytesSliceArray(bytesStream.getOriginBytes(), totalSize, dataOffset, size); - } - - public static SingleBytesSliceArray create(BytesInputStream bytesStream, int itemSize) { - int offset = bytesStream.getPosition(); - bytesStream.skip(itemSize); - return new SingleBytesSliceArray(bytesStream.getOriginBytes(), itemSize, offset, itemSize); - } - - public static SingleBytesSliceArray create(byte[] dataBytes, int offset, int size) { - return new SingleBytesSliceArray(dataBytes, size, offset, size); - } - -} diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/security/SHA256Hash.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/security/SHA256Hash.java deleted file mode 100644 index 6faa2a86..00000000 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/security/SHA256Hash.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.utils.security; - -public interface SHA256Hash { - - /** - * 追加要一起计算哈希的数据; - * - * @param bytes - */ - void update(byte[] bytes); - - /** - * 追加要一起计算哈希的数据; - * - * @param bytes - */ - void update(byte[] bytes, int offset, int len); - - /** - * 完成哈希计算并返回结果; - * - * @return - */ - byte[] complete(); - -} diff --git a/source/utils/utils-common/src/main/resources/complex.jar b/source/utils/utils-common/src/main/resources/complex.jar deleted file mode 100644 index 6f40ca02..00000000 Binary files a/source/utils/utils-common/src/main/resources/complex.jar and /dev/null differ diff --git a/source/utils/utils-common/src/test/java/test/my/utils/ArgumentSetTest.java b/source/utils/utils-common/src/test/java/test/my/utils/ArgumentSetTest.java deleted file mode 100644 index 95a10767..00000000 --- a/source/utils/utils-common/src/test/java/test/my/utils/ArgumentSetTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package test.my.utils; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.jd.blockchain.utils.ArgumentSet; - -public class ArgumentSetTest { - - @Test - public void test() { - String[] args = { "-n", "my", "-o", "./keys" }; - ArgumentSet argSet = ArgumentSet.resolve(args, ArgumentSet.setting().prefix("-n", "-o")); - - assertNotNull(argSet.getArg("-n")); - assertEquals("my",argSet.getArg("-n").getValue()); - assertNotNull(argSet.getArg("-o")); - assertEquals("./keys",argSet.getArg("-o").getValue()); - - } - -} diff --git a/source/utils/utils-common/src/test/java/test/my/utils/PropertiesUtilsTest.java b/source/utils/utils-common/src/test/java/test/my/utils/PropertiesUtilsTest.java deleted file mode 100644 index 881bca26..00000000 --- a/source/utils/utils-common/src/test/java/test/my/utils/PropertiesUtilsTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package test.my.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.Properties; - -import org.junit.Test; - -import com.jd.blockchain.utils.PropertiesUtils; - -public class PropertiesUtilsTest { - - public static class TestData { - - private String name; - - private int id; - - private boolean enable; - - private long life; - - private HomeAddress homeAddress; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - public long getLife() { - return life; - } - - public void setLife(long life) { - this.life = life; - } - - public HomeAddress getHomeAddress() { - return homeAddress; - } - - public void setHomeAddress(HomeAddress homeAddress) { - this.homeAddress = homeAddress; - } - - } - - public static class HomeAddress { - - private int number; - - private String street; - - public int getNumber() { - return number; - } - - public void setNumber(int number) { - this.number = number; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - } - - @Test - public void test() { - Properties props = new Properties(); - props.setProperty("name", "john"); - props.setProperty("id", "10"); - props.setProperty("enable", "true"); - props.setProperty("life", "120088835993666666"); - props.setProperty("remark", "dfdafew"); - props.setProperty("homeAddress.number", "18"); - props.setProperty("homeAddress.street", "newyork"); - - TestData data = PropertiesUtils.createInstance(TestData.class, props); - assertNotNull(data); - assertEquals("john", data.getName()); - assertEquals(10, data.getId()); - assertEquals(true, data.isEnable()); - assertEquals(120088835993666666L, data.getLife()); - assertNotNull(data.getHomeAddress()); - assertEquals(18, data.getHomeAddress().getNumber()); - assertEquals("newyork", data.getHomeAddress().getStreet()); - - Properties props1 = new Properties(); - props1.setProperty("abc.name", "john"); - props1.setProperty("abc.id", "10"); - props1.setProperty("abc.enable", "true"); - props1.setProperty("abc.life", "120088835993666666"); - props1.setProperty("remark", "dfdafew"); - props1.setProperty("abc.homeAddress.number", "18"); - - TestData data1 = PropertiesUtils.createInstance(TestData.class, props1, "abc."); - assertNotNull(data1); - assertEquals("john", data1.getName()); - assertEquals(10, data1.getId()); - assertEquals(true, data1.isEnable()); - assertEquals(120088835993666666L, data1.getLife()); - assertNotNull(data1.getHomeAddress()); - assertEquals(18, data1.getHomeAddress().getNumber()); - assertNull(data1.getHomeAddress().getStreet()); - } - -} diff --git a/source/utils/utils-common/src/test/java/test/my/utils/concurrent/FutureTest.java b/source/utils/utils-common/src/test/java/test/my/utils/concurrent/FutureTest.java deleted file mode 100644 index d60c43b9..00000000 --- a/source/utils/utils-common/src/test/java/test/my/utils/concurrent/FutureTest.java +++ /dev/null @@ -1,10 +0,0 @@ -package test.my.utils.concurrent; - -public class FutureTest { - - public static void main(String[] args) { - // TODO Auto-generated method stub - - } - -} diff --git a/source/utils/utils-common/src/test/java/test/my/utils/io/BytesTest.java b/source/utils/utils-common/src/test/java/test/my/utils/io/BytesTest.java deleted file mode 100644 index b408c0f4..00000000 --- a/source/utils/utils-common/src/test/java/test/my/utils/io/BytesTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package test.my.utils.io; - -import static org.junit.Assert.*; - -import java.util.Arrays; - -import org.junit.Test; - -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; - -public class BytesTest { - - @Test - public void test() { - Bytes prefix = Bytes.fromString("A"); - byte[] textBytes = BytesUtils.toBytes("B"); - Bytes key1 = new Bytes(prefix, textBytes); - byte[] key1Bytes = key1.toBytes(); - assertEquals(prefix.size() + textBytes.length, key1.size()); - assertEquals(prefix.size() + textBytes.length, key1Bytes.length); - assertEquals(Arrays.hashCode(key1Bytes), key1.hashCode()); - } - -} diff --git a/source/utils/utils-common/src/test/resources/complex.jar b/source/utils/utils-common/src/test/resources/complex.jar deleted file mode 100644 index 6f40ca02..00000000 Binary files a/source/utils/utils-common/src/test/resources/complex.jar and /dev/null differ diff --git a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/NamedParam.java b/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/NamedParam.java deleted file mode 100644 index eec11802..00000000 --- a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/NamedParam.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jd.blockchain.utils.http; - -public class NamedParam { - private String name; - - private String value; - - public NamedParam(String name, String value) { - this.name = name; - this.value = value; - } - - public String getName() { - return name; - } - - public String getValue() { - return value; - } -} diff --git a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/NamedParamMap.java b/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/NamedParamMap.java deleted file mode 100644 index 49308a0c..00000000 --- a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/NamedParamMap.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jd.blockchain.utils.http; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -public class NamedParamMap { - - private Map> params = new LinkedHashMap<>(); - - public NamedParam[] getParams() { - List allParams = new ArrayList<>(); - for (List namedParams : params.values()) { - allParams.addAll(namedParams); - } - return allParams.toArray(new NamedParam[allParams.size()]); - } - - public NamedParam addParam(String name, String value) { - List values = params.get(name); - if (values == null) { - values = new ArrayList<>(); - params.put(name, values); - } - NamedParam p = new NamedParam(name, value); - values.add(p); - return p; - } - - public boolean isEmpty() { - return params.isEmpty(); - } - - /** - * 合并; - * @param extParams - * @param prefix 附加的新参数的前缀; - */ - public void merge(NamedParamMap extParams) { - merge(extParams, null); - } - - /** - * 合并; - * @param extParams - * @param prefix 附加的新参数的前缀; - */ - public void merge(NamedParamMap extParams, String prefix) { - if (prefix == null || prefix.length() == 0) { - NamedParam[] paramArr = extParams.getParams(); - for (NamedParam np : paramArr) { - addParam(np.getName(), np.getValue()); - } - } else { - NamedParam[] paramArr = extParams.getParams(); - for (NamedParam np : paramArr) { - addParam(prefix + np.getName(), np.getValue()); - } - } - } -} diff --git a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/agent/HttpClientPool.java b/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/agent/HttpClientPool.java deleted file mode 100644 index 54f9842e..00000000 --- a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/agent/HttpClientPool.java +++ /dev/null @@ -1,287 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.utils.http.agent.HttpClientPool - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2019/1/14 下午3:20 - * Description: - */ -package com.jd.blockchain.utils.http.agent; - -import org.apache.http.*; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.LayeredConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.io.UnsupportedEncodingException; -import java.net.UnknownHostException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * - * @author shaozhuguang - * @create 2019/1/14 - * @since 1.0.0 - */ - -public class HttpClientPool { - - private static final int TIME_OUT = 10 * 1000; - - private static final int CONNECT_TIME_OUT = 10 * 1000; - - private static final int SOCKET_TIME_OUT = 10 * 1000; - - private static final int MAX_TOTAL = 200; - - private static final int MAX_PER_ROUTE = 40; - - private static final int MAX_ROUTE = 100; - - private static final int RETRY_COUNT = 5; - - private static final String DEFAULT_CHARSET = "UTF-8"; - - private static final Map httpClients = new ConcurrentHashMap<>(); - - private final static Lock lock = new ReentrantLock(); - - private static void config(HttpRequestBase httpRequestBase) { - // 配置请求的超时设置 - RequestConfig requestConfig = RequestConfig.custom() - .setConnectionRequestTimeout(TIME_OUT) - .setConnectTimeout(CONNECT_TIME_OUT) - .setSocketTimeout(SOCKET_TIME_OUT) - .build(); - httpRequestBase.setConfig(requestConfig); - } - - /** - * 获取HttpClient对象 - * - * @param url - * @return - */ - public static CloseableHttpClient getHttpClient(String url) { - String hostName = url.split("/")[2]; - int port = 80; - if (hostName.contains(":")) { - String[] arr = hostName.split(":"); - hostName = arr[0]; - port = Integer.parseInt(arr[1]); - } - return getHttpClient(hostName, port); - } - - /** - * 获取HttpClient对象 - * - * @param hostName - * @param port - * @return - */ - public static CloseableHttpClient getHttpClient(String hostName, int port) { - String key = hostName + ":" + port; - CloseableHttpClient httpClient = httpClients.get(key); - if (httpClient == null) { - try { - lock.lock(); - if (httpClient == null) { - httpClient = createHttpClient(MAX_TOTAL, MAX_PER_ROUTE, MAX_ROUTE, hostName, port); - httpClients.put(key, httpClient); - } - } finally { - lock.unlock(); - } - } - return httpClient; - } - - /** - * 创建HttpClient - * - * @param maxTotal - * @param maxPerRoute - * @param maxRoute - * @param hostname - * @param port - * @return - */ - public static CloseableHttpClient createHttpClient(int maxTotal, - int maxPerRoute, int maxRoute, String hostname, int port) { - ConnectionSocketFactory plainsf = PlainConnectionSocketFactory - .getSocketFactory(); - LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory - .getSocketFactory(); - Registry registry = RegistryBuilder - . create().register("http", plainsf) - .register("https", sslsf).build(); - PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( - registry); - cm.setMaxTotal(maxTotal); - cm.setDefaultMaxPerRoute(maxPerRoute); - HttpHost httpHost = new HttpHost(hostname, port); - cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); - HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> { - if (executionCount >= RETRY_COUNT) {// 最多重试5次 - return false; - }else if (exception instanceof NoHttpResponseException) { - return true; - }else if (exception instanceof SSLException) { - return false; - }else if (exception instanceof InterruptedIOException) { - return false; - }else if (exception instanceof SSLHandshakeException) { - return false; - }else if (exception instanceof UnknownHostException) { - return false; - }else if (exception instanceof ConnectTimeoutException) { - return false; - } - - HttpClientContext clientContext = HttpClientContext - .adapt(context); - HttpRequest request = clientContext.getRequest(); - if (!(request instanceof HttpEntityEnclosingRequest)) { - return true; - } - return false; - }; - - CloseableHttpClient httpClient = HttpClients.custom() - .setConnectionManager(cm) - .setRetryHandler(httpRequestRetryHandler).build(); - - return httpClient; - } - - private static void setPostParams(HttpPost httpPost, - Map params) { - List nameValuePairs = new ArrayList(); - Set keySet = params.keySet(); - for (String key : keySet) { - nameValuePairs.add(new BasicNameValuePair(key, params.get(key).toString())); - } - try { - httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET)); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - - /** - * POST请求 - * - * @param url - * @param params - * @return String - * @throws IOException - */ - public static String post(String url, Map params) throws IOException { - HttpPost httpPost = new HttpPost(url); - config(httpPost); - setPostParams(httpPost, params); - try (CloseableHttpResponse response = httpPost(url, httpPost)) { - return parseResponse(response); - } - } - - /** - * GET请求 - * - * @param url - * @return String - */ - public static String get(String url) throws IOException { - HttpGet httpGet = new HttpGet(url); - config(httpGet); - try (CloseableHttpResponse response = httpGet(url, httpGet)) { - return parseResponse(response); - } - } - - /** - * Get请求的真实执行 - * - * @param url - * @param httpGet - * @return - * @throws IOException - */ - private static CloseableHttpResponse httpGet(String url, HttpGet httpGet) throws IOException { - return getHttpClient(url) - .execute(httpGet, HttpClientContext.create()); - } - - /** - * POST请求的真实执行 - * - * @param url - * @param httpPost - * @return - * @throws IOException - */ - private static CloseableHttpResponse httpPost(String url, HttpPost httpPost) throws IOException { - return getHttpClient(url) - .execute(httpPost, HttpClientContext.create()); - } - - /** - * 解析response - * - * @param response - * @return - * @throws IOException - */ - private static String parseResponse(CloseableHttpResponse response) throws IOException { - HttpEntity entity = response.getEntity(); - String result = EntityUtils.toString(entity, DEFAULT_CHARSET); - EntityUtils.consume(entity); - return result; - } - - public static String jsonPost(String url, String json) throws IOException { - HttpPost httpPost = new HttpPost(url); - config(httpPost); - setJsonPostParams(httpPost, json); - try (CloseableHttpResponse response = httpPost(url, httpPost)) { - return parseResponse(response); - } - } - - private static void setJsonPostParams(HttpPost httpPost, String json) { - httpPost.addHeader("Content-type","application/json; charset=utf-8"); - httpPost.setHeader("Accept", "application/json"); - httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8"))); - } -} \ No newline at end of file diff --git a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/converters/BinarySerializeRequestBodyConverter.java b/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/converters/BinarySerializeRequestBodyConverter.java deleted file mode 100644 index 402e91f4..00000000 --- a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/converters/BinarySerializeRequestBodyConverter.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.converters.BinarySerializeRequestBodyConverter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/5 下午5:09 - * Description: 序列化请求体 - */ -package com.jd.blockchain.utils.http.converters; - -import java.io.IOException; -import java.io.OutputStream; - -import com.jd.blockchain.utils.http.RequestBodyConverter; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; - -public class BinarySerializeRequestBodyConverter implements RequestBodyConverter { - - @Override - public void write(Object param, OutputStream out) throws IOException { - BinarySerializeUtils.serialize(param, out); - } -} \ No newline at end of file diff --git a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/converters/BinarySerializeResponseConverter.java b/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/converters/BinarySerializeResponseConverter.java deleted file mode 100644 index a9da4670..00000000 --- a/source/utils/utils-http/src/main/java/com/jd/blockchain/utils/http/converters/BinarySerializeResponseConverter.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.converters.BinarySerializeResponseConverter - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/5 下午5:22 - * Description: - */ -package com.jd.blockchain.utils.http.converters; - -import java.io.InputStream; - -import com.jd.blockchain.utils.http.HttpServiceContext; -import com.jd.blockchain.utils.http.ResponseConverter; -import com.jd.blockchain.utils.http.agent.ServiceRequest; -import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; - -public class BinarySerializeResponseConverter implements ResponseConverter { - - @Override - public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext) - throws Exception { - return BinarySerializeUtils.deserialize(responseStream); - } - -} \ No newline at end of file diff --git a/source/utils/utils-serialize/src/main/java/com/jd/blockchain/utils/serialize/binary/FilteredObjectInputStream.java b/source/utils/utils-serialize/src/main/java/com/jd/blockchain/utils/serialize/binary/FilteredObjectInputStream.java deleted file mode 100644 index 897aa115..00000000 --- a/source/utils/utils-serialize/src/main/java/com/jd/blockchain/utils/serialize/binary/FilteredObjectInputStream.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jd.blockchain.utils.serialize.binary; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectStreamClass; -import java.util.HashSet; -import java.util.Set; - -public class FilteredObjectInputStream extends ObjectInputStream { - - private static final Set classBlacklist = new HashSet(); - - /** - * 把指定类型加入禁止反序列化的类型黑名单; - * - * @param className - */ - public static void addBlackList(String className) { - classBlacklist.add(className); - } - - public FilteredObjectInputStream(InputStream in) throws IOException { - super(in); - } - - @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { - if (classBlacklist.contains(desc.getName())) { - throw new SecurityException("Class["+desc.getName()+"] is forbidden to deserialize because it is in the blacklist!"); - } - return super.resolveClass(desc); - } - -} diff --git a/source/utils/utils-serialize/src/test/java/test/my/utils/serialize/ICar.java b/source/utils/utils-serialize/src/test/java/test/my/utils/serialize/ICar.java deleted file mode 100644 index 81c0a538..00000000 --- a/source/utils/utils-serialize/src/test/java/test/my/utils/serialize/ICar.java +++ /dev/null @@ -1,10 +0,0 @@ -package test.my.utils.serialize; - -public interface ICar { - - int getWeight(); - - int getCost(); - - Wheel getWheel(); -} \ No newline at end of file diff --git a/source/utils/utils-serialize/src/test/java/test/my/utils/serialize/Wheel.java b/source/utils/utils-serialize/src/test/java/test/my/utils/serialize/Wheel.java deleted file mode 100644 index 56cb8186..00000000 --- a/source/utils/utils-serialize/src/test/java/test/my/utils/serialize/Wheel.java +++ /dev/null @@ -1,15 +0,0 @@ -package test.my.utils.serialize; - -public class Wheel { - - private String black; - - public String getBlack() { - return black; - } - - public void setBlack(String black) { - this.black = black; - } - -} diff --git a/test b/test new file mode 160000 index 00000000..ee858192 --- /dev/null +++ b/test @@ -0,0 +1 @@ +Subproject commit ee858192ff9b0cc4bb8c55d9c0baa83e02fc5ca0