/
msg_builder.go
370 lines (319 loc) · 10.6 KB
/
msg_builder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package vbft
import (
"encoding/json"
"fmt"
"time"
"github.com/mixbee/mixbee-crypto/keypair"
"github.com/mixbee/mixbee/common"
"github.com/mixbee/mixbee/common/log"
"github.com/mixbee/mixbee/consensus/vbft/config"
"github.com/mixbee/mixbee/core/ledger"
"github.com/mixbee/mixbee/core/signature"
"github.com/mixbee/mixbee/core/types"
)
type ConsensusMsgPayload struct {
Type MsgType `json:"type"`
Len uint32 `json:"len"`
Payload []byte `json:"payload"`
}
func DeserializeVbftMsg(msgPayload []byte) (ConsensusMsg, error) {
m := &ConsensusMsgPayload{}
if err := json.Unmarshal(msgPayload, m); err != nil {
return nil, fmt.Errorf("unmarshal consensus msg payload: %s", err)
}
if m.Len < uint32(len(m.Payload)) {
return nil, fmt.Errorf("invalid payload length: %d", m.Len)
}
switch m.Type {
case BlockProposalMessage:
t := &blockProposalMsg{}
if err := t.UnmarshalJSON(m.Payload); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case BlockEndorseMessage:
t := &blockEndorseMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case BlockCommitMessage:
t := &blockCommitMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case PeerHandshakeMessage:
t := &peerHandshakeMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case PeerHeartbeatMessage:
t := &peerHeartbeatMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case BlockInfoFetchMessage:
t := &BlockInfoFetchMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case BlockInfoFetchRespMessage:
t := &BlockInfoFetchRespMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case BlockFetchMessage:
t := &blockFetchMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case BlockFetchRespMessage:
t := &BlockFetchRespMsg{}
if err := t.Deserialize(m.Payload); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
case ProposalFetchMessage:
t := &proposalFetchMsg{}
if err := json.Unmarshal(m.Payload, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal msg (type: %d): %s", m.Type, err)
}
return t, nil
}
return nil, fmt.Errorf("unknown msg type: %d", m.Type)
}
func SerializeVbftMsg(msg ConsensusMsg) ([]byte, error) {
payload, err := msg.Serialize()
if err != nil {
return nil, err
}
return json.Marshal(&ConsensusMsgPayload{
Type: msg.Type(),
Len: uint32(len(payload)),
Payload: payload,
})
}
func (self *Server) constructHandshakeMsg() (*peerHandshakeMsg, error) {
blkNum := self.GetCurrentBlockNo() - 1
block, blockhash := self.blockPool.getSealedBlock(blkNum)
if block == nil {
return nil, fmt.Errorf("failed to get sealed block, current block: %d", self.GetCurrentBlockNo())
}
msg := &peerHandshakeMsg{
CommittedBlockNumber: blkNum,
CommittedBlockHash: blockhash,
CommittedBlockLeader: block.getProposer(),
ChainConfig: self.config,
}
return msg, nil
}
func (self *Server) constructHeartbeatMsg() (*peerHeartbeatMsg, error) {
blkNum := self.GetCurrentBlockNo() - 1
block, blockhash := self.blockPool.getSealedBlock(blkNum)
if block == nil {
return nil, fmt.Errorf("failed to get sealed block, current block: %d", self.GetCurrentBlockNo())
}
bookkeepers := make([][]byte, 0)
endorsePks := block.Block.Header.Bookkeepers
sigData := block.Block.Header.SigData
if len(endorsePks) == len(sigData) {
for i := 0; i < len(endorsePks); i++ {
bookkeepers = append(bookkeepers, keypair.SerializePublicKey(endorsePks[i]))
}
} else {
log.Errorf("Invalid signature counts in block %d: %d vs %d", blkNum, len(endorsePks), len(sigData))
sigData = make([][]byte, 0)
}
msg := &peerHeartbeatMsg{
CommittedBlockNumber: blkNum,
CommittedBlockHash: blockhash,
CommittedBlockLeader: block.getProposer(),
Endorsers: bookkeepers,
EndorsersSig: sigData,
ChainConfigView: self.config.View,
}
return msg, nil
}
func (self *Server) constructBlock(blkNum uint32, prevBlkHash common.Uint256, txs []*types.Transaction, consensusPayload []byte, blocktimestamp uint32) (*types.Block, error) {
txHash := []common.Uint256{}
for _, t := range txs {
txHash = append(txHash, t.Hash())
}
txRoot := common.ComputeMerkleRoot(txHash)
blockRoot := ledger.DefLedger.GetBlockRootWithNewTxRoot(txRoot)
blkHeader := &types.Header{
PrevBlockHash: prevBlkHash,
TransactionsRoot: txRoot,
BlockRoot: blockRoot,
Timestamp: blocktimestamp,
Height: uint32(blkNum),
ConsensusData: common.GetNonce(),
ConsensusPayload: consensusPayload,
}
blk := &types.Block{
Header: blkHeader,
Transactions: txs,
}
blkHash := blk.Hash()
sig, err := signature.Sign(self.account, blkHash[:])
if err != nil {
return nil, fmt.Errorf("sign block failed, block hash:%s, error: %s", blkHash.ToHexString(), err)
}
blkHeader.Bookkeepers = []keypair.PublicKey{self.account.PublicKey}
blkHeader.SigData = [][]byte{sig}
return blk, nil
}
func (self *Server) constructProposalMsg(blkNum uint32, sysTxs, userTxs []*types.Transaction, chainconfig *vconfig.ChainConfig) (*blockProposalMsg, error) {
prevBlk, prevBlkHash := self.blockPool.getSealedBlock(blkNum - 1)
if prevBlk == nil {
return nil, fmt.Errorf("failed to get prevBlock (%d)", blkNum-1)
}
blocktimestamp := uint32(time.Now().Unix())
if prevBlk.Block.Header.Timestamp >= blocktimestamp {
blocktimestamp = prevBlk.Block.Header.Timestamp + 1
}
vrfValue, vrfProof, err := computeVrf(self.account.PrivateKey, blkNum, prevBlk.getVrfValue())
if err != nil {
return nil, fmt.Errorf("failed to get vrf and proof: %s", err)
}
lastConfigBlkNum := prevBlk.Info.LastConfigBlockNum
if prevBlk.Info.NewChainConfig != nil {
lastConfigBlkNum = prevBlk.getBlockNum()
}
if chainconfig != nil {
lastConfigBlkNum = blkNum
}
vbftBlkInfo := &vconfig.VbftBlockInfo{
Proposer: self.Index,
VrfValue: vrfValue,
VrfProof: vrfProof,
LastConfigBlockNum: lastConfigBlkNum,
NewChainConfig: chainconfig,
}
consensusPayload, err := json.Marshal(vbftBlkInfo)
if err != nil {
return nil, err
}
emptyBlk, err := self.constructBlock(blkNum, prevBlkHash, sysTxs, consensusPayload, blocktimestamp)
if err != nil {
return nil, fmt.Errorf("failed to construct empty block: %s", err)
}
blk, err := self.constructBlock(blkNum, prevBlkHash, append(sysTxs, userTxs...), consensusPayload, blocktimestamp)
if err != nil {
return nil, fmt.Errorf("failed to constuct blk: %s", err)
}
msg := &blockProposalMsg{
Block: &Block{
Block: blk,
EmptyBlock: emptyBlk,
Info: vbftBlkInfo,
},
}
return msg, nil
}
func (self *Server) constructEndorseMsg(proposal *blockProposalMsg, forEmpty bool) (*blockEndorseMsg, error) {
// TODO, support faultyMsg reporting
var proposerSig, endorserSig []byte
var blkHash common.Uint256
var err error
if !forEmpty {
proposerSig = proposal.Block.Block.Header.SigData[0]
blkHash = proposal.Block.Block.Hash()
} else {
if proposal.Block.EmptyBlock == nil {
return nil, fmt.Errorf("blk %d proposal from %d has no empty proposal",
proposal.GetBlockNum(), proposal.Block.getProposer())
}
proposerSig = proposal.Block.EmptyBlock.Header.SigData[0]
blkHash = proposal.Block.EmptyBlock.Hash()
}
endorserSig, err = signature.Sign(self.account, blkHash[:])
if err != nil {
return nil, fmt.Errorf("endorser failed to sign block. hash:%x, err: %s", blkHash, err)
}
msg := &blockEndorseMsg{
Endorser: self.Index,
EndorsedProposer: proposal.Block.getProposer(),
BlockNum: proposal.Block.getBlockNum(),
EndorsedBlockHash: blkHash,
EndorseForEmpty: forEmpty,
ProposerSig: proposerSig,
EndorserSig: endorserSig,
}
return msg, nil
}
func (self *Server) constructCommitMsg(proposal *blockProposalMsg, endorses []*blockEndorseMsg, forEmpty bool) (*blockCommitMsg, error) {
// TODO, support faultyMsg reporting
var proposerSig, committerSig []byte
var blkHash common.Uint256
var err error
if !forEmpty {
proposerSig = proposal.Block.Block.Header.SigData[0]
blkHash = proposal.Block.Block.Hash()
} else {
if proposal.Block.EmptyBlock == nil {
return nil, fmt.Errorf("blk %d proposal from %d has no empty proposal",
proposal.GetBlockNum(), proposal.Block.getProposer())
}
proposerSig = proposal.Block.EmptyBlock.Header.SigData[0]
blkHash = proposal.Block.EmptyBlock.Hash()
}
committerSig, err = signature.Sign(self.account, blkHash[:])
if err != nil {
return nil, fmt.Errorf("endorser failed to sign block. hash:%x, caused by: %s", blkHash, err)
}
endorsersSig := make(map[uint32][]byte)
for _, e := range endorses {
endorsersSig[e.Endorser] = e.EndorserSig
}
msg := &blockCommitMsg{
Committer: self.Index,
BlockProposer: proposal.Block.getProposer(),
BlockNum: proposal.Block.getBlockNum(),
CommitBlockHash: blkHash,
CommitForEmpty: forEmpty,
ProposerSig: proposerSig,
EndorsersSig: endorsersSig,
CommitterSig: committerSig,
}
return msg, nil
}
func (self *Server) constructBlockFetchMsg(blkNum uint32) (*blockFetchMsg, error) {
msg := &blockFetchMsg{
BlockNum: blkNum,
}
return msg, nil
}
func (self *Server) constructBlockFetchRespMsg(blkNum uint32, blk *Block, blkHash common.Uint256) (*BlockFetchRespMsg, error) {
msg := &BlockFetchRespMsg{
BlockNumber: blkNum,
BlockHash: blkHash,
BlockData: blk,
}
return msg, nil
}
func (self *Server) constructBlockInfoFetchMsg(startBlkNum uint32) (*BlockInfoFetchMsg, error) {
msg := &BlockInfoFetchMsg{
StartBlockNum: startBlkNum,
}
return msg, nil
}
func (self *Server) constructBlockInfoFetchRespMsg(blockInfos []*BlockInfo_) (*BlockInfoFetchRespMsg, error) {
msg := &BlockInfoFetchRespMsg{
Blocks: blockInfos,
}
return msg, nil
}
func (self *Server) constructProposalFetchMsg(blkNum uint32, proposer uint32) (*proposalFetchMsg, error) {
msg := &proposalFetchMsg{
ProposerID: proposer,
BlockNum: blkNum,
}
return msg, nil
}