forked from 0xPolygon/pbft-consensus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstate.go
363 lines (294 loc) · 7.73 KB
/
state.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
package pbft
import (
"bytes"
"fmt"
"sync/atomic"
"time"
)
type MsgType int32
const (
MessageReq_RoundChange MsgType = 0
MessageReq_Preprepare MsgType = 1
MessageReq_Commit MsgType = 2
MessageReq_Prepare MsgType = 3
)
func (m MsgType) String() string {
switch m {
case MessageReq_RoundChange:
return "RoundChange"
case MessageReq_Preprepare:
return "Preprepare"
case MessageReq_Commit:
return "Commit"
case MessageReq_Prepare:
return "Prepare"
default:
panic(fmt.Sprintf("BUG: Bad msgtype %d", m))
}
}
type MessageReq struct {
// type is the type of the message
Type MsgType
// from is the address of the sender
From NodeID
// seal is the committed seal for the proposal (only for commit messages)
Seal []byte
// view is the view assigned to the message
View *View
// hash of the proposal
Hash []byte
// proposal is the arbitrary data proposal (only for preprepare messages)
Proposal []byte
}
func (m *MessageReq) Validate() error {
// Hash field has to exist for state != RoundStateChange
if m.Type != MessageReq_RoundChange {
if m.Hash == nil {
return fmt.Errorf("hash is empty for type %s", m.Type.String())
}
}
// TODO
return nil
}
func (m *MessageReq) SetProposal(proposal []byte) {
m.Proposal = append([]byte{}, proposal...)
}
func (m *MessageReq) Copy() *MessageReq {
mm := new(MessageReq)
*mm = *m
if m.View != nil {
mm.View = m.View.Copy()
}
if m.Proposal != nil {
mm.SetProposal(m.Proposal)
}
if m.Seal != nil {
mm.Seal = append([]byte{}, m.Seal...)
}
return mm
}
type View struct {
// round is the current round/height being finalized
Round uint64
// Sequence is a sequence number inside the round
Sequence uint64
}
func (v *View) Copy() *View {
vv := new(View)
*vv = *v
return vv
}
func (v *View) String() string {
return fmt.Sprintf("(Sequence=%d, Round=%d)", v.Sequence, v.Round)
}
func ViewMsg(sequence, round uint64) *View {
return &View{
Round: round,
Sequence: sequence,
}
}
type NodeID string
type PbftState uint32
// Define the states in PBFT
const (
AcceptState PbftState = iota
RoundChangeState
ValidateState
CommitState
SyncState
DoneState
)
// String returns the string representation of the passed in state
func (i PbftState) String() string {
switch i {
case AcceptState:
return "AcceptState"
case RoundChangeState:
return "RoundChangeState"
case ValidateState:
return "ValidateState"
case CommitState:
return "CommitState"
case SyncState:
return "SyncState"
case DoneState:
return "DoneState"
}
panic(fmt.Sprintf("BUG: Pbft state not found %d", i))
}
type Proposal struct {
// Data is an arbitrary set of data to approve in consensus
Data []byte
// Time is the time to create the proposal
Time time.Time
// Hash is the digest of the data to seal
Hash []byte
}
// Equal compares whether two proposals have the same hash
func (p *Proposal) Equal(pp *Proposal) bool {
return bytes.Equal(p.Hash, pp.Hash)
}
// Copy makes a copy of the Proposal
func (p *Proposal) Copy() *Proposal {
pp := new(Proposal)
*pp = *p
pp.Data = append([]byte{}, p.Data...)
pp.Hash = append([]byte{}, p.Hash...)
return pp
}
// currentState defines the current state object in PBFT
type currentState struct {
// validators represent the current validator set
validators ValidatorSet
// state is the current state
state uint64
// proposal stores information about the height proposal
proposal *Proposal
// The selected proposer
proposer NodeID
// Current view
view *View
// List of prepared messages
prepared map[NodeID]*MessageReq
// List of committed messages
committed map[NodeID]*MessageReq
// List of round change messages
roundMessages map[uint64]map[NodeID]*MessageReq
// Locked signals whether the proposal is locked
locked bool
// Describes whether there has been an error during the computation
err error
}
// newState creates a new state with reset round messages
func newState() *currentState {
c := ¤tState{}
c.resetRoundMsgs()
return c
}
func (c *currentState) GetSequence() uint64 {
return c.view.Sequence
}
func (c *currentState) getCommittedSeals() [][]byte {
committedSeals := [][]byte{}
for _, commit := range c.committed {
committedSeals = append(committedSeals, commit.Seal)
}
return committedSeals
}
// getState returns the current state
func (c *currentState) getState() PbftState {
stateAddr := (*uint64)(&c.state)
return PbftState(atomic.LoadUint64(stateAddr))
}
// setState sets the current state
func (c *currentState) setState(s PbftState) {
stateAddr := (*uint64)(&c.state)
atomic.StoreUint64(stateAddr, uint64(s))
}
// MaxFaultyNodes returns the maximum number of allowed faulty nodes (F), based on the current validator set size
func (c *currentState) MaxFaultyNodes() int {
return MaxFaultyNodes(c.validators.Len())
}
// NumValid returns the number of required messages
func (c *currentState) NumValid() int {
// 2 * F + 1
// + 1 is up to the caller to add
// the current node tallying the messages will include its own message
return QuorumSize(c.validators.Len()) - 1
}
// getErr returns the current error, if any, and consumes it
func (c *currentState) getErr() error {
err := c.err
c.err = nil
return err
}
func (c *currentState) maxRound() (maxRound uint64, found bool) {
num := c.MaxFaultyNodes() + 1
for currentRound, messages := range c.roundMessages {
if len(messages) < num {
continue
}
if maxRound < currentRound {
maxRound = currentRound
found = true
}
}
return
}
// resetRoundMsgs resets the prepared, committed and round messages in the current state
func (c *currentState) resetRoundMsgs() {
c.prepared = map[NodeID]*MessageReq{}
c.committed = map[NodeID]*MessageReq{}
c.roundMessages = map[uint64]map[NodeID]*MessageReq{}
}
// CalcProposer calculates the proposer and sets it to the state
func (c *currentState) CalcProposer() {
c.proposer = c.validators.CalcProposer(c.view.Round)
}
func (c *currentState) lock() {
c.locked = true
}
func (c *currentState) unlock() {
c.proposal = nil
c.locked = false
}
// cleanRound deletes the specific round messages
func (c *currentState) cleanRound(round uint64) {
delete(c.roundMessages, round)
}
// AddRoundMessage adds a message to the round, and returns the round message size
func (c *currentState) AddRoundMessage(msg *MessageReq) int {
if msg.Type != MessageReq_RoundChange {
return 0
}
c.addMessage(msg)
return len(c.roundMessages[msg.View.Round])
}
// addPrepared adds a prepared message
func (c *currentState) addPrepared(msg *MessageReq) {
if msg.Type != MessageReq_Prepare {
return
}
c.addMessage(msg)
}
// addCommitted adds a committed message
func (c *currentState) addCommitted(msg *MessageReq) {
if msg.Type != MessageReq_Commit {
return
}
c.addMessage(msg)
}
// addMessage adds a new message to one of the following message lists: committed, prepared, roundMessages
func (c *currentState) addMessage(msg *MessageReq) {
addr := NodeID(msg.From)
if !c.validators.Includes(addr) {
// only include messages from validators
return
}
if msg.Type == MessageReq_Commit {
c.committed[addr] = msg
} else if msg.Type == MessageReq_Prepare {
c.prepared[addr] = msg
} else if msg.Type == MessageReq_RoundChange {
view := msg.View
roundMessages, exists := c.roundMessages[view.Round]
if !exists {
roundMessages = map[NodeID]*MessageReq{}
c.roundMessages[view.Round] = roundMessages
}
roundMessages[addr] = msg
}
}
// numPrepared returns the number of messages in the prepared message list
func (c *currentState) numPrepared() int {
return len(c.prepared)
}
// numCommitted returns the number of messages in the committed message list
func (c *currentState) numCommitted() int {
return len(c.committed)
}
type ValidatorSet interface {
CalcProposer(round uint64) NodeID
Includes(id NodeID) bool
Len() int
}