mirror of
https://gitee.com/BTAJL/repchain.git
synced 2024-12-02 03:38:08 +08:00
repchain2.0-update169:增加轻节点验证配置信息;增加轻节点验证的API接口。
This commit is contained in:
parent
fff2a2df2d
commit
e3540fc1cd
@ -83,7 +83,7 @@ system {
|
||||
}
|
||||
|
||||
#交易生产方式
|
||||
trans_create_type = 1#0,手动;1,自动
|
||||
trans_create_type = 0#0,手动;1,自动
|
||||
#是否进行TPS测试
|
||||
statistic_enable = 0 # 0,unable;able
|
||||
|
||||
@ -105,7 +105,7 @@ system {
|
||||
use_custom_broadcast = 0 #0=使用系统的发布和订阅广播;1=使用自定义方式广播,默认=0
|
||||
block {
|
||||
#块内交易的最大数量
|
||||
trans_num_limit = 200
|
||||
trans_num_limit = 10
|
||||
#块内交易标准最小数量
|
||||
trans_num_min = 1
|
||||
#交易数量不足,重试次数
|
||||
@ -142,6 +142,11 @@ system {
|
||||
contract_method = "parameterAdjustment"
|
||||
}
|
||||
|
||||
accumulator{
|
||||
enable_transaction_accumulator = false //默认为false 不开启
|
||||
enable_world_state_accumulator = false //默认为false 不开启
|
||||
}
|
||||
|
||||
censor {
|
||||
filter=0 #是否启用违规数据过滤,true:启用;false:不启用
|
||||
is_censor=0 #是否为监管节点
|
||||
@ -241,7 +246,7 @@ system {
|
||||
#共识类型,目前只支持一种
|
||||
type = "CFRD"//内置三种共识协议,CFRD、RAFT、PBFT、CFRDINSTREAM
|
||||
synch_type = "CFRD"//内置两种同步类型,CFRD最高的高度的节点数大于一半;RAFT按照最高高度进行同步
|
||||
block_number_of_raft = 1
|
||||
block_number_of_raft = 3
|
||||
is_stream = 1
|
||||
}
|
||||
|
||||
|
@ -82,7 +82,7 @@ system {
|
||||
}
|
||||
|
||||
#交易生产方式
|
||||
trans_create_type = 1#0,手动;1,自动
|
||||
trans_create_type = 0#0,手动;1,自动
|
||||
#是否进行TPS测试
|
||||
statistic_enable = 0 # 0,unable;able
|
||||
|
||||
@ -104,7 +104,7 @@ system {
|
||||
use_custom_broadcast = 0 #0=使用系统的发布和订阅广播;1=使用自定义方式广播,默认=0
|
||||
block {
|
||||
#块内交易的最大数量
|
||||
trans_num_limit = 200
|
||||
trans_num_limit = 10
|
||||
#块内交易标准最小数量
|
||||
trans_num_min = 1
|
||||
#交易数量不足,重试次数
|
||||
@ -141,6 +141,11 @@ consensus_parameter {
|
||||
contract_method = "parameterAdjustment"
|
||||
}
|
||||
|
||||
accumulator{
|
||||
enable_transaction_accumulator = false //默认为false 不开启
|
||||
enable_world_state_accumulator = false //默认为false 不开启
|
||||
}
|
||||
|
||||
censor {
|
||||
filter=0 #是否启用违规数据过滤,true:启用;false:不启用
|
||||
is_censor=0 #是否为监管节点
|
||||
@ -240,7 +245,7 @@ consensus_parameter {
|
||||
#共识类型,目前只支持一种
|
||||
type = "CFRD"//内置三种共识协议,CFRD、RAFT、PBFT、CFRDINSTREAM
|
||||
synch_type = "CFRD"//内置两种同步类型,CFRD最高的高度的节点数大于一半;RAFT按照最高高度进行同步
|
||||
block_number_of_raft = 1
|
||||
block_number_of_raft = 3
|
||||
is_stream = 1
|
||||
}
|
||||
|
||||
|
@ -82,7 +82,7 @@ system {
|
||||
}
|
||||
|
||||
#交易生产方式
|
||||
trans_create_type = 1#0,手动;1,自动
|
||||
trans_create_type = 0#0,手动;1,自动
|
||||
#是否进行TPS测试
|
||||
statistic_enable = 0 # 0,unable;able
|
||||
|
||||
@ -104,7 +104,7 @@ system {
|
||||
use_custom_broadcast = 0 #0=使用系统的发布和订阅广播;1=使用自定义方式广播,默认=0
|
||||
block {
|
||||
#块内交易的最大数量
|
||||
trans_num_limit = 200
|
||||
trans_num_limit = 10
|
||||
#块内交易标准最小数量
|
||||
trans_num_min = 1
|
||||
#交易数量不足,重试次数
|
||||
@ -141,6 +141,11 @@ consensus_parameter {
|
||||
contract_method = "parameterAdjustment"
|
||||
}
|
||||
|
||||
accumulator{
|
||||
enable_transaction_accumulator = false //默认为false 不开启
|
||||
enable_world_state_accumulator = false //默认为false 不开启
|
||||
}
|
||||
|
||||
censor {
|
||||
filter=0 #是否启用违规数据过滤,true:启用;false:不启用
|
||||
is_censor=0 #是否为监管节点
|
||||
@ -240,7 +245,7 @@ consensus_parameter {
|
||||
#共识类型,目前只支持一种
|
||||
type = "CFRD"//内置三种共识协议,CFRD、RAFT、PBFT、CFRDINSTREAM
|
||||
synch_type = "CFRD"//内置两种同步类型,CFRD最高的高度的节点数大于一半;RAFT按照最高高度进行同步
|
||||
block_number_of_raft = 1
|
||||
block_number_of_raft = 3
|
||||
is_stream = 1
|
||||
}
|
||||
|
||||
|
@ -81,7 +81,7 @@ system {
|
||||
}
|
||||
|
||||
#交易生产方式
|
||||
trans_create_type = 1#0,手动;1,自动
|
||||
trans_create_type = 0#0,手动;1,自动
|
||||
#是否进行TPS测试
|
||||
statistic_enable = 0 # 0,unable;able
|
||||
#实时图的事件是否发送,如果不发送,前端实时图将收不到任何消息。
|
||||
@ -103,7 +103,7 @@ system {
|
||||
use_custom_broadcast = 0 #0=使用系统的发布和订阅广播;1=使用自定义方式广播,默认=0
|
||||
block {
|
||||
#块内交易的最大数量
|
||||
trans_num_limit = 200
|
||||
trans_num_limit = 10
|
||||
#块内交易标准最小数量
|
||||
trans_num_min = 1
|
||||
#交易数量不足,重试次数
|
||||
@ -140,6 +140,11 @@ consensus_parameter {
|
||||
contract_method = "parameterAdjustment"
|
||||
}
|
||||
|
||||
accumulator{
|
||||
enable_transaction_accumulator = false //默认为false 不开启
|
||||
enable_world_state_accumulator = false //默认为false 不开启
|
||||
}
|
||||
|
||||
censor {
|
||||
filter=0 #是否启用违规数据过滤,true:启用;false:不启用
|
||||
is_censor=0 #是否为监管节点
|
||||
@ -239,7 +244,7 @@ consensus_parameter {
|
||||
#共识类型,目前只支持一种
|
||||
type = "CFRD"//内置三种共识协议,CFRD、RAFT、PBFT、CFRDINSTREAM
|
||||
synch_type = "CFRD"//内置两种同步类型,CFRD最高的高度的节点数大于一半;RAFT按照最高高度进行同步
|
||||
block_number_of_raft = 1
|
||||
block_number_of_raft = 3
|
||||
is_stream = 1
|
||||
}
|
||||
|
||||
|
@ -82,7 +82,7 @@ system {
|
||||
}
|
||||
|
||||
#交易生产方式
|
||||
trans_create_type = 1#0,手动;1,自动
|
||||
trans_create_type = 0#0,手动;1,自动
|
||||
#是否进行TPS测试
|
||||
statistic_enable = 0 # 0,unable;able
|
||||
|
||||
@ -103,7 +103,7 @@ system {
|
||||
use_custom_broadcast = 0 #0=使用系统的发布和订阅广播;1=使用自定义方式广播,默认=0
|
||||
block {
|
||||
#块内交易的最大数量
|
||||
trans_num_limit = 200
|
||||
trans_num_limit = 10
|
||||
#块内交易标准最小数量
|
||||
trans_num_min = 1
|
||||
#交易数量不足,重试次数
|
||||
@ -140,6 +140,11 @@ system {
|
||||
contract_method = "parameterAdjustment"
|
||||
}
|
||||
|
||||
accumulator{
|
||||
enable_transaction_accumulator = false //默认为false 不开启
|
||||
enable_world_state_accumulator = false //默认为false 不开启
|
||||
}
|
||||
|
||||
censor {
|
||||
filter=0 #是否启用违规数据过滤,true:启用;false:不启用
|
||||
is_censor=0 #是否为监管节点
|
||||
@ -241,7 +246,7 @@ system {
|
||||
#共识类型,目前只支持一种
|
||||
type = "CFRD"//内置三种共识协议,CFRD、RAFT、PBFT、CFRDINSTREAM
|
||||
synch_type = "CFRD"//内置两种同步类型,CFRD最高的高度的节点数大于一半;RAFT按照最高高度进行同步
|
||||
block_number_of_raft = 1
|
||||
block_number_of_raft = 3
|
||||
is_stream = 1
|
||||
}
|
||||
|
||||
|
File diff suppressed because one or more lines are too long
@ -4,24 +4,21 @@ import java.math.BigInteger
|
||||
import scala.collection.mutable.ArrayBuffer
|
||||
import scala.util.control.Breaks.{break, breakable}
|
||||
import rep.crypto.Sha256
|
||||
import rep.accumulator.Accumulator.{
|
||||
AccumulatorWithMembershipProof, MembershipProof,
|
||||
NonMembershipProof, NonWitness, Witness, bitLength, product
|
||||
}
|
||||
import rep.accumulator.verkle.MiddleNode.{VerkleProofOfMembership, VerkleProofOfNonMembership}
|
||||
import rep.accumulator.Accumulator.{AccumulatorWithMembershipProof, bitLength, product}
|
||||
import rep.accumulator.verkle.util.{MembershipProof, NonMembershipProof, NonWitness, VerkleProofOfMembership, VerkleProofOfNonMembership, Witness}
|
||||
|
||||
object Accumulator {
|
||||
val bitLength = 256
|
||||
|
||||
case class NonWitness(d_coefficient: BigInteger, v_coefficient: BigInteger, gv_inv: BigInteger)
|
||||
//case class NonWitness(d_coefficient: BigInteger, v_coefficient: BigInteger, gv_inv: BigInteger)
|
||||
|
||||
case class Witness(witness: BigInteger)
|
||||
//case class Witness(witness: BigInteger)
|
||||
|
||||
case class MembershipProof(proof: BigInteger, witness: Witness)
|
||||
//case class MembershipProof(proof: BigInteger, witness: Witness)
|
||||
|
||||
case class AccumulatorWithMembershipProof(acc: Accumulator, proof: MembershipProof)
|
||||
|
||||
case class NonMembershipProof(nonWitness: NonWitness, proof_poe: BigInteger, proof_poke2: Poke2.proofStruct)
|
||||
//case class NonMembershipProof(nonWitness: NonWitness, proof_poe: BigInteger, proof_poke2: Poke2.proofStruct)
|
||||
|
||||
def verifyMembershipProof(member: BigInteger, proof: VerkleProofOfMembership, hashTool: Sha256): Boolean = {
|
||||
Poe.verify(proof.proof.witness.witness, member, proof.acc_value, proof.proof.proof, bitLength, hashTool)
|
||||
@ -109,12 +106,12 @@ class Accumulator(acc_base: BigInteger, last_acc: BigInteger, hashTool: Sha256)
|
||||
def addAndProof(element: BigInteger): AccumulatorWithMembershipProof = {
|
||||
val new_acc = add(element)
|
||||
val proof = Poe.prove(this.acc_value, element, new_acc.getAccVaule, bitLength, hashTool)
|
||||
AccumulatorWithMembershipProof(new_acc, MembershipProof(proof, Witness(this.acc_value)))
|
||||
AccumulatorWithMembershipProof(new_acc, new MembershipProof(proof, new Witness(this.acc_value)))
|
||||
}
|
||||
|
||||
def getMemberProof4Witness(element: BigInteger, witness: Witness): AccumulatorWithMembershipProof = {
|
||||
val proof = Poe.prove(witness.witness, element, this.acc_value, bitLength, hashTool)
|
||||
AccumulatorWithMembershipProof(this, MembershipProof(proof, witness))
|
||||
AccumulatorWithMembershipProof(this, new MembershipProof(proof, witness))
|
||||
}
|
||||
|
||||
def addAndProof(elements: Array[BigInteger]): AccumulatorWithMembershipProof = {
|
||||
@ -158,7 +155,7 @@ class Accumulator(acc_base: BigInteger, last_acc: BigInteger, hashTool: Sha256)
|
||||
|
||||
def membershipWitness(member: BigInteger, witness: Witness): Witness = {
|
||||
val acc = deleteWithWitness(member, witness)
|
||||
Witness(acc.getAccVaule)
|
||||
new Witness(acc.getAccVaule)
|
||||
}
|
||||
/////////////////////累加器的累加操作(累加,累加之后输出证明)、验证证明----结束/////////////////////////
|
||||
|
||||
@ -185,7 +182,7 @@ class Accumulator(acc_base: BigInteger, last_acc: BigInteger, hashTool: Sha256)
|
||||
buf += Tuple2(element, witness.witness)
|
||||
val acc = delete(buf.toArray)
|
||||
val proof = Poe.prove(acc.getAccVaule, element, this.acc_value, bitLength, hashTool)
|
||||
AccumulatorWithMembershipProof(acc, MembershipProof(proof, Witness(acc.getAccVaule)))
|
||||
AccumulatorWithMembershipProof(acc, new MembershipProof(proof, new Witness(acc.getAccVaule)))
|
||||
}
|
||||
|
||||
private def delete(elements: Array[(BigInteger, BigInteger)]): Accumulator = {
|
||||
@ -272,11 +269,11 @@ class Accumulator(acc_base: BigInteger, last_acc: BigInteger, hashTool: Sha256)
|
||||
val d = if (zout.sign_a) Rsa2048.exp(Rsa2048.inv(g), zout.coefficient_a) else Rsa2048.exp(g, zout.coefficient_a)
|
||||
val v = if (zout.sign_b) Rsa2048.exp(Rsa2048.inv(this.acc_value), zout.coefficient_b) else Rsa2048.exp(this.acc_value, zout.coefficient_b)
|
||||
val gv_inv = Rsa2048.op(g, Rsa2048.inv(v))
|
||||
val w = NonWitness(d, v, gv_inv)
|
||||
val w = new NonWitness(d, v, gv_inv)
|
||||
val tr = Rsa2048.exp(d, x)
|
||||
val poke2_proof = Poke2.prove(this.acc_value, zout.coefficient_b, v, bitLength, hashTool)
|
||||
val poe_proof = Poe.prove(d, x, gv_inv, bitLength, hashTool)
|
||||
r = NonMembershipProof(w, poe_proof, poke2_proof)
|
||||
r = new NonMembershipProof(w, poe_proof, poke2_proof)
|
||||
}
|
||||
}
|
||||
r
|
||||
@ -332,7 +329,7 @@ class Accumulator(acc_base: BigInteger, last_acc: BigInteger, hashTool: Sha256)
|
||||
val w_to_b = if (zout.sign_b) Rsa2048.exp(Rsa2048.inv(w.getAccVaule), zout.coefficient_b) else Rsa2048.exp(w.getAccVaule, zout.coefficient_b)
|
||||
val acc_new_to_a = if (zout.sign_a) Rsa2048.exp(Rsa2048.inv(this.getAccVaule), zout.coefficient_a) else Rsa2048.exp(this.getAccVaule, zout.coefficient_a)
|
||||
val promise = Rsa2048.op(w_to_b, acc_new_to_a)
|
||||
r = Witness(promise)
|
||||
r = new Witness(promise)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -412,7 +409,7 @@ class Accumulator(acc_base: BigInteger, last_acc: BigInteger, hashTool: Sha256)
|
||||
val acc = if (this.acc_value.compareTo(BigInteger.ZERO) == 0) this.acc_base_value else this.acc_value
|
||||
val ws = root_factor(acc, elems)
|
||||
for (i <- 0 to elems.length - 1) {
|
||||
val w = (elems(i), Witness(ws(i)))
|
||||
val w = (elems(i), new Witness(ws(i)))
|
||||
bf += w
|
||||
}
|
||||
bf.toArray
|
||||
|
@ -5,10 +5,8 @@ import java.math.BigInteger
|
||||
import scala.collection.mutable.ArrayBuffer
|
||||
import scala.util.control.Breaks.{break, breakable}
|
||||
import rep.crypto.Sha256
|
||||
import rep.accumulator.Accumulator4Aggregate.{
|
||||
AccumulatorWithMembershipProof, MembershipProof,
|
||||
NonWitness, NonmembershipProof, Witness, bitLength
|
||||
}
|
||||
import rep.accumulator.Accumulator4Aggregate.{AccumulatorWithMembershipProof, MembershipProof, NonWitness, NonmembershipProof, Witness, bitLength}
|
||||
import rep.accumulator.verkle.util.proofStruct
|
||||
|
||||
object Accumulator4Aggregate{
|
||||
val bitLength = 256
|
||||
@ -16,7 +14,7 @@ object Accumulator4Aggregate{
|
||||
case class Witness(promise:BigInteger,agg:BigInteger)
|
||||
case class MembershipProof(proof:BigInteger,witness:Witness)
|
||||
case class AccumulatorWithMembershipProof(acc:Accumulator4Aggregate,proof: MembershipProof)
|
||||
case class NonmembershipProof(nonWitness:NonWitness,proof_poe:BigInteger,proof_poke2:Poke2.proofStruct)
|
||||
case class NonmembershipProof(nonWitness:NonWitness,proof_poe:BigInteger,proof_poke2:proofStruct)
|
||||
}
|
||||
|
||||
class Accumulator4Aggregate(acc_base: BigInteger, last_acc: BigInteger, last_aggregate: BigInteger, hashTool: Sha256) {
|
||||
|
@ -1,12 +1,14 @@
|
||||
package rep.accumulator
|
||||
|
||||
|
||||
import rep.accumulator.verkle.util.proofStruct
|
||||
import rep.crypto.Sha256
|
||||
|
||||
import java.math.BigInteger
|
||||
|
||||
|
||||
object Poke2 {
|
||||
case class proofStruct(z:BigInteger,Q:BigInteger,r:BigInteger)
|
||||
//case class proofStruct(z:BigInteger,Q:BigInteger,r:BigInteger)
|
||||
private var bg : BigInteger = null
|
||||
|
||||
def get_g(bitLength:Int):BigInteger={
|
||||
@ -27,7 +29,7 @@ object Poke2 {
|
||||
val q = div._1
|
||||
val r = div._2
|
||||
val Q = Rsa2048.exp(Rsa2048.op(base,Rsa2048.exp(g,alpha)),q)
|
||||
proofStruct(z,Q,r)
|
||||
new proofStruct(z,Q,r)
|
||||
}
|
||||
|
||||
def verify(base:BigInteger, result:BigInteger, proof:proofStruct,bitLength:Int,hash:Sha256):Boolean={
|
||||
|
@ -1,5 +1,6 @@
|
||||
package rep.accumulator
|
||||
|
||||
|
||||
import java.math.BigInteger
|
||||
|
||||
object Util {
|
||||
@ -128,4 +129,5 @@ object Util {
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
package rep.accumulator.chain
|
||||
|
||||
import rep.accumulator.{Accumulator, PrimeTool}
|
||||
import rep.accumulator.Accumulator.Witness
|
||||
import rep.accumulator.chain.VectorCommitment.{BlockVectorCommitment, TxAndPrime, TxWitness, TxWitnessesOfBlock}
|
||||
import rep.accumulator.verkle.VerkleTreeType
|
||||
import rep.accumulator.verkle.util.Witness
|
||||
import rep.app.system.RepChainSystemContext
|
||||
import rep.proto.rc2.{Block, Transaction}
|
||||
|
||||
@ -35,7 +36,7 @@ class VectorCommitment(ctx:RepChainSystemContext) {
|
||||
def getTransactionWitnesses(txs:Array[TxAndPrime],height:Long,tx_acc_value:BigInteger,isCreateWitness:Boolean=false):TxWitnessesOfBlock={
|
||||
var r : TxWitnessesOfBlock = null
|
||||
if(txs != null && txs.length > 0){
|
||||
val old_acc = new Accumulator(ctx.getTxAccBase, tx_acc_value, ctx.getHashTool)
|
||||
val old_acc = new Accumulator(ctx.getVerkleTreeAccRoot(VerkleTreeType.TransactionTree), tx_acc_value, ctx.getHashTool)
|
||||
val tx_primes = for(tx<-txs) yield {
|
||||
tx.prime
|
||||
}
|
||||
|
@ -1,14 +1,14 @@
|
||||
package rep.accumulator.verkle
|
||||
|
||||
|
||||
import rep.accumulator.Accumulator.{ Witness}
|
||||
import rep.accumulator.{Accumulator, PrimeTool}
|
||||
import rep.accumulator.verkle.LeafNode.{LeafNodeAccValuePrefix, LeafNodeAccWitPrefix, LeafNodePrimesPrefix, LeafNodeValuesPrefix}
|
||||
import rep.accumulator.verkle.MiddleNode.{VerkleProofOfMembership, VerkleProofOfNonMembership}
|
||||
import rep.accumulator.verkle.util.verkleTool
|
||||
import rep.accumulator.verkle.VerkleTreeType.VerkleTreeType
|
||||
import rep.accumulator.verkle.util.{VerkleProofOfMembership, VerkleProofOfNonMembership, Witness, verkleTool}
|
||||
import rep.app.system.RepChainSystemContext
|
||||
import rep.storage.db.factory.DBFactory
|
||||
import rep.utils.SerializeUtils
|
||||
|
||||
import java.math.BigInteger
|
||||
import scala.collection.mutable.ArrayBuffer
|
||||
|
||||
@ -19,7 +19,7 @@ object LeafNode {
|
||||
val LeafNodeAccWitPrefix = "a_l_w_"
|
||||
}
|
||||
|
||||
class LeafNode(ctx: RepChainSystemContext, nodeId: Array[Int]) {
|
||||
class LeafNode(ctx: RepChainSystemContext, nodeId: Array[Int],verkleTreeType: VerkleTreeType) {
|
||||
private val db = DBFactory.getDBAccess(ctx.getConfig)
|
||||
private var values: ArrayBuffer[Array[Byte]] = null
|
||||
private var primes: ArrayBuffer[BigInteger] = null
|
||||
@ -29,6 +29,14 @@ class LeafNode(ctx: RepChainSystemContext, nodeId: Array[Int]) {
|
||||
|
||||
loader
|
||||
|
||||
private def getTypePrefix: String = {
|
||||
if (verkleTreeType == VerkleTreeType.TransactionTree) {
|
||||
"t-"
|
||||
} else {
|
||||
"w-"
|
||||
}
|
||||
}
|
||||
|
||||
def leafToString: String = {
|
||||
val sb = new StringBuffer()
|
||||
sb.append(s"node-type=leaf\tnode-name=${node_name},")
|
||||
@ -41,21 +49,21 @@ class LeafNode(ctx: RepChainSystemContext, nodeId: Array[Int]) {
|
||||
}
|
||||
|
||||
private def loader: Unit = {
|
||||
val v = db.getObject[ArrayBuffer[Array[Byte]]](LeafNodeValuesPrefix + node_name)
|
||||
val v = db.getObject[ArrayBuffer[Array[Byte]]](getTypePrefix+LeafNodeValuesPrefix + node_name)
|
||||
if (v != None) this.values = v.get else this.values = new ArrayBuffer[Array[Byte]]()
|
||||
val p = db.getObject[ArrayBuffer[BigInteger]](LeafNodePrimesPrefix + node_name)
|
||||
val p = db.getObject[ArrayBuffer[BigInteger]](getTypePrefix+LeafNodePrimesPrefix + node_name)
|
||||
if (p != None) this.primes = p.get else this.primes = new ArrayBuffer[BigInteger]()
|
||||
val av = db.getObject[BigInteger](LeafNodeAccValuePrefix + node_name)
|
||||
val av = db.getObject[BigInteger](getTypePrefix+LeafNodeAccValuePrefix + node_name)
|
||||
if (av != None) this.acc_value = av.get
|
||||
val lw = db.getObject[BigInteger](LeafNodeAccWitPrefix + node_name)
|
||||
val lw = db.getObject[BigInteger](getTypePrefix+LeafNodeAccWitPrefix + node_name)
|
||||
if (lw != None) this.last_witness = lw.get
|
||||
}
|
||||
|
||||
private def update: Unit = {
|
||||
db.putBytes(LeafNodeValuesPrefix + node_name, SerializeUtils.serialise(this.values))
|
||||
db.putBytes(LeafNodePrimesPrefix + node_name, SerializeUtils.serialise(this.primes))
|
||||
db.putBytes(LeafNodeAccValuePrefix + node_name, SerializeUtils.serialise(this.acc_value))
|
||||
db.putBytes(LeafNodeAccWitPrefix + node_name, SerializeUtils.serialise(this.last_witness))
|
||||
db.putBytes(getTypePrefix+LeafNodeValuesPrefix + node_name, SerializeUtils.serialise(this.values))
|
||||
db.putBytes(getTypePrefix+LeafNodePrimesPrefix + node_name, SerializeUtils.serialise(this.primes))
|
||||
db.putBytes(getTypePrefix+LeafNodeAccValuePrefix + node_name, SerializeUtils.serialise(this.acc_value))
|
||||
db.putBytes(getTypePrefix+LeafNodeAccWitPrefix + node_name, SerializeUtils.serialise(this.last_witness))
|
||||
}
|
||||
|
||||
def add(v: Array[Byte]): BigInteger = {
|
||||
@ -65,13 +73,13 @@ class LeafNode(ctx: RepChainSystemContext, nodeId: Array[Int]) {
|
||||
|
||||
def add(v: Array[Byte], p: BigInteger): BigInteger = {
|
||||
if (!this.primes.contains(p)) {
|
||||
val acc = new Accumulator(ctx.getStateAccBase, this.acc_value, ctx.getHashTool)
|
||||
val acc = new Accumulator(ctx.getVerkleTreeAccRoot(verkleTreeType), this.acc_value, ctx.getHashTool)
|
||||
val new_acc = acc.add(p)
|
||||
if (new_acc != null) {
|
||||
this.primes += p
|
||||
this.values += v
|
||||
if (this.acc_value == null) {
|
||||
this.last_witness = ctx.getStateAccBase
|
||||
this.last_witness = ctx.getVerkleTreeAccRoot(verkleTreeType)
|
||||
} else {
|
||||
this.last_witness = this.acc_value
|
||||
}
|
||||
@ -101,14 +109,14 @@ class LeafNode(ctx: RepChainSystemContext, nodeId: Array[Int]) {
|
||||
}
|
||||
|
||||
def getMembershipProof(prime: BigInteger): VerkleProofOfMembership = {
|
||||
val acc = new Accumulator(ctx.getStateAccBase, this.acc_value, ctx.getHashTool)
|
||||
val proof = acc.getMemberProof4Witness(prime, Witness(this.last_witness))
|
||||
VerkleProofOfMembership(node_name, this.acc_value, proof.proof)
|
||||
val acc = new Accumulator(ctx.getVerkleTreeAccRoot(verkleTreeType), this.acc_value, ctx.getHashTool)
|
||||
val proof = acc.getMemberProof4Witness(prime, new Witness(this.last_witness))
|
||||
new VerkleProofOfMembership(node_name, this.acc_value, proof.proof)
|
||||
}
|
||||
|
||||
def getNonMembershipProof(prime: BigInteger): VerkleProofOfNonMembership = {
|
||||
val acc = new Accumulator(ctx.getStateAccBase, this.acc_value, ctx.getHashTool)
|
||||
VerkleProofOfNonMembership(node_name, this.acc_value, acc.nonmemberShipProof(this.primes.toArray, Array(prime)))
|
||||
val acc = new Accumulator(ctx.getVerkleTreeAccRoot(verkleTreeType), this.acc_value, ctx.getHashTool)
|
||||
new VerkleProofOfNonMembership(node_name, this.acc_value, acc.nonmemberShipProof(this.primes.toArray, Array(prime)))
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,12 +1,13 @@
|
||||
package rep.accumulator.verkle
|
||||
|
||||
import rep.accumulator.Accumulator.{MembershipProof, NonMembershipProof, Witness}
|
||||
import rep.accumulator.{Accumulator, PrimeTool, Rsa2048}
|
||||
import rep.accumulator.verkle.MiddleNode.{ChildIdentifier, MiddleNodeAccValuesPrefix, MiddleNodePrimeValuesPrefix, MiddleNodeValuesPrefix, VerkleProofOfMembership, VerkleProofOfNonMembership, degree}
|
||||
import rep.accumulator.verkle.util.verkleTool
|
||||
import rep.accumulator.verkle.MiddleNode.{ChildIdentifier, MiddleNodeAccValuesPrefix, MiddleNodePrimeValuesPrefix, MiddleNodeValuesPrefix, degree}
|
||||
import rep.accumulator.verkle.VerkleTreeType.VerkleTreeType
|
||||
import rep.accumulator.verkle.util.{VerkleProofOfMembership, VerkleProofOfNonMembership, Witness, verkleTool}
|
||||
import rep.app.system.RepChainSystemContext
|
||||
import rep.storage.db.factory.DBFactory
|
||||
import rep.utils.SerializeUtils
|
||||
|
||||
import java.math.BigInteger
|
||||
import scala.collection.mutable.ArrayBuffer
|
||||
import scala.util.control.Breaks.{break, breakable}
|
||||
@ -14,9 +15,9 @@ import scala.util.control.Breaks.{break, breakable}
|
||||
object MiddleNode {
|
||||
case class ChildIdentifier(id: Array[Int], childType: Int, acc_value: BigInteger, prime: BigInteger) //childType 0=leafnode;1=middlenode
|
||||
|
||||
case class VerkleProofOfMembership(nodeId: String, acc_value: BigInteger, proof: MembershipProof)
|
||||
//case class VerkleProofOfMembership(nodeId: String, acc_value: BigInteger, proof: MembershipProof)
|
||||
|
||||
case class VerkleProofOfNonMembership(nodeId: String, acc_value: BigInteger, proof: NonMembershipProof)
|
||||
//case class VerkleProofOfNonMembership(nodeId: String, acc_value: BigInteger, proof: NonMembershipProof)
|
||||
|
||||
val degree = 256
|
||||
val MiddleNodeValuesPrefix = "m_n_v_"
|
||||
@ -24,12 +25,19 @@ object MiddleNode {
|
||||
val MiddleNodePrimeValuesPrefix = "m_n_p_v_"
|
||||
}
|
||||
|
||||
class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int],verkleTreeType: VerkleTreeType) {
|
||||
private val db = DBFactory.getDBAccess(ctx.getConfig)
|
||||
private var children: Array[ChildIdentifier] = null
|
||||
private var acc_value: BigInteger = null
|
||||
private var prime_value: BigInteger = BigInteger.ONE
|
||||
|
||||
private def getTypePrefix: String = {
|
||||
if (verkleTreeType == VerkleTreeType.TransactionTree) {
|
||||
"t-"
|
||||
} else {
|
||||
"w-"
|
||||
}
|
||||
}
|
||||
loader
|
||||
|
||||
private def getKeyPrefixLength: Int = {
|
||||
@ -49,18 +57,18 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
}
|
||||
|
||||
def loader: Unit = {
|
||||
val v = db.getObject[Array[ChildIdentifier]](MiddleNodeValuesPrefix + verkleTool.getKey(keyPrefix))
|
||||
val v = db.getObject[Array[ChildIdentifier]](getTypePrefix+MiddleNodeValuesPrefix + verkleTool.getKey(keyPrefix))
|
||||
this.children = if (v != None) v.get else new Array[ChildIdentifier](degree)
|
||||
val av = db.getObject[BigInteger](MiddleNodeAccValuesPrefix + verkleTool.getKey(keyPrefix))
|
||||
val av = db.getObject[BigInteger](getTypePrefix+MiddleNodeAccValuesPrefix + verkleTool.getKey(keyPrefix))
|
||||
if (av != None) this.acc_value = av.get
|
||||
val pv = db.getObject[BigInteger](MiddleNodePrimeValuesPrefix + verkleTool.getKey(keyPrefix))
|
||||
val pv = db.getObject[BigInteger](getTypePrefix+MiddleNodePrimeValuesPrefix + verkleTool.getKey(keyPrefix))
|
||||
if (pv != None) this.prime_value = pv.get
|
||||
}
|
||||
|
||||
private def updateToDB: Unit = {
|
||||
db.putBytes(MiddleNodeValuesPrefix + verkleTool.getKey(keyPrefix), SerializeUtils.serialise(this.children))
|
||||
db.putBytes(MiddleNodeAccValuesPrefix + verkleTool.getKey(keyPrefix), SerializeUtils.serialise(this.acc_value))
|
||||
db.putBytes(MiddleNodePrimeValuesPrefix + verkleTool.getKey(keyPrefix), SerializeUtils.serialise(this.prime_value))
|
||||
db.putBytes(getTypePrefix+MiddleNodeValuesPrefix + verkleTool.getKey(keyPrefix), SerializeUtils.serialise(this.children))
|
||||
db.putBytes(getTypePrefix+MiddleNodeAccValuesPrefix + verkleTool.getKey(keyPrefix), SerializeUtils.serialise(this.acc_value))
|
||||
db.putBytes(getTypePrefix+MiddleNodePrimeValuesPrefix + verkleTool.getKey(keyPrefix), SerializeUtils.serialise(this.prime_value))
|
||||
}
|
||||
|
||||
def addState(key: Array[Int], data: Array[Byte], prime: BigInteger): Unit = {
|
||||
@ -70,7 +78,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
//存在节点
|
||||
if (obj.childType == 0) {
|
||||
//已经存在叶子节点,继续添加
|
||||
val leaf = this.ctx.getVerkleNodeBuffer.readLeafNode(obj.id)
|
||||
val leaf = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType).readLeafNode(obj.id)
|
||||
if (!leaf.isExist(prime)) {
|
||||
val md = this.addMiddleNode(idx)
|
||||
md.addLeafNode(key, data, prime)
|
||||
@ -80,7 +88,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
}
|
||||
} else if (obj.childType == 1) {
|
||||
//属于中间节点,继续递归
|
||||
val child = this.ctx.getVerkleNodeBuffer.readMiddleNode(obj.id)
|
||||
val child = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType).readMiddleNode(obj.id)
|
||||
child.addState(key, data, prime)
|
||||
}
|
||||
} else {
|
||||
@ -90,7 +98,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
}
|
||||
|
||||
private def addMiddleNode(idx: Int): MiddleNode = {
|
||||
val vb = this.ctx.getVerkleNodeBuffer
|
||||
val vb = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType)
|
||||
val md = vb.readMiddleNode(this.linkKeyPrefix(Array(idx)))
|
||||
md
|
||||
}
|
||||
@ -101,7 +109,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
}
|
||||
|
||||
private def addLeafNode(key: Array[Int], data: Array[Byte], prime: BigInteger): LeafNode = {
|
||||
val vb = this.ctx.getVerkleNodeBuffer
|
||||
val vb = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType)
|
||||
val leaf = vb.readLeafNode(key)
|
||||
val acc_value = leaf.add(data, prime)
|
||||
val identifier = ChildIdentifier(key, 0, acc_value,
|
||||
@ -128,7 +136,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
//当前是根节点
|
||||
null
|
||||
} else {
|
||||
val vb = this.ctx.getVerkleNodeBuffer
|
||||
val vb = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType)
|
||||
if (this.keyPrefix.length == 1) {
|
||||
vb.readMiddleNode(null)
|
||||
} else if (this.keyPrefix.length > 1) {
|
||||
@ -179,7 +187,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
v_primes = this.prime_value
|
||||
}
|
||||
v_primes = Rsa2048.mul(v_primes, new_prime)
|
||||
val new_acc = Rsa2048.exp(this.ctx.getStateAccBase, v_primes)
|
||||
val new_acc = Rsa2048.exp(this.ctx.getVerkleTreeAccRoot(verkleTreeType), v_primes)
|
||||
System.out.println(s"updateAccValue:id=${verkleTool.getKey(this.keyPrefix)},prime=${v_primes}")
|
||||
new Tuple2[BigInteger, BigInteger](v_primes, new_acc)
|
||||
}
|
||||
@ -193,10 +201,10 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
if (this.children(i) != null) {
|
||||
sb.append(s"son(${i})\t")
|
||||
if (this.children(i).childType == 0) {
|
||||
val l = this.ctx.getVerkleNodeBuffer.readLeafNode(this.children(i).id)
|
||||
val l = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType).readLeafNode(this.children(i).id)
|
||||
sb.append(l.leafToString)
|
||||
} else {
|
||||
val m = this.ctx.getVerkleNodeBuffer.readMiddleNode(this.children(i).id)
|
||||
val m = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType).readMiddleNode(this.children(i).id)
|
||||
sb.append("\r")
|
||||
val tmp = m.middleToString
|
||||
sb.append(tmp)
|
||||
@ -212,7 +220,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
val obj = this.children(idx)
|
||||
if (obj != null) {
|
||||
//存在节点
|
||||
val vb = this.ctx.getVerkleNodeBuffer
|
||||
val vb = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType)
|
||||
val p = getMembershipProof(obj.prime)
|
||||
proofs += p
|
||||
if (obj.childType == 0) {
|
||||
@ -231,7 +239,7 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
//属于中间节点,输出中间证明,继续递归
|
||||
val p = getMembershipProof(obj.prime)
|
||||
proofs += p
|
||||
val child = this.ctx.getVerkleNodeBuffer.readMiddleNode(obj.id)
|
||||
val child = this.ctx.getVerkleTreeNodeBuffer(this.verkleTreeType).readMiddleNode(obj.id)
|
||||
val ps = child.getProofs(key, data, prime)
|
||||
proofs += ps.toArray
|
||||
}
|
||||
@ -278,15 +286,19 @@ class MiddleNode(ctx: RepChainSystemContext, keyPrefix: Array[Int]) {
|
||||
}
|
||||
|
||||
def getMembershipProof(prime: BigInteger): VerkleProofOfMembership = {
|
||||
val acc = new Accumulator(ctx.getStateAccBase, this.acc_value, ctx.getHashTool)
|
||||
val acc = new Accumulator(ctx.getVerkleTreeAccRoot(verkleTreeType), this.acc_value, ctx.getHashTool)
|
||||
val p = Rsa2048.div(this.prime_value, prime)
|
||||
val wit = Rsa2048.exp(ctx.getStateAccBase, p)
|
||||
val proof = acc.getMemberProof4Witness(prime, Witness(wit))
|
||||
VerkleProofOfMembership(verkleTool.getKey(this.keyPrefix), this.acc_value, proof.proof)
|
||||
val wit = Rsa2048.exp(ctx.getVerkleTreeAccRoot(verkleTreeType), p)
|
||||
val proof = acc.getMemberProof4Witness(prime, new Witness(wit))
|
||||
new VerkleProofOfMembership(verkleTool.getKey(this.keyPrefix), this.acc_value, proof.proof)
|
||||
}
|
||||
|
||||
def getNonMembershipProof(prime: BigInteger): VerkleProofOfNonMembership = {
|
||||
val acc = new Accumulator(ctx.getStateAccBase, this.acc_value, ctx.getHashTool)
|
||||
VerkleProofOfNonMembership(verkleTool.getKey(this.keyPrefix), this.acc_value, acc.nonmemberShipProof(Array(this.prime_value), Array(prime)))
|
||||
val acc = new Accumulator(ctx.getVerkleTreeAccRoot(verkleTreeType), this.acc_value, ctx.getHashTool)
|
||||
new VerkleProofOfNonMembership(verkleTool.getKey(this.keyPrefix), this.acc_value, acc.nonmemberShipProof(Array(this.prime_value), Array(prime)))
|
||||
}
|
||||
|
||||
def getAccValue():BigInteger={
|
||||
this.acc_value
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,11 @@
|
||||
package rep.accumulator.verkle
|
||||
|
||||
import com.googlecode.concurrentlinkedhashmap.{ConcurrentLinkedHashMap, Weighers}
|
||||
import rep.accumulator.verkle.VerkleTreeType.VerkleTreeType
|
||||
import rep.app.system.RepChainSystemContext
|
||||
|
||||
|
||||
class VerkleNodeBuffer(ctx:RepChainSystemContext) {
|
||||
class VerkleNodeBuffer(ctx:RepChainSystemContext,verkleTreeType: VerkleTreeType) {
|
||||
final val cacheMaxSize = 100000
|
||||
final val leafNodePrefix = "leaf-"
|
||||
final val middleNodePrefix = "middle-"
|
||||
@ -12,9 +13,17 @@ class VerkleNodeBuffer(ctx:RepChainSystemContext) {
|
||||
.maximumWeightedCapacity(cacheMaxSize)
|
||||
.weigher(Weighers.singleton[Option[Any]]).build
|
||||
|
||||
private def getTypePrefix:String={
|
||||
if (verkleTreeType == VerkleTreeType.TransactionTree) {
|
||||
"t-"
|
||||
} else {
|
||||
"w-"
|
||||
}
|
||||
}
|
||||
|
||||
private def createLeafNode(nodeId:Array[Int]):LeafNode={
|
||||
val key = this.leafNodePrefix+util.verkleTool.getKey(nodeId)
|
||||
val leaf_new = new LeafNode(this.ctx, nodeId)
|
||||
val key = getTypePrefix+this.leafNodePrefix+util.verkleTool.getKey(nodeId)
|
||||
val leaf_new = new LeafNode(this.ctx, nodeId,this.verkleTreeType)
|
||||
val leaf = this.cache.putIfAbsent(key, Some(leaf_new))
|
||||
if (leaf != null) {
|
||||
leaf.get.asInstanceOf[LeafNode]
|
||||
@ -24,7 +33,7 @@ class VerkleNodeBuffer(ctx:RepChainSystemContext) {
|
||||
}
|
||||
|
||||
def readLeafNode(nodeId:Array[Int]):LeafNode={
|
||||
val name = this.leafNodePrefix+util.verkleTool.getKey(nodeId)
|
||||
val name = getTypePrefix+this.leafNodePrefix+util.verkleTool.getKey(nodeId)
|
||||
if(this.cache.containsKey(name)){
|
||||
val obj = this.cache.get(name)
|
||||
if(obj != None){
|
||||
@ -38,8 +47,8 @@ class VerkleNodeBuffer(ctx:RepChainSystemContext) {
|
||||
}
|
||||
|
||||
private def createMiddleNode(nodeId: Array[Int]): MiddleNode = {
|
||||
val key = this.middleNodePrefix + (if(nodeId == null) "root" else util.verkleTool.getKey(nodeId))
|
||||
val middle_new = new MiddleNode(this.ctx, nodeId)
|
||||
val key = getTypePrefix+this.middleNodePrefix + (if(nodeId == null) "root" else util.verkleTool.getKey(nodeId))
|
||||
val middle_new = new MiddleNode(this.ctx, nodeId,this.verkleTreeType)
|
||||
val middle = this.cache.putIfAbsent(key, Some(middle_new))
|
||||
if (middle != null) {
|
||||
middle.get.asInstanceOf[MiddleNode]
|
||||
@ -49,7 +58,7 @@ class VerkleNodeBuffer(ctx:RepChainSystemContext) {
|
||||
}
|
||||
|
||||
def readMiddleNode(nodeId: Array[Int]): MiddleNode = {
|
||||
val name = this.middleNodePrefix + (if(nodeId == null) "root" else util.verkleTool.getKey(nodeId))
|
||||
val name = getTypePrefix+this.middleNodePrefix + (if(nodeId == null) "root" else util.verkleTool.getKey(nodeId))
|
||||
if (this.cache.containsKey(name)) {
|
||||
val obj = this.cache.get(name)
|
||||
if (obj != None) {
|
||||
|
@ -0,0 +1,9 @@
|
||||
package rep.accumulator.verkle
|
||||
|
||||
object VerkleTreeType extends Enumeration {
|
||||
type VerkleTreeType = Value
|
||||
|
||||
val WorldStateTree = Value(1, "WorldStateTree")
|
||||
val TransactionTree = Value(2, "TransactionTree")
|
||||
val TransactionResultTree = Value(3, "TransactionResultTree")
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package rep.accumulator.verkle.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class MembershipProof {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger proof;
|
||||
public Witness witness;
|
||||
|
||||
public MembershipProof(BigInteger proof,Witness witness){
|
||||
this.proof = proof;
|
||||
this.witness = witness;
|
||||
}
|
||||
|
||||
public static MembershipProof Deserial(LinkedHashMap<String,Object> ps){
|
||||
BigInteger p = new BigInteger(ps.get("proof").toString());
|
||||
LinkedHashMap<String,Object> tmp = (LinkedHashMap<String,Object>)ps.get("witness");
|
||||
return new MembershipProof(p,Witness.Deserial(tmp));
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package rep.accumulator.verkle.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class NonMembershipProof {
|
||||
public NonWitness nonWitness;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger proof_poe;
|
||||
public proofStruct proof_poke2;
|
||||
|
||||
public NonMembershipProof(NonWitness nonWitness, BigInteger proof_poe, proofStruct proof_poke2){
|
||||
this.nonWitness = nonWitness;
|
||||
this.proof_poe = proof_poe;
|
||||
this.proof_poke2 = proof_poke2;
|
||||
}
|
||||
|
||||
public static NonMembershipProof Deserial(LinkedHashMap<String,Object> ps){
|
||||
LinkedHashMap<String,Object> tmp = (LinkedHashMap<String,Object>)ps.get("nonWitness");
|
||||
LinkedHashMap<String,Object> tmp1 = (LinkedHashMap<String,Object>)ps.get("proof_poke2");
|
||||
BigInteger p = new BigInteger(ps.get("proof_poe").toString());
|
||||
return new NonMembershipProof(NonWitness.Deserial(tmp),p,proofStruct.Deserial(tmp1));
|
||||
}
|
||||
}
|
29
src/main/scala/rep/accumulator/verkle/util/NonWitness.java
Normal file
29
src/main/scala/rep/accumulator/verkle/util/NonWitness.java
Normal file
@ -0,0 +1,29 @@
|
||||
package rep.accumulator.verkle.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class NonWitness {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger d_coefficient;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger v_coefficient;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger gv_inv;
|
||||
|
||||
public NonWitness(BigInteger d_coefficient, BigInteger v_coefficient, BigInteger gv_inv){
|
||||
this.d_coefficient = d_coefficient;
|
||||
this.v_coefficient = v_coefficient;
|
||||
this.gv_inv = gv_inv;
|
||||
}
|
||||
|
||||
public static NonWitness Deserial(LinkedHashMap<String,Object> ps){
|
||||
BigInteger d = new BigInteger(ps.get("d_coefficient").toString());
|
||||
BigInteger v = new BigInteger(ps.get("v_coefficient").toString());
|
||||
BigInteger gv = new BigInteger(ps.get("gv_inv").toString());
|
||||
return new NonWitness(d,v,gv);
|
||||
}
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package rep.accumulator.verkle.util
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import rep.utils.SerializeUtils
|
||||
import java.util.LinkedHashMap
|
||||
|
||||
object ProofSerialize {
|
||||
case class serialObj(p:String,n:String)
|
||||
private def getProofType(p: Any): String = {
|
||||
if (p.isInstanceOf[VerkleProofOfMembership]) {
|
||||
"VerkleProofOfMembership"
|
||||
} else if (p.isInstanceOf[VerkleProofOfNonMembership]) {
|
||||
"VerkleProofOfNonMembership"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
private def getProofObj(p:String,n:String):Any={
|
||||
val objectMapper = new ObjectMapper()
|
||||
if(n.equalsIgnoreCase("VerkleProofOfMembership")){
|
||||
val tmp = objectMapper.readValue(p, classOf[Any])
|
||||
if(tmp.isInstanceOf[LinkedHashMap[String,Object]]){
|
||||
val hm = tmp.asInstanceOf[LinkedHashMap[String,Object]]
|
||||
VerkleProofOfMembership.Deserial(hm)
|
||||
}else{
|
||||
null
|
||||
}
|
||||
}else if(n.equalsIgnoreCase("VerkleProofOfNonMembership")){
|
||||
val tmp = objectMapper.readValue(p, classOf[Any])
|
||||
if (tmp.isInstanceOf[LinkedHashMap[String, Object]]) {
|
||||
val hm = tmp.asInstanceOf[LinkedHashMap[String, Object]]
|
||||
VerkleProofOfNonMembership.Deserial(hm)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}else{
|
||||
objectMapper.readValue(p, classOf[Any])
|
||||
}
|
||||
}
|
||||
|
||||
def SerialProof(proofs: Array[Any]): String = {
|
||||
val rs = new Array[String](proofs.length)
|
||||
val objectMapper = new ObjectMapper()
|
||||
for (i <- 0 to proofs.length - 1) {
|
||||
val tmp = objectMapper.writeValueAsString(proofs(i))
|
||||
val name = getProofType(proofs(i))
|
||||
rs(i) = new String(org.apache.commons.codec.binary.Hex.encodeHex(SerializeUtils.serialise(serialObj(tmp,name))))
|
||||
//new String(SerializeUtils.serialise(serialObj(tmp,name)))
|
||||
}
|
||||
val json = SerializeUtils.serialise(rs)
|
||||
val hJson = new String(org.apache.commons.codec.binary.Hex.encodeHex(json))
|
||||
hJson
|
||||
}
|
||||
|
||||
def DeserialProof(hstr: String): Array[Any] = {
|
||||
val json = org.apache.commons.codec.binary.Hex.decodeHex(hstr)
|
||||
val strs = SerializeUtils.deserialise(json)
|
||||
if (strs.isInstanceOf[Array[String]]) {
|
||||
val strArray = strs.asInstanceOf[Array[String]]
|
||||
val proofs = new Array[Any](strArray.length)
|
||||
for (i <- 0 to strArray.length - 1) {
|
||||
val tmp = SerializeUtils.deserialise(org.apache.commons.codec.binary.Hex.decodeHex(strArray(i)))
|
||||
//SerializeUtils.deserialise(strArray(i).getBytes)
|
||||
if(tmp.isInstanceOf[serialObj]){
|
||||
val sObj = tmp.asInstanceOf[serialObj]
|
||||
proofs(i) = getProofObj(sObj.p,sObj.n)
|
||||
}
|
||||
}
|
||||
proofs
|
||||
}else{
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package rep.accumulator.verkle.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class VerkleProofOfMembership {
|
||||
public String nodeId;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger acc_value;
|
||||
public MembershipProof proof;
|
||||
|
||||
public VerkleProofOfMembership(String nodeId, BigInteger acc_value, MembershipProof proof){
|
||||
this.nodeId = nodeId;
|
||||
this.acc_value = acc_value;
|
||||
this.proof = proof;
|
||||
}
|
||||
|
||||
public static VerkleProofOfMembership Deserial(LinkedHashMap<String,Object> ps){
|
||||
String id = ps.get("nodeId").toString();
|
||||
BigInteger v = new BigInteger(ps.get("acc_value").toString());
|
||||
LinkedHashMap<String,Object> tmp = (LinkedHashMap<String,Object>)ps.get("proof");
|
||||
return new VerkleProofOfMembership(id,v,MembershipProof.Deserial(tmp));
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package rep.accumulator.verkle.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class VerkleProofOfNonMembership {
|
||||
public String nodeId;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger acc_value;
|
||||
public NonMembershipProof proof;
|
||||
|
||||
public VerkleProofOfNonMembership(String nodeId,BigInteger acc_value,NonMembershipProof proof){
|
||||
this.nodeId = nodeId;
|
||||
this.acc_value = acc_value;
|
||||
this.proof = proof;
|
||||
}
|
||||
|
||||
public static VerkleProofOfNonMembership Deserial(LinkedHashMap<String,Object> ps){
|
||||
String id = ps.get("nodeId").toString();
|
||||
BigInteger v = new BigInteger(ps.get("acc_value").toString());
|
||||
LinkedHashMap<String,Object> tmp = (LinkedHashMap<String,Object>)ps.get("proof");
|
||||
return new VerkleProofOfNonMembership(id,v,NonMembershipProof.Deserial(tmp));
|
||||
}
|
||||
}
|
21
src/main/scala/rep/accumulator/verkle/util/Witness.java
Normal file
21
src/main/scala/rep/accumulator/verkle/util/Witness.java
Normal file
@ -0,0 +1,21 @@
|
||||
package rep.accumulator.verkle.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class Witness {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger witness;
|
||||
|
||||
public Witness(BigInteger witness){
|
||||
this.witness = witness;
|
||||
}
|
||||
|
||||
public static Witness Deserial(LinkedHashMap<String,Object> ps){
|
||||
BigInteger w = new BigInteger(ps.get("witness").toString());
|
||||
return new Witness(w);
|
||||
}
|
||||
}
|
29
src/main/scala/rep/accumulator/verkle/util/proofStruct.java
Normal file
29
src/main/scala/rep/accumulator/verkle/util/proofStruct.java
Normal file
@ -0,0 +1,29 @@
|
||||
package rep.accumulator.verkle.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class proofStruct {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger z;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger Q;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
public BigInteger r;
|
||||
public proofStruct(BigInteger z,BigInteger Q,BigInteger r){
|
||||
this.z = z;
|
||||
this.Q = Q;
|
||||
this.r = r;
|
||||
}
|
||||
|
||||
public static proofStruct Deserial(LinkedHashMap<String,Object> ps){
|
||||
BigInteger z1 = new BigInteger(ps.get("z").toString());
|
||||
BigInteger q1 = new BigInteger(ps.get("Q").toString());
|
||||
BigInteger r1 = new BigInteger(ps.get("r").toString());
|
||||
return new proofStruct(z1,q1,r1);
|
||||
}
|
||||
|
||||
}
|
@ -18,6 +18,8 @@ package rep.api.rest
|
||||
|
||||
import akka.util.{ByteString, Timeout}
|
||||
import akka.util.Timeout
|
||||
import org.json4s.jackson.JsonMethods.{pretty, render}
|
||||
import org.json4s.DefaultFormats
|
||||
|
||||
import scala.concurrent.duration._
|
||||
import rep.crypto._
|
||||
@ -29,7 +31,7 @@ import rep.network.base.ModuleBase
|
||||
import rep.network.consensus.byzantium.ConsensusCondition
|
||||
import rep.network.module.ModuleActorType
|
||||
import rep.proto.rc2.{ActionResult, ChaincodeId, Event, Transaction, TransactionResult}
|
||||
import rep.sc.Sandbox.DoTransactionResult
|
||||
import scalapb.json4s.JsonFormat
|
||||
import rep.sc.TypeOfSender
|
||||
import rep.storage.chain.block.BlockSearcher
|
||||
import rep.storage.db.factory.DBFactory
|
||||
@ -38,6 +40,10 @@ import rep.utils.{IdTool, MessageToJson, SerializeUtils}
|
||||
|
||||
import scala.concurrent.Await
|
||||
import akka.pattern.ask
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import rep.accumulator.verkle.VerkleTreeType
|
||||
import rep.accumulator.verkle.util.ProofSerialize
|
||||
import rep.accumulator.{Accumulator, PrimeTool, verkle}
|
||||
import rep.api.rest.ResultCode._
|
||||
import rep.censor.DataFilter
|
||||
import rep.sc.SandboxDispatcher.DoTransaction
|
||||
@ -79,6 +85,9 @@ object RestActor {
|
||||
|
||||
case class TransactionId(txid: String)
|
||||
|
||||
case class ProofOfTransaction(txid:String)
|
||||
case class ProofOfOutput(proof:String,txid:String)
|
||||
|
||||
case class TransactionStreamId(txid: String)
|
||||
|
||||
case class TranInfoAndHeightId(txid: String)
|
||||
@ -382,6 +391,50 @@ class RestActor(moduleName: String) extends ModuleBase(moduleName) {
|
||||
}
|
||||
sender ! r
|
||||
|
||||
case ProofOfTransaction(txId) =>
|
||||
val r = sr.getTransactionByTxId(txId) match {
|
||||
case None =>
|
||||
QueryResult(None)
|
||||
case t: Some[Transaction] =>
|
||||
val tg = t.get
|
||||
val tgb = tg.toByteArray
|
||||
val idx = verkle.util.verkleTool.getIndex(pe.getRepChainContext.getHashTool.hash(tgb))
|
||||
val prime = PrimeTool.hash2Prime(tgb, Accumulator.bitLength, pe.getRepChainContext.getHashTool)
|
||||
val root = pe.getRepChainContext.getVerkleTreeNodeBuffer(VerkleTreeType.TransactionTree).readMiddleNode(null)
|
||||
val proofs = root.getProofs(idx, tgb, prime)
|
||||
//val objectMapper = new ObjectMapper()
|
||||
//val json = objectMapper.writeValueAsString(proofs)
|
||||
//val hJson = new String(org.apache.commons.codec.binary.Hex.encodeHex(json.getBytes))
|
||||
val hJson = ProofSerialize.SerialProof(proofs)
|
||||
val rs = s"""{"proof": "${hJson}", "txid": "${txId}"}"""
|
||||
QueryResult(Option(JsonMethods.parse(rs)))
|
||||
}
|
||||
sender ! r
|
||||
|
||||
case ProofOfOutput(proof,txId) =>
|
||||
/*val json = new String(org.apache.commons.codec.binary.Hex.decodeHex(proof))
|
||||
val objectMapper = new ObjectMapper()
|
||||
val proofs = objectMapper.readValue(json, classOf[Array[Any]])*/
|
||||
val proofs = ProofSerialize.DeserialProof(proof)
|
||||
val r = sr.getTransactionByTxId(txId) match {
|
||||
case None =>
|
||||
QueryResult(Option(JsonMethods.parse(s"""{"result": "验证失败,没有找到交易", "txid": "${txId}"}""")))
|
||||
case t: Some[Transaction] =>
|
||||
val tg = t.get
|
||||
val tgb = tg.toByteArray
|
||||
val idx = verkle.util.verkleTool.getIndex(pe.getRepChainContext.getHashTool.hash(tgb))
|
||||
val prime = PrimeTool.hash2Prime(tgb, Accumulator.bitLength, pe.getRepChainContext.getHashTool)
|
||||
val root = pe.getRepChainContext.getVerkleTreeNodeBuffer(VerkleTreeType.TransactionTree).readMiddleNode(null)
|
||||
val b = root.verifyProofs(prime, proofs)
|
||||
var rs = if(b){
|
||||
s"""{"result": "验证成功", "txid": "${txId}"}"""
|
||||
}else{
|
||||
s"""{"result": "验证失败", "txid": "${txId}"}"""
|
||||
}
|
||||
QueryResult(Option(JsonMethods.parse(rs)))
|
||||
}
|
||||
sender ! r
|
||||
|
||||
// 根据txid检索交易字节流
|
||||
case TransactionStreamId(txId) =>
|
||||
val r = sr.getTransactionByTxId(txId)
|
||||
|
@ -380,7 +380,69 @@ class TransactionService(ra: ActorRef, repContext: RepChainSystemContext, isChec
|
||||
//只能处理application/json
|
||||
unmarshaller[CSpec].forContentTypes(MediaTypes.`application/json`))
|
||||
|
||||
val route = getTransaction ~ getTransactionStream ~ tranInfoAndHeightOfTranId ~ postSignTransaction ~ postTransaction ~ postSignTransactionStream
|
||||
val route = getTransaction ~ getTransactionStream ~ tranInfoAndHeightOfTranId ~ postSignTransaction ~ postTransaction ~ postSignTransactionStream ~ proofOfTransaction ~ verifyTransactionProof
|
||||
|
||||
@POST
|
||||
@Path("/verifyTransactionProof")
|
||||
@Operation(tags = Array("transaction"), summary = "验证交易证明", description = "verifyTransactionProof", method = "POST",
|
||||
requestBody = new RequestBody(description = "交易证明文件字符串", required = true,
|
||||
content = Array(new Content(mediaType = MediaType.APPLICATION_JSON, schema = new Schema(name = "交易证明文件字符串", description = "交易证明文件字符串", implementation = classOf[ProofOfOutput])))))
|
||||
@ApiResponses(Array(
|
||||
new ApiResponse(responseCode = "200", description = "返回交易证明的验证结果", content = Array(new Content(mediaType = "application/json", schema = new Schema(implementation = classOf[PostResult])))),
|
||||
new ApiResponse(responseCode = "202", description = "处理存在异常", content = Array(new Content(mediaType = "application/json", schema = new Schema(implementation = classOf[PostResult])))))
|
||||
)
|
||||
def verifyTransactionProof =
|
||||
path("transaction" / "verifyTransactionProof") {
|
||||
post {
|
||||
extractClientIP { ip =>
|
||||
entity(as[ProofOfOutput]) { proofOfOutput =>
|
||||
complete {
|
||||
(ra ? proofOfOutput).mapTo[QueryResult]
|
||||
}
|
||||
}
|
||||
// complete { (StatusCodes.Accepted, PostResult("hahhaha",None, Some("处理存在异常"))) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/proofOfTransaction/{transactionId}")
|
||||
@Operation(tags = Array("transaction"), summary = "返回指定id的交易证明", description = "proofOfTransaction", method = "GET")
|
||||
@Parameters(Array(
|
||||
new Parameter(name = "transactionId", description = "交易id", required = false, schema = new Schema(`type` = "string"), in = ParameterIn.PATH)))
|
||||
@ApiResponses(Array(
|
||||
new ApiResponse(responseCode = "200", description = "返回交易证明的json字符串", content = Array(new Content(mediaType = "application/json", schema = new Schema(implementation = classOf[QueryResult])))))
|
||||
)
|
||||
def proofOfTransaction =
|
||||
path("transaction" / "proofOfTransaction" / Segment) { transactionId =>
|
||||
get {
|
||||
extractClientIP { ip =>
|
||||
RepLogger.debug(RepLogger.APIAccess_Logger, s"remoteAddr=${ip} get transaction for txid,txid=${transactionId}")
|
||||
if (isCheckClientPermission) {
|
||||
headerValueByType[`Tls-Session-Info`]() { sessionInfo =>
|
||||
val cert = RepChainConfigFilePathMgr.getCert(sessionInfo)
|
||||
try {
|
||||
if (cert != null && repContext.getPermissionVerify.CheckPermissionOfX509Certificate(cert, "transaction", null)) {
|
||||
complete {
|
||||
(ra ? ProofOfTransaction(transactionId)).mapTo[QueryResult]
|
||||
}
|
||||
} else {
|
||||
complete(QueryResult(Option(JsonMethods.parse(string2JsonInput(PermissionVerify.errorInfo_None_Permission)))))
|
||||
}
|
||||
} catch {
|
||||
case e: Exception =>
|
||||
complete(QueryResult(Option(JsonMethods.parse(string2JsonInput(PermissionVerify.errorInfo_Cert_or_permission)))))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
complete {
|
||||
(ra ? ProofOfTransaction(transactionId)).mapTo[QueryResult]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@GET
|
||||
@Path("/{transactionId}")
|
||||
|
@ -490,6 +490,22 @@ class RepChainConfig {
|
||||
this.sysConf.getString("system.storage.block_file_type")
|
||||
}
|
||||
|
||||
def getEnableTxAccumulator: Boolean = {
|
||||
try {
|
||||
this.sysConf.getBoolean("system.accumulator.enable_transaction_accumulator")
|
||||
} catch {
|
||||
case e: Exception => false
|
||||
}
|
||||
}
|
||||
|
||||
def getEnableWtAccumulator: Boolean = {
|
||||
try {
|
||||
this.sysConf.getBoolean("system.accumulator.enable_world_state_accumulator")
|
||||
} catch {
|
||||
case e: Exception => false
|
||||
}
|
||||
}
|
||||
|
||||
def isEncryptedStorage:Boolean={
|
||||
try {
|
||||
this.sysConf.getBoolean("system.storage.is_encrypted")
|
||||
|
@ -4,7 +4,8 @@ package rep.app.system
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import akka.actor.{ActorRef, Address}
|
||||
import rep.accumulator.Accumulator.bitLength
|
||||
import rep.accumulator.verkle.VerkleNodeBuffer
|
||||
import rep.accumulator.verkle.{VerkleNodeBuffer, VerkleTreeType}
|
||||
import rep.accumulator.verkle.VerkleTreeType.VerkleTreeType
|
||||
import rep.accumulator.{PrimeTool, Rsa2048}
|
||||
import rep.app.conf.consensus.ConsensusParameterConfig
|
||||
import rep.app.conf.{RepChainConfig, SystemCertList, TimePolicy}
|
||||
@ -34,8 +35,8 @@ import rep.utils.SerializeUtils
|
||||
import java.math.BigInteger
|
||||
|
||||
class RepChainSystemContext (systemName:String){//},cs:ClusterSystem) {
|
||||
private val tx_acc_base_key = "tx_acc_base"
|
||||
private val state_acc_base_key = "state_acc_base"
|
||||
//private val tx_acc_base_key = "tx_acc_base"
|
||||
//private val state_acc_base_key = "state_acc_base"
|
||||
private val config : RepChainConfig = new RepChainConfig(systemName)
|
||||
private val customBroadcast : BroadcastOfCustom = new BroadcastOfCustom(this)
|
||||
private val timePolicy : TimePolicy = new TimePolicy(config.getSystemConf)
|
||||
@ -65,10 +66,11 @@ class RepChainSystemContext (systemName:String){//},cs:ClusterSystem) {
|
||||
private val registerClusterNode:ConcurrentHashMap[String,Address] = new ConcurrentHashMap[String,Address]()
|
||||
private val nodemgr = new NodeMgr
|
||||
|
||||
private val tx_acc_base : BigInteger = getAccBase(tx_acc_base_key)
|
||||
private val state_acc_base : BigInteger = getAccBase(state_acc_base_key)
|
||||
private val vb : VerkleNodeBuffer = new VerkleNodeBuffer(this)
|
||||
|
||||
//private val tx_acc_base : BigInteger = getAccBase(tx_acc_base_key)
|
||||
//private val state_acc_base : BigInteger = getAccBase(state_acc_base_key)
|
||||
private val tx_vb : VerkleNodeBuffer = new VerkleNodeBuffer(this,VerkleTreeType.TransactionTree)
|
||||
private val wt_vb : VerkleNodeBuffer = new VerkleNodeBuffer(this,VerkleTreeType.WorldStateTree)
|
||||
private val tx_r_vb: VerkleNodeBuffer = new VerkleNodeBuffer(this,VerkleTreeType.TransactionResultTree)
|
||||
private var ml : ActorRef = null
|
||||
|
||||
private val ContractStateChanged:ConcurrentHashMap[String,String] = new ConcurrentHashMap[String,String]()
|
||||
@ -110,19 +112,40 @@ class RepChainSystemContext (systemName:String){//},cs:ClusterSystem) {
|
||||
this.ml
|
||||
}
|
||||
|
||||
def getTxAccBase:BigInteger={
|
||||
/*def getTxAccBase:BigInteger={
|
||||
this.tx_acc_base
|
||||
}
|
||||
|
||||
def getStateAccBase:BigInteger={
|
||||
this.state_acc_base
|
||||
}*/
|
||||
|
||||
def getVerkleTreeAccRoot(verkleTreeType: VerkleTreeType):BigInteger={
|
||||
val nodeBuffer = this.getVerkleTreeNodeBuffer(verkleTreeType)
|
||||
val root = nodeBuffer.readMiddleNode(null)
|
||||
if(root != null){
|
||||
val tmp = root.getAccValue()
|
||||
if(tmp == null){
|
||||
PrimeTool.getPrimeOfRandom(bitLength, Rsa2048.getHalfModulus)
|
||||
}else{
|
||||
tmp
|
||||
}
|
||||
}else{
|
||||
PrimeTool.getPrimeOfRandom(bitLength, Rsa2048.getHalfModulus)
|
||||
}
|
||||
}
|
||||
|
||||
def getVerkleNodeBuffer:VerkleNodeBuffer={
|
||||
this.vb
|
||||
def getVerkleTreeNodeBuffer(verkleTreeType: VerkleTreeType):VerkleNodeBuffer={
|
||||
if(verkleTreeType == VerkleTreeType.TransactionTree){
|
||||
this.tx_vb
|
||||
}else if(verkleTreeType == VerkleTreeType.TransactionResultTree){
|
||||
this.tx_r_vb
|
||||
}else{
|
||||
this.wt_vb
|
||||
}
|
||||
}
|
||||
|
||||
private def getAccBase(key:String):BigInteger={
|
||||
/*private def getAccBase(key:String):BigInteger={
|
||||
var r = PrimeTool.getPrimeOfRandom(bitLength, Rsa2048.getHalfModulus)
|
||||
val db = DBFactory.getDBAccess(this.getConfig)
|
||||
|
||||
@ -138,7 +161,7 @@ class RepChainSystemContext (systemName:String){//},cs:ClusterSystem) {
|
||||
db.putBytes(KeyPrefixManager.getWorldStateKey(this.getConfig, key, "_"),SerializeUtils.serialise(r.toString()))
|
||||
}
|
||||
r
|
||||
}
|
||||
}*/
|
||||
|
||||
def getNodeMgr: NodeMgr = {
|
||||
this.nodemgr
|
||||
|
@ -1,91 +0,0 @@
|
||||
package rep.network.consensus.cfrd.block
|
||||
|
||||
import akka.actor.Props
|
||||
import rep.log.{RepLogger, RepTimeTracer}
|
||||
import rep.network.autotransaction.Topic
|
||||
import rep.network.consensus.cfrd.MsgOfCFRD.{CollectEndorsement,
|
||||
CreateBlock, ForceVoteInfo,VoteOfBlocker}
|
||||
import rep.network.consensus.common.block.IBlocker
|
||||
import rep.network.module.cfrd.CFRDActorType
|
||||
import rep.network.util.NodeHelp
|
||||
import rep.proto.rc2.{Block, Event}
|
||||
import rep.utils.GlobalUtils.{BlockerInfo, EventType}
|
||||
|
||||
object BlockerOfCFRDInMultipleBlocks{
|
||||
def props(name: String): Props = Props(classOf[BlockerOfCFRDInMultipleBlocks], name)
|
||||
}
|
||||
|
||||
class BlockerOfCFRDInMultipleBlocks (moduleName: String) extends IBlocker(moduleName){
|
||||
var preblock: Block = null
|
||||
var blockerInfo : BlockerInfo = null
|
||||
|
||||
override def preStart(): Unit = {
|
||||
RepLogger.info(RepLogger.Consensus_Logger, this.getLogMsgPrefix("CFRDBlocker module start"))
|
||||
super.preStart()
|
||||
}
|
||||
|
||||
private def CreateBlockHandler = {
|
||||
var blc : Block = null
|
||||
|
||||
if (blc ==null)
|
||||
blc = PackedBlock(0)
|
||||
if (blc != null) {
|
||||
RepTimeTracer.setEndTime(pe.getSysTag, "createBlock", System.currentTimeMillis(), blc.getHeader.height, blc.transactions.size)
|
||||
this.preblock = blc
|
||||
this.blockerInfo = pe.getBlocker
|
||||
schedulerLink = clearSched()
|
||||
//在发出背书时,告诉对方我是当前出块人,取出系统的名称
|
||||
RepTimeTracer.setStartTime(pe.getSysTag, "Endorsement", System.currentTimeMillis(), blc.getHeader.height, blc.transactions.size)
|
||||
//RepLogger.print(RepLogger.zLogger,"send CollectEndorsement, " + pe.getSysTag
|
||||
// + ", " + pe.getCurrentBlockHash+ ", " + blc.previousBlockHash.toStringUtf8)
|
||||
//pe.getActorRef(CFRDActorType.ActorType.endorsementcollectioner) ! CollectEndorsement(this.preblock, pe.getSysTag)
|
||||
//pe.getActorRef(CFRDActorType.ActorType.endorsementcollectioner) ! CollectEndorsement(this.preblock, pe.getSysTag,pe.getBlocker.VoteIndex)
|
||||
pe.getActorRef(CFRDActorType.ActorType.endorsementcollectioner) ! CollectEndorsement(this.preblock, ForceVoteInfo(this.blockerInfo.voteBlockHash,this.blockerInfo.VoteHeight,this.blockerInfo.VoteIndex,pe.getSysTag))
|
||||
} else {
|
||||
RepLogger.trace(RepLogger.Consensus_Logger, this.getLogMsgPrefix("create new block error,CreateBlock is null" + "~" + selfAddr))
|
||||
pe.getActorRef(CFRDActorType.ActorType.voter) ! VoteOfBlocker
|
||||
}
|
||||
}
|
||||
|
||||
override def receive = {
|
||||
//创建块请求(给出块人)
|
||||
case CreateBlock =>
|
||||
if (!pe.isSynching) {
|
||||
if (NodeHelp.isBlocker(pe.getBlocker.blocker, pe.getSysTag) && pe.getBlocker.voteBlockHash == pe.getCurrentBlockHash) {
|
||||
sendEvent(EventType.PUBLISH_INFO, mediator, pe.getSysTag, Topic.Block, Event.Action.CANDIDATOR)
|
||||
//是出块节点
|
||||
if (preblock == null || (preblock.getHeader.hashPrevious.toStringUtf8() != pe.getBlocker.voteBlockHash)) {
|
||||
CreateBlockHandler
|
||||
}else{
|
||||
if(preblock != null && preblock.getHeader.hashPrevious.toStringUtf8() == pe.getBlocker.voteBlockHash && this.blockerInfo != null
|
||||
&& this.blockerInfo.VoteIndex < pe.getBlocker.VoteIndex ){
|
||||
//这种情况说明系统在出块超时重新抽签是又抽到了自己,由于之前已经在同一高度上建立了新块,但是在背书上已经失败,背书失败的原因是可能是抽签不同步导致背书失败。
|
||||
// 由于在窄带上考虑带宽的问题,限制了背书信息的发送,背书发送模块停止,在此发送消息,启动再次背书。
|
||||
//此处就是发送再次背书的消息,以启动出块
|
||||
//更新抽签索引
|
||||
this.blockerInfo = pe.getBlocker
|
||||
//发送背书启动消息给背书收集器
|
||||
RepLogger.trace(RepLogger.Consensus_Logger, this.getLogMsgPrefix(s"created new block,restart endorsement,new height=${this.preblock.getHeader.height},local height=${pe.getCurrentHeight}" + "~" + selfAddr))
|
||||
//pe.getActorRef(CFRDActorType.ActorType.endorsementcollectioner) ! CollectEndorsement(this.preblock, pe.getSysTag)
|
||||
//pe.getActorRef(CFRDActorType.ActorType.endorsementcollectioner) ! CollectEndorsement(this.preblock, pe.getSysTag,pe.getBlocker.VoteIndex)
|
||||
pe.getActorRef(CFRDActorType.ActorType.endorsementcollectioner) ! CollectEndorsement(this.preblock, ForceVoteInfo(this.blockerInfo.voteBlockHash,this.blockerInfo.VoteHeight,this.blockerInfo.VoteIndex,pe.getSysTag))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//出块标识错误,暂时不用做任何处理
|
||||
RepLogger.trace(RepLogger.Consensus_Logger, this.getLogMsgPrefix(s"create new block,do not blocker or blocker hash not equal current hash,height=${pe.getCurrentHeight}" + "~" + selfAddr))
|
||||
}
|
||||
} else {
|
||||
//节点状态不对
|
||||
RepLogger.trace(RepLogger.Consensus_Logger, this.getLogMsgPrefix(s"create new block,node status error,status is synching,height=${pe.getCurrentHeight}" + "~" + selfAddr))
|
||||
}
|
||||
|
||||
//zhjtps
|
||||
/* case CreateBlockTPS(ts : Seq[Transaction], trs : Seq[TransactionResult]) =>
|
||||
tsTPS = ts
|
||||
trsTPS = trs*/
|
||||
|
||||
case _ => //ignore
|
||||
}
|
||||
}
|
||||
|
@ -1,209 +0,0 @@
|
||||
package rep.network.consensus.cfrd.vote
|
||||
|
||||
import akka.actor.Props
|
||||
import rep.log.RepLogger
|
||||
import rep.network.autotransaction.Topic
|
||||
import rep.network.consensus.byzantium.ConsensusCondition
|
||||
import rep.network.consensus.cfrd.MsgOfCFRD.{CreateBlock, ForceVoteInfo, SpecifyVoteHeight, VoteOfBlocker, VoteOfForce, VoteOfReset}
|
||||
import rep.network.consensus.cfrd.vote.VoterOfCFRDInMultipleBlocks.{CheckZero, RequestWithZeroTransaction}
|
||||
import rep.network.consensus.common.algorithm.IRandomAlgorithmOfVote
|
||||
import rep.network.consensus.common.vote.IVoter
|
||||
import rep.network.module.cfrd.CFRDActorType
|
||||
import rep.network.util.NodeHelp
|
||||
import scala.collection.mutable.ArrayBuffer
|
||||
|
||||
|
||||
object VoterOfCFRDInMultipleBlocks{
|
||||
def props(name: String): Props = Props(classOf[VoterOfCFRDInMultipleBlocks],name)
|
||||
|
||||
|
||||
case object CheckZero
|
||||
|
||||
case class RequestWithZeroTransaction(height: Long, systemName: String)
|
||||
|
||||
case class ZeroTransactionRequests(height: Long, nodes: ArrayBuffer[String])
|
||||
}
|
||||
|
||||
class VoterOfCFRDInMultipleBlocks (moduleName: String) extends IVoter(moduleName: String) {
|
||||
|
||||
import scala.concurrent.duration._
|
||||
import context.dispatcher
|
||||
|
||||
override def preStart(): Unit = {
|
||||
//注册接收交易为空的广播
|
||||
if (pe.getRepChainContext.getConsensusNodeConfig.getVoteListOfConfig.contains(pe.getSysTag)) {
|
||||
//共识节点可以订阅交易为空的广播事件
|
||||
if (pe.getRepChainContext.getConfig.useCustomBroadcast) {
|
||||
pe.getRepChainContext.getCustomBroadcastHandler.SubscribeTopic(Topic.MessageWithZeroTransaction, "/user/modulemanager/voter")
|
||||
RepLogger.info(RepLogger.System_Logger, this.getLogMsgPrefix("Subscribe custom broadcast,/user/modulemanager/voter"))
|
||||
}
|
||||
//else {
|
||||
SubscribeTopic(mediator, self, selfAddr, Topic.MessageWithZeroTransaction, false)
|
||||
RepLogger.info(RepLogger.System_Logger,this.getLogMsgPrefix("Subscribe system broadcast,/user/modulemanager/voter"))
|
||||
//}
|
||||
}
|
||||
RepLogger.info(RepLogger.Consensus_Logger, this.getLogMsgPrefix("VoterOfCFRD module start"))
|
||||
super.preStart()
|
||||
}
|
||||
|
||||
this.algorithmInVoted = new IRandomAlgorithmOfVote
|
||||
|
||||
//////////////交易数为零导致无法进行抽签,广播交易数为零请求,接收到该请求的节点,
|
||||
// 获得了大于1/2的节点请求之后,如果本节点有未出块的交易,广播一条交易。
|
||||
// 如果当前节点与大于1/2节点的高度不一致,发送同步命令,进行同步
|
||||
private var schedulerOfZero: akka.actor.Cancellable = null
|
||||
|
||||
|
||||
private def checkZeroScheduler: Unit = {
|
||||
if (!checkTranNum) {
|
||||
if (schedulerOfZero == null) {
|
||||
this.schedulerOfZero = scheduler.scheduleWithFixedDelay(15.second,15.second, self, VoterOfCFRD.CheckZero)
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag}," +
|
||||
s"startup scheduler" + "~" + selfAddr))
|
||||
}
|
||||
} else {
|
||||
if (schedulerOfZero != null) {
|
||||
schedulerOfZero.cancel()
|
||||
this.schedulerOfZero = null
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag}," +
|
||||
s"delete scheduler" + "~" + selfAddr))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
override protected def NoticeBlockerMsg: Unit = {
|
||||
if (this.Blocker.blocker.equals(pe.getSysTag)) {
|
||||
//发送建立新块的消息
|
||||
pe.getActorRef(CFRDActorType.ActorType.blocker) ! CreateBlock
|
||||
}
|
||||
}
|
||||
|
||||
override protected def DelayVote: Unit = {
|
||||
if (voteCount >= 50)
|
||||
this.voteCount = 1
|
||||
else
|
||||
this.voteCount += 1
|
||||
val time = this.voteCount * pe.getRepChainContext.getTimePolicy.getVoteRetryDelay
|
||||
schedulerLink = clearSched()
|
||||
schedulerLink = scheduler.scheduleOnce(time.millis, self, VoteOfBlocker)
|
||||
}
|
||||
|
||||
|
||||
override protected def vote(isForce: Boolean, forceInfo: ForceVoteInfo): Unit = {
|
||||
checkZeroScheduler
|
||||
if (checkTranNum || isForce) {
|
||||
val currentblockhash = pe.getCurrentBlockHash
|
||||
val currentheight = pe.getCurrentHeight
|
||||
if (this.Blocker.voteBlockHash == "") {
|
||||
this.cleanVoteInfo
|
||||
this.resetCandidator(currentblockhash)
|
||||
this.resetBlocker(0, currentblockhash, currentheight)
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},first voter,blocker=${this.Blocker.blocker},voteidx=${this.Blocker.VoteIndex}" + "~" + selfAddr))
|
||||
} else {
|
||||
if (!this.Blocker.voteBlockHash.equals(currentblockhash)) {
|
||||
//抽签的基础块已经变化,需要重续选择候选人
|
||||
this.cleanVoteInfo
|
||||
this.resetCandidator(currentblockhash)
|
||||
this.resetBlocker(0, currentblockhash, currentheight)
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},hash change,reset voter,height=${currentheight},hash=${currentblockhash},blocker=${this.Blocker.blocker},voteidx=${this.Blocker.VoteIndex}" + "~" + selfAddr))
|
||||
} else {
|
||||
if (this.Blocker.blocker == "") {
|
||||
this.cleanVoteInfo
|
||||
this.resetCandidator(currentblockhash)
|
||||
this.resetBlocker(0, currentblockhash, currentheight)
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},blocker=null,reset voter,height=${currentheight},blocker=${this.Blocker.blocker},voteidx=${this.Blocker.VoteIndex}" + "~" + selfAddr))
|
||||
} else {
|
||||
/*if ((System.currentTimeMillis() - this.Blocker.voteTime) / 1000 > TimePolicy.getTimeOutBlock) {
|
||||
//说明出块超时
|
||||
/*if(NodeHelp.isBlocker(this.Blocker.blocker, pe.getSysTag)){
|
||||
pe.getTransPoolMgr.rollbackTransaction("identifier-"+(pe.getCurrentHeight+1))
|
||||
}*/
|
||||
this.voteCount = 0
|
||||
this.resetBlocker(this.Blocker.VoteIndex + 1, currentblockhash, currentheight)
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},block timeout,reset voter,height=${currentheight},blocker=${this.Blocker.blocker},voteidx=${this.Blocker.VoteIndex}" + "~" + selfAddr))
|
||||
} else {
|
||||
NoticeBlockerMsg
|
||||
}*/
|
||||
if (isForce && forceInfo != null) {
|
||||
if (this.Blocker.voteBlockHash.equals(forceInfo.blockHash) && this.Blocker.VoteIndex < forceInfo.voteIndex) {
|
||||
this.voteCount = 0
|
||||
this.resetBlocker(forceInfo.voteIndex, currentblockhash, currentheight)
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},SpecifyVoteHeight,reset voter,height=${currentheight},blocker=${this.Blocker.blocker}," +
|
||||
s"voteidx=${this.Blocker.VoteIndex}" + "~" + selfAddr))
|
||||
} else {
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},SpecifyVoteHeight failed,reset voter,height=${currentheight},blocker=${this.Blocker.blocker}," +
|
||||
s"SpecifyVoteHeight=${forceInfo.voteIndex}" + "~" + selfAddr))
|
||||
}
|
||||
} else {
|
||||
if ((System.currentTimeMillis() - this.Blocker.voteTime) / 1000 > pe.getRepChainContext.getTimePolicy.getTimeOutBlock) {
|
||||
//说明出块超时
|
||||
pe.getRepChainContext.getProblemAnalysis.AddBlockFailure(pe.getSysTag,this.Blocker.blocker)
|
||||
//RepLogger.sendAlertToDB(pe.getRepChainContext.getHttpLogger(), AlertInfo("CONSENSUS", 5, s"block timeout,reset voter,height=${currentheight},blocker=${this.Blocker.blocker},voteidx=${this.Blocker.VoteIndex}."))
|
||||
this.voteCount = 0
|
||||
this.resetBlocker(this.Blocker.VoteIndex + 1, currentblockhash, currentheight)
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},block timeout,reset voter,height=${currentheight},blocker=${this.Blocker.blocker},voteidx=${this.Blocker.VoteIndex}" + "~" + selfAddr))
|
||||
} else {
|
||||
NoticeBlockerMsg
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag},transaction is not enough,waiting transaction,height=${pe.getCurrentHeight}" + "~" + selfAddr))
|
||||
}
|
||||
}
|
||||
|
||||
override def receive: Receive = {
|
||||
case VoteOfBlocker =>
|
||||
if (NodeHelp.isCandidateNow(pe.getSysTag, pe.getRepChainContext.getSystemCertList.getVoteList)) {
|
||||
voteMsgHandler(false, null)
|
||||
}
|
||||
case VoteOfForce =>
|
||||
voteMsgHandler(true, null)
|
||||
case VoteOfReset =>
|
||||
cleanVoteInfo
|
||||
voteMsgHandler(true, null)
|
||||
case SpecifyVoteHeight(voteinfo) =>
|
||||
voteMsgHandler(true, voteinfo)
|
||||
case CheckZero =>
|
||||
if (new ConsensusCondition(pe.getRepChainContext).CheckWorkConditionOfSystem(pe.getRepChainContext.getNodeMgr.getStableNodes.size)) {
|
||||
if (!pe.isSynching) {
|
||||
if (checkTranNum) {
|
||||
//如果产生交易了,删除定时器,什么也不做
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag}," +
|
||||
s"CheckZero stop" + "~" + selfAddr))
|
||||
if (schedulerOfZero != null) schedulerOfZero.cancel()
|
||||
this.schedulerOfZero = null
|
||||
} else {
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag}," +
|
||||
s"CheckZero ,broadcast RequestWithZeroTransaction " + "~" + selfAddr))
|
||||
pe.getRepChainContext.getCustomBroadcastHandler.PublishOfCustom(context,mediator,Topic.MessageWithZeroTransaction,RequestWithZeroTransaction(pe.getCurrentHeight, pe.getSysTag))
|
||||
//mediator ! Publish(Topic.MessageWithZeroTransaction, RequestWithZeroTransaction(pe.getCurrentHeight, pe.getSysTag))
|
||||
}
|
||||
}
|
||||
}
|
||||
case RequestWithZeroTransaction(h, sn) =>
|
||||
recvZeroTransactionHandle(VoterOfCFRDInMultipleBlocks.RequestWithZeroTransaction(h, sn))
|
||||
}
|
||||
|
||||
private def recvZeroTransactionHandle(zt: RequestWithZeroTransaction): Unit = {
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag}," +
|
||||
s"recv RequestWithZeroTransaction,height=${zt.height},requester=${zt.systemName}" + "~" + selfAddr))
|
||||
if (new ConsensusCondition(pe.getRepChainContext).CheckWorkConditionOfSystem(pe.getRepChainContext.getNodeMgr.getStableNodes.size)) {
|
||||
if (!pe.isSynching && checkTranNum) {
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag}," +
|
||||
s"recv RequestWithZeroTransaction,broadcast transaction,requester=${zt.systemName}" + "~" + selfAddr))
|
||||
val t = pe.getRepChainContext.getTransactionPool.getRandomTransaction
|
||||
if (t != null) {
|
||||
RepLogger.trace(RepLogger.Vote_Logger, this.getLogMsgPrefix(s"sysname=${pe.getSysTag}," +
|
||||
s"recv RequestWithZeroTransaction,get transaction ,broadcast transaction,tid=${t.id},requester=${zt.systemName}" + "~" + selfAddr))
|
||||
//mediator ! Publish(Topic.Transaction, t)
|
||||
pe.getRepChainContext.getCustomBroadcastHandler.PublishOfCustom(context,mediator,Topic.Transaction,t)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -80,7 +80,10 @@ abstract class IBlocker(moduleName: String) extends ModuleBase(moduleName) {
|
||||
//块hash在预执行中生成
|
||||
//blc = BlockHelp.AddBlockHash(blc)
|
||||
RepLogger.trace(RepLogger.Consensus_Logger, this.getLogMsgPrefix(s"create new block,AddBlockHash success,height=${blc.getHeader.height},local height=${pe.getBlocker.VoteHeight}" + "~" + selfAddr))
|
||||
blc.withHeader(BlockHelp.AddHeaderSignToBlock(blc.getHeader, pe.getSysTag,pe.getRepChainContext.getSignTool))
|
||||
//区块hash的计算放到出块人打包区块模块
|
||||
var rBlock = BlockHelp.addTransactionToVerkleTree(blc, pe.getRepChainContext)
|
||||
rBlock = BlockHelp.AddBlockHeaderHash(rBlock, pe.getRepChainContext.getHashTool)
|
||||
blc.withHeader(BlockHelp.AddHeaderSignToBlock(rBlock.getHeader, pe.getSysTag,pe.getRepChainContext.getSignTool))
|
||||
} else {
|
||||
RepLogger.trace(RepLogger.Consensus_Logger, this.getLogMsgPrefix("create new block error,preload error" + "~" + selfAddr))
|
||||
//PackedBlock(start + trans.size)
|
||||
|
@ -18,12 +18,19 @@ package rep.network.consensus.util
|
||||
|
||||
import com.google.protobuf.ByteString
|
||||
import com.google.protobuf.timestamp.Timestamp
|
||||
import rep.accumulator.verkle.VerkleTreeType
|
||||
import rep.accumulator.verkle.util.verkleTool
|
||||
import rep.accumulator.{Accumulator, PrimeTool, verkle}
|
||||
import scalapb.json4s.JsonFormat
|
||||
import rep.app.conf.RepChainConfig
|
||||
import rep.app.system.RepChainSystemContext
|
||||
import rep.crypto.{BytesHex, Sha256}
|
||||
import rep.utils.{IdTool, SerializeUtils, TimeUtils}
|
||||
import rep.crypto.cert.SignTool
|
||||
import rep.proto.rc2.{Block, BlockHeader, Signature, Transaction}
|
||||
import rep.proto.rc2.{Block, BlockHeader, Signature, Transaction, TransactionResult}
|
||||
|
||||
import java.math.BigInteger
|
||||
import scala.collection.mutable.ArrayBuffer
|
||||
|
||||
object BlockHelp {
|
||||
|
||||
@ -101,6 +108,42 @@ object BlockHelp {
|
||||
}
|
||||
}
|
||||
|
||||
//计算交易字节所对应的素数,返回交易的字节hash,素数和交易字节
|
||||
private def handleTransaction(data: Array[Transaction],sha256: Sha256): Array[(Array[Int], Array[Byte], BigInteger)] = {
|
||||
val sb = new ArrayBuffer[(Array[Int], Array[Byte], BigInteger)]()
|
||||
data.foreach(t => {
|
||||
val tb = t.toByteArray
|
||||
val prime = PrimeTool.hash2Prime(tb, Accumulator.bitLength, sha256)
|
||||
sb += Tuple3(verkle.util.verkleTool.getIndex(sha256.hash(tb)), tb, prime)
|
||||
})
|
||||
sb.toArray
|
||||
}
|
||||
|
||||
def addTransactionToVerkleTree(block:Block,ctx:RepChainSystemContext):Block = {
|
||||
val Root:String = ""
|
||||
if(ctx.getConfig.getEnableTxAccumulator){
|
||||
val root = ctx.getVerkleTreeNodeBuffer(VerkleTreeType.TransactionTree).readMiddleNode(null)
|
||||
val ts = handleTransaction(block.transactions.toArray,ctx.getHashTool)
|
||||
ts.foreach(t=>{
|
||||
System.out.println(s"serial=${t._1} id=${verkleTool.getKey(t._1)},prime=${t._3}")
|
||||
root.addState(t._1, t._2, t._3)
|
||||
})
|
||||
val txAccRoot = root.getAccValue().toString()
|
||||
val head = block.getHeader.withCommitTx(_root_.com.google.protobuf.ByteString.copyFrom(txAccRoot,"UTF-8"))
|
||||
block.withHeader(head)
|
||||
}else{
|
||||
block
|
||||
}
|
||||
}
|
||||
|
||||
/*def addWorldStateToVerkleTree(block: Block, cfg: RepChainConfig): Unit = {
|
||||
val Root: String = "";
|
||||
if (cfg.getEnableWtAccumulator) {
|
||||
|
||||
}
|
||||
|
||||
}*/
|
||||
|
||||
def GetOnlyBlockHeaderHash(header: BlockHeader, sha256: Sha256): String = {
|
||||
try {
|
||||
val headerOutEndorse = header.clearEndorsements
|
||||
|
@ -84,6 +84,8 @@ class GenesisBlocker(moduleName: String) extends ModuleBase(moduleName) {
|
||||
preblock = ExecuteTransactionOfBlock(preblock)
|
||||
if (preblock != null) {
|
||||
//preblock = BlockHelp.AddBlockHash(preblock)
|
||||
preblock = BlockHelp.addTransactionToVerkleTree(preblock,pe.getRepChainContext)
|
||||
preblock = BlockHelp.AddBlockHeaderHash(preblock,pe.getRepChainContext.getHashTool)
|
||||
preblock = preblock.withHeader(BlockHelp.AddHeaderSignToBlock(preblock.getHeader, pe.getSysTag,pe.getRepChainContext.getSignTool))
|
||||
//sendEvent(EventType.RECEIVE_INFO, mediator, selfAddr, Topic.Block, Event.Action.BLOCK_NEW)
|
||||
//mediator ! Publish(Topic.Block, ConfirmedBlock(preblock, self))
|
||||
|
@ -4,13 +4,13 @@ import akka.actor.Props
|
||||
import rep.log.RepLogger
|
||||
import rep.network.cache.TransactionOfCollectioner
|
||||
import rep.network.confirmblock.common.ConfirmOfBlock
|
||||
import rep.network.consensus.cfrd.block.{BlockerOfCFRD, BlockerOfCFRDInMultipleBlocks, EndorseCollector}
|
||||
import rep.network.consensus.cfrd.block.{BlockerOfCFRD, EndorseCollector}
|
||||
import rep.network.consensus.cfrd.endorse.DispatchOfRecvEndorsement
|
||||
import rep.network.consensus.cfrd.MsgOfCFRD.VoteOfBlocker
|
||||
import rep.network.module.{IModuleManager, ModuleActorType}
|
||||
import rep.network.sync.response.SynchronizeResponser
|
||||
import rep.network.sync.request.cfrd.SynchRequesterOfCFRD
|
||||
import rep.network.consensus.cfrd.vote.{VoterOfCFRD, VoterOfCFRDInMultipleBlocks}
|
||||
import rep.network.consensus.cfrd.vote.{VoterOfCFRD}
|
||||
import rep.network.persistence.cfrd.StoragerOfCFRD
|
||||
import rep.network.sync.request.raft.SynchRequesterOfRAFT
|
||||
|
||||
@ -42,16 +42,16 @@ class ModuleManagerOfCFRD(moduleName: String, isStartup: Boolean) extends IModul
|
||||
}
|
||||
pe.register(ModuleActorType.ActorType.storager,context.actorOf(StoragerOfCFRD.props("storager"), "storager"))
|
||||
|
||||
//pe.register(CFRDActorType.ActorType.blocker,context.actorOf(BlockerOfCFRD.props("blocker"), "blocker"))
|
||||
pe.register(CFRDActorType.ActorType.blocker, context.actorOf(BlockerOfCFRDInMultipleBlocks.props("blocker"), "blocker"))
|
||||
pe.register(CFRDActorType.ActorType.blocker,context.actorOf(BlockerOfCFRD.props("blocker"), "blocker"))
|
||||
//pe.register(CFRDActorType.ActorType.blocker, context.actorOf(BlockerOfCFRDInMultipleBlocks.props("blocker"), "blocker"))
|
||||
|
||||
|
||||
pe.register(CFRDActorType.ActorType.confirmerofblock,context.actorOf(ConfirmOfBlock.props("confirmerofblock"), "confirmerofblock"))
|
||||
pe.register(CFRDActorType.ActorType.endorsementcollectioner,context.actorOf(EndorseCollector.props("endorsementcollectioner"), "endorsementcollectioner"))
|
||||
pe.register(CFRDActorType.ActorType.dispatchofRecvendorsement,context.actorOf(DispatchOfRecvEndorsement.props("dispatchofRecvendorsement"), "dispatchofRecvendorsement"))
|
||||
|
||||
//pe.register(CFRDActorType.ActorType.voter,context.actorOf(VoterOfCFRD.props("voter"), "voter"))
|
||||
pe.register(CFRDActorType.ActorType.voter,context.actorOf(VoterOfCFRDInMultipleBlocks.props("voter"), "voter"))
|
||||
pe.register(CFRDActorType.ActorType.voter,context.actorOf(VoterOfCFRD.props("voter"), "voter"))
|
||||
//pe.register(CFRDActorType.ActorType.voter,context.actorOf(VoterOfCFRDInMultipleBlocks.props("voter"), "voter"))
|
||||
|
||||
if(pe.getRepChainContext.getConfig.getConsensusSynchType == "CFRD"){
|
||||
pe.register(CFRDActorType.ActorType.synchrequester,context.actorOf(SynchRequesterOfCFRD.props("synchrequester"), "synchrequester"))
|
||||
|
@ -104,7 +104,9 @@ class PreloaderForTransaction(moduleName: String) extends ModuleBase(moduleName)
|
||||
//RepLogger.error(RepLogger.Business_Logger, this.getLogMsgPrefix( s" current block height=${block.height},trans create serial: ${outputTransSerialOfBlock(block,rblock)}"))
|
||||
if (rBlock.getHeader.hashPresent == _root_.com.google.protobuf.ByteString.EMPTY) {
|
||||
//如果没有当前块的hash在这里生成,如果是背书已经有了hash不再进行计算
|
||||
rBlock = BlockHelp.AddBlockHeaderHash(rBlock,pe.getRepChainContext.getHashTool)
|
||||
//这两行代码放到出块人模块执行
|
||||
//rBlock = BlockHelp.addTransactionToVerkleTree(rBlock,pe.getRepChainContext)
|
||||
//rBlock = BlockHelp.AddBlockHeaderHash(rBlock,pe.getRepChainContext.getHashTool)
|
||||
}
|
||||
Some(rBlock)
|
||||
} catch {
|
||||
|
@ -89,7 +89,7 @@ class ContractAssetsTPL extends IContract {
|
||||
if (dfrom < data.amount)
|
||||
throw ContractException("余额不足")
|
||||
|
||||
////跨合约调用样例
|
||||
////跨合约调用
|
||||
/*val cid = ChaincodeId("ParallelPutProofTPL", 1)
|
||||
val cdata = ProofDataSingle("cky1", dfrom.toString)
|
||||
|
||||
|
@ -39,7 +39,7 @@ object CreateTestTransactionService{
|
||||
class CreateTestTransactionService {
|
||||
val test_transaction_prefix = "acc_test_tx_"
|
||||
val test_max_key = "acc_test_tx_max"
|
||||
val max_tx_limited: Int = 10000000
|
||||
val max_tx_limited: Int = 100
|
||||
var current_max_tx_number: AtomicInteger = new AtomicInteger(-1)
|
||||
var read_tx_number : AtomicInteger = new AtomicInteger(0)
|
||||
val ctx = new RepChainSystemContext("121000005l35120456.node1")
|
||||
|
@ -3,6 +3,7 @@ package rep.accumulator
|
||||
|
||||
import org.apache.commons.codec.BinaryEncoder
|
||||
import rep.accumulator.CreateTestTransactionService.tx_data
|
||||
import rep.accumulator.verkle.VerkleTreeType
|
||||
import rep.accumulator.verkle.util.verkleTool
|
||||
import rep.crypto.Sha256
|
||||
import rep.utils.SerializeUtils
|
||||
@ -15,8 +16,8 @@ object Verkle_test extends App {
|
||||
val ctx = tx_service.ctx
|
||||
val hash_tool = new Sha256(ctx.getCryptoMgr.getInstance)
|
||||
|
||||
//test_Tree
|
||||
test_sha
|
||||
test_Tree
|
||||
//test_sha
|
||||
def test_sha:Unit={
|
||||
val str = "adf-sle-"
|
||||
val str1 = "adf-sle-"+"sdd"
|
||||
@ -30,13 +31,15 @@ object Verkle_test extends App {
|
||||
def test_Tree: Unit = {
|
||||
val t = getTransaction(60)
|
||||
val ts = handleTransaction(t)
|
||||
val root = ctx.getVerkleNodeBuffer.readMiddleNode(null)
|
||||
for (i <- 0 to 49) {
|
||||
val root = ctx.getVerkleTreeNodeBuffer(VerkleTreeType.TransactionTree).readMiddleNode(null)
|
||||
for (i <- 0 to 10) {
|
||||
System.out.println(s"serial=${i} id=${verkleTool.getKey(ts(i)._1)},prime=${ts(i)._3}")
|
||||
root.addState(ts(i)._1, ts(i)._2, ts(i)._3)
|
||||
val tmpNode = ctx.getVerkleTreeNodeBuffer(VerkleTreeType.TransactionTree).readMiddleNode(null)
|
||||
System.out.println(tmpNode.middleToString)
|
||||
}
|
||||
|
||||
for (i <- 40 to 49) {
|
||||
for (i <- 3 to 6) {
|
||||
val d = ts(i)
|
||||
val proofs = root.getProofs(d._1, d._2, d._3)
|
||||
System.out.println("proof length=" + SerializeUtils.serialise(proofs).length)
|
||||
@ -44,11 +47,11 @@ object Verkle_test extends App {
|
||||
if (b) {
|
||||
System.out.println(s"serial=${i} id=${verkleTool.getKey(d._1)},verify member proof ok")
|
||||
} else {
|
||||
System.out.println(s"serial=${i} id=${verkleTool.getKey(d._1)},verify member proof ok")
|
||||
System.out.println(s"serial=${i} id=${verkleTool.getKey(d._1)},verify member proof false")
|
||||
}
|
||||
}
|
||||
|
||||
for (i <- 50 to 59) {
|
||||
for (i <- 7 to 10) {
|
||||
val d = ts(i)
|
||||
val proofs = root.getProofs(d._1, d._2, d._3)
|
||||
System.out.println("proof length=" + SerializeUtils.serialise(proofs).length)
|
||||
@ -56,7 +59,7 @@ object Verkle_test extends App {
|
||||
if (b) {
|
||||
System.out.println(s"serial=${i} id=${verkleTool.getKey(d._1)},verify Nonmember proof ok")
|
||||
} else {
|
||||
System.out.println(s"serial=${i} id=${verkleTool.getKey(d._1)},verify Nonmember proof ok")
|
||||
System.out.println(s"serial=${i} id=${verkleTool.getKey(d._1)},verify Nonmember proof false")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,8 +1,9 @@
|
||||
package rep.accumulator
|
||||
|
||||
|
||||
import rep.accumulator.Accumulator.Witness
|
||||
import rep.accumulator.CreateTestTransactionService.tx_data
|
||||
import rep.accumulator.verkle.VerkleTreeType
|
||||
import rep.accumulator.verkle.util.Witness
|
||||
import rep.crypto.Sha256
|
||||
|
||||
import java.math.BigInteger
|
||||
@ -27,7 +28,7 @@ object testTxAccumulator extends App {
|
||||
test_compute_individual_witnesses
|
||||
|
||||
def test_compute_individual_witnesses:Unit={
|
||||
val root_acc = new Accumulator(tx_service.ctx.getTxAccBase, null, hash_tool)
|
||||
val root_acc = new Accumulator(tx_service.ctx.getVerkleTreeAccRoot(VerkleTreeType.TransactionTree), null, hash_tool)
|
||||
val a = block1(0).prime
|
||||
val b = block1(1).prime
|
||||
val c = block1(2).prime
|
||||
@ -101,7 +102,7 @@ object testTxAccumulator extends App {
|
||||
val d = block1(3).prime
|
||||
val acc1 = root_acc.addOfBatch(Array(a, b, c))
|
||||
val acc2 = root_acc.addOfBatch(Array(c, d))
|
||||
val acc2_wit = Witness(acc2.getAccVaule)
|
||||
val acc2_wit = new Witness(acc2.getAccVaule)
|
||||
|
||||
val wit_new = acc1.updateMembershipWitness(Array(a), acc2_wit, Array(b),
|
||||
Array(a))
|
||||
@ -118,7 +119,7 @@ object testTxAccumulator extends App {
|
||||
val d = block1(3).prime
|
||||
val acc1 = root_acc.addOfBatch(Array(a,b,c))
|
||||
val acc2 = root_acc.addOfBatch(Array(c,d))
|
||||
val acc2_wit = Witness(acc2.getAccVaule)
|
||||
val acc2_wit = new Witness(acc2.getAccVaule)
|
||||
|
||||
val wit_new = acc1.updateMembershipWitness(Array(a),acc2_wit,Array(b),
|
||||
Array(d))
|
||||
|
@ -12,6 +12,7 @@ import java.math.BigInteger
|
||||
import scala.math.abs
|
||||
import scala.util.Random
|
||||
import org.apache.commons.codec.binary.{Base32, Base64, BinaryCodec, Hex}
|
||||
import rep.accumulator.verkle.VerkleTreeType
|
||||
|
||||
object vectorCommitment_test extends App {
|
||||
val tx_service = new CreateTestTransactionService
|
||||
@ -71,7 +72,7 @@ object vectorCommitment_test extends App {
|
||||
val vc2 = vc.getTransactionWitnessesWithBlock(block2._1,vc1.tx_acc_value,true)
|
||||
val vc3 = vc.getTransactionWitnessesWithBlock(block3._1,vc2.tx_acc_value,true)
|
||||
|
||||
val acc3 = new Accumulator(ctx.getTxAccBase,vc3.tx_acc_value,ctx.getHashTool)
|
||||
val acc3 = new Accumulator(ctx.getVerkleTreeAccRoot(VerkleTreeType.TransactionTree),vc3.tx_acc_value,ctx.getHashTool)
|
||||
val ri = abs(new Random().nextInt(10))
|
||||
val wi = vc3.txWitnesses(ri)
|
||||
val proof = acc3.getMemberProof4Witness(wi.prime,wi.witnessInBlock)
|
||||
|
Loading…
Reference in New Issue
Block a user