github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/consense/dpoa/comm/types.go (about)

     1  package comm
     2  
     3  import (
     4  	"encoding/json"
     5  	//"github.com/ontio/ontology-crypto/keypair"
     6  	//"github.com/sixexorg/magnetic-ring/core/types"
     7  	"github.com/sixexorg/magnetic-ring/common"
     8  
     9  	//"github.com/sixexorg/magnetic-ring/consensus/vbft/config"
    10  	"github.com/sixexorg/magnetic-ring/common/serialization"
    11  	//"github.com/sixexorg/magnetic-ring/common/config"
    12  	"bytes"
    13  	//"strings"
    14  
    15  	"fmt"
    16  	"math"
    17  
    18  	"github.com/sixexorg/magnetic-ring/core/mainchain/types"
    19  	"github.com/sixexorg/magnetic-ring/crypto"
    20  	"github.com/sixexorg/magnetic-ring/rlp"
    21  )
    22  
    23  // 用户角色
    24  type roletype int
    25  
    26  const (
    27  	Observer roletype = iota
    28  	Processer
    29  	Failor
    30  )
    31  
    32  type MsgType uint8
    33  
    34  const (
    35  	BlockProposalMessage MsgType = iota
    36  	BlockEndorseMessage
    37  	BlockCommitMessage
    38  	PeerHandshakeMessage
    39  	PeerHeartbeatMessage
    40  	BlockInfoFetchMessage
    41  	BlockInfoFetchRespMessage
    42  	ProposalFetchMessage
    43  	BlockFetchMessage
    44  	BlockFetchRespMessage
    45  
    46  	ConsensePrepare
    47  	ConsensePromise
    48  	ConsenseProposer
    49  	ConsenseAccept
    50  	ConsenseDone
    51  	ViewTimeout
    52  	EvilEvent
    53  	EarthFetchRspSigs
    54  	EventFetchMessage
    55  	EventFetchRspMessage
    56  	EvilFetchMessage
    57  	EvilFetchRspMessage
    58  	TimeoutFetchMessage
    59  	TimeoutFetchRspMessage
    60  )
    61  
    62  type ParticiConfig struct {
    63  	BlkNum      uint64
    64  	View        uint32
    65  	ProcNodes   []string
    66  	ObserNodes  []string
    67  	FailsNodes  []string
    68  	PartiRaw    []string
    69  	StarsSorted []string
    70  }
    71  
    72  type ConsenseNotify struct {
    73  	BlkNum    uint64
    74  	ProcNodes []string
    75  	Istart    bool
    76  }
    77  
    78  type ConsensusMsg interface {
    79  	Type() MsgType
    80  	Verify(pub crypto.PublicKey) error
    81  	GetBlockNum() uint64
    82  	Serialize() ([]byte, error)
    83  }
    84  
    85  type PeerHeartbeatMsg struct {
    86  	CommittedBlockNumber uint64 `json:"committed_block_number"`
    87  	TimeStamp            []byte `json:"timestamp"`
    88  }
    89  
    90  func (msg *PeerHeartbeatMsg) Type() MsgType {
    91  	return PeerHeartbeatMessage
    92  }
    93  
    94  func (msg *PeerHeartbeatMsg) Verify(pub crypto.PublicKey) error {
    95  	return nil
    96  }
    97  
    98  func (msg *PeerHeartbeatMsg) GetBlockNum() uint64 {
    99  	return 0
   100  }
   101  
   102  func (msg *PeerHeartbeatMsg) Serialize() ([]byte, error) {
   103  	return json.Marshal(msg)
   104  }
   105  
   106  type PeerHandshakeMsg struct {
   107  	CommittedBlockNumber uint64 `json:"committed_block_number"`
   108  	//CommittedBlockHash   common.Hash  `json:"committed_block_hash"`
   109  	//CommittedBlockLeader uint32       `json:"committed_block_leader"`
   110  	//ChainConfig          *ChainConfig `json:"chain_config"`
   111  }
   112  
   113  func (msg *PeerHandshakeMsg) Type() MsgType {
   114  	return PeerHandshakeMessage
   115  }
   116  
   117  func (msg *PeerHandshakeMsg) Verify(pub crypto.PublicKey) error {
   118  
   119  	return nil
   120  }
   121  
   122  func (msg *PeerHandshakeMsg) GetBlockNum() uint64 {
   123  	return 0
   124  }
   125  
   126  func (msg *PeerHandshakeMsg) Serialize() ([]byte, error) {
   127  	return json.Marshal(msg)
   128  }
   129  
   130  type BlockFetchRespMsg struct {
   131  	BlockNumber uint64      `json:"block_number"`
   132  	BlockHash   common.Hash `json:"block_hash"`
   133  	BlockData   *Block      `json:"block_data"`
   134  }
   135  
   136  func (msg *BlockFetchRespMsg) Type() MsgType {
   137  	return BlockFetchRespMessage
   138  }
   139  
   140  func (msg *BlockFetchRespMsg) Verify(pub crypto.PublicKey) error {
   141  	return nil
   142  }
   143  
   144  func (msg *BlockFetchRespMsg) GetBlockNum() uint64 {
   145  	return 0
   146  }
   147  
   148  func (msg *BlockFetchRespMsg) Serialize() ([]byte, error) {
   149  	buffer := bytes.NewBuffer([]byte{})
   150  	serialization.WriteUint64(buffer, msg.BlockNumber)
   151  	msg.BlockHash.Serialize(buffer)
   152  	blockbuff, err := msg.BlockData.Serialize()
   153  	if err != nil {
   154  		return nil, err
   155  	}
   156  	buffer.Write(blockbuff)
   157  	return buffer.Bytes(), nil
   158  }
   159  
   160  func (msg *BlockFetchRespMsg) Deserialize(data []byte) error {
   161  	buffer := bytes.NewBuffer(data)
   162  	blocknum, err := serialization.ReadUint64(buffer)
   163  	if err != nil {
   164  		return err
   165  	}
   166  	msg.BlockNumber = blocknum
   167  	err = msg.BlockHash.Deserialize(buffer)
   168  	if err != nil {
   169  		return err
   170  	}
   171  	blk := &Block{}
   172  	if err := blk.Deserialize(buffer.Bytes()); err != nil {
   173  		return fmt.Errorf("unmarshal block type: %s", err)
   174  	}
   175  	msg.BlockData = blk
   176  	return nil
   177  }
   178  
   179  type BlockInfoFetchMsg struct {
   180  	StartBlockNum uint64 `json:"start_block_num"`
   181  }
   182  
   183  func (msg *BlockInfoFetchMsg) Type() MsgType {
   184  	return BlockInfoFetchMessage
   185  }
   186  
   187  func (msg *BlockInfoFetchMsg) Verify(pub crypto.PublicKey) error {
   188  	return nil
   189  }
   190  
   191  func (msg *BlockInfoFetchMsg) GetBlockNum() uint64 {
   192  	return 0
   193  }
   194  
   195  func (msg *BlockInfoFetchMsg) Serialize() ([]byte, error) {
   196  	return json.Marshal(msg)
   197  }
   198  
   199  type BlockInfo_ struct {
   200  	BlockNum   uint64            `json:"block_num"`
   201  	Proposer   uint32            `json:"proposer"`
   202  	Signatures map[uint32][]byte `json:"signatures"`
   203  }
   204  
   205  type BlockInfoFetchRespMsg struct {
   206  	Blocks []*BlockInfo_ `json:"blocks"`
   207  }
   208  
   209  func (msg *BlockInfoFetchRespMsg) Type() MsgType {
   210  	return BlockInfoFetchRespMessage
   211  }
   212  
   213  func (msg *BlockInfoFetchRespMsg) Verify(pub crypto.PublicKey) error {
   214  	return nil
   215  }
   216  
   217  func (msg *BlockInfoFetchRespMsg) GetBlockNum() uint64 {
   218  	return 0
   219  }
   220  
   221  func (msg *BlockInfoFetchRespMsg) Serialize() ([]byte, error) {
   222  	return json.Marshal(msg)
   223  }
   224  
   225  type ChainConfig struct {
   226  	Peers []string `json:"peers"`
   227  }
   228  
   229  //type VbftBlockInfo struct {
   230  //	Proposer           string       `json:"leader"`
   231  //	VrfValue           []byte       `json:"vrf_value"`
   232  //	VrfProof           []byte       `json:"vrf_proof"`
   233  //	LastConfigBlockNum uint32       `json:"last_config_block_num"`
   234  //	NewChainConfig     *ChainConfig `json:"new_chain_config"`
   235  //}
   236  
   237  type Block struct {
   238  	Block *types.Block
   239  	//EmptyBlock *types.Block
   240  	Info *VbftBlockInfo
   241  }
   242  
   243  func (blk *Block) GetViews() uint32 {
   244  	return blk.Info.View
   245  }
   246  
   247  func (blk *Block) GetProposer() string {
   248  	return blk.Info.Miner
   249  }
   250  
   251  func (blk *Block) GetBlockNum() uint64 {
   252  	return blk.Block.Header.Height
   253  }
   254  
   255  //func (blk *Block) GetEmptyBlockNum() uint64 {
   256  //	return blk.EmptyBlock.Header.Height
   257  //}
   258  
   259  func (blk *Block) GetPrevBlockHash() common.Hash {
   260  	return blk.Block.Header.PrevBlockHash
   261  }
   262  
   263  func (blk *Block) GetLastConfigBlockNum() uint64 {
   264  	return blk.Info.LastConfigBlockNum
   265  }
   266  
   267  func (blk *Block) GetNewChainConfig() *ChainConfig {
   268  	//return blk.Info.NewChainConfig
   269  	return nil
   270  }
   271  
   272  //
   273  // getVrfValue() is a helper function for participant selection.
   274  //
   275  func (blk *Block) GetVrfValue() []byte {
   276  	return blk.Info.VrfValue
   277  }
   278  
   279  func (blk *Block) GetVrfProof() []byte {
   280  	return blk.Info.VrfProof
   281  }
   282  
   283  func (blk *Block) Serialize() ([]byte, error) {
   284  
   285  	buf := bytes.NewBuffer(nil)
   286  	err := blk.Block.Serialize(buf)
   287  	if err != nil {
   288  		return nil, fmt.Errorf("serialize block: %s", err)
   289  	}
   290  	if blk.Info.NewChainConfig == nil {
   291  		blk.Info.NewChainConfig = &ChainConfig{
   292  			Peers: make([]string, 0),
   293  		}
   294  	}
   295  	if err = rlp.Encode(buf, blk.Info); err != nil {
   296  		return nil, fmt.Errorf("serialize info: %s", err)
   297  	}
   298  	return buf.Bytes(), nil
   299  }
   300  
   301  func (blk *Block) Deserialize(data []byte) error {
   302  	buff := bytes.NewBuffer(data)
   303  	blk.Block = &types.Block{}
   304  	err := blk.Block.Deserialize(buff)
   305  	if err != nil {
   306  		return err
   307  	}
   308  	blk.Info = &VbftBlockInfo{}
   309  	if err = rlp.Decode(buff, blk.Info); err != nil {
   310  		return err
   311  	}
   312  	return nil
   313  }
   314  
   315  func InitVbftBlock(block *types.Block) (*Block, error) {
   316  	if block == nil {
   317  		return nil, fmt.Errorf("nil block in initVbftBlock")
   318  	}
   319  	//if block.Header.Height == 1{
   320  	//	blkInfo := &VbftBlockInfo{}
   321  	//	blkInfo.VrfValue = []byte("1c9810aa9822e511d5804a9c4db9dd08497c31087b0daafa34d768a3253441fa20515e2f30f81741102af0ca3cefc4818fef16adb825fbaa8cad78647f3afb590e")
   322  	//	blkInfo.VrfProof = []byte("c57741f934042cb8d8b087b44b161db56fc3ffd4ffb675d36cd09f83935be853d8729f3f5298d12d6fd28d45dde515a4b9d7f67682d182ba5118abf451ff1988")
   323  	//	block.Header.ConsensusPayload, _ = json.Marshal(blkInfo)
   324  	//}
   325  
   326  	blkInfo := &VbftBlockInfo{}
   327  	if err := json.Unmarshal(block.Header.ConsensusPayload, blkInfo); err != nil {
   328  		return nil, fmt.Errorf("unmarshal blockInfo: %s", err)
   329  	}
   330  
   331  	return &Block{
   332  		Block: block,
   333  		Info:  blkInfo,
   334  	}, nil
   335  }
   336  
   337  //
   338  //type VRFValue [64]byte
   339  //var NilVRF = VRFValue{}
   340  //
   341  //func (v VRFValue) Bytes() []byte {
   342  //	return v[:]
   343  //}
   344  //
   345  //func (v VRFValue) IsNil() bool {
   346  //	return bytes.Compare(v.Bytes(), NilVRF.Bytes()) == 0
   347  //}
   348  
   349  func genConsensusPayload() ([]byte, error) {
   350  	//if cfg.C == 0 {
   351  	//	return nil, fmt.Errorf("C must larger than zero")
   352  	//}
   353  	//if int(cfg.K) > len(cfg.Peers) {
   354  	//	return nil, fmt.Errorf("peer count is less than K")
   355  	//}
   356  	//if cfg.K < 2*cfg.C+1 {
   357  	//	return nil, fmt.Errorf("invalid config, K: %d, C: %d", cfg.K, cfg.C)
   358  	//}
   359  	//if cfg.L%cfg.K != 0 || cfg.L < cfg.K*2 {
   360  	//	return nil, fmt.Errorf("invalid config, K: %d, L: %d", cfg.K, cfg.L)
   361  	//}
   362  	//chainConfig, err := GenesisChainConfig(cfg, cfg.Peers, txhash, height)
   363  	//if err != nil {
   364  	//	return nil, err
   365  	//}
   366  	//
   367  	//// save VRF in genesis config file, to genesis block
   368  	//vrfValue, err := hex.DecodeString(cfg.VrfValue)
   369  	//if err != nil {
   370  	//	return nil, fmt.Errorf("invalid config, vrf_value: %s", err)
   371  	//}
   372  	//
   373  	//vrfProof, err := hex.DecodeString(cfg.VrfProof)
   374  	//if err != nil {
   375  	//	return nil, fmt.Errorf("invalid config, vrf_proof: %s", err)
   376  	//}
   377  
   378  	// Notice:
   379  	// take genesis msg as random source,
   380  	// don't need verify (genesisProposer, vrfValue, vrfProof)
   381  
   382  	vbftBlockInfo := &VbftBlockInfo{
   383  		//Proposer:           "",
   384  		//VrfValue:           vrfValue,
   385  		//VrfProof:           vrfProof,
   386  		LastConfigBlockNum: math.MaxUint32,
   387  		//NewChainConfig:     chainConfig,
   388  	}
   389  	return json.Marshal(vbftBlockInfo)
   390  }
   391  
   392  //
   393  //func GenesisConsensusPayload(txhash common.Uint256, height uint32) ([]byte, error) {
   394  //	consensusType := strings.ToLower(config.DefConfig.Genesis.ConsensusType)
   395  //
   396  //	switch consensusType {
   397  //	case "vbft":
   398  //		return genConsensusPayload(config.DefConfig.Genesis.VBFT, txhash, height)
   399  //	}
   400  //	return nil, nil
   401  //}
   402  
   403  type VbftBlockInfo struct {
   404  	View               uint32       `json:"view"`
   405  	Miner              string       `json:"miner"`
   406  	Proposer           uint32       `json:"leader"`
   407  	VrfValue           []byte       `json:"vrf_value"`
   408  	VrfProof           []byte       `json:"vrf_proof"`
   409  	LastConfigBlockNum uint64       `json:"last_config_block_num"`
   410  	NewChainConfig     *ChainConfig `json:"new_chain_config"`
   411  }
   412  
   413  const (
   414  	VRF_SIZE            = 64 // bytes
   415  	MAX_PROPOSER_COUNT  = 32
   416  	MAX_ENDORSER_COUNT  = 240
   417  	MAX_COMMITTER_COUNT = 240
   418  )
   419  
   420  type VRFValue [VRF_SIZE]byte
   421  
   422  var NilVRF = VRFValue{}
   423  
   424  func (v VRFValue) Bytes() []byte {
   425  	return v[:]
   426  }
   427  
   428  func (v VRFValue) IsNil() bool {
   429  	return bytes.Compare(v.Bytes(), NilVRF.Bytes()) == 0
   430  }
   431  
   432  type Account interface {
   433  	Sign(hash []byte) (sig []byte, err error)
   434  	Verify(hash, sig []byte) (bool, error)
   435  	Address() common.Address
   436  }
   437  
   438  type DataHandler interface {
   439  	DelOrder(key string)
   440  }