Merge remote-tracking branch 'origin/dev_jby_preview' into yf_preview

# Conflicts:
#	conf/system.conf
This commit is contained in:
brightestboy 2019-03-17 10:48:45 +08:00
commit 5c6ae5e97e
10 changed files with 147 additions and 224 deletions

View File

@ -97,7 +97,7 @@ system {
vote_node_list = ["121000005l35120456.node1","2","3","4"]
}
account{
chaincodename = "ACCOUNTCHAINCODENAME"//账户管理合约的名称
chaincodename = "REPCHAINACCOUNTMGR"//账户管理合约的名称
accountversion = 1
}

View File

@ -82,17 +82,17 @@ message ChaincodeId {
// ,/
message ChaincodeDeploy {
//Type only support javascript
int32 timeout = 3;
int32 timeout = 1;
//
string code_package = 4;
string code_package = 2;
//
string legal_prose =5;
string legal_prose =3;
enum CodeType {
CODE_UNDEFINED = 0;
CODE_JAVASCRIPT = 1;
CODE_SCALA = 2;
}
CodeType ctype = 6;
CodeType ctype = 4;
}
/*

View File

@ -23,6 +23,7 @@ import java.io._
import java.util.{ ArrayList, List }
import rep.app.conf.SystemProfile
import scala.util.control.Breaks._
import fastparse.utils.Base64
/**
* 负责签名和验签的工具了所有相关的功能都调用该类
@ -168,4 +169,19 @@ object SignTool {
})
r
}
def getCertByPem(pemcert: String): Certificate = {
val cf = CertificateFactory.getInstance("X.509")
val cert = cf.generateCertificate(
new ByteArrayInputStream(
Base64.Decoder(pemcert.replaceAll("\r\n", "").stripPrefix("-----BEGIN CERTIFICATE-----").stripSuffix("-----END CERTIFICATE-----")).toByteArray))
cert
}
def getCertByFile(path:String):Certificate = {
val certF = CertificateFactory.getInstance("X.509")
val fileInputStream = new FileInputStream(path)
certF.generateCertificate(fileInputStream)
}
}

View File

@ -97,7 +97,10 @@ object PeerHelper {
if (chaincodeId == null) t
val txid = IdTool.getUUID()
val cip = new ChaincodeDeploy(timeout, spcPackage, legal_prose, ctype)
var cip = new ChaincodeDeploy(timeout)
cip = cip.withCodePackage(spcPackage)
cip = cip.withLegalProse(legal_prose)
cip = cip.withCtype(ctype)
t = t.withId(txid)
t = t.withCid(chaincodeId)
t = t.withSpec(cip)

View File

@ -76,7 +76,7 @@ object Sandbox {
* @return 链码id字符串
*/
def getChaincodeId(c: ChaincodeId): String={
c.chaincodeName + SplitChainCodeId + c.version
IdTool.getCid(c)
}
/** 从部署合约的交易获得其部署的合约的链码id
* @param t 交易对象

View File

@ -22,13 +22,14 @@ import org.json4s.jackson.JsonMethods._
import rep.sc.contract._
import rep.sc.contract.ContractContext
import rep.sc.contract.IContract
import rep.app.conf.SystemProfile
/**
* 资产管理合约
*/
class ContractAssetsTPL extends IContract{
case class Transfer(from:String, to:String, amount:Int)
val prefix = SystemProfile.getAccountChaincodeName
implicit val formats = DefaultFormats
@ -45,10 +46,15 @@ case class Transfer(from:String, to:String, amount:Int)
}
def transfer(ctx: ContractContext, data:Transfer) :ActionResult={
if(!data.from.equals(ctx.t.getSignature.getCertId.creditCode))
return new ActionResult(-1, Some("只允许从本人账户转出"))
val signerKey = prefix + "_" + data.to
if(ctx.api.getVal(signerKey)==null)
return new ActionResult(-2, Some("目标账户不存在"))
val sfrom = ctx.api.getVal(data.from)
var dfrom =sfrom.toString.toInt
var dfrom =sfrom.asInstanceOf[Int]
if(dfrom < data.amount)
new ActionResult(-1, Some("余额不足"))
new ActionResult(-3, Some("余额不足"))
var dto = ctx.api.getVal(data.to).toString.toInt
ctx.api.setVal(data.from,dfrom - data.amount)
ctx.api.setVal(data.to,dto + data.amount)

View File

@ -17,6 +17,10 @@ import rep.utils.{IdTool, SerializeUtils}
/**
* @author zyf
*/
// 证书状态
case class CertStatus(credit_code: String, name: String, status: Boolean)
case class CertInfo(credit_code: String,name: String, cert: Certificate)
class ContractCert extends IContract {
implicit val formats = DefaultFormats
@ -41,9 +45,7 @@ class ContractCert extends IContract {
val UpdateSigner = "UpdateSigner"
}
// 证书状态
case class CertStatus(credit_code: String, name: String, status: Boolean)
case class CertInfo(credit_code: String,name: String, cert: Certificate)
/**
* 注册Signer账户

View File

@ -30,6 +30,7 @@ import org.json4s.DefaultFormats._
import rep.network.consensus.block.BlockHelper
import rep.crypto.cert.SignTool
import scala.collection.mutable
import rep.sc.tpl._
/**
* 用于生成创世块json文件,该json文件可以在链初始化时由节点加载
@ -42,39 +43,62 @@ object GenesisBuilder {
implicit val formats = DefaultFormats
def main(args: Array[String]): Unit = {
SignTool.loadPrivateKey("121000005L35120456.node1", "123", "jks/121000005L35120456.node1.jks")
SignTool.loadPrivateKey("121000005l35120456.node1", "123", "jks/121000005l35120456.node1.jks")
SignTool.loadNodeCertList("changeme", "jks/mytruststore.jks")
SignTool.loadPrivateKey("951002007L78123233.super_admin", "super_admin", "jks/951002007L78123233.super_admin.jks")
SignTool.loadPrivateKey("951002007l78123233.super_admin", "super_admin", "jks/951002007l78123233.super_admin.jks")
val sysName = "121000005l35120456.node1"
//交易发起人是超级管理员
//增加scala的资产管理合约
// read deploy funcs
val s1 = scala.io.Source.fromFile("src/main/scala/ContractAssetsTPL.scala")
val s1 = scala.io.Source.fromFile("src/main/scala/rep/sc/tpl/ContractCert.scala")
val l1 = try s1.mkString finally s1.close()
//todo 运行时请定义名称
val chaincodeId = new ChaincodeId("chaincodename_1",1)
val t1 = PeerHelper.createTransaction4Deploy("super_admin", chaincodeId, l1, "",
100, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
//val t1 = transactionCreator("super_admin", rep.protos.peer.Transaction.Type.CHAINCODE_DEPLOY,
// "", "", List(), l1, None, rep.protos.peer.ChaincodeSpec.CodeType.CODE_SCALA)
// read invoke scala contract
val s2 = scala.io.Source.fromFile("scripts/set.json")
val l2 = try s2.mkString finally s2.close()
val t2 = PeerHelper.createTransaction4Invoke("super_admin", chaincodeId, "set",Seq(l2))
val cid = new ChaincodeId("REPCHAINACCOUNTMGR",1)
var translist : Array[Transaction] = new Array[Transaction] (13)
val dep_trans = PeerHelper.createTransaction4Deploy(sysName, cid,
l1, "",5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_SCALA)
translist(0) = dep_trans
System.out.println(Json4s.compactJson(dep_trans))
var signers : Array[Signer] = new Array[Signer](6)
signers(0) = Signer("node1","121000005l35120456","18912345678",List("node1"))
signers(1) = Signer("node2","12110107bi45jh675g","18912345678",List("node2"))
signers(2) = Signer("node3","122000002n00123567","18912345678",List("node3"))
signers(3) = Signer("node4","921000005k36123789","18912345678",List("node4"))
signers(4) = Signer("node5","921000006e0012v696","18912345678",List("node5"))
signers(5) = Signer("super_admin","951002007l78123233","18912345678",List("super_admin"))
for(i<-0 to 5){
translist(i+1) = PeerHelper.createTransaction4Invoke("951002007l78123233.super_admin", cid,
"signUpSigner", Seq(Json4s.compactJson(signers(i))))
}
for(i<-0 to 5){
//val certfile = scala.io.Source.fromFile("jks/"+signers(i).creditCode+"."+signers(i).name+".cer")
//val certstr = try certfile.mkString finally certfile.close()
val cert = SignTool.getCertByFile("jks/"+signers(i).creditCode+"."+signers(i).name+".cer")
val millis = System.currentTimeMillis()
val tmp = rep.protos.peer.Certificate(Json4s.compactJson(cert),"SHA1withECDSA",true,Option(Timestamp(millis/1000 , ((millis % 1000) * 1000000).toInt)))
val a : CertInfo = CertInfo(signers(i).creditCode,signers(i).name,tmp)
translist(i+7) = PeerHelper.createTransaction4Invoke("951002007l78123233.super_admin", cid,
"signUpSigner", Seq(Json4s.compactJson(a)))
}
//val t2 = transactionCreator("super_admin",rep.protos.peer.Transaction.Type.CHAINCODE_INVOKE,
// "", "set" ,Seq(l2),"", Option(t1.payload.get.chaincodeID.get.name))
//create gensis block
val millis = ConfigFactory.load().getLong("akka.genesisblock.creationBlockTime")
var blk = new Block(1, 1,
List(t1,t2),
Seq(),
_root_.com.google.protobuf.ByteString.EMPTY, _root_.com.google.protobuf.ByteString.EMPTY)
var blk = new Block(1,1,translist,Seq(),_root_.com.google.protobuf.ByteString.EMPTY,
_root_.com.google.protobuf.ByteString.EMPTY)
//获得管理员证书和签名
// val (priKA, pubKA, certA) = ECDSASign.getKeyPair("super_admin")
// val (prik, pubK, cert) = ECDSASign.getKeyPair("1")
@ -83,8 +107,9 @@ object GenesisBuilder {
//val blk_hash = Sha256.hash(blk.toByteArray)
//超级管理员背书角色
//创建者背书1
blk = blk.withEndorsements(Seq(BlockHelper.endorseBlock4NonHash(blk_hash,"super_admin"),
BlockHelper.endorseBlock4NonHash(blk_hash,"1")))
blk = blk.withEndorsements(Seq(
BlockHelper.endorseBlock4NonHash(blk_hash,"951002007l78123233.super_admin"),
BlockHelper.endorseBlock4NonHash(blk_hash,"121000005l35120456.node1")))
// blk = blk.withConsensusMetadata(Seq(Endorsement(ByteString.copyFromUtf8(ECDSASign.getBitcoinAddrByCert(certA)),
// ByteString.copyFrom(ECDSASign.sign(priKA, blk_hash))),
// Endorsement(ByteString.copyFromUtf8(ECDSASign.getBitcoinAddrByCert(cert)),ByteString.copyFrom(ECDSASign.sign(prik,blk_hash)))))
@ -92,6 +117,7 @@ object GenesisBuilder {
val r = JsonFormat.toJson(blk)
val rstr = pretty(render(r))
println(rstr)
// println(Json4s.compactJson(blk))
val blk2 = JsonFormat.fromJsonString[Block](rstr)
val t = blk2.transactions.head
// println(t.cert.toStringUtf8)

View File

@ -1,57 +1,57 @@
/*
* Copyright 2018 Blockchain Technology and Application Joint Lab, Linkel Technology Co., Ltd, Beijing, Fintech Research Center of ISCAS.
* 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" BA SIS,
* 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.
*
*/
package rep.utils
/**
* @author c4w
*/
object Json4s {
import org.json4s._
def encodeJson(src: Any): JValue = {
import org.json4s.JsonDSL.WithDouble._
import org.json4s.jackson.Serialization
implicit val formats = Serialization.formats(NoTypeHints)
Extraction.decompose(src)
}
def compactJson(src: Any): String = {
import org.json4s.jackson.Serialization
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
implicit val formats = Serialization.formats(NoTypeHints)
compact(render(Extraction.decompose(src)))
}
def parseJson[T: Manifest](src: String):T = {
import org.json4s.jackson.JsonMethods._
implicit val formats = DefaultFormats
val json = parse(src)
json.extract[T]
}
def parseAny(src: String):Any = {
import org.json4s.jackson.JsonMethods._
implicit val formats = DefaultFormats
try{
val json = parse(src)
json.extract[Any]
}catch{
case e => src
}
}
/*
* Copyright 2018 Blockchain Technology and Application Joint Lab, Linkel Technology Co., Ltd, Beijing, Fintech Research Center of ISCAS.
* 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" BA SIS,
* 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.
*
*/
package rep.utils
/**
* @author c4w
*/
object Json4s {
import org.json4s._
def encodeJson(src: Any): JValue = {
import org.json4s.JsonDSL.WithDouble._
import org.json4s.jackson.Serialization
implicit val formats = Serialization.formats(NoTypeHints)
Extraction.decompose(src)
}
def compactJson(src: Any): String = {
import org.json4s.jackson.Serialization
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
implicit val formats = Serialization.formats(NoTypeHints)
compact(render(Extraction.decompose(src)))
}
def parseJson[T: Manifest](src: String):T = {
import org.json4s.jackson.JsonMethods._
implicit val formats = DefaultFormats
val json = parse(src)
json.extract[T]
}
def parseAny(src: String):Any = {
import org.json4s.jackson.JsonMethods._
implicit val formats = DefaultFormats
try{
val json = parse(src)
json.extract[Any]
}catch{
case e => src
}
}
}

View File

@ -67,51 +67,6 @@ class SandboxSpec(_system: ActorSystem)
override def afterAll: Unit = Await.ready(system.terminate(), Duration.Inf)
//JavaScript实现的存证合约测试, 包括合约部署调用返回结果测试
/*
"sandbox" should "deploy functions and call them then" in {
val sysName = "1"
val dbTag = "1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val pm = system.actorOf(ModuleManager.props("pm", sysName))
//加载合约脚本
val s1 = scala.io.Source.fromFile("scripts/proof/deploy.js")
val l1 = try s1.mkString finally s1.close()
//加载合约调用脚本
val s2 = scala.io.Source.fromFile("scripts/proof/invoke.js")
val l2 = try s2.mkString finally s2.close()
//准备探针以验证调用返回结果
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
var sandbox = system.actorOf(TransProcessor.props("sandbox", "", probe.ref))
//生成deploy交易
val cid = new ChaincodeId("Transfer",1)
val t1 = PeerHelper.createTransaction4Deploy(sysName, cid, l1, "", 5000, rep.protos.peer.ChaincodeDeploy.CodeType.CODE_JAVASCRIPT)
val msg_send1 = new DoTransaction(t1, probe.ref, "")
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Sandbox.DoTransactionResult](1000.seconds)
val ol1 = msg_recv1.ol
val ol1str = compactJson(ol1)
//生成invoke交易
//获取deploy生成的chainCodeId
val t2 = PeerHelper.createTransaction4Invoke(sysName, cid, l2, List())
val msg_send2 = new DoTransaction(t2, probe.ref, "")
for (i <- 1 to 10) {
println(s"----Span doTransaction-----")
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Sandbox.DoTransactionResult](1000.seconds)
val ol2 = msg_recv2.ol
val ol2str = compactJson(ol2)
//获得交易返回值
val rv2 = msg_recv2.r.asInstanceOf[JValue]
val re2 = rv2.extract[String]
re2 should be("json content")
}
}
*/
//Scala实现的资产管理合约测试包括合约的部署调用结果返回验证
"container" should "deploy scala contract and call it then" in {
val sysName = "1"
@ -196,89 +151,4 @@ class SandboxSpec(_system: ActorSystem)
}
}
//JavaScript的合约实现同一个合约串行执行测试
/* "sandbox" should "process trasactions Synchronously" in {
val sysName = "1"
//建立PeerManager实例是为了调用transactionCreator(需要用到密钥签名)无他
val f1 =
"""
var Thread = Java.type("java.lang.Thread");
function waitprint(span,output) {
Thread.sleep(span);
print(output);
return output
}
"""
val s1 =
"""
waitprint(5000,"FirstPrint");
"""
val s2 =
"""
waitprint(5,"SecondPrint");
"""
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
var sandbox = system.actorOf(TransProcessor.props("sandbox", "", probe.ref))
//deploy
val t1 = transactionCreator(sysName, rep.protos.peer.Transaction.Type.CHAINCODE_DEPLOY,
"", "", List(), f1, None)
val msg_send1 = new DoTransaction(t1, probe.ref, "")
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Sandbox.DoTransactionResult](10000.seconds)
//invoke
val cname = t1.payload.get.chaincodeID.get.name
val t2 = transactionCreator(sysName, rep.protos.peer.Transaction.Type.CHAINCODE_INVOKE,
"", s1, List(), "", Option(cname))
val msg_send2 = new DoTransaction(t2, probe.ref, "")
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Sandbox.DoTransactionResult](10000.seconds)
val rv2 = msg_recv2.r.asInstanceOf[JValue]
val re2 = rv2.extract[String]
re2 should be("FirstPrint")
val t3 = transactionCreator(sysName, rep.protos.peer.Transaction.Type.CHAINCODE_INVOKE,
"", s2, List(), "", Option(cname))
val msg_send3 = new DoTransaction(t3, probe.ref, "")
probe.send(sandbox, msg_send3)
val msg_recv3 = probe.expectMsgType[Sandbox.DoTransactionResult](10000.seconds)
val rv3 = msg_recv3.r.asInstanceOf[JValue]
rv3.extract[String] should be("SecondPrint")
}
//在合约脚本中访问正在处理的签名交易测试
"sandbox scripts" should "can access the Trasaction being processed" in {
val sysName = "1"
val f1 =
"""
print(tx);
"""
val s1 =
"""
r=tx;
"""
val probe = TestProbe()
val db = ImpDataAccess.GetDataAccess(sysName)
var sandbox = system.actorOf(TransProcessor.props("sandbox", "", probe.ref))
//deploy
val t1 = transactionCreator(sysName, rep.protos.peer.Transaction.Type.CHAINCODE_DEPLOY,
"", "", List(), f1, None)
val msg_send1 = new DoTransaction(t1, probe.ref, "")
probe.send(sandbox, msg_send1)
val msg_recv1 = probe.expectMsgType[Sandbox.DoTransactionResult](10000.seconds)
//invoke
val cname = t1.payload.get.chaincodeID.get.name
val t2 = transactionCreator(sysName, rep.protos.peer.Transaction.Type.CHAINCODE_INVOKE,
"", s1, List(), "", Option(cname))
val msg_send2 = new DoTransaction(t2, probe.ref, "")
probe.send(sandbox, msg_send2)
val msg_recv2 = probe.expectMsgType[Sandbox.DoTransactionResult](10000.seconds)
val rv2 = msg_recv2.r.asInstanceOf[JValue]
val re2 = rv2.extract[Transaction]
re2.id should be(t2.txid)
}
*/
}