Commit 697b6b89 authored by 张振华's avatar 张振华

update

parent 56e73c7f
This diff is collapsed.
This diff is collapsed.
......@@ -14,7 +14,6 @@ import (
"sync"
"sync/atomic"
"time"
"errors"
"github.com/33cn/chain33/common/crypto"
ttypes "github.com/33cn/plugin/plugin/consensus/dpos/types"
......@@ -294,7 +293,7 @@ func (node *Node) listenRoutine() {
func (node *Node) StartConsensusRoutine() {
for {
//zzh
if !node.IsRunning(){
if !node.IsRunning() {
break
}
//TODO:the peer count need be optimized
......@@ -502,7 +501,7 @@ func (node *Node) FilterConnByAddr(addr net.Addr) error {
}
if !legalIP {
return errors.New(fmt.Sprintf("%s is not legal seeds ip", ip))
return fmt.Errorf("%s is not legal seeds ip", ip)
}
return nil
}
......
......@@ -3,16 +3,20 @@ syntax = "proto3";
package types;
//CycleBoundaryInfo cycle边界信息
message CycleBoundaryInfo{
int64 cycle = 1;
int64 stopHeight = 2;
string stopHash = 3;
}
//SuperNode 超级节点信息
message SuperNode{
bytes address = 1;
bytes pubKey = 2;
}
//VoteItem 投票信息
message VoteItem {
int32 votedNodeIndex = 1; //被投票的节点索引
bytes votedNodeAddress = 2; //被投票的节点地址
......@@ -39,6 +43,7 @@ message DPosVote {
bytes signature = 5; //投票者签名
}
//DPosVoteReply 投票响应。
message DPosVoteReply {
DPosVote vote = 1;
}
......@@ -54,6 +59,7 @@ message DPosNotify {
bytes signature = 7; //通知节点的签名
}
//DPosCBInfo Cycle boundary注册信息。
message DPosCBInfo {
int64 cycle = 1;
int64 stopHeight = 2;
......
This diff is collapsed.
......@@ -69,13 +69,13 @@ func TestDecideTaskByTime(t *testing.T) {
setParams(2, 3, 12)
/*
for i := 0; i < 120; i++ {
now = time.Now().Unix()
task = DecideTaskByTime(now)
printTask(now, &task)
assertTask(&task, t)
time.Sleep(time.Second * 1)
}
*/
/*
for i := 0; i < 120; i++ {
now = time.Now().Unix()
task = DecideTaskByTime(now)
printTask(now, &task)
assertTask(&task, t)
time.Sleep(time.Second * 1)
}
*/
}
package dpos
import (
"github.com/stretchr/testify/assert"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestTicker(t *testing.T) {
......@@ -13,15 +12,15 @@ func TestTicker(t *testing.T) {
ti := timeoutInfo{
Duration: time.Second * time.Duration(2),
State: InitStateType,
State: InitStateType,
}
now := time.Now().Unix()
ticker.ScheduleTimeout(ti)
<- ticker.Chan()
<-ticker.Chan()
end := time.Now().Unix()
ticker.Stop()
assert.True(t, end - now == 2)
assert.True(t, end-now == 2)
}
\ No newline at end of file
}
......@@ -33,6 +33,7 @@ var _ = math.Inf
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// CycleBoundaryInfo cycle边界信息
type CycleBoundaryInfo struct {
Cycle int64 `protobuf:"varint,1,opt,name=cycle" json:"cycle,omitempty"`
StopHeight int64 `protobuf:"varint,2,opt,name=stopHeight" json:"stopHeight,omitempty"`
......@@ -65,6 +66,7 @@ func (m *CycleBoundaryInfo) GetStopHash() string {
return ""
}
// SuperNode 超级节点信息
type SuperNode struct {
Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
PubKey []byte `protobuf:"bytes,2,opt,name=pubKey,proto3" json:"pubKey,omitempty"`
......@@ -89,6 +91,7 @@ func (m *SuperNode) GetPubKey() []byte {
return nil
}
// VoteItem 投票信息
type VoteItem struct {
VotedNodeIndex int32 `protobuf:"varint,1,opt,name=votedNodeIndex" json:"votedNodeIndex,omitempty"`
VotedNodeAddress []byte `protobuf:"bytes,2,opt,name=votedNodeAddress,proto3" json:"votedNodeAddress,omitempty"`
......@@ -258,6 +261,7 @@ func (m *DPosVote) GetSignature() []byte {
return nil
}
// DPosVoteReply 投票响应。
type DPosVoteReply struct {
Vote *DPosVote `protobuf:"bytes,1,opt,name=vote" json:"vote,omitempty"`
}
......@@ -339,6 +343,7 @@ func (m *DPosNotify) GetSignature() []byte {
return nil
}
// DPosCBInfo Cycle boundary注册信息。
type DPosCBInfo struct {
Cycle int64 `protobuf:"varint,1,opt,name=cycle" json:"cycle,omitempty"`
StopHeight int64 `protobuf:"varint,2,opt,name=stopHeight" json:"stopHeight,omitempty"`
......
......@@ -9,18 +9,18 @@ import (
"os"
"testing"
)
const(
err_genesis_file = `{"genesis_time:"2018-08-16T15:38:56.951569432+08:00","chain_id":"chain33-Z2cgFj","validators":[{"pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"name":""},{"pub_key":{"type":"secp256k1","data":"027848E7FA630B759DB406940B5506B666A344B1060794BBF314EB459D40881BB3"},"name":""},{"pub_key":{"type":"secp256k1","data":"03F4AB6659E61E8512C9A24AC385CC1AC4D52B87D10ADBDF060086EA82BE62CDDE"},"name":""}],"app_hash":null}`
genesis_file = `{"genesis_time":"2018-08-16T15:38:56.951569432+08:00","chain_id":"chain33-Z2cgFj","validators":[{"pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"name":""},{"pub_key":{"type":"secp256k1","data":"027848E7FA630B759DB406940B5506B666A344B1060794BBF314EB459D40881BB3"},"name":""},{"pub_key":{"type":"secp256k1","data":"03F4AB6659E61E8512C9A24AC385CC1AC4D52B87D10ADBDF060086EA82BE62CDDE"},"name":""}],"app_hash":null}`
const (
errGenesisFile = `{"genesis_time:"2018-08-16T15:38:56.951569432+08:00","chain_id":"chain33-Z2cgFj","validators":[{"pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"name":""},{"pub_key":{"type":"secp256k1","data":"027848E7FA630B759DB406940B5506B666A344B1060794BBF314EB459D40881BB3"},"name":""},{"pub_key":{"type":"secp256k1","data":"03F4AB6659E61E8512C9A24AC385CC1AC4D52B87D10ADBDF060086EA82BE62CDDE"},"name":""}],"app_hash":null}`
genesisFile = `{"genesis_time":"2018-08-16T15:38:56.951569432+08:00","chain_id":"chain33-Z2cgFj","validators":[{"pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"name":""},{"pub_key":{"type":"secp256k1","data":"027848E7FA630B759DB406940B5506B666A344B1060794BBF314EB459D40881BB3"},"name":""},{"pub_key":{"type":"secp256k1","data":"03F4AB6659E61E8512C9A24AC385CC1AC4D52B87D10ADBDF060086EA82BE62CDDE"},"name":""}],"app_hash":null}`
)
func init(){
func init() {
//为了使用VRF,需要使用SECP256K1体系的公私钥
cr, err := crypto.New(types.GetSignName("", types.SECP256K1))
if err != nil {
panic("init ConsensusCrypto failed.")
return
}
ConsensusCrypto = cr
......@@ -37,21 +37,20 @@ func TestGenesisDocFromFile(t *testing.T) {
}
func TestGenesisDocFromJSON(t *testing.T) {
genDoc, err := GenesisDocFromJSON([]byte(genesis_file))
genDoc, err := GenesisDocFromJSON([]byte(genesisFile))
require.NotNil(t, genDoc)
require.Nil(t, err)
assert.True(t, genDoc.ChainID == "chain33-Z2cgFj")
assert.True(t, genDoc.AppHash == nil)
assert.True(t, len(genDoc.Validators) == 3)
genDoc, err = GenesisDocFromJSON([]byte(err_genesis_file))
genDoc, err = GenesisDocFromJSON([]byte(errGenesisFile))
require.NotNil(t, err)
require.Nil(t, genDoc)
}
func TestSaveAs(t *testing.T) {
genDoc, err := GenesisDocFromJSON([]byte(genesis_file))
genDoc, err := GenesisDocFromJSON([]byte(genesisFile))
require.NotNil(t, genDoc)
require.Nil(t, err)
assert.True(t, genDoc.ChainID == "chain33-Z2cgFj")
......@@ -61,13 +60,12 @@ func TestSaveAs(t *testing.T) {
err = genDoc.SaveAs("./tmp_genesis.json")
require.Nil(t, err)
genDoc2, err := GenesisDocFromFile("./tmp_genesis.json")
require.NotNil(t, genDoc2)
require.Nil(t, err)
assert.True(t, genDoc.ChainID == genDoc2.ChainID)
assert.True(t, genDoc.GenesisTime == genDoc2.GenesisTime)
assert.True(t, bytes.Equal(genDoc.AppHash , genDoc2.AppHash))
assert.True(t, bytes.Equal(genDoc.AppHash, genDoc2.AppHash))
assert.True(t, genDoc.Validators[0].Name == genDoc2.Validators[0].Name)
assert.True(t, genDoc.Validators[0].PubKey.Data == genDoc2.Validators[0].PubKey.Data)
......@@ -87,7 +85,7 @@ func TestSaveAs(t *testing.T) {
}
func TestValidateAndComplete(t *testing.T) {
genDoc, err := GenesisDocFromJSON([]byte(genesis_file))
genDoc, err := GenesisDocFromJSON([]byte(genesisFile))
require.NotNil(t, genDoc)
require.Nil(t, err)
......@@ -110,10 +108,10 @@ func TestValidateAndComplete(t *testing.T) {
}
func TestValidatorHash(t *testing.T) {
genDoc, err := GenesisDocFromJSON([]byte(genesis_file))
genDoc, err := GenesisDocFromJSON([]byte(genesisFile))
require.NotNil(t, genDoc)
require.Nil(t, err)
hash := genDoc.ValidatorHash()
assert.True(t, len(hash) > 0)
}
\ No newline at end of file
}
......@@ -21,7 +21,6 @@ const (
NotifyID = byte(0x08)
CBInfoID = byte(0x09)
PacketTypePing = byte(0xff)
PacketTypePong = byte(0xfe)
)
......
......@@ -36,7 +36,7 @@ type PrivValidator interface {
SignNotify(chainID string, notify *Notify) error
SignMsg(msg []byte) (sig crypto.Signature, err error)
SignTx(tx *types.Transaction)
VrfEvaluate(input []byte) (hash [32]byte, proof []byte)
VrfEvaluate(input []byte) (hash [32]byte, proof []byte)
VrfProof(pubkey []byte, input []byte, hash [32]byte, proof []byte) bool
}
......@@ -44,8 +44,8 @@ type PrivValidator interface {
// to prevent double signing. The Signer itself can be mutated to use
// something besides the default, for instance a hardware signer.
type PrivValidatorFS struct {
Address string `json:"address"`
PubKey KeyText `json:"pub_key"`
Address string `json:"address"`
PubKey KeyText `json:"pub_key"`
//LastSignature *KeyText `json:"last_signature,omitempty"` // so we dont lose signatures
//LastSignBytes string `json:"last_signbytes,omitempty"` // so we dont lose signatures
......@@ -55,8 +55,8 @@ type PrivValidatorFS struct {
// PrivValidatorImp ...
type PrivValidatorImp struct {
Address []byte
PubKey crypto.PubKey
Address []byte
PubKey crypto.PubKey
//LastSignature crypto.Signature
//LastSignBytes []byte
......@@ -129,22 +129,7 @@ func PubKeyFromString(pubkeystring string) (crypto.PubKey, error) {
return pubkey, nil
}
// SignatureFromString ...
/*
func SignatureFromString(sigString string) (crypto.Signature, error) {
sigbyte, err := hex.DecodeString(sigString)
if err != nil {
return nil, errors.New(Fmt("PubKeyFromString:DecodeString:%v failed,err:%v", sigString, err))
}
sig, err := ConsensusCrypto.SignatureFromBytes(sigbyte)
if err != nil {
return nil, errors.New(Fmt("PubKeyFromString:SignatureFromBytes:%v failed,err:%v", sigbyte, err))
}
return sig, nil
}
*/
// GenPrivValidatorImp generates a new validator with randomly generated private key
// and sets the filePath, but does not call Save().
// GenPrivValidatorImp generates a new validator with randomly generated private key and sets the filePath, but does not call Save().
func GenPrivValidatorImp(filePath string) *PrivValidatorImp {
privKey, err := ConsensusCrypto.GenKey()
if err != nil {
......@@ -223,22 +208,22 @@ func LoadPrivValidatorFSWithSigner(filePath string, signerFunc func(PrivValidato
privValImp.PubKey = pubKey
/*
if len(privVal.LastSignBytes) != 0 {
tmp, err = hex.DecodeString(privVal.LastSignBytes)
if err != nil {
Exit(Fmt("Error DecodeString LastSignBytes data failed: %v\n", err))
if len(privVal.LastSignBytes) != 0 {
tmp, err = hex.DecodeString(privVal.LastSignBytes)
if err != nil {
Exit(Fmt("Error DecodeString LastSignBytes data failed: %v\n", err))
}
privValImp.LastSignBytes = tmp
}
privValImp.LastSignBytes = tmp
}
if privVal.LastSignature != nil {
signature, err := SignatureFromString(privVal.LastSignature.Data)
if err != nil {
Exit(Fmt("Error SignatureFromBytes failed: %v\n", err))
if privVal.LastSignature != nil {
signature, err := SignatureFromString(privVal.LastSignature.Data)
if err != nil {
Exit(Fmt("Error SignatureFromBytes failed: %v\n", err))
}
privValImp.LastSignature = signature
} else {
privValImp.LastSignature = nil
}
privValImp.LastSignature = signature
} else {
privValImp.LastSignature = nil
}
*/
privValImp.filePath = filePath
privValImp.Signer = signerFunc(privValImp)
......@@ -259,20 +244,20 @@ func (pv *PrivValidatorImp) save() {
addr := Fmt("%X", pv.Address[:])
privValFS := &PrivValidatorFS{
Address: addr,
Address: addr,
//LastSignature: nil,
}
privValFS.PrivKey = KeyText{Kind: "secp256k1", Data: Fmt("%X", pv.PrivKey.Bytes()[:])}
privValFS.PubKey = KeyText{Kind: "secp256k1", Data: pv.PubKey.KeyString()}
/*
if len(pv.LastSignBytes) != 0 {
tmp := Fmt("%X", pv.LastSignBytes[:])
privValFS.LastSignBytes = tmp
}
if pv.LastSignature != nil {
sig := Fmt("%X", pv.LastSignature.Bytes()[:])
privValFS.LastSignature = &KeyText{Kind: "ed25519", Data: sig}
}
if len(pv.LastSignBytes) != 0 {
tmp := Fmt("%X", pv.LastSignBytes[:])
privValFS.LastSignBytes = tmp
}
if pv.LastSignature != nil {
sig := Fmt("%X", pv.LastSignature.Bytes()[:])
privValFS.LastSignature = &KeyText{Kind: "ed25519", Data: sig}
}
*/
jsonBytes, err := json.Marshal(privValFS)
if err != nil {
......@@ -326,7 +311,7 @@ func (pv *PrivValidatorImp) SignNotify(chainID string, notify *Notify) error {
return nil
}
// SignCBInfo signs a canonical representation of the DposCBInfo, Implements PrivValidator.
// SignMsg signs a msg.
func (pv *PrivValidatorImp) SignMsg(msg []byte) (sig crypto.Signature, err error) {
pv.mtx.Lock()
defer pv.mtx.Unlock()
......@@ -335,8 +320,9 @@ func (pv *PrivValidatorImp) SignMsg(msg []byte) (sig crypto.Signature, err error
//sig = hex.EncodeToString(signature.Bytes())
return signature, nil
}
// SignTx signs a tx, Implements PrivValidator.
func (pv *PrivValidatorImp)SignTx(tx *types.Transaction){
func (pv *PrivValidatorImp) SignTx(tx *types.Transaction) {
tx.Sign(types.SECP256K1, pv.PrivKey)
}
......@@ -351,6 +337,7 @@ func (pv *PrivValidatorImp) VrfEvaluate(input []byte) (hash [32]byte, proof []by
return hash, proof
}
// VrfProof check the vrf.
func (pv *PrivValidatorImp) VrfProof(pubkey []byte, input []byte, hash [32]byte, proof []byte) bool {
pv.mtx.Lock()
defer pv.mtx.Unlock()
......@@ -364,7 +351,7 @@ func (pv *PrivValidatorImp) VrfProof(pubkey []byte, input []byte, hash [32]byte,
if err != nil {
return false
}
if bytes.Equal(hash[:], vrfHash[:]){
if bytes.Equal(hash[:], vrfHash[:]) {
return true
}
......
......@@ -16,10 +16,11 @@ import (
"testing"
"time"
)
const(
priv_validator_file = `{"address":"2FA286246F0222C4FF93210E91AECE0C66723F15","pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"last_height":1679,"last_round":0,"last_step":3,"last_signature":{"type":"secp256k1","data":"37892A916D6E487ADF90F9E88FE37024597677B6C6FED47444AD582F74144B3D6E4B364EAF16AF03A4E42827B6D3C86415D734A5A6CCA92E114B23EB9265AF09"},"last_signbytes":"7B22636861696E5F6964223A22636861696E33332D5A326367466A222C22766F7465223A7B22626C6F636B5F6964223A7B2268617368223A224F6A657975396B2B4149426A6E4859456739584765356A7A462B673D222C227061727473223A7B2268617368223A6E756C6C2C22746F74616C223A307D7D2C22686569676874223A313637392C22726F756E64223A302C2274696D657374616D70223A22323031382D30382D33315430373A35313A34332E3935395A222C2274797065223A327D7D","priv_key":{"type":"secp256k1","data":"5A6A14DA6F5A42835E529D75D87CC8904544F59EEE5387A37D87EEAD194D7EB2"}}`
strAddr = "2FA286246F0222C4FF93210E91AECE0C66723F15"
strPubkey = "03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"
const (
privValidatorFile = `{"address":"2FA286246F0222C4FF93210E91AECE0C66723F15","pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"last_height":1679,"last_round":0,"last_step":3,"last_signature":{"type":"secp256k1","data":"37892A916D6E487ADF90F9E88FE37024597677B6C6FED47444AD582F74144B3D6E4B364EAF16AF03A4E42827B6D3C86415D734A5A6CCA92E114B23EB9265AF09"},"last_signbytes":"7B22636861696E5F6964223A22636861696E33332D5A326367466A222C22766F7465223A7B22626C6F636B5F6964223A7B2268617368223A224F6A657975396B2B4149426A6E4859456739584765356A7A462B673D222C227061727473223A7B2268617368223A6E756C6C2C22746F74616C223A307D7D2C22686569676874223A313637392C22726F756E64223A302C2274696D657374616D70223A22323031382D30382D33315430373A35313A34332E3935395A222C2274797065223A327D7D","priv_key":{"type":"secp256k1","data":"5A6A14DA6F5A42835E529D75D87CC8904544F59EEE5387A37D87EEAD194D7EB2"}}`
strAddr = "2FA286246F0222C4FF93210E91AECE0C66723F15"
strPubkey = "03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"
addr1 = "79F9608B6826762CACCA843E81AE86837ABFFB21"
addr2 = "3480088E35099CBA75958DAE7A364A8AAD2C1BD0"
......@@ -27,18 +28,17 @@ const(
addr4 = "70A51AD9777EF1F97250F7E4C156D8637BC7143C"
)
func init(){
func init() {
//为了使用VRF,需要使用SECP256K1体系的公私钥
cr, err := crypto.New(types.GetSignName("", types.SECP256K1))
if err != nil {
panic("init ConsensusCrypto failed.")
return
}
ConsensusCrypto = cr
}
func save(filename , filecontent string) {
func save(filename, filecontent string) {
f, err := os.Create(filename)
if err != nil {
fmt.Println("err = ", err)
......@@ -61,7 +61,7 @@ func remove(filename string) {
}
func read(filename string) bool{
func read(filename string) bool {
f, err := os.Open(filename)
if err != nil {
fmt.Println("err=", err)
......@@ -69,7 +69,7 @@ func read(filename string) bool{
}
defer f.Close()
buf := make([]byte, 1024 * 2)
buf := make([]byte, 1024*2)
_, err1 := f.Read(buf)
if err1 != nil && err1 != io.EOF {
fmt.Println("err1=", err1)
......@@ -80,15 +80,14 @@ func read(filename string) bool{
return true
}
func TestLoadOrGenPrivValidatorFS(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
require.NotNil(t, privValidator)
assert.True(t, strings.EqualFold(strAddr,hex.EncodeToString(privValidator.GetAddress())))
assert.True(t, strings.EqualFold(strPubkey,hex.EncodeToString(privValidator.GetPubKey().Bytes())))
assert.True(t, strings.EqualFold(strAddr, hex.EncodeToString(privValidator.GetAddress())))
assert.True(t, strings.EqualFold(strPubkey, hex.EncodeToString(privValidator.GetPubKey().Bytes())))
fmt.Println(privValidator.String())
......@@ -97,7 +96,7 @@ func TestLoadOrGenPrivValidatorFS(t *testing.T) {
func TestGenPrivValidatorImp(t *testing.T) {
filename := "tmp_priv_validator2.json"
//save(filename, priv_validator_file)
//save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
require.NotNil(t, privValidator)
......@@ -117,10 +116,10 @@ func TestGenPrivValidatorImp(t *testing.T) {
func TestPrivValidatorImpSort(t *testing.T) {
var arr []*PrivValidatorImp
Addr1 , _ := hex.DecodeString(addr1)
Addr2 , _ := hex.DecodeString(addr2)
Addr3 , _ := hex.DecodeString(addr3)
Addr4 , _ := hex.DecodeString(addr4)
Addr1, _ := hex.DecodeString(addr1)
Addr2, _ := hex.DecodeString(addr2)
Addr3, _ := hex.DecodeString(addr3)
Addr4, _ := hex.DecodeString(addr4)
imp1 := &PrivValidatorImp{
Address: Addr1,
......@@ -132,7 +131,6 @@ func TestPrivValidatorImpSort(t *testing.T) {
}
arr = append(arr, imp2)
imp3 := &PrivValidatorImp{
Address: Addr3,
}
......@@ -145,15 +143,15 @@ func TestPrivValidatorImpSort(t *testing.T) {
sort.Sort(PrivValidatorsByAddress(arr))
assert.True(t, strings.EqualFold(addr2,hex.EncodeToString(arr[0].Address)))
assert.True(t, strings.EqualFold(addr4,hex.EncodeToString(arr[1].Address)))
assert.True(t, strings.EqualFold(addr1,hex.EncodeToString(arr[2].Address)))
assert.True(t, strings.EqualFold(addr3,hex.EncodeToString(arr[3].Address)))
assert.True(t, strings.EqualFold(addr2, hex.EncodeToString(arr[0].Address)))
assert.True(t, strings.EqualFold(addr4, hex.EncodeToString(arr[1].Address)))
assert.True(t, strings.EqualFold(addr1, hex.EncodeToString(arr[2].Address)))
assert.True(t, strings.EqualFold(addr3, hex.EncodeToString(arr[3].Address)))
}
func TestSignAndVerifyVote(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
now := time.Now().Unix()
......@@ -207,7 +205,7 @@ func TestSignAndVerifyVote(t *testing.T) {
func TestSignAndVerifyNotify(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
now := time.Now().Unix()
......@@ -230,7 +228,6 @@ func TestSignAndVerifyNotify(t *testing.T) {
voteItem.VoteID = crypto.Ripemd160(encode)
chainID := "test-chain-Ep9EcD"
notify := &Notify{
......@@ -263,7 +260,7 @@ func TestSignAndVerifyNotify(t *testing.T) {
func TestSignMsg(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
byteCB := []byte("asdfadsasf")
......@@ -277,16 +274,14 @@ func TestSignMsg(t *testing.T) {
func TestVrf(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
input := []byte("abcdefghijklmn")
hash, proof := privValidator.VrfEvaluate(input)
assert.True(t, 32 == len(hash))
assert.True(t, 0 < len(proof))
result := privValidator.VrfProof(privValidator.PubKey.Bytes(), input, hash, proof)
assert.True(t, result)
......@@ -295,15 +290,14 @@ func TestVrf(t *testing.T) {
func TestSignTx(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
tx := &types.Transaction{}
privValidator.SignTx(tx)
assert.True(t, types.SECP256K1 == tx.Signature.Ty)
assert.True(t, bytes.Equal(privValidator.PubKey.Bytes(), tx.Signature.Pubkey))
assert.True(t, 0 < len(tx.Signature.Signature))
assert.True(t, 0 < len(tx.Signature.Signature))
remove(filename)
}
\ No newline at end of file
}
......@@ -30,7 +30,7 @@ var (
votelog = log15.New("module", "tendermint-vote")
ConsensusCrypto crypto.Crypto
ConsensusCrypto crypto.Crypto
SecureConnCrypto crypto.Crypto
)
......
......@@ -11,12 +11,11 @@ import (
"time"
)
func init(){
func init() {
//为了使用VRF,需要使用SECP256K1体系的公私钥
cr, err := crypto.New(types.GetSignName("", types.SECP256K1))
if err != nil {
panic("init ConsensusCrypto failed.")
return
}
ConsensusCrypto = cr
......@@ -24,7 +23,7 @@ func init(){
func TestVote(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
now := time.Now().Unix()
......@@ -69,7 +68,7 @@ func TestVote(t *testing.T) {
func TestNotify(t *testing.T) {
filename := "./tmp_priv_validator.json"
save(filename, priv_validator_file)
save(filename, privValidatorFile)
privValidator := LoadOrGenPrivValidatorFS(filename)
now := time.Now().Unix()
......@@ -92,7 +91,6 @@ func TestNotify(t *testing.T) {
voteItem.VoteID = crypto.Ripemd160(encode)
chainID := "test-chain-Ep9EcD"
notify := &Notify{
......@@ -114,4 +112,4 @@ func TestNotify(t *testing.T) {
require.Nil(t, err)
assert.True(t, 0 < len(notify.Hash()))
remove(filename)
}
\ No newline at end of file
}
......@@ -12,13 +12,13 @@ import (
"time"
)
func init(){
func init() {
Init()
}
func TestWriteFile(t *testing.T) {
filename := "./tmp_priv_validator.json"
err := WriteFile(filename, []byte(priv_validator_file), 0664)
err := WriteFile(filename, []byte(privValidatorFile), 0664)
require.Nil(t, err)
file, err := os.Stat(filename)
......@@ -35,7 +35,7 @@ func TestWriteFile(t *testing.T) {
func TestWriteFileAtomic(t *testing.T) {
filename := "./tmp_priv_validator.json"
err := WriteFileAtomic(filename, []byte(priv_validator_file), 0664)
err := WriteFileAtomic(filename, []byte(privValidatorFile), 0664)
require.Nil(t, err)
file, err := os.Stat(filename)
......@@ -56,7 +56,7 @@ func TestTempfile(t *testing.T) {
fmt.Println(name)
require.NotNil(t, file)
_, err := file.Write([]byte(priv_validator_file))
_, err := file.Write([]byte(privValidatorFile))
if err == nil {
err = file.Sync()
}
......@@ -85,19 +85,19 @@ func TestKill(t *testing.T) {
c := make(chan os.Signal)
signal.Notify(c)
go Kill()
s := <- c
s := <-c
assert.True(t, s.String() == "terminated")
}
var (
go_index = 0
go_sum = 0
goIndex = 0
goSum = 0
)
func test() {
go_index++
time.Sleep(time.Second * time.Duration(go_index))
go_sum++
goIndex++
time.Sleep(time.Second * time.Duration(goIndex))
goSum++
}
func TestParallel(t *testing.T) {
......@@ -107,9 +107,9 @@ func TestParallel(t *testing.T) {
f2 := test
f2()
go_sum = 0
goSum = 0
Parallel(f1, f2)
assert.True(t, go_sum == 2)
assert.True(t, goSum == 2)
}
func TestRandInt63n(t *testing.T) {
......@@ -138,8 +138,8 @@ func TestRandUint32(t *testing.T) {
}
func TestPanicSanity(t *testing.T) {
defer func(){
if r:= recover(); r != nil {
defer func() {
if r := recover(); r != nil {
//fmt.Println(r)
assert.True(t, strings.HasPrefix(r.(string), "Panicked on a Sanity Check: "))
}
......@@ -149,8 +149,8 @@ func TestPanicSanity(t *testing.T) {
}
func TestPanicCrisis(t *testing.T) {
defer func(){
if r:= recover(); r != nil {
defer func() {
if r := recover(); r != nil {
//fmt.Println(r)
assert.True(t, strings.HasPrefix(r.(string), "Panicked on a Crisis: "))
}
......@@ -160,12 +160,12 @@ func TestPanicCrisis(t *testing.T) {
}
func TestPanicQ(t *testing.T) {
defer func(){
if r:= recover(); r != nil {
defer func() {
if r := recover(); r != nil {
//fmt.Println(r)
assert.True(t, strings.HasPrefix(r.(string), "Panicked questionably: "))
}
}()
PanicQ("hello")
}
\ No newline at end of file
}
......@@ -3,13 +3,13 @@ package types
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"strings"
"testing"
"fmt"
)
const (
......@@ -20,6 +20,7 @@ const (
pubkey11 = "03541AB9887951C038273648545072E5B6A46A639BFF535F3957E8150CBE2A70D7"
pubkey12 = "03F2A7AFFA090763C42B370C6F33CC3E9B6140228ABAF0591240F3B88E8792F890"
)
var (
val1 *Validator
val2 *Validator
......@@ -29,36 +30,35 @@ var (
val12 *Validator
)
func init(){
func init() {
//为了使用VRF,需要使用SECP256K1体系的公私钥
cr, err := crypto.New(types.GetSignName("", types.SECP256K1))
if err != nil {
panic("init ConsensusCrypto failed.")
return
}
ConsensusCrypto = cr
pkbytes , err := hex.DecodeString(pubkey1)
pkbytes, _ := hex.DecodeString(pubkey1)
pk1, err := ConsensusCrypto.PubKeyFromBytes(pkbytes)
pk1, _ := ConsensusCrypto.PubKeyFromBytes(pkbytes)
pkbytes , err = hex.DecodeString(pubkey2)
pk2, err := ConsensusCrypto.PubKeyFromBytes(pkbytes)
pkbytes, _ = hex.DecodeString(pubkey2)
pk2, _ := ConsensusCrypto.PubKeyFromBytes(pkbytes)
pkbytes , err = hex.DecodeString(pubkey3)
pk3, err := ConsensusCrypto.PubKeyFromBytes(pkbytes)
pkbytes, _ = hex.DecodeString(pubkey3)
pk3, _ := ConsensusCrypto.PubKeyFromBytes(pkbytes)
val1 = NewValidator(pk1)
val2 = NewValidator(pk2)
val3 = NewValidator(pk3)
pkbytes , err = hex.DecodeString(pubkey11)
pk11, err := ConsensusCrypto.PubKeyFromBytes(pkbytes)
pkbytes, _ = hex.DecodeString(pubkey11)
pk11, _ := ConsensusCrypto.PubKeyFromBytes(pkbytes)
val11 = NewValidator(pk11)
pkbytes , err = hex.DecodeString(pubkey12)
pk12, err := ConsensusCrypto.PubKeyFromBytes(pkbytes)
pkbytes, _ = hex.DecodeString(pubkey12)
pk12, _ := ConsensusCrypto.PubKeyFromBytes(pkbytes)
val12 = NewValidator(pk12)
}
......@@ -72,7 +72,7 @@ func TestValidator(t *testing.T) {
}
func match(index int, val *Validator) bool {
if bytes.Equal(val.Address, val1.Address){
if bytes.Equal(val.Address, val1.Address) {
return true
}
......@@ -157,7 +157,7 @@ func TestValidatorsByAddress(t *testing.T) {
assert.True(t, arr.Less(0, 1) == false)
assert.True(t, arr.Less(0, 2) == true)
arr.Swap(0,1)
arr.Swap(0, 1)
assert.True(t, bytes.Equal(arr[0].PubKey, val2.PubKey))
}
......@@ -167,4 +167,4 @@ func TestValidatorSetException(t *testing.T) {
valset := NewValidatorSet(vals)
assert.True(t, len(valset.Validators) == 0)
}
\ No newline at end of file
}
......@@ -20,8 +20,14 @@ var (
)
const (
//ShuffleTypeNoVrf shuffle type: NoVrf, use default address order
ShuffleTypeNoVrf = iota
//ShuffleTypeVrf shuffle type: Vrf
ShuffleTypeVrf
//ShuffleTypePartVrf shuffle type: PartVrf
ShuffleTypePartVrf
)
......@@ -34,12 +40,12 @@ type ValidatorMgr struct {
// so we can query for historical validator sets.
// Note that if s.LastBlockHeight causes a valset change,
// we set s.LastHeightValidatorsChanged = s.LastBlockHeight + 1
Validators *ttypes.ValidatorSet
VrfValidators *ttypes.ValidatorSet
NoVrfValidators *ttypes.ValidatorSet
Validators *ttypes.ValidatorSet
VrfValidators *ttypes.ValidatorSet
NoVrfValidators *ttypes.ValidatorSet
LastCycleBoundaryInfo *dty.DposCBInfo
ShuffleCycle int64
ShuffleType int64 //0-no vrf 1-vrf 2-part vrf
ShuffleCycle int64
ShuffleType int64 //0-no vrf 1-vrf 2-part vrf
// The latest AppHash we've received from calling abci.Commit()
AppHash []byte
}
......@@ -47,11 +53,11 @@ type ValidatorMgr struct {
// Copy makes a copy of the State for mutating.
func (s ValidatorMgr) Copy() ValidatorMgr {
mgr := ValidatorMgr{
ChainID: s.ChainID,
Validators: s.Validators.Copy(),
AppHash: s.AppHash,
ChainID: s.ChainID,
Validators: s.Validators.Copy(),
AppHash: s.AppHash,
ShuffleCycle: s.ShuffleCycle,
ShuffleType: s.ShuffleType,
ShuffleType: s.ShuffleType,
//VrfValidators: s.VrfValidators.Copy(),
//NoVrfValidators: s.NoVrfValidators.Copy(),
//LastCycleBoundaryInfo: &dty.DposCBInfo{
......@@ -65,12 +71,12 @@ func (s ValidatorMgr) Copy() ValidatorMgr {
if s.LastCycleBoundaryInfo != nil {
mgr.LastCycleBoundaryInfo = &dty.DposCBInfo{
Cycle: s.LastCycleBoundaryInfo.Cycle,
StopHeight: s.LastCycleBoundaryInfo.StopHeight,
StopHash: s.LastCycleBoundaryInfo.StopHash,
Pubkey: s.LastCycleBoundaryInfo.Pubkey,
Signature: s.LastCycleBoundaryInfo.Signature,
}
Cycle: s.LastCycleBoundaryInfo.Cycle,
StopHeight: s.LastCycleBoundaryInfo.StopHeight,
StopHash: s.LastCycleBoundaryInfo.StopHash,
Pubkey: s.LastCycleBoundaryInfo.Pubkey,
Signature: s.LastCycleBoundaryInfo.Signature,
}
}
if s.VrfValidators != nil {
......@@ -138,6 +144,7 @@ func MakeGenesisValidatorMgr(genDoc *ttypes.GenesisDoc) (ValidatorMgr, error) {
}, nil
}
// GetValidatorByIndex method
func (s *ValidatorMgr) GetValidatorByIndex(index int) (addres []byte, val *ttypes.Validator) {
if index < 0 || index >= len(s.Validators.Validators) {
return nil, nil
......@@ -153,15 +160,16 @@ func (s *ValidatorMgr) GetValidatorByIndex(index int) (addres []byte, val *ttype
if index < len(s.VrfValidators.Validators) {
val = s.VrfValidators.Validators[index]
return address.PubKeyToAddress(val.PubKey).Hash160[:], val.Copy()
} else {
val = s.NoVrfValidators.Validators[index - len(s.VrfValidators.Validators)]
return address.PubKeyToAddress(val.PubKey).Hash160[:], val.Copy()
}
val = s.NoVrfValidators.Validators[index-len(s.VrfValidators.Validators)]
return address.PubKeyToAddress(val.PubKey).Hash160[:], val.Copy()
}
return nil, nil
}
// GetIndexByPubKey method
func (s *ValidatorMgr) GetIndexByPubKey(pubkey []byte) (index int) {
if nil == pubkey {
return -1
......@@ -202,6 +210,7 @@ func (s *ValidatorMgr) GetIndexByPubKey(pubkey []byte) (index int) {
return index
}
// FillVoteItem method
func (s *ValidatorMgr) FillVoteItem(voteItem *ttypes.VoteItem) {
if s.LastCycleBoundaryInfo != nil {
voteItem.LastCBInfo = &ttypes.CycleBoundaryInfo{
......@@ -214,15 +223,15 @@ func (s *ValidatorMgr) FillVoteItem(voteItem *ttypes.VoteItem) {
voteItem.ShuffleType = s.ShuffleType
for i := 0; s.Validators != nil && i < s.Validators.Size(); i++ {
node := &ttypes.SuperNode{
PubKey: s.Validators.Validators[i].PubKey,
PubKey: s.Validators.Validators[i].PubKey,
Address: s.Validators.Validators[i].Address,
}
voteItem.Validators = append(voteItem.Validators, node)
}
for i := 0; s.VrfValidators != nil && i < s.VrfValidators.Size(); i++ {
for i := 0; s.VrfValidators != nil && i < s.VrfValidators.Size(); i++ {
node := &ttypes.SuperNode{
PubKey: s.VrfValidators.Validators[i].PubKey,
PubKey: s.VrfValidators.Validators[i].PubKey,
Address: s.VrfValidators.Validators[i].Address,
}
voteItem.VrfValidators = append(voteItem.VrfValidators, node)
......@@ -230,16 +239,17 @@ func (s *ValidatorMgr) FillVoteItem(voteItem *ttypes.VoteItem) {
for i := 0; s.NoVrfValidators != nil && i < s.NoVrfValidators.Size(); i++ {
node := &ttypes.SuperNode{
PubKey: s.NoVrfValidators.Validators[i].PubKey,
PubKey: s.NoVrfValidators.Validators[i].PubKey,
Address: s.NoVrfValidators.Validators[i].Address,
}
voteItem.NoVrfValidators = append(voteItem.NoVrfValidators, node)
}
}
// UpdateFromVoteItem method
func (s *ValidatorMgr) UpdateFromVoteItem(voteItem *ttypes.VoteItem) bool {
validators := voteItem.Validators
if len(s.Validators.Validators) != len(voteItem.Validators){
if len(s.Validators.Validators) != len(voteItem.Validators) {
return false
}
......@@ -273,7 +283,7 @@ func (s *ValidatorMgr) UpdateFromVoteItem(voteItem *ttypes.VoteItem) bool {
for i := 0; i < len(voteItem.VrfValidators); i++ {
val := &ttypes.Validator{
Address: voteItem.VrfValidators[i].Address,
PubKey: voteItem.VrfValidators[i].PubKey,
PubKey: voteItem.VrfValidators[i].PubKey,
}
vrfVals = append(vrfVals, val)
......@@ -285,7 +295,7 @@ func (s *ValidatorMgr) UpdateFromVoteItem(voteItem *ttypes.VoteItem) bool {
for i := 0; i < len(voteItem.NoVrfValidators); i++ {
val := &ttypes.Validator{
Address: voteItem.NoVrfValidators[i].Address,
PubKey: voteItem.NoVrfValidators[i].PubKey,
PubKey: voteItem.NoVrfValidators[i].PubKey,
}
noVrfVals = append(noVrfVals, val)
......@@ -294,4 +304,4 @@ func (s *ValidatorMgr) UpdateFromVoteItem(voteItem *ttypes.VoteItem) bool {
s.NoVrfValidators = ttypes.NewValidatorSet(noVrfVals)
return true
}
\ No newline at end of file
}
......@@ -6,40 +6,39 @@ import (
"github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/types"
ttypes "github.com/33cn/plugin/plugin/consensus/dpos/types"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
dty "github.com/33cn/plugin/plugin/dapp/dposvote/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"fmt"
"os"
"testing"
"fmt"
)
const (
genesis_content = `{"genesis_time":"2018-08-16T15:38:56.951569432+08:00","chain_id":"chain33-Z2cgFj","validators":[{"pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"name":""},{"pub_key":{"type":"secp256k1","data":"027848E7FA630B759DB406940B5506B666A344B1060794BBF314EB459D40881BB3"},"name":""},{"pub_key":{"type":"secp256k1","data":"03F4AB6659E61E8512C9A24AC385CC1AC4D52B87D10ADBDF060086EA82BE62CDDE"},"name":""}],"app_hash":null}`
pubkey11 = "03541AB9887951C038273648545072E5B6A46A639BFF535F3957E8150CBE2A70D7"
const (
genesisContent = `{"genesis_time":"2018-08-16T15:38:56.951569432+08:00","chain_id":"chain33-Z2cgFj","validators":[{"pub_key":{"type":"secp256k1","data":"03EF0E1D3112CF571743A3318125EDE2E52A4EB904BCBAA4B1F75020C2846A7EB4"},"name":""},{"pub_key":{"type":"secp256k1","data":"027848E7FA630B759DB406940B5506B666A344B1060794BBF314EB459D40881BB3"},"name":""},{"pub_key":{"type":"secp256k1","data":"03F4AB6659E61E8512C9A24AC385CC1AC4D52B87D10ADBDF060086EA82BE62CDDE"},"name":""}],"app_hash":null}`
pubkey11 = "03541AB9887951C038273648545072E5B6A46A639BFF535F3957E8150CBE2A70D7"
)
var (
genDoc *ttypes.GenesisDoc
)
func init(){
func init() {
//为了使用VRF,需要使用SECP256K1体系的公私钥
cr, err := crypto.New(types.GetSignName("", types.SECP256K1))
if err != nil {
panic("init ConsensusCrypto failed.")
return
}
ttypes.ConsensusCrypto = cr
remove("./genesis.json")
save("./genesis.json", genesis_content)
save("./genesis.json", genesisContent)
genDoc, _ = ttypes.GenesisDocFromFile("./genesis.json")
}
func save(filename , filecontent string) {
func save(filename, filecontent string) {
f, err := os.Create(filename)
if err != nil {
fmt.Println("err = ", err)
......@@ -115,7 +114,6 @@ func TestGetValidatorByIndex(t *testing.T) {
val, flag := vMgr.VrfValidators.Remove(addr)
assert.True(t, flag)
vMgr.NoVrfValidators = &ttypes.ValidatorSet{}
vMgr.NoVrfValidators.Validators = append(vMgr.NoVrfValidators.Validators, val)
addr, val = vMgr.GetValidatorByIndex(2)
......@@ -123,7 +121,7 @@ func TestGetValidatorByIndex(t *testing.T) {
assert.True(t, bytes.Equal(val.PubKey, vMgr.NoVrfValidators.Validators[0].PubKey))
}
func TestGetIndexByPubKey(t *testing.T){
func TestGetIndexByPubKey(t *testing.T) {
vMgr, err := MakeGenesisValidatorMgr(genDoc)
require.Nil(t, err)
assert.True(t, vMgr.ChainID == "chain33-Z2cgFj")
......@@ -198,10 +196,10 @@ func TestFillVoteItem(t *testing.T) {
vMgr.VrfValidators = ttypes.NewValidatorSet(vMgr.Validators.Validators)
vMgr.ShuffleType = ShuffleTypeVrf
vMgr.LastCycleBoundaryInfo = &dty.DposCBInfo{
Cycle: 110,
StopHeight:1111,
StopHash: "abcdefg",
Pubkey:"xxxxxxxx",
Cycle: 110,
StopHeight: 1111,
StopHash: "abcdefg",
Pubkey: "xxxxxxxx",
}
voteItem = &ttypes.VoteItem{}
......@@ -215,7 +213,6 @@ func TestFillVoteItem(t *testing.T) {
assert.True(t, len(voteItem.VrfValidators) == 3)
assert.True(t, voteItem.NoVrfValidators == nil)
vMgr.ShuffleType = ShuffleTypePartVrf
val, flag := vMgr.VrfValidators.Remove(vMgr.Validators.Validators[2].Address)
assert.True(t, flag == true)
......@@ -267,20 +264,19 @@ func TestUpdateFromVoteItem(t *testing.T) {
assert.True(t, flag == false)
/////
pkbytes , err := hex.DecodeString(pubkey11)
pk11, err := ttypes.ConsensusCrypto.PubKeyFromBytes(pkbytes)
pkbytes, _ := hex.DecodeString(pubkey11)
pk11, _ := ttypes.ConsensusCrypto.PubKeyFromBytes(pkbytes)
val.PubKey = pk11.Bytes()
newMgr.Validators.Add(val)
flag = newMgr.UpdateFromVoteItem(voteItem)
assert.True(t, flag == false)
/////
vMgr.LastCycleBoundaryInfo = &dty.DposCBInfo{
Cycle: 110,
StopHeight:1111,
StopHash: "abcdefg",
Pubkey:"xxxxxxxx",
Cycle: 110,
StopHeight: 1111,
StopHash: "abcdefg",
Pubkey: "xxxxxxxx",
}
voteItem = &ttypes.VoteItem{}
vMgr.FillVoteItem(voteItem)
......@@ -288,20 +284,19 @@ func TestUpdateFromVoteItem(t *testing.T) {
newMgr = vMgr.Copy()
newMgr.LastCycleBoundaryInfo = nil
newMgr.UpdateFromVoteItem(voteItem)
assert.True(t, newMgr.LastCycleBoundaryInfo != nil)
assert.True(t, newMgr.LastCycleBoundaryInfo.Cycle == voteItem.LastCBInfo.Cycle)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHeight == voteItem.LastCBInfo.StopHeight)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHash == voteItem.LastCBInfo.StopHash)
assert.True(t, newMgr.LastCycleBoundaryInfo != nil)
assert.True(t, newMgr.LastCycleBoundaryInfo.Cycle == voteItem.LastCBInfo.Cycle)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHeight == voteItem.LastCBInfo.StopHeight)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHash == voteItem.LastCBInfo.StopHash)
/////
newMgr = vMgr.Copy()
newMgr.LastCycleBoundaryInfo.Cycle = 111110
newMgr.UpdateFromVoteItem(voteItem)
assert.True(t, newMgr.LastCycleBoundaryInfo != nil)
assert.True(t, newMgr.LastCycleBoundaryInfo.Cycle == voteItem.LastCBInfo.Cycle)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHeight == voteItem.LastCBInfo.StopHeight)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHash == voteItem.LastCBInfo.StopHash)
assert.True(t, newMgr.LastCycleBoundaryInfo != nil)
assert.True(t, newMgr.LastCycleBoundaryInfo.Cycle == voteItem.LastCBInfo.Cycle)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHeight == voteItem.LastCBInfo.StopHeight)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHash == voteItem.LastCBInfo.StopHash)
/////
vMgr.VrfValidators = ttypes.NewValidatorSet(vMgr.Validators.Validators)
......@@ -322,15 +317,14 @@ func TestUpdateFromVoteItem(t *testing.T) {
newMgr.ShuffleType = ShuffleTypeNoVrf
newMgr.VrfValidators = nil
newMgr.UpdateFromVoteItem(voteItem)
assert.True(t, newMgr.LastCycleBoundaryInfo != nil)
assert.True(t, newMgr.LastCycleBoundaryInfo.Cycle == voteItem.LastCBInfo.Cycle)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHeight == voteItem.LastCBInfo.StopHeight)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHash == voteItem.LastCBInfo.StopHash)
assert.True(t, newMgr.LastCycleBoundaryInfo != nil)
assert.True(t, newMgr.LastCycleBoundaryInfo.Cycle == voteItem.LastCBInfo.Cycle)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHeight == voteItem.LastCBInfo.StopHeight)
assert.True(t, newMgr.LastCycleBoundaryInfo.StopHash == voteItem.LastCBInfo.StopHash)
assert.True(t, newMgr.ShuffleType == ShuffleTypeVrf)
assert.True(t, len(newMgr.Validators.Validators) == 3)
assert.True(t, len(newMgr.VrfValidators.Validators) == 3)
///
vMgr.ShuffleType = ShuffleTypePartVrf
val, flag = vMgr.VrfValidators.Remove(vMgr.Validators.Validators[2].Address)
......@@ -355,4 +349,4 @@ func TestUpdateFromVoteItem(t *testing.T) {
assert.True(t, len(newMgr.Validators.Validators) == 3)
assert.True(t, len(newMgr.VrfValidators.Validators) == 2)
assert.True(t, len(newMgr.NoVrfValidators.Validators) == 1)
}
\ No newline at end of file
}
This diff is collapsed.
This diff is collapsed.
......@@ -16,14 +16,14 @@ import (
"strings"
"time"
vrf "github.com/33cn/chain33/common/vrf/secp256k1"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types"
dty "github.com/33cn/plugin/plugin/dapp/dposvote/types"
ttypes "github.com/33cn/plugin/plugin/consensus/dpos/types"
"github.com/spf13/cobra"
vrf "github.com/33cn/chain33/common/vrf/secp256k1"
dty "github.com/33cn/plugin/plugin/dapp/dposvote/types"
secp256k1 "github.com/btcsuite/btcd/btcec"
"github.com/spf13/cobra"
)
var (
......@@ -31,6 +31,7 @@ var (
genFile = "genesis_file.json"
pvFile = "priv_validator_"
)
//DPosCmd DPosVote合约命令行
func DPosCmd() *cobra.Command {
cmd := &cobra.Command{
......@@ -89,7 +90,6 @@ func regist(cmd *cobra.Command, args []string) {
address, _ := cmd.Flags().GetString("address")
ip, _ := cmd.Flags().GetString("ip")
payload := fmt.Sprintf("{\"pubkey\":\"%s\", \"address\":\"%s\", \"ip\":\"%s\"}", pubkey, address, ip)
params := &rpctypes.CreateTxIn{
Execer: types.ExecName(dty.DPosX),
......@@ -296,8 +296,7 @@ func candidatorQuery(cmd *cobra.Command, args []string) {
case "pubkeys":
keys := strings.Split(pubkeys, ";")
req := &dty.CandidatorQuery{
}
req := &dty.CandidatorQuery{}
for _, key := range keys {
req.Pubkeys = append(req.Pubkeys, key)
}
......@@ -309,7 +308,6 @@ func candidatorQuery(cmd *cobra.Command, args []string) {
}
}
//DPosVoteQueryCmd 构造投票信息查询的命令行
func DPosVoteQueryCmd() *cobra.Command {
cmd := &cobra.Command{
......@@ -477,7 +475,7 @@ func vrfQuery(cmd *cobra.Command, args []string) {
}
req := &dty.DposVrfQuery{
Ty: dty.QueryVrfByTime,
Ty: dty.QueryVrfByTime,
Timestamp: t.Unix(),
}
......@@ -494,7 +492,7 @@ func vrfQuery(cmd *cobra.Command, args []string) {
}
req := &dty.DposVrfQuery{
Ty: dty.QueryVrfByTime,
Ty: dty.QueryVrfByTime,
Timestamp: timestamp,
}
......@@ -511,7 +509,7 @@ func vrfQuery(cmd *cobra.Command, args []string) {
}
req := &dty.DposVrfQuery{
Ty: dty.QueryVrfByCycle,
Ty: dty.QueryVrfByCycle,
Cycle: cycle,
}
......@@ -528,7 +526,7 @@ func vrfQuery(cmd *cobra.Command, args []string) {
}
req := &dty.DposVrfQuery{
Ty: dty.QueryVrfByCycleForTopN,
Ty: dty.QueryVrfByCycleForTopN,
Cycle: cycle,
}
......@@ -545,7 +543,7 @@ func vrfQuery(cmd *cobra.Command, args []string) {
}
req := &dty.DposVrfQuery{
Ty: dty.QueryVrfByCycleForPubkeys,
Ty: dty.QueryVrfByCycleForPubkeys,
Cycle: cycle,
}
......@@ -563,7 +561,7 @@ func vrfQuery(cmd *cobra.Command, args []string) {
}
//CreateCmd to create keyfiles
//DPosCreateCmd to create keyfiles
func DPosCreateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "init_keyfile",
......@@ -644,7 +642,7 @@ func createFiles(cmd *cobra.Command, args []string) {
// create genesis validator by the pubkey of private validator
gv := ttypes.GenesisValidator{
PubKey: ttypes.KeyText{Kind: "secp256k1", Data: privValidator.GetPubKey().KeyString()},
Name: "",
Name: "",
}
genDoc.Validators = append(genDoc.Validators, gv)
}
......@@ -656,7 +654,7 @@ func createFiles(cmd *cobra.Command, args []string) {
fmt.Printf("Generated genesis file path %v\n", genFile)
}
//CreateCmd to create keyfiles
//DPosVrfVerifyCmd to create keyfiles
func DPosVrfVerifyCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "vrfVerify",
......@@ -693,7 +691,6 @@ func verify(cmd *cobra.Command, args []string) {
hash, _ := cmd.Flags().GetString("hash")
proof, _ := cmd.Flags().GetString("proof")
m := []byte(data)
r, err := hex.DecodeString(hash)
......@@ -739,7 +736,7 @@ func verify(cmd *cobra.Command, args []string) {
fmt.Println("vrf hash is same with input hash, vrf Verify succeed")
}
//CreateCmd to create keyfiles
//DPosVrfEvaluateCmd to create keyfiles
func DPosVrfEvaluateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "vrfEvaluate",
......@@ -785,7 +782,7 @@ func evaluate(cmd *cobra.Command, args []string) {
fmt.Println(fmt.Sprintf("proof:%x", vrfProof))
}
//CreateCmd to create keyfiles
//DPosCBRecordCmd to create keyfiles
func DPosCBRecordCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "cbRecord",
......@@ -834,10 +831,10 @@ func recordCB(cmd *cobra.Command, args []string) {
buf := new(bytes.Buffer)
canonical := dty.CanonicalOnceCBInfo{
Cycle: cycle,
Cycle: cycle,
StopHeight: height,
StopHash: hash,
Pubkey: hex.EncodeToString(privKey.PubKey().Bytes()),
StopHash: hash,
Pubkey: hex.EncodeToString(privKey.PubKey().Bytes()),
}
byteCB, err := json.Marshal(&canonical)
......@@ -902,7 +899,7 @@ func cbQuery(cmd *cobra.Command, args []string) {
switch ty {
case "cycle":
req := &dty.DposCBQuery{
Ty: dty.QueryCBInfoByCycle,
Ty: dty.QueryCBInfoByCycle,
Cycle: cycle,
}
......@@ -914,7 +911,7 @@ func cbQuery(cmd *cobra.Command, args []string) {
case "height":
req := &dty.DposCBQuery{
Ty: dty.QueryCBInfoByHeight,
Ty: dty.QueryCBInfoByHeight,
StopHeight: height,
}
......@@ -926,7 +923,7 @@ func cbQuery(cmd *cobra.Command, args []string) {
case "hash":
req := &dty.DposCBQuery{
Ty: dty.QueryCBInfoByHash,
Ty: dty.QueryCBInfoByHash,
StopHash: hash,
}
......@@ -938,7 +935,7 @@ func cbQuery(cmd *cobra.Command, args []string) {
}
}
//DPosVrfQueryCmd 构造VRF相关信息查询的命令行
//DPosTopNQueryCmd 构造TopN相关信息查询的命令行
func DPosTopNQueryCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "topNQuery",
......@@ -958,7 +955,6 @@ func topNQuery(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
version, _ := cmd.Flags().GetInt64("version")
var params rpctypes.Query4Jrpc
params.Execer = dty.DPosX
......@@ -971,4 +967,4 @@ func topNQuery(cmd *cobra.Command, args []string) {
var res dty.TopNCandidatorsReply
ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
ctx.Run()
}
\ No newline at end of file
}
......@@ -16,32 +16,32 @@ var logger = log.New("module", "execs.dposvote")
var driverName = dty.DPosX
var (
dposDelegateNum int64 = 3 //委托节点个数,从配置读取,以后可以根据投票结果来定
dposBlockInterval int64 = 3 //出块间隔,当前按3s
dposContinueBlockNum int64 = 6 //一个委托节点当选后,一次性持续出块数量
dposCycle = dposDelegateNum * dposBlockInterval * dposContinueBlockNum
dposPeriod = dposBlockInterval * dposContinueBlockNum
dposDelegateNum int64 = 3 //委托节点个数,从配置读取,以后可以根据投票结果来定
dposBlockInterval int64 = 3 //出块间隔,当前按3s
dposContinueBlockNum int64 = 6 //一个委托节点当选后,一次性持续出块数量
dposCycle = dposDelegateNum * dposBlockInterval * dposContinueBlockNum
dposPeriod = dposBlockInterval * dposContinueBlockNum
blockNumToUpdateDelegate int64 = 20000
registTopNHeightLimit int64 = 100
updateTopNHeightLimit int64 = 200
registTopNHeightLimit int64 = 100
updateTopNHeightLimit int64 = 200
)
// CycleInfo indicates the start and stop of a cycle
type CycleInfo struct {
cycle int64
cycleStart int64
cycleStop int64
}
func calcCycleByTime(now int64) *CycleInfo {
cycle := now / dposCycle
cycleStart := now - now % dposCycle
cycleStart := now - now%dposCycle
cycleStop := cycleStart + dposCycle - 1
return &CycleInfo{
cycle: cycle,
cycle: cycle,
cycleStart: cycleStart,
cycleStop: cycleStop,
cycleStop: cycleStop,
}
}
......@@ -64,14 +64,14 @@ func Init(name string, sub []byte) {
drivers.Register(driverName, newDposVote, types.GetDappFork(driverName, "Enable"))
//读取一下配置项,用于和共识模块一致计算cycle
dposDelegateNum = types.Conf("config.consensus.sub.dpos").GInt("delegateNum")
dposBlockInterval = types.Conf("config.consensus.sub.dpos").GInt("blockInterval")
dposContinueBlockNum = types.Conf("config.consensus.sub.dpos").GInt("continueBlockNum")
dposDelegateNum = types.Conf("config.consensus.sub.dpos").GInt("delegateNum")
dposBlockInterval = types.Conf("config.consensus.sub.dpos").GInt("blockInterval")
dposContinueBlockNum = types.Conf("config.consensus.sub.dpos").GInt("continueBlockNum")
blockNumToUpdateDelegate = types.Conf("config.consensus.sub.dpos").GInt("blockNumToUpdateDelegate")
registTopNHeightLimit = types.Conf("config.consensus.sub.dpos").GInt("registTopNHeightLimit")
updateTopNHeightLimit = types.Conf("config.consensus.sub.dpos").GInt("updateTopNHeightLimit")
dposCycle = dposDelegateNum * dposBlockInterval * dposContinueBlockNum
dposPeriod = dposBlockInterval * dposContinueBlockNum
registTopNHeightLimit = types.Conf("config.consensus.sub.dpos").GInt("registTopNHeightLimit")
updateTopNHeightLimit = types.Conf("config.consensus.sub.dpos").GInt("updateTopNHeightLimit")
dposCycle = dposDelegateNum * dposBlockInterval * dposContinueBlockNum
dposPeriod = dposBlockInterval * dposContinueBlockNum
}
//DPos 执行器,用于Dpos候选节点注册、投票,VRF信息注册管理等功能
......
This diff is collapsed.
......@@ -25,8 +25,8 @@ func (d *DPos) rollbackCand(cand *dty.CandidatorInfo, log *dty.ReceiptCandicator
//如果投票了,则需要把投票回滚
if log.VoteType == dty.VoteTypeVote {
for i := 0; i < len(cand.Voters); i++{
if cand.Voters[i].Index == log.Vote.Index && cand.Voters[i].FromAddr == log.Vote.FromAddr && bytes.Equal(cand.Voters[i].Pubkey, log.Vote.Pubkey){
for i := 0; i < len(cand.Voters); i++ {
if cand.Voters[i].Index == log.Vote.Index && cand.Voters[i].FromAddr == log.Vote.FromAddr && bytes.Equal(cand.Voters[i].Pubkey, log.Vote.Pubkey) {
cand.Voters = append(cand.Voters[0:i], cand.Voters[i+1:]...)
break
}
......@@ -264,4 +264,4 @@ func (d *DPos) ExecDelLocal_RecordCB(payload *dty.DposCBInfo, tx *types.Transact
//ExecDelLocal_RegistTopN method
func (d *DPos) ExecDelLocal_RegistTopN(payload *dty.TopNCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return d.execDelLocal(receiptData)
}
\ No newline at end of file
}
......@@ -5,9 +5,9 @@
package executor
import (
"fmt"
"github.com/33cn/chain33/types"
dty "github.com/33cn/plugin/plugin/dapp/dposvote/types"
"fmt"
)
func (d *DPos) updateCandVote(log *dty.ReceiptCandicator) (kvs []*types.KeyValue, err error) {
......@@ -101,15 +101,15 @@ func (d *DPos) updateVrf(log *dty.ReceiptVrf) (kvs []*types.KeyValue, err error)
if log.Status == dty.VrfStatusMRegist {
vrfMTable := dty.NewDposVrfMTable(d.GetLocalDB())
vrfM := &dty.DposVrfM{
Index: log.Index,
Pubkey: log.Pubkey,
Cycle: log.Cycle,
Height: log.Height,
M: log.M,
Time: log.Time,
CycleStart: log.CycleStart,
Index: log.Index,
Pubkey: log.Pubkey,
Cycle: log.Cycle,
Height: log.Height,
M: log.M,
Time: log.Time,
CycleStart: log.CycleStart,
CycleMiddle: log.CycleMiddle,
CycleStop: log.CycleStop,
CycleStop: log.CycleStop,
}
err = vrfMTable.Add(vrfM)
......@@ -124,17 +124,17 @@ func (d *DPos) updateVrf(log *dty.ReceiptVrf) (kvs []*types.KeyValue, err error)
} else if log.Status == dty.VrfStatusRPRegist {
VrfRPTable := dty.NewDposVrfRPTable(d.GetLocalDB())
vrfRP := &dty.DposVrfRP{
Index: log.Index,
Pubkey: log.Pubkey,
Cycle: log.Cycle,
Height: log.Height,
R: log.R,
P: log.P,
M: log.M,
Time: log.Time,
CycleStart: log.CycleStart,
Index: log.Index,
Pubkey: log.Pubkey,
Cycle: log.Cycle,
Height: log.Height,
R: log.R,
P: log.P,
M: log.M,
Time: log.Time,
CycleStart: log.CycleStart,
CycleMiddle: log.CycleMiddle,
CycleStop: log.CycleStop,
CycleStop: log.CycleStop,
}
err = VrfRPTable.Add(vrfRP)
......@@ -187,7 +187,7 @@ func (d *DPos) execLocal(receipt *types.ReceiptData) (*types.LocalDBSet, error)
return nil, err
}
dbSet.KV = append(dbSet.KV, kvs...)
} else if item.Ty >= dty.TyLogVrfMRegist && item.Ty <= dty.TyLogVrfRPRegist {
} else if item.Ty >= dty.TyLogVrfMRegist && item.Ty <= dty.TyLogVrfRPRegist {
var vrfLog dty.ReceiptVrf
err := types.Decode(item.Log, &vrfLog)
if err != nil {
......@@ -242,12 +242,12 @@ func (d *DPos) ExecLocal_CancelVote(payload *dty.DposCancelVote, tx *types.Trans
return d.execLocal(receiptData)
}
//ExecLocal_VrfMRegist method
//ExecLocal_RegistVrfM method
func (d *DPos) ExecLocal_RegistVrfM(payload *dty.DposVrfMRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return d.execLocal(receiptData)
}
//ExecLocal_VrfRPRegist method
//ExecLocal_RegistVrfRP method
func (d *DPos) ExecLocal_RegistVrfRP(payload *dty.DposVrfRPRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return d.execLocal(receiptData)
}
......@@ -260,4 +260,4 @@ func (d *DPos) ExecLocal_RecordCB(payload *dty.DposCBInfo, tx *types.Transaction
//ExecLocal_RegistTopN method
func (d *DPos) ExecLocal_RegistTopN(payload *dty.TopNCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return d.execLocal(receiptData)
}
\ No newline at end of file
}
......@@ -62,4 +62,4 @@ func (d *DPos) Query_QueryCBInfoByHash(in *dty.DposCBQuery) (types.Message, erro
//Query_QueryTopNByVersion method
func (d *DPos) Query_QueryTopNByVersion(in *dty.TopNCandidatorsQuery) (types.Message, error) {
return queryTopNByVersion(d.GetStateDB(), in)
}
\ No newline at end of file
}
......@@ -6,7 +6,7 @@ package types;
message CandidatorInfo {
bytes pubkey = 1; //候选节点的公钥
string address = 2; //后续节点的地址
string ip = 3; //候选节点的运行IP
string IP = 3; //候选节点的运行IP
int64 votes = 4; //候选节点的投票数
int64 status = 5; //候选节点的状态,0:注册,1:当选,2:取消注册
int64 preStatus = 6;
......@@ -19,6 +19,7 @@ message CandidatorInfo {
repeated DposVoter voters = 13;
}
//DposVoter 投票者信息
message DposVoter{
string fromAddr = 1;
bytes pubkey = 2; //候选节点的公钥
......@@ -31,7 +32,7 @@ message DposVoter{
message Candidator {
bytes pubkey = 1; //候选节点的公钥
string address = 2; //后续节点的地址
string ip = 3; //候选节点的运行IP
string IP = 3; //候选节点的运行IP
int64 votes = 4; //候选节点的投票数
int64 status = 5; //候选节点的状态,0:注册,1:当选,2:取消注册
}
......@@ -40,7 +41,7 @@ message Candidator {
message DposCandidatorRegist{
string pubkey = 1; //候选节点的公钥
string address = 2; //候选节点的地址
string ip = 3; //候选节点的共识IP地址
string IP = 3; //候选节点的共识IP地址
}
//DposCandidatorCancelRegist 注销Dpos候选节点,解冻抵押的币
......@@ -83,6 +84,7 @@ message DposVoteAction {
int32 ty = 15;
}
//CandidatorQuery 候选节点查询
message CandidatorQuery{
repeated string pubkeys = 1; //候选节点公钥集合
int32 topN = 2; //topN
......@@ -91,24 +93,28 @@ message CandidatorQuery{
//Candidator 候选节点信息
message JsonCandidator {
//JSONCandidator 候选节点Json格式信息
message JSONCandidator {
string pubkey = 1; //候选节点的公钥
string address = 2; //后续节点的地址
string ip = 3; //候选节点的运行IP
string IP = 3; //候选节点的运行IP
int64 votes = 4; //候选节点的投票数
int64 status = 5; //候选节点的状态,0:注册,1:当选,2:取消注册
}
//CandidatorReply 候选节点查询响应
message CandidatorReply{
repeated JsonCandidator candidators = 1; //候选节点
repeated JSONCandidator candidators = 1; //候选节点
}
//DposVoteQuery 投票查询
message DposVoteQuery{
repeated string pubkeys = 1; //候选节点的公钥,如果为空,则查询所有,否则,查询该地址给具体候选节点的投票
string addr = 2; //要查询的地址
}
message JsonDposVoter{
//JSONDposVoter Json格式的投票者信息
message JSONDposVoter{
string fromAddr = 1;
string pubkey = 2; //候选节点的公钥
int64 votes = 3; //投给候选节点的票数,不能超过锁在合约中的未使用票数
......@@ -116,8 +122,9 @@ message JsonDposVoter{
int64 time = 5;
}
//DposVoteReply 投票查询响应
message DposVoteReply{
repeated JsonDposVoter votes = 1; //某地址对具体候选节点的投票情况
repeated JSONDposVoter votes = 1; //某地址对具体候选节点的投票情况
}
//ReceiptCandicator 候选者收据信息
......@@ -135,6 +142,7 @@ message ReceiptCandicator {
int64 time = 11;
}
//DposVrfM VrfM信息
message DposVrfM{
int64 Index = 1;
bytes pubkey = 2;
......@@ -147,6 +155,7 @@ message DposVrfM{
int64 cycleStop = 9;
}
//DposVrfRP VrfRP信息
message DposVrfRP{
int64 Index = 1;
bytes pubkey = 2;
......@@ -161,12 +170,14 @@ message DposVrfRP{
int64 cycleStop = 11;
}
//DposVrfMRegist VrfM注册请求
message DposVrfMRegist{
string pubkey = 1;
int64 cycle = 2;
string m = 3; //vrf的输入
}
//DposVrfRPRegist VrfRP注册请求
message DposVrfRPRegist{
string pubkey = 1;
int64 cycle = 2;
......@@ -191,7 +202,7 @@ message ReceiptVrf {
int64 cycleStop = 12;
}
//VrfInfo vrf信息
message VrfInfo {
int64 Index = 1;
bytes pubkey = 2;
......@@ -203,6 +214,7 @@ message VrfInfo {
int64 time = 9;
}
//DposVrfQuery vrf查询请求
message DposVrfQuery{
repeated string pubkeys = 1;
int64 ty = 2;
......@@ -210,7 +222,8 @@ message DposVrfQuery{
int64 cycle = 4;
}
message JsonVrfInfo {
//JSONVrfInfo json格式的vrf信息
message JSONVrfInfo {
int64 Index = 1;
string pubkey = 2;
int64 cycle = 4;
......@@ -221,10 +234,12 @@ message JsonVrfInfo {
int64 time = 9;
}
//DposVrfReply vrf查询响应
message DposVrfReply{
repeated JsonVrfInfo vrf = 1;
repeated JSONVrfInfo vrf = 1;
}
//DposCycleBoundaryInfo cycle边界信息
message DposCycleBoundaryInfo {
int64 cycle = 1;
int64 stopHeight = 2;
......@@ -233,6 +248,7 @@ message DposCycleBoundaryInfo {
bytes signature = 5;
}
//DposCBInfo cycle边界记录请求消息
message DposCBInfo {
int64 cycle = 1;
int64 stopHeight = 2;
......@@ -241,6 +257,7 @@ message DposCBInfo {
string signature = 5;
}
//DposCBQuery cycle边界记录查询请求
message DposCBQuery {
int64 cycle = 1;
int64 stopHeight = 2;
......@@ -248,6 +265,7 @@ message DposCBQuery {
int32 ty = 4;
}
//DposCBReply cycle边界记录查询响应
message DposCBReply {
DposCBInfo cbInfo = 1;
}
......@@ -266,6 +284,7 @@ message ReceiptCB {
DposCycleBoundaryInfo cbInfo = 10;
}
//TopNCandidator topN候选者
message TopNCandidator{
repeated Candidator cands = 1;
bytes hash = 2;
......@@ -274,6 +293,7 @@ message TopNCandidator{
bytes signature = 5;
}
//TopNCandidators topN候选者(复数)
message TopNCandidators{
repeated TopNCandidator candsVotes = 1;
int64 version = 2;
......@@ -281,18 +301,22 @@ message TopNCandidators{
repeated Candidator finalCands = 4;
}
//TopNCandidatorRegist topN候选者注册请求
message TopNCandidatorRegist{
TopNCandidator cand = 1;
}
//TopNCandidatorsQuery topN候选者查询请求
message TopNCandidatorsQuery{
int64 version = 1;
}
//TopNCandidatorsReply topN候选者查询响应
message TopNCandidatorsReply{
TopNCandidators topN = 1;
}
//ReceiptTopN topN注册的收据信息
message ReceiptTopN {
int64 Index = 1;
bytes pubkey = 2;
......
......@@ -32,35 +32,50 @@ const (
//log ty
const (
TyLogCandicatorRegist = 1001
TyLogCandicatorVoted = 1002
TyLogCandicatorCancelVoted = 1003
TyLogCandicatorCancelRegist = 1004
TyLogCandicatorReRegist = 1005
TyLogVrfMRegist = 1006
TyLogVrfRPRegist = 1007
TyLogCBInfoRecord = 1008
TyLogTopNCandidatorRegist = 1009
TyLogCandicatorRegist = 1001
TyLogCandicatorVoted = 1002
TyLogCandicatorCancelVoted = 1003
TyLogCandicatorCancelRegist = 1004
TyLogCandicatorReRegist = 1005
TyLogVrfMRegist = 1006
TyLogVrfRPRegist = 1007
TyLogCBInfoRecord = 1008
TyLogTopNCandidatorRegist = 1009
)
const (
VoteFrozenTime = 3 * 24 * 3600
//VoteFrozenTime = 3 * 24 * 3600
//RegistFrozenCoins 注册为候选节点需要抵押冻结的代币数量
RegistFrozenCoins = 1000000000000
//VoteTypeNone 非投票类型
VoteTypeNone int32 = 1
//VoteTypeVote 投票类型
VoteTypeVote int32 = 2
//VoteTypeCancelVote 撤销投票类型
VoteTypeCancelVote int32 = 3
//VoteTypeCancelAllVote 撤销所有投票类型
VoteTypeCancelAllVote int32 = 4
TopNCandidatorsVoteInit int64 = 0
TopNCandidatorsVoteMajorOK int64 = 1
//TopNCandidatorsVoteInit topN投票状态:初始状态
TopNCandidatorsVoteInit int64 = 0
//TopNCandidatorsVoteMajorOK topN投票状态:2/3多数达成一致
TopNCandidatorsVoteMajorOK int64 = 1
//TopNCandidatorsVoteMajorFail topN投票状态:2/3多数达成一致失败
TopNCandidatorsVoteMajorFail int64 = 2
)
//包的名字可以通过配置文件来配置
//建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字
//如果发生重名,可以通过配置文件修改这些名字
var (
DPosX = "dpos"
DPosX = "dpos"
ExecerDposVote = []byte(DPosX)
)
......@@ -132,7 +147,7 @@ const (
FuncNameQueryCBInfoByHash = "QueryCBInfoByHash"
//FuncNameQueryLatestCBInfoByHeight func name
FuncNameQueryLatestCBInfoByHeight = "QueryLatestCBInfoByHeight"
//FuncNameQueryLatestCBInfoByHeight = "QueryLatestCBInfoByHeight"
//QueryCBInfoByCycle 根据cycle查询cycle boundary信息
QueryCBInfoByCycle = 1
......@@ -143,8 +158,8 @@ const (
//QueryCBInfoByHash 根据stopHash查询cycle boundary信息
QueryCBInfoByHash = 3
//QueryCBInfoByHeight 根据stopHeight查询cycle boundary信息
QueryLatestCBInfoByHeight = 4
//QueryLatestCBInfoByHeight 根据stopHeight查询cycle boundary信息
//QueryLatestCBInfoByHeight = 4
//FuncNameQueryTopNByVersion func name
FuncNameQueryTopNByVersion = "QueryTopNByVersion"
......
This diff is collapsed.
......@@ -4,10 +4,9 @@ import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
ttypes "github.com/33cn/plugin/plugin/consensus/dpos/types"
"github.com/33cn/chain33/common/crypto"
ttypes "github.com/33cn/plugin/plugin/consensus/dpos/types"
)
// CanonicalOnceCBInfo ...
......@@ -21,79 +20,78 @@ type CanonicalOnceCBInfo struct {
// CanonicalCBInfo ...
func CanonicalCBInfo(cb *DposCBInfo) CanonicalOnceCBInfo {
return CanonicalOnceCBInfo{
Cycle: cb.Cycle,
Cycle: cb.Cycle,
StopHeight: cb.StopHeight,
StopHash: cb.StopHash,
Pubkey: cb.Pubkey,
StopHash: cb.StopHash,
Pubkey: cb.Pubkey,
}
}
// CanonicalCBInfo ...
func (cb *DposCBInfo)Verify() error {
// Verify ...
func (cb *DposCBInfo) Verify() error {
buf := new(bytes.Buffer)
canonical := CanonicalCBInfo(cb)
byteCB, err := json.Marshal(&canonical)
if err != nil {
return errors.New(fmt.Sprintf("Error marshal CanonicalOnceCBInfo: %v", err))
return fmt.Errorf("Error marshal CanonicalOnceCBInfo: %v", err)
}
_, err = buf.Write(byteCB)
if err != nil {
return errors.New(fmt.Sprintf("Error write buffer: %v", err))
return fmt.Errorf("Error write buffer: %v", err)
}
bPubkey, err := hex.DecodeString(cb.Pubkey)
if err != nil {
return errors.New(fmt.Sprintf("Error Decode pubkey: %v", err))
return fmt.Errorf("Error Decode pubkey: %v", err)
}
pubkey, err := ttypes.ConsensusCrypto.PubKeyFromBytes(bPubkey)
if err != nil {
return errors.New(fmt.Sprintf("Error PubKeyFromBytes: %v", err))
return fmt.Errorf("Error PubKeyFromBytes: %v", err)
}
signature, err := hex.DecodeString(cb.Signature)
if err != nil {
return errors.New(fmt.Sprintf("Error Decode Signature: %v", err))
return fmt.Errorf("Error Decode Signature: %v", err)
}
sig, err := ttypes.ConsensusCrypto.SignatureFromBytes(signature)
if err != nil {
return errors.New(fmt.Sprintf("Error SignatureFromBytes: %v", err))
return fmt.Errorf("Error SignatureFromBytes: %v", err)
}
if !pubkey.VerifyBytes(buf.Bytes(), sig) {
return errors.New(fmt.Sprintf("Error VerifyBytes: %v", err))
return fmt.Errorf("Error VerifyBytes: %v", err)
}
return nil
}
// OnceCandidator ...
type OnceCandidator struct {
Pubkey []byte `json:"pubkey,omitempty"`
Address string `json:"address,omitempty"`
Ip string `json:"ip,omitempty"`
IP string `json:"ip,omitempty"`
}
// CanonicalOnceTopNCandidator ...
type CanonicalOnceTopNCandidator struct {
Cands []*OnceCandidator `json:"cands,omitempty"`
Hash []byte `json:"hash,omitempty"`
Height int64 `json:"height,omitempty"`
SignerPubkey []byte `json:"signerPubkey,omitempty"`
Signature []byte `json:"signature,omitempty"`
Hash []byte `json:"hash,omitempty"`
Height int64 `json:"height,omitempty"`
SignerPubkey []byte `json:"signerPubkey,omitempty"`
Signature []byte `json:"signature,omitempty"`
}
func (topN *CanonicalOnceTopNCandidator) onlyCopyCands() CanonicalOnceTopNCandidator{
func (topN *CanonicalOnceTopNCandidator) onlyCopyCands() CanonicalOnceTopNCandidator {
obj := CanonicalOnceTopNCandidator{}
for i := 0; i < len(topN.Cands); i++ {
cand := &OnceCandidator{
Pubkey: topN.Cands[i].Pubkey,
Pubkey: topN.Cands[i].Pubkey,
Address: topN.Cands[i].Address,
Ip: topN.Cands[i].Ip,
IP: topN.Cands[i].IP,
}
obj.Cands = append(obj.Cands, cand)
}
......@@ -101,7 +99,8 @@ func (topN *CanonicalOnceTopNCandidator) onlyCopyCands() CanonicalOnceTopNCandid
return obj
}
func (topN *CanonicalOnceTopNCandidator) ID() []byte{
// ID ...
func (topN *CanonicalOnceTopNCandidator) ID() []byte {
obj := topN.onlyCopyCands()
encode, err := json.Marshal(&obj)
if err != nil {
......@@ -109,28 +108,29 @@ func (topN *CanonicalOnceTopNCandidator) ID() []byte{
}
return crypto.Ripemd160(encode)
}
// CanonicalCBInfo ...
// CanonicalTopNCandidator ...
func CanonicalTopNCandidator(topN *TopNCandidator) CanonicalOnceTopNCandidator {
onceTopNCandidator := CanonicalOnceTopNCandidator{
Height: topN.Height,
Height: topN.Height,
SignerPubkey: topN.SignerPubkey,
}
for i := 0; i < len(topN.Cands); i++ {
cand := &OnceCandidator{
Pubkey: topN.Cands[i].Pubkey,
Pubkey: topN.Cands[i].Pubkey,
Address: topN.Cands[i].Address,
Ip: topN.Cands[i].Ip,
IP: topN.Cands[i].IP,
}
onceTopNCandidator.Cands = append(onceTopNCandidator.Cands, cand)
}
return onceTopNCandidator
}
func (topN *TopNCandidator)copyWithoutSig() *TopNCandidator {
func (topN *TopNCandidator) copyWithoutSig() *TopNCandidator {
cpy := &TopNCandidator{
Hash: topN.Hash,
Height: topN.Height,
Hash: topN.Hash,
Height: topN.Height,
SignerPubkey: topN.SignerPubkey,
}
......@@ -140,55 +140,60 @@ func (topN *TopNCandidator)copyWithoutSig() *TopNCandidator {
}
return cpy
}
// Verify ...
func (topN *TopNCandidator)Verify() error {
func (topN *TopNCandidator) Verify() error {
buf := new(bytes.Buffer)
cpy := topN.copyWithoutSig()
byteCB, err := json.Marshal(cpy)
if err != nil {
return errors.New(fmt.Sprintf("Error marshal TopNCandidator: %v", err))
return fmt.Errorf("Error marshal TopNCandidator: %v", err)
}
_, err = buf.Write(byteCB)
if err != nil {
return errors.New(fmt.Sprintf("Error write buffer: %v", err))
return fmt.Errorf("Error write buffer: %v", err)
}
pubkey, err := ttypes.ConsensusCrypto.PubKeyFromBytes(topN.SignerPubkey)
if err != nil {
return errors.New(fmt.Sprintf("Error PubKeyFromBytes: %v", err))
return fmt.Errorf("Error PubKeyFromBytes: %v", err)
}
sig, err := ttypes.ConsensusCrypto.SignatureFromBytes(topN.Signature)
if err != nil {
return errors.New(fmt.Sprintf("Error SignatureFromBytes: %v", err))
return fmt.Errorf("Error SignatureFromBytes: %v", err)
}
if !pubkey.VerifyBytes(buf.Bytes(), sig) {
return errors.New(fmt.Sprintf("Error VerifyBytes: %v", err))
return fmt.Errorf("Error VerifyBytes: %v", err)
}
return nil
}
func (cand *Candidator)Copy() *Candidator {
// Copy ...
func (cand *Candidator) Copy() *Candidator {
cpy := &Candidator{
Address: cand.Address,
Ip: cand.Ip,
Votes: cand.Votes,
Status: cand.Status,
IP: cand.IP,
Votes: cand.Votes,
Status: cand.Status,
}
cpy.Pubkey = make([]byte, len(cand.Pubkey))
copy(cpy.Pubkey, cand.Pubkey)
return cpy
}
func (topNs *TopNCandidators)CheckVoteStauts(delegateNum int64) {
// CheckVoteStauts ...
func (topNs *TopNCandidators) CheckVoteStauts(delegateNum int64) {
if topNs.Status == TopNCandidatorsVoteMajorOK || topNs.Status == TopNCandidatorsVoteMajorFail {
return
}
voteMap := make(map[string] int64)
voteMap := make(map[string]int64)
for i := 0; i < len(topNs.CandsVotes); i++ {
key := hex.EncodeToString(topNs.CandsVotes[i].Hash)
......@@ -206,8 +211,8 @@ func (topNs *TopNCandidators)CheckVoteStauts(delegateNum int64) {
}
}
var maxVotes int64 = 0
var sumVotes int64 = 0
var maxVotes int64
var sumVotes int64
for _, v := range voteMap {
if v > maxVotes {
maxVotes = v
......@@ -215,7 +220,7 @@ func (topNs *TopNCandidators)CheckVoteStauts(delegateNum int64) {
sumVotes += v
}
if maxVotes + (delegateNum - sumVotes) < (delegateNum * 2 / 3) {
if maxVotes+(delegateNum-sumVotes) < (delegateNum * 2 / 3) {
topNs.Status = TopNCandidatorsVoteMajorFail
}
}
\ No newline at end of file
}
......@@ -121,12 +121,11 @@ func (tx *DposCandidatorRow) Get(key string) ([]byte, error) {
return nil, types.ErrNotFound
}
var opt_dpos_vrfm = &table.Option{
Prefix: "LODB-dpos",
Name: "vrfm",
Primary: "index",
Index: []string{"pubkey_cycle","cycle"},
Index: []string{"pubkey_cycle", "cycle"},
}
//NewDposVrfMTable 新建表
......@@ -176,7 +175,6 @@ func (tx *DposVrfMRow) Get(key string) ([]byte, error) {
return nil, types.ErrNotFound
}
var opt_dpos_vrfrp = &table.Option{
Prefix: "LODB-dpos",
Name: "vrfrp",
......@@ -231,8 +229,6 @@ func (tx *DposVrfRPRow) Get(key string) ([]byte, error) {
return nil, types.ErrNotFound
}
var opt_dpos_cb = &table.Option{
Prefix: "LODB-dpos",
Name: "cb",
......@@ -240,7 +236,7 @@ var opt_dpos_cb = &table.Option{
Index: []string{"height", "hash"},
}
//NewDposVrfRPTable 新建表
//NewDposCBTable 新建表
func NewDposCBTable(kvdb db.KV) *table.Table {
rowmeta := NewDposCBRow()
table, err := table.NewTable(rowmeta, kvdb, opt_dpos_cb)
......@@ -255,7 +251,7 @@ type DposCBRow struct {
*DposCycleBoundaryInfo
}
//NewDposVrfRPRow 新建一个meta 结构
//NewDposCBRow 新建一个meta 结构
func NewDposCBRow() *DposCBRow {
return &DposCBRow{DposCycleBoundaryInfo: &DposCycleBoundaryInfo{}}
}
......
......@@ -17,7 +17,7 @@ func init() {
types.RegisterDappFork(DPosX, "Enable", 0)
}
// GuessType struct
// DPosType struct
type DPosType struct {
types.ExecTypeBase
}
......@@ -37,15 +37,15 @@ func (t *DPosType) GetPayload() types.Message {
// GetTypeMap method
func (t *DPosType) GetTypeMap() map[string]int32 {
return map[string]int32{
"Regist": DposVoteActionRegist,
"CancelRegist": DposVoteActionCancelRegist,
"ReRegist": DposVoteActionReRegist,
"Vote": DposVoteActionVote,
"CancelVote": DposVoteActionCancelVote,
"RegistVrfM": DposVoteActionRegistVrfM,
"RegistVrfRP": DposVoteActionRegistVrfRP,
"RecordCB": DposVoteActionRecordCB,
"RegistTopN": DPosVoteActionRegistTopNCandidator,
"Regist": DposVoteActionRegist,
"CancelRegist": DposVoteActionCancelRegist,
"ReRegist": DposVoteActionReRegist,
"Vote": DposVoteActionVote,
"CancelVote": DposVoteActionCancelVote,
"RegistVrfM": DposVoteActionRegistVrfM,
"RegistVrfRP": DposVoteActionRegistVrfRP,
"RecordCB": DposVoteActionRecordCB,
"RegistTopN": DPosVoteActionRegistTopNCandidator,
}
}
......@@ -57,9 +57,9 @@ func (t *DPosType) GetLogMap() map[int64]*types.LogInfo {
TyLogCandicatorCancelVoted: {Ty: reflect.TypeOf(ReceiptCandicator{}), Name: "TyLogCandicatorCancelVoted"},
TyLogCandicatorCancelRegist: {Ty: reflect.TypeOf(ReceiptCandicator{}), Name: "TyLogCandicatorCancelRegist"},
TyLogCandicatorReRegist: {Ty: reflect.TypeOf(ReceiptCandicator{}), Name: "TyLogCandicatorReRegist"},
TyLogVrfMRegist: {Ty: reflect.TypeOf(ReceiptVrf{}), Name: "TyLogVrfMRegist"},
TyLogVrfRPRegist: {Ty: reflect.TypeOf(ReceiptVrf{}), Name: "TyLogVrfRPRegist"},
TyLogCBInfoRecord: {Ty: reflect.TypeOf(ReceiptCB{}), Name: "TyLogCBInfoRecord"},
TyLogTopNCandidatorRegist: {Ty: reflect.TypeOf(ReceiptTopN{}), Name: "TyLogTopNCandidatorRegist"},
TyLogVrfMRegist: {Ty: reflect.TypeOf(ReceiptVrf{}), Name: "TyLogVrfMRegist"},
TyLogVrfRPRegist: {Ty: reflect.TypeOf(ReceiptVrf{}), Name: "TyLogVrfRPRegist"},
TyLogCBInfoRecord: {Ty: reflect.TypeOf(ReceiptCB{}), Name: "TyLogCBInfoRecord"},
TyLogTopNCandidatorRegist: {Ty: reflect.TypeOf(ReceiptTopN{}), Name: "TyLogTopNCandidatorRegist"},
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment