原有的合约相关测试用例,修改适配为did版本,

This commit is contained in:
brightestboy 2021-11-03 08:55:24 +08:00
parent b08031455e
commit bd78e22dd6
11 changed files with 888 additions and 860 deletions

View File

@ -21,8 +21,8 @@ import org.json4s.jackson.JsonMethods.parse
import rep.protos.peer.ActionResult
import rep.sc.scalax.{ContractContext, IContract}
final case class proofDataSingle(key: String, value: String)
class parallelPutProofTPL extends IContract{
final case class ProofDataSingle(key: String, value: String)
class ParallelPutProofTPL extends IContract{
type proofDataMap = Map[String, Any]
val split = "_"
@ -53,7 +53,7 @@ class parallelPutProofTPL extends IContract{
* @param data
* @return
*/
def putProof(ctx: ContractContext, data: proofDataSingle): ActionResult = {
def putProof(ctx: ContractContext, data: ProofDataSingle): ActionResult = {
ctx.api.setVal(ctx.t.id + split + data.key, data.value)
print("putProof:"+ data.key + ":" + data.value)
null
@ -69,7 +69,7 @@ class parallelPutProofTPL extends IContract{
action match {
case "putProofSingle" =>
println("-----------"+sdata)
putProof(ctx, json.extract[proofDataSingle])
putProof(ctx, json.extract[ProofDataSingle])
case "putProofMap" =>
putProof(ctx, json.extract[proofDataMap])
}

View File

@ -32,138 +32,140 @@ import rep.sc.scalax.ContractContext
import rep.protos.peer.ActionResult
/**
* 供应链分账合约
*/
* 供应链分账合约
*/
class SupplyTPL extends IContract {
val SPLIT_CHAR = "_";
val TPL_MODE = "_PM";
implicit val formats = DefaultFormats
def init(ctx: ContractContext){
println(s"tid: $ctx.t.id")
}
/**
* 设计方原料方生产方销售方 签订对销售额的分成合约, 对于销售方账号+产品型号决定唯一的分账合约
*/
def signShare(ctx: ContractContext, data:IPTSignShare ):ActionResult={
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid+TPL_MODE
//签约输入持久化,默认的类型转换无法胜任以json字符串形式持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Share)
null
}
def signFixed(ctx: ContractContext, data:IPTSignFixed ):ActionResult={
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid+TPL_MODE
//签约输入持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Fixed)
null
val SPLIT_CHAR = "_"
val TPL_MODE = "_PM"
implicit val formats = DefaultFormats
def init(ctx: ContractContext) {
println(s"tid: $ctx.t.id")
}
/**
* 设计方原料方生产方销售方 签订对销售额的分成合约, 对于销售方账号+产品型号决定唯一的分账合约
*/
def signShare(ctx: ContractContext, data: IPTSignShare): ActionResult = {
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
//签约输入持久化,默认的类型转换无法胜任以json字符串形式持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Share)
null
}
def signFixed(ctx: ContractContext, data: IPTSignFixed): ActionResult = {
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
//签约输入持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Fixed)
null
}
/**
* 分账的调度方法负责根据调用相应的分账模版, 传入模版定制参数和销售数据,进行分账
*/
def split(ctx: ContractContext, data: IPTSplit): ActionResult = {
//根据销售方账号和产品Id获得分账脚本
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
val tm = ctx.api.getVal(pid).asInstanceOf[String]
//根据签约时选择的分账方式模版,验证定制参数
val mr = tm match {
case TPL.Share =>
val sp0: Any = ctx.api.getVal(sid)
val sp = read[IPTSignShare](ctx.api.getVal(sid).asInstanceOf[String])
splitShare(data.amount, sp.account_remain, sp.tpl_param)
case TPL.Fixed =>
val sp = read[IPTSignFixed](ctx.api.getVal(sid).asInstanceOf[String])
splitFixedRatio(data.amount, sp.account_remain, sp.ratio)
}
/**
* 分账的调度方法负责根据调用相应的分账模版, 传入模版定制参数和销售数据,进行分账
*/
def split(ctx: ContractContext, data:IPTSplit ):ActionResult={
//根据销售方账号和产品Id获得分账脚本
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
val tm = ctx.api.getVal(pid).asInstanceOf[String]
//根据签约时选择的分账方式模版,验证定制参数
val mr = tm match {
case TPL.Share =>
val sp0:Any = ctx.api.getVal(sid)
val sp = read[IPTSignShare](ctx.api.getVal(sid).asInstanceOf[String])
splitShare(data.amount, sp.account_remain, sp.tpl_param)
case TPL.Fixed =>
val sp = read[IPTSignFixed](ctx.api.getVal(sid).asInstanceOf[String])
splitFixedRatio(data.amount, sp.account_remain, sp.ratio)
}
//返回分账计算结果
addToAccount(ctx, mr)
null
//返回分账计算结果
addToAccount(ctx, mr)
null
}
/**
* 将分账结果增加到账户并持久化
*/
def addToAccount(ctx: ContractContext, mr: Map[String, Int]) {
for ((k, v) <- mr) {
val sk: Any = ctx.api.getVal(k)
var dk = if (sk == null) 0 else sk.toString.toInt
ctx.api.setVal(k, dk + v)
}
/**
* 将分账结果增加到账户并持久化
*/
def addToAccount(ctx: ContractContext, mr:Map[String,Int]){
for ((k, v) <- mr) {
val sk :Any= ctx.api.getVal(k)
var dk = if(sk==null) 0 else sk.toString.toInt
ctx.api.setVal(k, dk+v)
}
/**
* 合约方法入口
*/
def onAction(ctx: ContractContext, action: String, sdata: String): ActionResult = {
val json = parse(sdata)
action match {
case ACTION.SignShare =>
signShare(ctx, json.extract[IPTSignShare])
case ACTION.SignFixed =>
signFixed(ctx, json.extract[IPTSignFixed])
case ACTION.Split =>
split(ctx, json.extract[IPTSplit])
}
}
/**
* 内部函数, 获得分阶段的分成
*/
def getShare(sr: Int, ar: Array[ShareRatio]): Int = {
var rv = 0
for (el <- ar) {
//击中金额范围
if (sr > el.from && sr <= el.to) {
//固定金额
if (el.fixed > 0)
rv = el.fixed
else //按比例分成
rv = (sr * el.ratio).toInt
}
}
/**
* 合约方法入口
*/
def onAction(ctx: ContractContext,action:String, sdata:String ):ActionResult={
val json = parse(sdata)
action match {
case ACTION.SignShare =>
signShare(ctx,json.extract[IPTSignShare])
case ACTION.SignFixed =>
signFixed(ctx,json.extract[IPTSignFixed])
case ACTION.Split =>
split(ctx, json.extract[IPTSplit])
}
rv
}
/**
* 合约中内置多种分账模版签约时可选择模版,如果出现新的分账模版则部署一版新的合约
* 分成模型, 除了销售方之外, 其他各方要求一个最低金额分成按照金额阶段有所不同
*/
def splitShare(sr: Int, account_remain: String, rule: ShareMap): Map[String, Int] = {
//分账结果
val rm: Map[String, Int] = Map()
//分账余额
var remain = sr
for ((k, v) <- rule) {
val rv = getShare(sr, v)
rm += (k -> rv)
remain -= rv
}
/**
* 内部函数, 获得分阶段的分成
*/
def getShare(sr: Int, ar: Array[ShareRatio]) : Int={
var rv = 0
for(el <- ar) {
//击中金额范围
if(sr > el.from && sr <= el.to) {
//固定金额
if(el.fixed > 0)
rv = el.fixed
else //按比例分成
rv = (sr * el.ratio) .toInt
}
}
rv
}
/**
* 合约中内置多种分账模版签约时可选择模版,如果出现新的分账模版则部署一版新的合约
* 分成模型, 除了销售方之外, 其他各方要求一个最低金额分成按照金额阶段有所不同
*/
def splitShare(sr: Int, account_remain:String, rule: ShareMap): Map[String,Int] ={
//分账结果
val rm : Map[String, Int] = Map()
//分账余额
var remain = sr
for ((k, v) <- rule) {
val rv = getShare(sr, v)
rm += (k -> rv)
remain -= rv
}
rm += (account_remain -> remain)
}
/**
* 各方固定比例分成此模版仅仅为了合约对多模版的支持可能无实际用途
*/
def splitFixedRatio(sr: Int, account_remain: String, mr:FixedMap): Map[String,Int] ={
val rm : Map[String, Int] = Map()
var remain = sr
//根据固定分成
for ((k, v) <- mr) {
val rv = (sr* v ).toInt
rm += (k -> rv)
remain -= rv
}
//剩余的分给指定的余额账户
rm += (account_remain -> remain)
}
rm += (account_remain -> remain)
}
/**
* 各方固定比例分成此模版仅仅为了合约对多模版的支持可能无实际用途
*/
def splitFixedRatio(sr: Int, account_remain: String, mr: FixedMap): Map[String, Int] = {
val rm: Map[String, Int] = Map()
var remain = sr
//根据固定分成
for ((k, v) <- mr) {
val rv = (sr * v).toInt
rm += (k -> rv)
remain -= rv
}
//剩余的分给指定的余额账户
rm += (account_remain -> remain)
}
}

View File

@ -32,139 +32,141 @@ import rep.sc.scalax.ContractContext
import rep.protos.peer.ActionResult
/**
* 供应链分账合约
*/
* 供应链分账合约
*/
class SupplyTPL2 extends IContract {
val SPLIT_CHAR = "_";
val TPL_MODE = "_PM";
implicit val formats = DefaultFormats
def init(ctx: ContractContext){
println(s"tid: $ctx.t.id")
}
/**
* 设计方原料方生产方销售方 签订对销售额的分成合约, 对于销售方账号+产品型号决定唯一的分账合约
*/
def signShare(ctx: ContractContext, data:IPTSignShare ):ActionResult={
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid+TPL_MODE
//签约输入持久化,默认的类型转换无法胜任以json字符串形式持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Share)
null
}
def signFixed(ctx: ContractContext, data:IPTSignFixed ):ActionResult={
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid+TPL_MODE
//签约输入持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Fixed)
null
val SPLIT_CHAR = "_"
val TPL_MODE = "_PM"
implicit val formats = DefaultFormats
def init(ctx: ContractContext) {
println(s"tid: $ctx.t.id")
}
/**
* 设计方原料方生产方销售方 签订对销售额的分成合约, 对于销售方账号+产品型号决定唯一的分账合约
*/
def signShare(ctx: ContractContext, data: IPTSignShare): ActionResult = {
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
//签约输入持久化,默认的类型转换无法胜任以json字符串形式持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Share)
null
}
def signFixed(ctx: ContractContext, data: IPTSignFixed): ActionResult = {
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
//签约输入持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Fixed)
null
}
/**
* 分账的调度方法负责根据调用相应的分账模版, 传入模版定制参数和销售数据,进行分账
*/
def split(ctx: ContractContext, data: IPTSplit): ActionResult = {
//根据销售方账号和产品Id获得分账脚本
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
val tm = ctx.api.getVal(pid).asInstanceOf[String]
//根据签约时选择的分账方式模版,验证定制参数
val mr = tm match {
case TPL.Share =>
val sp0: Any = ctx.api.getVal(sid)
val sp = read[IPTSignShare](ctx.api.getVal(sid).asInstanceOf[String])
splitShare(data.amount, sp.account_remain, sp.tpl_param)
case TPL.Fixed =>
val sp = read[IPTSignFixed](ctx.api.getVal(sid).asInstanceOf[String])
splitFixedRatio(data.amount, sp.account_remain, sp.ratio)
}
/**
* 分账的调度方法负责根据调用相应的分账模版, 传入模版定制参数和销售数据,进行分账
*/
def split(ctx: ContractContext, data:IPTSplit ):ActionResult={
//根据销售方账号和产品Id获得分账脚本
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
val tm = ctx.api.getVal(pid).asInstanceOf[String]
//根据签约时选择的分账方式模版,验证定制参数
val mr = tm match {
case TPL.Share =>
val sp0:Any = ctx.api.getVal(sid)
val sp = read[IPTSignShare](ctx.api.getVal(sid).asInstanceOf[String])
splitShare(data.amount, sp.account_remain, sp.tpl_param)
case TPL.Fixed =>
val sp = read[IPTSignFixed](ctx.api.getVal(sid).asInstanceOf[String])
splitFixedRatio(data.amount, sp.account_remain, sp.ratio)
}
//返回分账计算结果
addToAccount(ctx, mr)
null
//返回分账计算结果
addToAccount(ctx, mr)
null
}
/**
* 将分账结果增加到账户并持久化
*/
def addToAccount(ctx: ContractContext, mr: Map[String, Int]) {
for ((k, v) <- mr) {
val sk: Any = ctx.api.getVal(k)
var dk = if (sk == null) 0 else sk.toString.toInt
ctx.api.setVal(k, dk + v)
}
/**
* 将分账结果增加到账户并持久化
*/
def addToAccount(ctx: ContractContext, mr:Map[String,Int]){
for ((k, v) <- mr) {
val sk:Any = ctx.api.getVal(k)
var dk = if(sk==null) 0 else sk.toString.toInt
ctx.api.setVal(k, dk+v)
}
/**
* 合约方法入口
*/
def onAction(ctx: ContractContext, action: String, sdata: String): ActionResult = {
val json = parse(sdata)
action match {
//for test 合约升级变体
//case ACTION.SignShare =>
// signShare(ctx,json.extract[IPTSignShare])
case ACTION.SignFixed =>
signFixed(ctx, json.extract[IPTSignFixed])
case ACTION.Split =>
split(ctx, json.extract[IPTSplit])
}
}
/**
* 内部函数, 获得分阶段的分成
*/
def getShare(sr: Int, ar: Array[ShareRatio]): Int = {
var rv = 0
for (el <- ar) {
//击中金额范围
if (sr > el.from && sr <= el.to) {
//固定金额
if (el.fixed > 0)
rv = el.fixed
else //按比例分成
rv = (sr * el.ratio).toInt
}
}
/**
* 合约方法入口
*/
def onAction(ctx: ContractContext,action:String, sdata:String ):ActionResult={
val json = parse(sdata)
action match {
//for test 合约升级变体
//case ACTION.SignShare =>
// signShare(ctx,json.extract[IPTSignShare])
case ACTION.SignFixed =>
signFixed(ctx,json.extract[IPTSignFixed])
case ACTION.Split =>
split(ctx, json.extract[IPTSplit])
}
rv
}
/**
* 合约中内置多种分账模版签约时可选择模版,如果出现新的分账模版则部署一版新的合约
* 分成模型, 除了销售方之外, 其他各方要求一个最低金额分成按照金额阶段有所不同
*/
def splitShare(sr: Int, account_remain: String, rule: ShareMap): Map[String, Int] = {
//分账结果
val rm: Map[String, Int] = Map()
//分账余额
var remain = sr
for ((k, v) <- rule) {
val rv = getShare(sr, v)
rm += (k -> rv)
remain -= rv
}
/**
* 内部函数, 获得分阶段的分成
*/
def getShare(sr: Int, ar: Array[ShareRatio]) : Int={
var rv = 0
for(el <- ar) {
//击中金额范围
if(sr > el.from && sr <= el.to) {
//固定金额
if(el.fixed > 0)
rv = el.fixed
else //按比例分成
rv = (sr * el.ratio) .toInt
}
}
rv
}
/**
* 合约中内置多种分账模版签约时可选择模版,如果出现新的分账模版则部署一版新的合约
* 分成模型, 除了销售方之外, 其他各方要求一个最低金额分成按照金额阶段有所不同
*/
def splitShare(sr: Int, account_remain:String, rule: ShareMap): Map[String,Int] ={
//分账结果
val rm : Map[String, Int] = Map()
//分账余额
var remain = sr
for ((k, v) <- rule) {
val rv = getShare(sr, v)
rm += (k -> rv)
remain -= rv
}
rm += (account_remain -> remain)
}
/**
* 各方固定比例分成此模版仅仅为了合约对多模版的支持可能无实际用途
*/
def splitFixedRatio(sr: Int, account_remain: String, mr:FixedMap): Map[String,Int] ={
val rm : Map[String, Int] = Map()
var remain = sr
//根据固定分成
for ((k, v) <- mr) {
val rv = (sr* v ).toInt
rm += (k -> rv)
remain -= rv
}
//剩余的分给指定的余额账户
rm += (account_remain -> remain)
}
rm += (account_remain -> remain)
}
/**
* 各方固定比例分成此模版仅仅为了合约对多模版的支持可能无实际用途
*/
def splitFixedRatio(sr: Int, account_remain: String, mr: FixedMap): Map[String, Int] = {
val rm: Map[String, Int] = Map()
var remain = sr
//根据固定分成
for ((k, v) <- mr) {
val rv = (sr * v).toInt
rm += (k -> rv)
remain -= rv
}
//剩余的分给指定的余额账户
rm += (account_remain -> remain)
}
}

View File

@ -32,139 +32,141 @@ import rep.sc.scalax.ContractContext
import rep.protos.peer.ActionResult
/**
* 供应链分账合约
*/
* 供应链分账合约
*/
class SupplyTPL3 extends IContract {
val SPLIT_CHAR = "_";
val TPL_MODE = "_PM";
implicit val formats = DefaultFormats
def init(ctx: ContractContext){
println(s"tid: $ctx.t.id")
}
/**
* 设计方原料方生产方销售方 签订对销售额的分成合约, 对于销售方账号+产品型号决定唯一的分账合约
*/
def signShare(ctx: ContractContext, data:IPTSignShare ):ActionResult={
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid+TPL_MODE
//签约输入持久化,默认的类型转换无法胜任以json字符串形式持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Share)
null
}
def signFixed(ctx: ContractContext, data:IPTSignFixed ):ActionResult={
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid+TPL_MODE
//签约输入持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Fixed)
null
val SPLIT_CHAR = "_"
val TPL_MODE = "_PM"
implicit val formats = DefaultFormats
def init(ctx: ContractContext) {
println(s"tid: $ctx.t.id")
}
/**
* 设计方原料方生产方销售方 签订对销售额的分成合约, 对于销售方账号+产品型号决定唯一的分账合约
*/
def signShare(ctx: ContractContext, data: IPTSignShare): ActionResult = {
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
//签约输入持久化,默认的类型转换无法胜任以json字符串形式持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Share)
null
}
def signFixed(ctx: ContractContext, data: IPTSignFixed): ActionResult = {
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
//签约输入持久化
ctx.api.setVal(sid, write(data))
ctx.api.setVal(pid, TPL.Fixed)
null
}
/**
* 分账的调度方法负责根据调用相应的分账模版, 传入模版定制参数和销售数据,进行分账
*/
def split(ctx: ContractContext, data: IPTSplit): ActionResult = {
//根据销售方账号和产品Id获得分账脚本
val sid = data.account_sale + SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
val tm = ctx.api.getVal(pid).asInstanceOf[String]
//根据签约时选择的分账方式模版,验证定制参数
val mr = tm match {
case TPL.Share =>
val sp0: Any = ctx.api.getVal(sid)
val sp = read[IPTSignShare](ctx.api.getVal(sid).asInstanceOf[String])
splitShare(data.amount, sp.account_remain, sp.tpl_param)
case TPL.Fixed =>
val sp = read[IPTSignFixed](ctx.api.getVal(sid).asInstanceOf[String])
splitFixedRatio(data.amount, sp.account_remain, sp.ratio)
}
/**
* 分账的调度方法负责根据调用相应的分账模版, 传入模版定制参数和销售数据,进行分账
*/
def split(ctx: ContractContext, data:IPTSplit ):ActionResult={
//根据销售方账号和产品Id获得分账脚本
val sid = data.account_sale +SPLIT_CHAR + data.product_id
val pid = sid + TPL_MODE
val tm = ctx.api.getVal(pid).asInstanceOf[String]
//根据签约时选择的分账方式模版,验证定制参数
val mr = tm match {
case TPL.Share =>
val sp0:Any = ctx.api.getVal(sid)
val sp = read[IPTSignShare](ctx.api.getVal(sid).asInstanceOf[String])
splitShare(data.amount, sp.account_remain, sp.tpl_param)
case TPL.Fixed =>
val sp = read[IPTSignFixed](ctx.api.getVal(sid).asInstanceOf[String])
splitFixedRatio(data.amount, sp.account_remain, sp.ratio)
}
//返回分账计算结果
addToAccount(ctx, mr)
null
//返回分账计算结果
addToAccount(ctx, mr)
null
}
/**
* 将分账结果增加到账户并持久化
*/
def addToAccount(ctx: ContractContext, mr: Map[String, Int]) {
for ((k, v) <- mr) {
val sk: Any = ctx.api.getVal(k)
var dk = if (sk == null) 0 else sk.toString.toInt
ctx.api.setVal(k, dk + v)
}
/**
* 将分账结果增加到账户并持久化
*/
def addToAccount(ctx: ContractContext, mr:Map[String,Int]){
for ((k, v) <- mr) {
val sk:Any = ctx.api.getVal(k)
var dk = if(sk==null) 0 else sk.toString.toInt
ctx.api.setVal(k, dk+v)
}
/**
* 合约方法入口
*/
def onAction(ctx: ContractContext, action: String, sdata: String): ActionResult = {
val json = parse(sdata)
action match {
case ACTION.SignShare =>
signShare(ctx, json.extract[IPTSignShare])
//for test 合约升级变体
//case ACTION.SignFixed =>
// signFixed(ctx,json.extract[IPTSignFixed])
case ACTION.Split =>
split(ctx, json.extract[IPTSplit])
}
}
/**
* 内部函数, 获得分阶段的分成
*/
def getShare(sr: Int, ar: Array[ShareRatio]): Int = {
var rv = 0
for (el <- ar) {
//击中金额范围
if (sr > el.from && sr <= el.to) {
//固定金额
if (el.fixed > 0)
rv = el.fixed
else //按比例分成
rv = (sr * el.ratio).toInt
}
}
/**
* 合约方法入口
*/
def onAction(ctx: ContractContext,action:String, sdata:String ):ActionResult={
val json = parse(sdata)
action match {
case ACTION.SignShare =>
signShare(ctx,json.extract[IPTSignShare])
//for test 合约升级变体
//case ACTION.SignFixed =>
// signFixed(ctx,json.extract[IPTSignFixed])
case ACTION.Split =>
split(ctx, json.extract[IPTSplit])
}
rv
}
/**
* 合约中内置多种分账模版签约时可选择模版,如果出现新的分账模版则部署一版新的合约
* 分成模型, 除了销售方之外, 其他各方要求一个最低金额分成按照金额阶段有所不同
*/
def splitShare(sr: Int, account_remain: String, rule: ShareMap): Map[String, Int] = {
//分账结果
val rm: Map[String, Int] = Map()
//分账余额
var remain = sr
for ((k, v) <- rule) {
val rv = getShare(sr, v)
rm += (k -> rv)
remain -= rv
}
/**
* 内部函数, 获得分阶段的分成
*/
def getShare(sr: Int, ar: Array[ShareRatio]) : Int={
var rv = 0
for(el <- ar) {
//击中金额范围
if(sr > el.from && sr <= el.to) {
//固定金额
if(el.fixed > 0)
rv = el.fixed
else //按比例分成
rv = (sr * el.ratio) .toInt
}
}
rv
}
/**
* 合约中内置多种分账模版签约时可选择模版,如果出现新的分账模版则部署一版新的合约
* 分成模型, 除了销售方之外, 其他各方要求一个最低金额分成按照金额阶段有所不同
*/
def splitShare(sr: Int, account_remain:String, rule: ShareMap): Map[String,Int] ={
//分账结果
val rm : Map[String, Int] = Map()
//分账余额
var remain = sr
for ((k, v) <- rule) {
val rv = getShare(sr, v)
rm += (k -> rv)
remain -= rv
}
rm += (account_remain -> remain)
}
/**
* 各方固定比例分成此模版仅仅为了合约对多模版的支持可能无实际用途
*/
def splitFixedRatio(sr: Int, account_remain: String, mr:FixedMap): Map[String,Int] ={
val rm : Map[String, Int] = Map()
var remain = sr
//根据固定分成
for ((k, v) <- mr) {
val rv = (sr* v ).toInt
rm += (k -> rv)
remain -= rv
}
//剩余的分给指定的余额账户
rm += (account_remain -> remain)
}
rm += (account_remain -> remain)
}
/**
* 各方固定比例分成此模版仅仅为了合约对多模版的支持可能无实际用途
*/
def splitFixedRatio(sr: Int, account_remain: String, mr: FixedMap): Map[String, Int] = {
val rm: Map[String, Int] = Map()
var remain = sr
//根据固定分成
for ((k, v) <- mr) {
val rv = (sr * v).toInt
rm += (k -> rv)
remain -= rv
}
//剩余的分给指定的余额账户
rm += (account_remain -> remain)
}
}

View File

@ -59,7 +59,8 @@ object OperOperation extends DidOperation {
/**
* 注册Operate
* 链密钥对为普通合约拥有者注册普通合约拥有者操作拥有者给自己注册
* 链密钥对为自己注册service为自己注册deploy与setState其他用户通过授权
* 普通合约拥有者操作拥有者给自己注册合约相关的操作
*
* @param ctx
* @param operate
@ -77,7 +78,6 @@ object OperOperation extends DidOperation {
if (!operate.register.equals(certId.creditCode)) {
throw ContractException(toJsonErrMsg(registerNotTranPoster))
}
// 链密钥对为普通合约拥有者注册普通合约拥有者操作拥有者给自己注册
if (ctx.api.getVal(operPrefix + operate.opId) == null) {
// 检查账户的有效性
val signer = checkSignerValid(ctx, operate.register)

View File

@ -16,34 +16,21 @@
package rep.sc
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import akka.actor.ActorSystem
import akka.testkit.TestKit
import akka.testkit.{TestKit, TestProbe}
import org.json4s.{DefaultFormats, jackson}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import rep.app.conf.SystemProfile
import rep.app.system.ClusterSystem
import rep.app.system.ClusterSystem.InitType
import rep.crypto.cert.SignTool
import rep.network.autotransaction.PeerHelper
import rep.protos.peer.ChaincodeDeploy.ContractClassification
import rep.protos.peer._
import rep.sc.SandboxDispatcher.DoTransaction
import scala.concurrent.Await
import scala.concurrent.duration._
import rep.protos.peer._
import rep.sc.Sandbox._
import rep.app.system.ClusterSystem
import rep.app.system.ClusterSystem.InitType
import org.json4s.{DefaultFormats, jackson}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._
import rep.network.module.cfrd.ModuleManagerOfCFRD
import rep.storage.ImpDataAccess
import rep.utils.SerializeUtils.deserialise
import java.nio.ByteBuffer
import java.io.IOException
import java.io.PrintWriter
import java.io.FileWriter
import java.io.File
import scala.collection.mutable.Map
import org.json4s.{DefaultFormats, Formats, jackson}
import org.json4s.native.Serialization.writePretty
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import rep.network.autotransaction.PeerHelper
/** 合约容器实现的单元测试
*
@ -51,22 +38,10 @@ import rep.network.autotransaction.PeerHelper
* @param _system 测试用例所在的actor System.
*
*/
class DeliveryAndStorageProofSpec(_system: ActorSystem)
extends TestKit(_system)
with Matchers
with FlatSpecLike
with BeforeAndAfterAll {
class DeliveryAndStorageProofSpec(_system: ActorSystem) extends TestKit(_system) with Matchers with FlatSpecLike with BeforeAndAfterAll {
import rep.sc.Sandbox.DoTransactionResult
import rep.sc.SandboxDispatcher.DoTransaction
import akka.testkit.TestProbe
import akka.testkit.TestActorRef
import Json4sSupport._
import rep.sc.tpl.SupplyType._
import rep.utils.SerializeUtils.toJson
implicit val serialization = jackson.Serialization
// or native.Serialization
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
def this() = this(ActorSystem("DeliveryAndStorageSpec", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
@ -74,29 +49,31 @@ class DeliveryAndStorageProofSpec(_system: ActorSystem)
override def afterAll: Unit = Await.ready(system.terminate(), Duration.Inf)
//Scala实现的资产管理合约测试包括合约的部署调用结果返回验证
"container" should "deploy supply contract and call it for splitting then" in {
"container" should "deploy contract --- DeliveryAndStorageProof" in {
val sysName = "121000005l35120456.node1"
val dbTag = "121000005l35120456.node1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val pm = system.actorOf(ModuleManagerOfCFRD.props("modulemanager", sysName, false, false, false), "modulemanager")
val superAdmin = "951002007l78123233.super_admin"
// 初始化配置项主要是为了初始化存储路径
SystemProfile.initConfigSystem(system.settings.config, sysName)
// 加载node1的私钥
SignTool.loadPrivateKey(sysName, "123", "jks/" + sysName + ".jks")
// 加载super_admin的私钥
SignTool.loadPrivateKey(superAdmin, "super_admin", "jks/" + superAdmin + ".jks")
//加载合约脚本
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/DeliveryAndStorageProof.scala")
val l1 = try s1.mkString finally s1.close()
//准备探针以验证调用返回结果
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
var sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
val sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
//生成deploy交易
val cid = new ChaincodeId("DeliveryAndStorageProof", 1)
val t1 = PeerHelper.createTransaction4Deploy(sysName, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send1 = new DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
val t1 = PeerHelper.createTransaction4Deploy(superAdmin, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send1 = DoTransaction(Seq[Transaction](t1), "test-db", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv1(0).err should be(None)
val msg_recv1 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv1.head.getResult.code should be(0)
}
}

View File

@ -23,28 +23,32 @@ import akka.testkit.TestKit
import scala.concurrent.Await
import scala.concurrent.duration._
import rep.protos.peer._
import rep.sc.Sandbox._
import rep.app.system.ClusterSystem
import rep.app.system.ClusterSystem.InitType
import org.json4s.{DefaultFormats, jackson}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._
import rep.network.module.cfrd.ModuleManagerOfCFRD
import rep.storage.ImpDataAccess
import rep.utils.SerializeUtils.deserialise
import java.nio.ByteBuffer
import java.io.IOException
import java.io.PrintWriter
import java.io.FileWriter
import java.io.File
import scala.collection.mutable.Map
import org.json4s.{DefaultFormats, Formats, jackson}
import org.json4s.native.Serialization.writePretty
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import rep.crypto.cert.SignTool
import rep.network.autotransaction.PeerHelper
import rep.sc.SandboxDispatcher.DoTransaction
import akka.testkit.TestProbe
import akka.testkit.TestActorRef
import Json4sSupport._
import com.google.protobuf.timestamp.Timestamp
import rep.app.conf.SystemProfile
import rep.crypto.Sha256
import rep.protos.peer.Authorize.TransferType
import rep.protos.peer.Certificate.CertType
import rep.protos.peer.ChaincodeDeploy.ContractClassification
import rep.protos.peer.Operate.OperateType
import rep.sc.TransferSpec.ACTION
import rep.utils.{IdTool, SerializeUtils}
import scalapb.json4s.JsonFormat
import scala.collection.mutable.ArrayBuffer
/** 合约容器实现的单元测试
*
@ -52,22 +56,10 @@ import rep.network.autotransaction.PeerHelper
* @param _system 测试用例所在的actor System.
*
*/
class DeploySpec(_system: ActorSystem)
extends TestKit(_system)
with Matchers
with FlatSpecLike
with BeforeAndAfterAll {
class DeploySpec(_system: ActorSystem) extends TestKit(_system) with Matchers with FlatSpecLike with BeforeAndAfterAll {
import rep.sc.Sandbox.DoTransactionResult
import rep.sc.SandboxDispatcher.DoTransaction
import akka.testkit.TestProbe
import akka.testkit.TestActorRef
import Json4sSupport._
import rep.sc.tpl.SupplyType._
implicit val serialization = jackson.Serialization
// or native.Serialization
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
def this() = this(ActorSystem("SandBoxSpec", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
@ -78,53 +70,123 @@ class DeploySpec(_system: ActorSystem)
"container" should "deploy asset contract and invoke it" in {
val sysName = "121000005l35120456.node1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val pm = system.actorOf(ModuleManagerOfCFRD.props("modulemanager", sysName, false, false, false), "modulemanager")
val node2Name = "12110107bi45jh675g.node2"
val superAdmin = "951002007l78123233.super_admin"
// 初始化配置项主要是为了初始化存储路径
SystemProfile.initConfigSystem(system.settings.config, sysName)
// 加载node1的私钥
SignTool.loadPrivateKey(sysName, "123", "jks/" + sysName + ".jks")
// 加载node2的私钥在这里添加一个私钥的装载因为系统默认只装载自己的节点私钥
SignTool.loadPrivateKey(node2Name, "123", "jks/" + node2Name + ".jks")
// 加载super_admin的私钥
SignTool.loadPrivateKey(superAdmin, "super_admin", "jks/" + superAdmin + ".jks")
//加载合约脚本
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/ContractAssetsTPL.scala")
val l1 = try s1.mkString finally s1.close()
val fm: Map[String, Int] = Map("A" -> 100, "B" -> 100)
//准备探针以验证调用返回结果
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
var sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
val sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
//生成deploy交易
val cid = new ChaincodeId("Assets", 1)
val t1 = PeerHelper.createTransaction4Deploy(sysName, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send1 = new DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
val t1 = PeerHelper.createTransaction4Deploy(superAdmin, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send1 = DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv1(0).err should be(None)
val msg_recv1 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv1(0).getResult.code should be(0)
//同样合约id不允许重复部署
val msg_send2 = new DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send1)
val msg_recv2 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv2(0).err.get.cause.getMessage should be(SandboxDispatcher.ERR_REPEATED_CID)
val t2 = PeerHelper.createTransaction4Deploy(superAdmin, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send2 = DoTransaction(Seq[Transaction](t2), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv2(0).getResult.reason should be(SandboxDispatcher.ERR_REPEATED_CID)
val cid3 = new ChaincodeId("Assets", 2)
//同一合约部署者允许部署同样名称不同版本合约
val t3 = PeerHelper.createTransaction4Deploy(sysName, cid3, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send3 = new DoTransaction(Seq[Transaction](t3), "dbnumber", TypeOfSender.FromAPI)
val t3 = PeerHelper.createTransaction4Deploy(superAdmin, cid3, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send3 = DoTransaction(Seq[Transaction](t3), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send3)
val msg_recv3 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv3(0).err should be(None)
val msg_recv3 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv3(0).getResult.code should be(0)
// 不允不具有权限的用户许部署同样名称不同版本合约
val cid4 = new ChaincodeId("Assets", 3)
val sysName2 = "12110107bi45jh675g.node2"
//不同合约部署者不允许部署同样名称不同版本合约
//在这里添加一个私钥的装载因为系统默认只装载自己的节点私钥
SignTool.loadPrivateKey("12110107bi45jh675g.node2", "123", "jks/12110107bi45jh675g.node2.jks")
val t4 = PeerHelper.createTransaction4Deploy(sysName2, cid4, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send4 = new DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
val t4 = PeerHelper.createTransaction4Deploy(sysName, cid4, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send4 = DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv4(0).err.get.cause.getMessage should be(SandboxDispatcher.ERR_CODER)
val msg_recv4 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv4(0).getResult.reason should be(SandboxDispatcher.ERR_NO_OPERATE)
// 部署账户管理合约
val cid2 = ChaincodeId(SystemProfile.getAccountChaincodeName, 1)
val s2 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/did/RdidOperateAuthorizeTPL.scala")
val l2 = try s2.mkString finally s2.close()
val t5 = PeerHelper.createTransaction4Deploy(superAdmin, cid2, l2, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_SYSTEM)
val msg_send5 = DoTransaction(Seq[Transaction](t5), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send5)
val msg_recv5 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv5(0).getResult.code should be(0)
// 注册账户
val superCert = scala.io.Source.fromFile("jks/certs/951002007l78123233.super_admin.cer", "UTF-8")
val superCertPem = try superCert.mkString finally superCert.close()
val superCertHash = Sha256.hashstr(superCertPem)
val superCertId = CertId("951002007l78123233", "super_admin")
var millis = System.currentTimeMillis()
//生成Did的身份证书
val superAuthCert = rep.protos.peer.Certificate(superCertPem, "SHA1withECDSA", true, Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, CertType.CERT_AUTHENTICATION, Option(superCertId), superCertHash, "1.0")
// 账户
val superSigner = Signer("super_admin", "951002007l78123233", "13856789234", Seq.empty, Seq.empty, Seq.empty, Seq.empty, List(superAuthCert), "", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t6 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.SignUpSigner, Seq(JsonFormat.toJsonString(superSigner)))
val msg_send6 = DoTransaction(Seq[Transaction](t6), "dbnumber", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send6)
val msg_recv6 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv6(0).getResult.reason.isEmpty should be(true)
// 注册账户
val node1CertFile = scala.io.Source.fromFile("jks/certs/121000005l35120456.node1.cer", "UTF-8")
val node1CertPem = try node1CertFile.mkString finally node1CertFile.close()
val node1CertHash = Sha256.hashstr(node1CertPem)
val node1CertId = CertId("121000005l35120456", "node1")
millis = System.currentTimeMillis()
//生成Did的身份证书
val node1AuthCert = rep.protos.peer.Certificate(node1CertPem, "SHA1withECDSA", true, Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, CertType.CERT_AUTHENTICATION, Option(node1CertId), node1CertHash, "1.0")
// 账户
val node1Signer = Signer("node1", "121000005l35120456", "13856789234", Seq.empty, Seq.empty, Seq.empty, Seq.empty, List(node1AuthCert), "", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t7 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.SignUpSigner, Seq(JsonFormat.toJsonString(node1Signer)))
val msg_send7 = DoTransaction(Seq[Transaction](t7), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send7)
val msg_recv7 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv7.head.getResult.reason.isEmpty should be(true)
val snls = List("transaction.stream", "transaction.postTranByString", "transaction.postTranStream", "transaction.postTran")
val setStateOpt = rep.protos.peer.Operate(Sha256.hashstr("Assets.deploy"), "修改合约状态", superAdmin.split("\\.")(0), isPublish = false, OperateType.OPERATE_CONTRACT,
snls, "*", "ContractAssetsTPL.setState", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t8 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, "signUpOperate", Seq(JsonFormat.toJsonString(setStateOpt)))
probe.send(sandbox, DoTransaction(Seq[Transaction](t8), "dbnumber", TypeOfSender.FromPreloader))
val msg_recv8 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv8.head.getResult.reason.isEmpty should be(true)
// superAdmin 为用户授权
val granteds = new ArrayBuffer[String]
granteds.+=(sysName.split("\\.")(0))
millis = System.currentTimeMillis()
val at = rep.protos.peer.Authorize(IdTool.getRandomUUID, superAdmin.split("\\.")(0), granteds, Seq(Sha256.hashstr("Assets.deploy")),
TransferType.TRANSFER_REPEATEDLY, Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val als: List[String] = List(JsonFormat.toJsonString(at))
val t10 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, "grantOperate", Seq(SerializeUtils.compactJson(als)))
probe.send(sandbox, DoTransaction(Seq[Transaction](t10), "dbnumber", TypeOfSender.FromAPI))
val msg_recv10 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv10.head.getResult.reason.isEmpty should be(true)
// 拥有权限即可升级对应的合约
val t11 = PeerHelper.createTransaction4Deploy(sysName, cid4, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send11 = DoTransaction(Seq[Transaction](t11), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send11)
val msg_recv11 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv11(0).getResult.code should be(0)
}
}

View File

@ -20,12 +20,14 @@ import akka.actor.ActorSystem
import akka.testkit.{TestKit, TestProbe}
import org.json4s.{DefaultFormats, jackson}
import org.json4s.native.Serialization.{write, writePretty}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, FunSuiteLike, Matchers}
import rep.app.system.ClusterSystem
import rep.app.system.ClusterSystem.InitType
import rep.crypto.cert.SignTool
import rep.network.autotransaction.PeerHelper
import rep.network.module.cfrd.ModuleManagerOfCFRD
import rep.protos.peer.{Certificate, ChaincodeId, Signer, Transaction}
import rep.protos.peer.ChaincodeDeploy.ContractClassification
import rep.protos.peer._
import rep.sc.SandboxSpec.{ACTION, SetMap}
import rep.sc.tpl._
//.{CertStatus,CertInfo}
@ -58,8 +60,7 @@ object SandboxSpec {
*
* @param _system
*/
class SandboxSpec(_system: ActorSystem)
extends TestKit(_system) with Matchers with FlatSpecLike with BeforeAndAfterAll {
class SandboxSpec(_system: ActorSystem) extends TestKit(_system) with Matchers with FunSuiteLike with BeforeAndAfterAll {
def this() = this(ActorSystem("TransferSpec", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
@ -67,95 +68,32 @@ class SandboxSpec(_system: ActorSystem)
shutdown(system)
}
implicit val serialization = jackson.Serialization
// or native.Serialization
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
"ContractAssetsTPL" should "can set assets and transfer from a to b" in {
test("判断合约容器返回交易执行结果的类型") {
val sysName = "121000005l35120456.node1"
val dbTag = "121000005l35120456.node1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val pm = system.actorOf(ModuleManagerOfCFRD.props("modulemanager", sysName, false, false, false), "modulemanager")
// 部署资产管理
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/ContractAssetsTPL.scala")
val l1 = try s1.mkString finally s1.close()
// 部署账户管理合约
val s2 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/ContractCert.scala")
val l2 = try s2.mkString finally s2.close()
val sm: SetMap = Map("121000005l35120456" -> 50, "12110107bi45jh675g" -> 50, "122000002n00123567" -> 50)
val sms = write(sm)
//val aa = new ContractCert
val tcs = Array(
Transfer("121000005l35120456", "12110107bi45jh675g", 5),
Transfer("121000005l35120456", "12110107bi45jh675g0", 5),
Transfer("121000005l35120456", "12110107bi45jh675g", 500))
val rcs = Array(None, "目标账户不存在", "余额不足")
val superAdmin = "951002007l78123233.super_admin"
// 初始化配置项主要是为了初始化存储路径
SystemProfile.initConfigSystem(system.settings.config, sysName)
// 加载node1的私钥
SignTool.loadPrivateKey(sysName, "123", "jks/" + sysName + ".jks")
// 加载super_admin的私钥
SignTool.loadPrivateKey(superAdmin, "super_admin", "jks/" + superAdmin + ".jks")
val signer = Signer("node2", "12110107bi45jh675g", "13856789234", Seq("node2"))
val cert = scala.io.Source.fromFile("jks/certs/12110107bi45jh675g.node2.cer")
val certStr = try cert.mkString finally cert.close()
val certinfo = CertInfo("12110107bi45jh675g", "node2", Certificate(certStr, "SHA1withECDSA", true, None, None))
//准备探针以验证调用返回结果
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
val sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
// 该处由于ContractAssetsTPL中判断用的ChainCodeIdName是用的系统设置因此现在暂定为系统设置的
val cid1 = ChaincodeId(SystemProfile.getAccountChaincodeName, 1)
val cid2 = ChaincodeId("ContractCert", 1)
//生成deploy交易
// 资产管理合约
val t1 = PeerHelper.createTransaction4Deploy(sysName, cid1, l1,
"", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
// 部署账户管理合约
val cid = ChaincodeId(SystemProfile.getAccountChaincodeName, 1)
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/did/RdidOperateAuthorizeTPL.scala")
val l1 = try s1.mkString finally s1.close()
val t1 = PeerHelper.createTransaction4Deploy(superAdmin, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_SYSTEM)
val msg_send1 = DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv1(0).err.isEmpty should be(true)
// 账户管理合约
val t2 = PeerHelper.createTransaction4Deploy(sysName, cid2, l2,
"", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send2 = DoTransaction(Seq[Transaction](t2), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send2)
// 生成invoke交易
// 注册账户
val t3 = PeerHelper.createTransaction4Invoke(sysName, cid2, ACTION.SignUpSigner, Seq(write(signer)))
val msg_send3 = DoTransaction(Seq[Transaction](t3), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send3)
//deploy紧接invoke测试
val msg_recv2 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv2(0).err.isEmpty should be(true)
val msg_recv3 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv3(0).err should be(None)
// 注册证书
val t4 = PeerHelper.createTransaction4Invoke(sysName, cid2, ACTION.SignUpCert, Seq(writePretty(certinfo)))
val msg_send4 = DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv4(0).err should be(None)
//生成invoke交易
val t5 = PeerHelper.createTransaction4Invoke(sysName, cid1, ACTION.set, Seq(sms))
val msg_send5 = DoTransaction(Seq[Transaction](t5), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send5)
val msg_recv5 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv5(0).err should be(None)
for (i <- 0 until tcs.length) {
val t6 = PeerHelper.createTransaction4Invoke(sysName, cid1, ACTION.transfer, Seq(write(tcs(i))))
val msg_send6 = DoTransaction(Seq[Transaction](t6), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send6)
val msg_recv6 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
if (msg_recv6(0).err.isEmpty && i == 0)
msg_recv6(0).err should be(rcs(0))
else
msg_recv6(0).err.get.cause.getMessage should be(rcs(i))
}
val msg_recv1 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
// 判断合约容器的返回类型
msg_recv1 shouldBe a[Seq[TransactionResult]]
}
}

View File

@ -18,25 +18,30 @@ package rep.sc
import akka.actor.ActorSystem
import akka.testkit.{TestKit, TestProbe}
import com.google.protobuf.timestamp.Timestamp
import org.json4s.native.Serialization.write
import org.json4s.{DefaultFormats, jackson}
import org.json4s.native.Serialization.{write, writePretty}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import rep.app.conf.SystemProfile
import rep.app.system.ClusterSystem
import rep.app.system.ClusterSystem.InitType
import rep.network.autotransaction.PeerHelper
import rep.network.module.cfrd.ModuleManagerOfCFRD
import rep.protos.peer.{Certificate, ChaincodeId, Signer, Transaction}
import rep.sc.TransferSpec.{ACTION, SetMap}
import rep.sc.tpl._
//.{CertStatus,CertInfo}
import rep.sc.tpl.Transfer
import rep.storage.ImpDataAccess
import rep.app.conf.SystemProfile
import scala.concurrent.duration._
import scala.collection.mutable.Map
import rep.sc.SandboxDispatcher.DoTransaction
import rep.crypto.Sha256
import rep.crypto.cert.SignTool
import rep.network.autotransaction.PeerHelper
import rep.network.tools.PeerExtension
import rep.protos.peer.Authorize.TransferType
import rep.protos.peer.Certificate.CertType
import rep.protos.peer.ChaincodeDeploy.ContractClassification
import rep.protos.peer.Operate.OperateType
import rep.protos.peer._
import rep.sc.SandboxDispatcher.DoTransaction
import rep.sc.TransferSpec.{ACTION, SetMap}
import rep.sc.tpl.Transfer
import rep.utils.{IdTool, SerializeUtils}
import scalapb.json4s.JsonFormat
import scala.collection.mutable.{ArrayBuffer, Map}
import scala.concurrent.duration._
object StateSpec {
@ -56,8 +61,7 @@ object StateSpec {
*
* @param _system
*/
class StateSpec(_system: ActorSystem)
extends TestKit(_system) with Matchers with FlatSpecLike with BeforeAndAfterAll {
class StateSpec(_system: ActorSystem) extends TestKit(_system) with Matchers with FlatSpecLike with BeforeAndAfterAll {
def this() = this(ActorSystem("StateSpec", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
@ -65,142 +69,204 @@ class StateSpec(_system: ActorSystem)
shutdown(system)
}
implicit val serialization = jackson.Serialization
// or native.Serialization
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
"ContractAssetsTPL" should "can set assets and transfer from a to b" in {
val sysName = "121000005l35120456.node1"
val dbTag = "121000005l35120456.node1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val pm = system.actorOf(ModuleManagerOfCFRD.props("modulemanager", sysName, false, false, false), "modulemanager")
val node2Name = "12110107bi45jh675g.node2"
val superAdmin = "951002007l78123233.super_admin"
// 初始化配置项主要是为了初始化存储路径
SystemProfile.initConfigSystem(system.settings.config, sysName)
PeerExtension(system).setSysTag(sysName)
// 加载node1的私钥
SignTool.loadPrivateKey(sysName, "123", "jks/" + sysName + ".jks")
// 加载node2的私钥
SignTool.loadPrivateKey(node2Name, "123", "jks/" + node2Name + ".jks")
// 加载super_admin的私钥
SignTool.loadPrivateKey(superAdmin, "super_admin", "jks/" + superAdmin + ".jks")
// 部署资产管理
val cid1 = ChaincodeId("ContractAssetsTPL", 1)
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/ContractAssetsTPL.scala")
val l1 = try s1.mkString finally s1.close()
// 部署账户管理合约
val s2 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/ContractCert.scala")
val cid2 = ChaincodeId(SystemProfile.getAccountChaincodeName, 1)
val s2 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/did/RdidOperateAuthorizeTPL.scala")
val l2 = try s2.mkString finally s2.close()
//准备探针以验证调用返回结果
val probe = TestProbe()
val sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
//生成deploy交易
val t1 = PeerHelper.createTransaction4Deploy(superAdmin, cid1, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send1 = DoTransaction(Seq[Transaction](t1), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv1(0).getResult.code should be(0)
val t2 = PeerHelper.createTransaction4Deploy(superAdmin, cid2, l2, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_SYSTEM)
val msg_send2 = DoTransaction(Seq[Transaction](t2), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv2(0).getResult.code should be(0)
// 注册账户
val superCert = scala.io.Source.fromFile("jks/certs/951002007l78123233.super_admin.cer", "UTF-8")
val superCertPem = try superCert.mkString finally superCert.close()
val superCertHash = Sha256.hashstr(superCertPem)
val superCertId = CertId("951002007l78123233", "super_admin")
var millis = System.currentTimeMillis()
//生成Did的身份证书
val superAuthCert = rep.protos.peer.Certificate(superCertPem, "SHA1withECDSA", true, Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, CertType.CERT_AUTHENTICATION, Option(superCertId), superCertHash, "1.0")
// 账户
val superSigner = Signer("super_admin", "951002007l78123233", "13856789234", Seq.empty, Seq.empty, Seq.empty, Seq.empty, List(superAuthCert), "", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t3 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.SignUpSigner, Seq(JsonFormat.toJsonString(superSigner)))
val msg_send3 = DoTransaction(Seq[Transaction](t3), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send3)
val msg_recv3 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv3(0).getResult.reason.isEmpty should be(true)
// 注册账户
val node1CertFile = scala.io.Source.fromFile("jks/certs/121000005l35120456.node1.cer", "UTF-8")
val node1CertPem = try node1CertFile.mkString finally node1CertFile.close()
val node1CertHash = Sha256.hashstr(node1CertPem)
val node1CertId = CertId("121000005l35120456", "node1")
millis = System.currentTimeMillis()
//生成Did的身份证书
val node1AuthCert = rep.protos.peer.Certificate(node1CertPem, "SHA1withECDSA", true, Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, CertType.CERT_AUTHENTICATION, Option(node1CertId), node1CertHash, "1.0")
// 账户
val node1Signer = Signer("node1", "121000005l35120456", "13856789234", Seq.empty, Seq.empty, Seq.empty, Seq.empty, List(node1AuthCert), "", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t9 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.SignUpSigner, Seq(JsonFormat.toJsonString(node1Signer)))
val msg_send9 = DoTransaction(Seq[Transaction](t9), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send9)
val msg_recv9 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv9.head.getResult.reason.isEmpty should be(true)
// 注册账户
val node2CertFile = scala.io.Source.fromFile("jks/certs/12110107bi45jh675g.node2.cer", "UTF-8")
val node2CertPem = try node2CertFile.mkString finally node2CertFile.close()
val node2CertHash = Sha256.hashstr(node2CertPem)
val node2CertId = CertId("12110107bi45jh675g", "node2")
millis = System.currentTimeMillis()
//生成Did的身份证书
val node2AuthCert = rep.protos.peer.Certificate(node2CertPem, "SHA1withECDSA", true, Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, CertType.CERT_AUTHENTICATION, Option(node2CertId), node2CertHash, "1.0")
// 账户
val node2Signer = Signer("node2", "12110107bi45jh675g", "13856789234", Seq.empty, Seq.empty, Seq.empty, Seq.empty, List(node2AuthCert), "", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t4 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.SignUpSigner, Seq(JsonFormat.toJsonString(node2Signer)))
val msg_send4 = DoTransaction(Seq[Transaction](t4), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv4.head.getResult.reason.isEmpty should be(true)
//生成invoke交易
val sm: SetMap = Map("121000005l35120456" -> 50, "12110107bi45jh675g" -> 50, "122000002n00123567" -> 50)
val sms = write(sm)
val t5 = PeerHelper.createTransaction4Invoke(superAdmin, cid1, ACTION.set, Seq(sms))
val msg_send5 = DoTransaction(Seq[Transaction](t5), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send5)
val msg_recv5 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv5(0).getResult.reason.isEmpty should be(true)
// superAdmin 为自己注册操作superAdmin不注册操作也能通过授权 目的是为了给其他用户授权
val snls = List("transaction.stream", "transaction.postTranByString", "transaction.postTranStream", "transaction.postTran")
// 公开操作无需授权
val transferOpt = rep.protos.peer.Operate(Sha256.hashstr("ContractAssetsTPL.transfer"), "转账交易", superAdmin.split("\\.")(0), true, OperateType.OPERATE_CONTRACT,
snls, "*", "ContractAssetsTPL.transfer", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t7 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, "signUpOperate", Seq(JsonFormat.toJsonString(transferOpt)))
probe.send(sandbox, DoTransaction(Seq[Transaction](t7), "test-db", TypeOfSender.FromPreloader))
val msg_recv7 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv7.head.getResult.reason.isEmpty should be(true)
//正常调用
val tcs = Array(
Transfer("121000005l35120456", "12110107bi45jh675g", 5),
Transfer("121000005l35120456", "12110107bi45jh675g0", 5),
Transfer("121000005l35120456", "12110107bi45jh675g", 500))
val rcs = Array(None, "目标账户不存在", "余额不足")
//val aa = new ContractCert
val signer = Signer("node2", "12110107bi45jh675g", "13856789234", Seq("node2"))
val cert = scala.io.Source.fromFile("jks/certs/12110107bi45jh675g.node2.cer")
val certStr = try cert.mkString finally cert.close()
val certinfo = CertInfo("12110107bi45jh675g", "node2", Certificate(certStr, "SHA1withECDSA", true, None, None))
//准备探针以验证调用返回结果
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
val sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
val cid2 = ChaincodeId(SystemProfile.getAccountChaincodeName, 1)
val cid1 = ChaincodeId("ContractAssetsTPL", 1)
//生成deploy交易
val t1 = PeerHelper.createTransaction4Deploy(sysName, cid1, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send1 = DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv1(0).err.isEmpty should be(true)
val t2 = PeerHelper.createTransaction4Deploy(sysName, cid2, l2, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send2 = DoTransaction(Seq[Transaction](t2), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv2(0).err.isEmpty should be(true)
// 生成invoke交易
// 注册账户
val t3 = PeerHelper.createTransaction4Invoke(sysName, cid2, ACTION.SignUpSigner, Seq(write(signer)))
val msg_send3 = DoTransaction(Seq[Transaction](t3), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send3)
val msg_recv3 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv3(0).err.isEmpty should be(true)
// 注册证书
val t4 = PeerHelper.createTransaction4Invoke(sysName, cid2, ACTION.SignUpCert, Seq(writePretty(certinfo)))
val msg_send4 = DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv4(0).err.isEmpty should be(true)
//生成invoke交易
val t5 = PeerHelper.createTransaction4Invoke(sysName, cid1, ACTION.set, Seq(sms))
val msg_send5 = DoTransaction(Seq[Transaction](t5), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send5)
val msg_recv5 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv5(0).err.isEmpty should be(true)
//正常调用
for (i <- 0 until 1) {
val t6 = PeerHelper.createTransaction4Invoke(sysName, cid1, ACTION.transfer, Seq(write(tcs(i))))
val msg_send6 = DoTransaction(Seq[Transaction](t6), "dbnumber", TypeOfSender.FromAPI)
val msg_send6 = DoTransaction(Seq[Transaction](t6), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send6)
val msg_recv6 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
if (msg_recv6(0).err.isEmpty && i == 0)
msg_recv6(0).err should be(rcs(0))
val msg_recv6 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
if (msg_recv6(0).getResult.reason.isEmpty && i == 0)
msg_recv6(0).getResult.reason.isEmpty should be(true)
else
msg_recv6(0).err.get.cause.getMessage should be(rcs(i))
msg_recv6(0).getResult.reason should be(rcs(i))
}
//非部署者无法禁用合约
val sysName2 = "12110107bi45jh675g.node2"
SignTool.loadPrivateKey("12110107bi45jh675g.node2", "123", "jks/12110107bi45jh675g.node2.jks")
var t = PeerHelper.createTransaction4State(sysName2, cid1, false)
var msg_send = DoTransaction(Seq[Transaction](t), "dbnumber", TypeOfSender.FromAPI)
probe.send(sandbox, msg_send)
var msg_recv = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv(0).err.get.cause.getMessage should be(SandboxDispatcher.ERR_CODER)
//部署者可以禁用合约
t = PeerHelper.createTransaction4State(sysName, cid1, false)
msg_send = DoTransaction(Seq[Transaction](t), "dbnumber", TypeOfSender.FromAPI)
// 不具有操作者不能禁用合约
var t = PeerHelper.createTransaction4State(node2Name, cid1, false)
var msg_send = DoTransaction(Seq[Transaction](t), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send)
msg_recv = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv4(0).err.isEmpty should be(true)
var msg_recv = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv(0).getResult.reason should equal(SandboxDispatcher.ERR_NO_OPERATE)
val setStateOpt = rep.protos.peer.Operate(Sha256.hashstr("ContractAssetsTPL.setState"), "修改合约状态", superAdmin.split("\\.")(0), isPublish = false, OperateType.OPERATE_CONTRACT,
snls, "*", "ContractAssetsTPL.setState", Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val t8 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, "signUpOperate", Seq(JsonFormat.toJsonString(setStateOpt)))
probe.send(sandbox, DoTransaction(Seq[Transaction](t8), "test-db", TypeOfSender.FromPreloader))
val msg_recv8 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv8.head.getResult.reason.isEmpty should be(true)
// superAdmin 为用户授权
val granteds = new ArrayBuffer[String]
granteds.+=(sysName.split("\\.")(0))
granteds.+=(node2Name.split("\\.")(0))
millis = System.currentTimeMillis()
val at = rep.protos.peer.Authorize(IdTool.getRandomUUID, superAdmin.split("\\.")(0), granteds, Seq(Sha256.hashstr("ContractAssetsTPL.setState")),
TransferType.TRANSFER_REPEATEDLY, Option(Timestamp(millis / 1000, ((millis % 1000) * 1000000).toInt)), None, true, "1.0")
val als: List[String] = List(JsonFormat.toJsonString(at))
val t10 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, "grantOperate", Seq(SerializeUtils.compactJson(als)))
probe.send(sandbox, DoTransaction(Seq[Transaction](t10), "test-db", TypeOfSender.FromPreloader))
val msg_recv10 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv10.head.getResult.reason.isEmpty should be(true)
//被授权者可以禁用合约
val t11 = PeerHelper.createTransaction4State(node2Name, cid1, state = false)
val msg_send11 = DoTransaction(Seq[Transaction](t11), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send11)
val msg_recv11 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv11(0).getResult.reason.isEmpty should be(true)
//禁用合约之后无法Invoke合约
for (i <- 0 until 1) {
val t6 = PeerHelper.createTransaction4Invoke(sysName, cid1, ACTION.transfer, Seq(write(tcs(i))))
val msg_send6 = DoTransaction(Seq[Transaction](t6), "dbnumber", TypeOfSender.FromAPI)
val msg_send6 = DoTransaction(Seq[Transaction](t6), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send6)
val msg_recv6 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv6(0).err.get.cause.getMessage should be(SandboxDispatcher.ERR_DISABLE_CID)
val msg_recv6 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv6(0).getResult.reason should be(SandboxDispatcher.ERR_DISABLE_CID)
}
//非部署者无法启用合约
t = PeerHelper.createTransaction4State(sysName2, cid1, true)
msg_send = DoTransaction(Seq[Transaction](t), "dbnumber", TypeOfSender.FromAPI)
t = PeerHelper.createTransaction4State(node2Name, cid1, true)
msg_send = DoTransaction(Seq[Transaction](t), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send)
msg_recv = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv(0).err.get.cause.getMessage should be(SandboxDispatcher.ERR_CODER)
msg_recv = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv(0).getResult.reason should be(SandboxDispatcher.ERR_CODER)
//部署者可以启用合约
t = PeerHelper.createTransaction4State(sysName, cid1, true)
msg_send = DoTransaction(Seq[Transaction](t), "dbnumber", TypeOfSender.FromAPI)
msg_send = DoTransaction(Seq[Transaction](t), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send)
msg_recv = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv4(0).err.isEmpty should be(true)
msg_recv = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv4(0).result.isEmpty should be(true)
//启用合约之后,可以Invoke合约
for (i <- 0 until 1) {
val t6 = PeerHelper.createTransaction4Invoke(sysName, cid1, ACTION.transfer, Seq(write(tcs(i))))
val msg_send6 = DoTransaction(Seq[Transaction](t6), "dbnumber", TypeOfSender.FromAPI)
val msg_send6 = DoTransaction(Seq[Transaction](t6), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send6)
val msg_recv6 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
if (msg_recv6(0).err.isEmpty && i == 0)
msg_recv6(0).err should be(rcs(0))
val msg_recv6 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
if (msg_recv6(0).result.isEmpty && i == 0)
msg_recv6(0).result.isEmpty should be(true)
else
msg_recv6(0).err.get.cause.getMessage should be(rcs(i))
msg_recv6(0).getResult.reason should equal(rcs(i))
}
}
}

View File

@ -16,34 +16,28 @@
package rep.sc
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import akka.actor.ActorSystem
import akka.testkit.TestKit
import scala.concurrent.Await
import scala.concurrent.duration._
import rep.protos.peer._
import rep.sc.Sandbox._
import akka.testkit.{TestKit, TestProbe}
import org.json4s.native.Serialization.{write, writePretty}
import org.json4s.{DefaultFormats, jackson}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import rep.app.conf.SystemProfile
import rep.app.system.ClusterSystem
import rep.app.system.ClusterSystem.InitType
import org.json4s.{DefaultFormats, jackson}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._
import rep.crypto.cert.SignTool
import rep.network.autotransaction.PeerHelper
import rep.network.module.cfrd.ModuleManagerOfCFRD
import rep.protos.peer.ChaincodeDeploy.ContractClassification
import rep.protos.peer._
import rep.sc.SandboxDispatcher.DoTransaction
import rep.sc.tpl.SupplyType._
import rep.storage.ImpDataAccess
import rep.utils.SerializeUtils.deserialise
import java.nio.ByteBuffer
import java.io.IOException
import java.io.PrintWriter
import java.io.FileWriter
import java.io.File
import rep.utils.SerializeUtils.{deserialise, toJson}
import scalapb.json4s.JsonFormat
import scala.collection.mutable.Map
import org.json4s.{DefaultFormats, Formats, jackson}
import org.json4s.native.Serialization.writePretty
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import rep.network.autotransaction.PeerHelper
import scala.concurrent.Await
import scala.concurrent.duration._
/** 合约容器实现的单元测试
*
@ -51,98 +45,91 @@ import rep.network.autotransaction.PeerHelper
* @param _system 测试用例所在的actor System.
*
*/
class SupplySpec(_system: ActorSystem)
extends TestKit(_system)
with Matchers
with FlatSpecLike
with BeforeAndAfterAll {
class SupplySpec(_system: ActorSystem) extends TestKit(_system) with Matchers with FlatSpecLike with BeforeAndAfterAll {
import rep.sc.Sandbox.DoTransactionResult
import rep.sc.SandboxDispatcher.DoTransaction
import akka.testkit.TestProbe
import akka.testkit.TestActorRef
import Json4sSupport._
import rep.sc.tpl.SupplyType._
import rep.utils.SerializeUtils.toJson
implicit val serialization = jackson.Serialization
// or native.Serialization
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
def this() = this(ActorSystem("SandBoxSpec", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
def this() = this(ActorSystem("SupplySpec", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
override def afterAll: Unit = Await.ready(system.terminate(), Duration.Inf)
//Scala实现的资产管理合约测试包括合约的部署调用结果返回验证
"container" should "deploy supply contract and call it for splitting then" in {
"container" can "deploy supply contract and call it for splitting then" in {
val sysName = "121000005l35120456.node1"
val dbTag = "121000005l35120456.node1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val pm = system.actorOf(ModuleManagerOfCFRD.props("modulemanager", sysName, false, false, false), "modulemanager")
//加载合约脚本
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/SupplyTPL.scala")
val l1 = try s1.mkString finally s1.close()
val superAdmin = "951002007l78123233.super_admin"
// 初始化配置项主要是为了初始化存储路径
SystemProfile.initConfigSystem(system.settings.config, sysName)
// 加载node1的私钥
SignTool.loadPrivateKey(sysName, "123", "jks/" + sysName + ".jks")
// 加载super_admin的私钥
SignTool.loadPrivateKey(superAdmin, "super_admin", "jks/" + superAdmin + ".jks")
val fm: FixedMap = Map("A" -> 0.2, "B" -> 0.2, "C" -> 0.1, "D" -> 0.1)
val sm: ShareMap = Map("A" -> Array(new ShareRatio(0, 100, 0.1, 0), new ShareRatio(100, 10000, 0.15, 0)),
"B" -> Array(new ShareRatio(0, 10000, 0, 10)),
"C" -> Array(new ShareRatio(0, 10000, 0.1, 0)),
"D" -> Array(new ShareRatio(0, 100, 0, 10), new ShareRatio(100, 10000, 0.15, 0)))
val sm: ShareMap = Map(
"A" -> Array(ShareRatio(0, 100, 0.1, 0), ShareRatio(100, 10000, 0.15, 0)),
"B" -> Array(ShareRatio(0, 10000, 0, 10)),
"C" -> Array(ShareRatio(0, 10000, 0.1, 0)),
"D" -> Array(ShareRatio(0, 100, 0, 10), ShareRatio(100, 10000, 0.15, 0))
)
val account_remain = "R"
val account_sales1 = "S1"
val account_sales2 = "S2"
val product_id = "P201806270001"
//构造签约交易合约模版1输入json字符串销售1选择了合约模版1
val ipt2 = new IPTSignFixed(account_sales1, product_id, account_remain, fm)
val ipt2 = IPTSignFixed(account_sales1, product_id, account_remain, fm)
val l2 = write(ipt2)
//构造签约交易合约模版2输入json字符串销售2选择了合约模版2
val ipt3 = new IPTSignShare(account_sales2, product_id, account_remain, sm)
//构造签约交易合约模版2输入json字符串销售2选择了合约模版2
val ipt3 = IPTSignShare(account_sales2, product_id, account_remain, sm)
val l3 = writePretty(ipt3)
//准备探针以验证调用返回结果
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
var sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
// val db = ImpDataAccess.GetDataAccess(sysName)
val sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
//生成deploy交易
//加载合约脚本
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/SupplyTPL.scala")
val l1 = try s1.mkString finally s1.close()
val cid = new ChaincodeId("Supply", 1)
val t1 = PeerHelper.createTransaction4Deploy(sysName, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send1 = new DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
//生成deploy交易
val t1 = PeerHelper.createTransaction4Deploy(superAdmin, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send1 = DoTransaction(Seq[Transaction](t1), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val ol1 = msg_recv1(0).ol
val msg_recv1 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
val ol1 = msg_recv1.head.ol
//生成invoke交易
//获取deploy生成的chainCodeId
//初始化资产
val t2 = PeerHelper.createTransaction4Invoke(sysName, cid, ACTION.SignFixed, Seq(l2))
val msg_send2 = new DoTransaction(Seq[Transaction](t2), "dbnumber", TypeOfSender.FromAPI)
val t2 = PeerHelper.createTransaction4Invoke(superAdmin, cid, ACTION.SignFixed, Seq(l2))
val msg_send2 = DoTransaction(Seq[Transaction](t2), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val msg_recv2 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
val t3 = PeerHelper.createTransaction4Invoke(sysName, cid, ACTION.SignShare, Seq(l3))
val msg_send3 = new DoTransaction(Seq[Transaction](t3), "dbnumber", TypeOfSender.FromAPI)
val t3 = PeerHelper.createTransaction4Invoke(superAdmin, cid, ACTION.SignShare, Seq(l3))
val msg_send3 = DoTransaction(Seq[Transaction](t3), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send3)
val msg_recv3 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val msg_recv3 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
//测试各种金额下的分账结果
val sr = Array(100, 200, 500, 1000)
for (el <- sr) {
//构造分账交易
val ipt4 = new IPTSplit(account_sales1, product_id, el)
val ipt4 = IPTSplit(account_sales1, product_id, el)
val l4 = write(ipt4)
val t4 = PeerHelper.createTransaction4Invoke(sysName, cid, ACTION.Split, Seq(l4))
val msg_send4 = new DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
val t4 = PeerHelper.createTransaction4Invoke(superAdmin, cid, ACTION.Split, Seq(l4))
val msg_send4 = DoTransaction(Seq[Transaction](t4), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val ol4 = msg_recv4(0).ol
val ol4str = toJson(ol4)
println(s"oper log:${ol4str}")
val msg_recv4 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
val ol4 = msg_recv4.head.ol
for (elem <- ol4) {
val elemStr = JsonFormat.toJsonString(elem)
println(s"oper log:$elemStr")
}
//分账之后总额应保持一致
var total = 0
ol4.foreach {
@ -151,21 +138,22 @@ class SupplySpec(_system: ActorSystem)
if (ol.oldValue != null)
total -= deserialise(ol.oldValue.toByteArray()).asInstanceOf[Int]
}
total should be(el)
total should equal(el)
}
for (el <- sr) {
//构造分账交易
val ipt4 = new IPTSplit(account_sales2, product_id, el)
val l4 = write(ipt4)
val t4 = PeerHelper.createTransaction4Invoke(sysName, cid, ACTION.Split, Seq(l4))
val msg_send4 = new DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
val t4 = PeerHelper.createTransaction4Invoke(superAdmin, cid, ACTION.Split, Seq(l4))
val msg_send4 = DoTransaction(Seq[Transaction](t4), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val ol4 = msg_recv4(0).ol
val ol4str = toJson(ol4)
println(s"oper log:${ol4str}")
val msg_recv4 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
val ol4 = msg_recv4.head.ol
for (elem <- ol4) {
val elemStr = JsonFormat.toJsonString(elem)
println(s"oper log:$elemStr")
}
//分账之后总额应保持一致
var total = 0
ol4.foreach {

View File

@ -16,34 +16,26 @@
package rep.sc
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import akka.actor.ActorSystem
import akka.testkit.TestKit
import scala.concurrent.Await
import scala.concurrent.duration._
import rep.protos.peer._
import rep.sc.Sandbox._
import akka.testkit.{TestKit, TestProbe}
import org.json4s.native.Serialization.{write, writePretty}
import org.json4s.{DefaultFormats, jackson}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import rep.app.conf.SystemProfile
import rep.app.system.ClusterSystem
import rep.app.system.ClusterSystem.InitType
import org.json4s.{DefaultFormats, jackson}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._
import rep.network.module.cfrd.ModuleManagerOfCFRD
import rep.storage.ImpDataAccess
import rep.utils.SerializeUtils.deserialise
import java.nio.ByteBuffer
import java.io.IOException
import java.io.PrintWriter
import java.io.FileWriter
import java.io.File
import rep.crypto.cert.SignTool
import rep.network.autotransaction.PeerHelper
import rep.protos.peer.ChaincodeDeploy.ContractClassification
import rep.protos.peer._
import rep.sc.SandboxDispatcher.DoTransaction
import rep.sc.tpl.SupplyType._
import rep.utils.SerializeUtils.{deserialise, toJson}
import scalapb.json4s.JsonFormat
import scala.collection.mutable.Map
import org.json4s.{DefaultFormats, Formats, jackson}
import org.json4s.native.Serialization.writePretty
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import rep.network.autotransaction.PeerHelper
import scala.concurrent.Await
import scala.concurrent.duration._
/** 合约容器实现的单元测试
*
@ -51,122 +43,120 @@ import rep.network.autotransaction.PeerHelper
* @param _system 测试用例所在的actor System.
*
*/
class SupplySpec2(_system: ActorSystem)
extends TestKit(_system)
with Matchers
with FlatSpecLike
with BeforeAndAfterAll {
class SupplySpec2(_system: ActorSystem) extends TestKit(_system) with Matchers with FlatSpecLike with BeforeAndAfterAll {
import rep.sc.Sandbox.DoTransactionResult
import rep.sc.SandboxDispatcher.DoTransaction
import akka.testkit.TestProbe
import akka.testkit.TestActorRef
import Json4sSupport._
import rep.sc.tpl.SupplyType._
import rep.utils.SerializeUtils.toJson
implicit val serialization = jackson.Serialization
// or native.Serialization
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
def this() = this(ActorSystem("SandBoxSpec", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
def this() = this(ActorSystem("SupplySpec2", new ClusterSystem("121000005l35120456.node1", InitType.MULTI_INIT, false).getConf))
override def afterAll: Unit = Await.ready(system.terminate(), Duration.Inf)
//Scala实现的资产管理合约测试包括合约的部署调用结果返回验证
"container" should "update contract & share kv" in {
"container" can "update contract & share kv" in {
val sysName = "121000005l35120456.node1"
val dbTag = "121000005l35120456.node1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val pm = system.actorOf(ModuleManagerOfCFRD.props("modulemanager", sysName, false, false, false), "modulemanager")
//加载合约脚本
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/SupplyTPL2.scala")
val l1 = try s1.mkString finally s1.close()
val s7 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/SupplyTPL3.scala")
val l7 = try s7.mkString finally s7.close()
val superAdmin = "951002007l78123233.super_admin"
// 初始化配置项主要是为了初始化存储路径
SystemProfile.initConfigSystem(system.settings.config, sysName)
// 加载node1的私钥
SignTool.loadPrivateKey(sysName, "123", "jks/" + sysName + ".jks")
// 加载super_admin的私钥
SignTool.loadPrivateKey(superAdmin, "super_admin", "jks/" + superAdmin + ".jks")
val fm: FixedMap = Map("A" -> 0.2, "B" -> 0.2, "C" -> 0.1, "D" -> 0.1)
val sm: ShareMap = Map("A" -> Array(new ShareRatio(0, 100, 0.1, 0), new ShareRatio(100, 10000, 0.15, 0)),
"B" -> Array(new ShareRatio(0, 10000, 0, 10)),
"C" -> Array(new ShareRatio(0, 10000, 0.1, 0)),
"D" -> Array(new ShareRatio(0, 100, 0, 10), new ShareRatio(100, 10000, 0.15, 0)))
val sm: ShareMap = Map(
"A" -> Array(ShareRatio(0, 100, 0.1, 0), ShareRatio(100, 10000, 0.15, 0)),
"B" -> Array(ShareRatio(0, 10000, 0, 10)),
"C" -> Array(ShareRatio(0, 10000, 0.1, 0)),
"D" -> Array(ShareRatio(0, 100, 0, 10), ShareRatio(100, 10000, 0.15, 0))
)
val account_remain = "R"
val account_sales1 = "S1"
val account_sales2 = "S2"
val product_id = "P201806270001"
//构造签约交易合约模版1输入json字符串销售1选择了合约模版1
val ipt2 = new IPTSignFixed(account_sales1, product_id, account_remain, fm)
val ipt2 = IPTSignFixed(account_sales1, product_id, account_remain, fm)
val l2 = write(ipt2)
//构造签约交易合约模版2输入json字符串销售2选择了合约模版2
val ipt3 = new IPTSignShare(account_sales2, product_id, account_remain, sm)
//构造签约交易合约模版2输入json字符串销售2选择了合约模版2
val ipt3 = IPTSignShare(account_sales2, product_id, account_remain, sm)
val l3 = writePretty(ipt3)
//准备探针以验证调用返回结果
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
var sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
// val db = ImpDataAccess.GetDataAccess(sysName)
val sandbox = system.actorOf(TransactionDispatcher.props("transactiondispatcher"), "transactiondispatcher")
//生成deploy交易
val cid = new ChaincodeId("Supply", 1)
val t1 = PeerHelper.createTransaction4Deploy(sysName, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
val msg_send1 = new DoTransaction(Seq[Transaction](t1), "dbnumber", TypeOfSender.FromAPI)
//加载合约脚本
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/SupplyTPL2.scala")
val l1 = try s1.mkString finally s1.close()
val cid = ChaincodeId("Supply", 2)
val t1 = PeerHelper.createTransaction4Deploy(superAdmin, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
val msg_send1 = DoTransaction(Seq[Transaction](t1), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val msg_recv1 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
val ol1 = msg_recv1(0).ol
//生成invoke交易
//获取deploy生成的chainCodeId
//初始化资产
val t2 = PeerHelper.createTransaction4Invoke(sysName, cid, ACTION.SignFixed, Seq(l2))
val msg_send2 = new DoTransaction(Seq[Transaction](t2), "dbnumber", TypeOfSender.FromAPI)
val t2 = PeerHelper.createTransaction4Invoke(superAdmin, cid, ACTION.SignFixed, Seq(l2))
val msg_send2 = DoTransaction(Seq[Transaction](t2), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
//由于版本1支持SignFixed 分账方法,因此能够正确处理
msg_recv2(0).err should be(None)
val msg_recv2 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
//由于版本2支持SignFixed 分账方法,因此能够正确处理
msg_recv2(0).getResult.code should be(0)
var t = PeerHelper.createTransaction4Invoke(sysName, cid, ACTION.SignShare, Seq(l3))
var msg_send = new DoTransaction(Seq[Transaction](t), "dbnumber", TypeOfSender.FromAPI)
var t = PeerHelper.createTransaction4Invoke(superAdmin, cid, ACTION.SignShare, Seq(l3))
var msg_send = DoTransaction(Seq[Transaction](t), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send)
var msg_recv = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
//由于版本1不支持SignShare 分账方法,因此无法正确处理
msg_recv(0).err should not be None
var msg_recv = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
//由于版本2不支持SignShare 分账方法,因此无法正确处理
msg_recv(0).getResult.code should be(102)
//部署版本2
val cid2 = new ChaincodeId("Supply", 2)
t = PeerHelper.createTransaction4Deploy(sysName, cid2, l7, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
msg_send = new DoTransaction(Seq[Transaction](t), "dbnumber", TypeOfSender.FromAPI)
//部署版本3
val s7 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/SupplyTPL3.scala")
val l7 = try s7.mkString finally s7.close()
val cid2 = new ChaincodeId("Supply", 3)
t = PeerHelper.createTransaction4Deploy(superAdmin, cid2, l7, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA, ContractClassification.CONTRACT_CUSTOM)
msg_send = DoTransaction(Seq[Transaction](t), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send)
msg_recv = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
msg_recv(0).err should be(None)
msg_recv = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
msg_recv(0).getResult.reason.isEmpty should be(true)
t = PeerHelper.createTransaction4Invoke(sysName, cid2, ACTION.SignShare, Seq(l3))
msg_send = new DoTransaction(Seq[Transaction](t), "dbnumber", TypeOfSender.FromAPI)
t = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.SignShare, Seq(l3))
msg_send = DoTransaction(Seq[Transaction](t), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send)
msg_recv = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
//由于版本2支持SignShare 分账方法,因此正确处理
msg_recv(0).err.isEmpty should be(true)
msg_recv = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
//由于版本3支持SignShare 分账方法,因此正确处理
msg_recv(0).getResult.reason.isEmpty should be(true)
t = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.SignFixed, Seq(l3))
msg_send = DoTransaction(Seq[Transaction](t), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send)
msg_recv = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
//由于版本3不支持SignFiexed 分账方法,因此无法正确处理
msg_recv(0).getResult.code should be(102)
//测试各种金额下的分账结果
val sr = Array(100, 200, 500, 1000)
for (el <- sr) {
//构造分账交易
val ipt4 = new IPTSplit(account_sales1, product_id, el)
val ipt4 = IPTSplit(account_sales1, product_id, el)
val l4 = write(ipt4)
val t4 = PeerHelper.createTransaction4Invoke(sysName, cid, ACTION.Split, Seq(l4))
val msg_send4 = new DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
val t4 = PeerHelper.createTransaction4Invoke(superAdmin, cid, ACTION.Split, Seq(l4))
val msg_send4 = DoTransaction(Seq[Transaction](t4), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val msg_recv4 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
val ol4 = msg_recv4(0).ol
val ol4str = toJson(ol4)
println(s"oper log:${ol4str}")
for (elem <- ol4) {
val elemStr = JsonFormat.toJsonString(elem)
println(s"oper log:$elemStr")
}
//分账之后总额应保持一致
var total = 0
ol4.foreach {
@ -182,14 +172,15 @@ class SupplySpec2(_system: ActorSystem)
//构造分账交易
val ipt4 = new IPTSplit(account_sales2, product_id, el)
val l4 = write(ipt4)
val t4 = PeerHelper.createTransaction4Invoke(sysName, cid2, ACTION.Split, Seq(l4))
val msg_send4 = new DoTransaction(Seq[Transaction](t4), "dbnumber", TypeOfSender.FromAPI)
val t4 = PeerHelper.createTransaction4Invoke(superAdmin, cid2, ACTION.Split, Seq(l4))
val msg_send4 = DoTransaction(Seq[Transaction](t4), "test-db", TypeOfSender.FromPreloader)
probe.send(sandbox, msg_send4)
val msg_recv4 = probe.expectMsgType[Seq[Sandbox.DoTransactionResult]](1000.seconds)
val msg_recv4 = probe.expectMsgType[Seq[TransactionResult]](1000.seconds)
val ol4 = msg_recv4(0).ol
val ol4str = toJson(ol4)
println(s"oper log:${ol4str}")
for (elem <- ol4) {
val elemStr = JsonFormat.toJsonString(elem)
println(s"oper log:$elemStr")
}
//分账之后总额应保持一致
var total = 0
ol4.foreach {