-
Notifications
You must be signed in to change notification settings - Fork 0
/
joining.go
497 lines (398 loc) · 12.8 KB
/
joining.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package isaacstates
import (
"context"
"sync"
"time"
"github.com/ProtoconNet/mitum2/base"
"github.com/ProtoconNet/mitum2/isaac"
"github.com/ProtoconNet/mitum2/storage"
"github.com/ProtoconNet/mitum2/util"
"github.com/pkg/errors"
)
type JoiningHandlerArgs struct {
*baseBallotHandlerArgs
LastManifestFunc func() (base.Manifest, bool, error)
JoinMemberlistFunc func(context.Context, base.Suffrage) error
LeaveMemberlistFunc func(time.Duration) error
WaitFirstVoteproof time.Duration
}
func NewJoiningHandlerArgs(params *isaac.LocalParams) *JoiningHandlerArgs {
return &JoiningHandlerArgs{
baseBallotHandlerArgs: newBaseBallotHandlerArgs(),
LastManifestFunc: func() (base.Manifest, bool, error) {
return nil, false, util.ErrNotImplemented.Errorf("LastManifestFunc")
},
JoinMemberlistFunc: func(context.Context, base.Suffrage) error {
return util.ErrNotImplemented.Errorf("JoinMemberlistFunc")
},
LeaveMemberlistFunc: func(time.Duration) error {
return util.ErrNotImplemented.Errorf("LeaveMemberlistFunc")
},
WaitFirstVoteproof: params.IntervalBroadcastBallot()*2 + params.WaitPreparingINITBallot(),
}
}
type JoiningHandler struct {
*baseBallotHandler
args *JoiningHandlerArgs
waitFirstVoteproof time.Duration
newvoteproofLock sync.Mutex
}
type NewJoiningHandlerType struct {
*JoiningHandler
}
func NewNewJoiningHandlerType(
local base.LocalNode,
params *isaac.LocalParams,
args *JoiningHandlerArgs,
) *NewJoiningHandlerType {
baseBallotHandler := newBaseBallotHandler(StateJoining, local, params, args.baseBallotHandlerArgs)
return &NewJoiningHandlerType{
JoiningHandler: &JoiningHandler{
baseBallotHandler: baseBallotHandler,
args: args,
waitFirstVoteproof: args.WaitFirstVoteproof,
},
}
}
func (h *NewJoiningHandlerType) new() (handler, error) {
return &JoiningHandler{
baseBallotHandler: h.baseBallotHandler.new(),
args: h.args,
waitFirstVoteproof: h.waitFirstVoteproof,
}, nil
}
func (st *JoiningHandler) enter(from StateType, i switchContext) (func(), error) {
e := util.StringErrorFunc("failed to enter joining state")
deferred, err := st.baseBallotHandler.enter(from, i)
if err != nil {
return nil, e(err, "")
}
jctx, ok := i.(joiningSwitchContext)
if !ok {
return nil, e(nil, "invalid stateSwitchContext, not for joining state; %T", i)
}
vp := jctx.vp
lvp := st.lastVoteproofs().Cap()
switch {
case lvp == nil:
case vp == nil:
vp = lvp
default:
if lvp.Point().Point.Compare(vp.Point().Point) > 0 {
vp = lvp
}
}
var manifest base.Manifest
switch m, found, err := st.args.LastManifestFunc(); {
case err != nil:
return nil, e(err, "")
case !found:
return nil, e(nil, "last manifest not found")
default:
manifest = m
}
switch suf, err := st.checkSuffrage(manifest.Height() + 1); {
case err != nil:
return nil, e(err, "")
case suf.Exists(st.local.Address()) && suf.Len() < 2: //nolint:gomnd // local is alone in suffrage node
st.Log().Debug().Msg("local alone in consensus nodes; will not wait new voteproof")
st.waitFirstVoteproof = 0
default:
switch jerr := st.joinMemberlist(suf); {
case jerr != nil:
st.Log().Error().Err(jerr).Msg("failed to join memberlist")
default:
st.Log().Debug().Msg("joined to memberlist")
}
}
return func() {
deferred()
if err := st.timers.StopTimersAll(); err != nil {
st.Log().Error().Err(err).Msg("failed to stop all timers")
}
go st.firstVoteproof(vp, manifest)
}, nil
}
func (st *JoiningHandler) exit(sctx switchContext) (func(), error) {
e := util.StringErrorFunc("failed to exit from joining state")
deferred, err := st.baseBallotHandler.exit(sctx)
if err != nil {
return nil, e(err, "")
}
return deferred, nil
}
func (st *JoiningHandler) newVoteproof(vp base.Voteproof) error {
switch _, _, isnew := st.baseBallotHandler.setNewVoteproof(vp); {
case isnew:
if st.resolver != nil {
st.resolver.Cancel(vp.Point())
}
var sctx switchContext
switch err := st.handleNewVoteproof(vp); {
case err == nil:
return nil
case errors.As(err, &sctx):
if sctx.next() == StateConsensus {
if _, err = st.checkSuffrage(vp.Point().Height()); err != nil {
return err
}
}
return sctx
default:
return err
}
default:
return nil
}
}
func (st *JoiningHandler) handleNewVoteproof(vp base.Voteproof) error {
st.newvoteproofLock.Lock()
defer st.newvoteproofLock.Unlock()
e := util.StringErrorFunc("failed to handle new voteproof")
l := st.Log().With().Dict("voteproof", base.VoteproofLog(vp)).Logger()
var manifest base.Manifest
switch i, found, err := st.args.LastManifestFunc(); {
case err != nil:
err = e(err, "failed to get last manifest")
l.Error().Err(err).Msg("moves to syncing state")
return newBrokenSwitchContext(StateJoining, err)
case !found:
l.Debug().Msg("empty last manifest; moves to syncing state")
height := vp.Point().Height()
if vp.Point().Stage() == base.StageINIT {
height = vp.Point().Height() - 1
}
return newSyncingSwitchContext(StateJoining, height)
default:
manifest = i
st.Log().Debug().Interface("last_manifest", manifest).Msg("new valid voteproof")
}
switch keep, err := st.checkStuckVoteproof(vp, manifest); {
case err != nil:
return err
case !keep:
return nil
}
switch vp.Point().Stage() {
case base.StageINIT:
return st.newINITVoteproof(vp.(base.INITVoteproof), manifest) //nolint:forcetypeassert //...
case base.StageACCEPT:
return st.newACCEPTVoteproof(vp.(base.ACCEPTVoteproof), manifest) //nolint:forcetypeassert //...
default:
return e(nil, "invalid voteproof received, %T", vp)
}
}
func (st *JoiningHandler) newINITVoteproof(ivp base.INITVoteproof, manifest base.Manifest) error {
l := st.Log().With().Dict("voteproof", base.VoteproofLog(ivp)).Logger()
var prevblock util.Hash
if ivp.Majority() != nil {
prevblock = ivp.Majority().(isaac.INITBallotFact).PreviousBlock() //nolint:forcetypeassert //...
}
switch expectedheight := manifest.Height() + 1; {
case ivp.Point().Height() < expectedheight: // NOTE lower height; ignore
return nil
case ivp.Point().Height() > expectedheight:
l.Debug().Msg("new init voteproof found; moves to syncing")
return newSyncingSwitchContext(StateJoining, ivp.Point().Height()-1)
case prevblock != nil && !prevblock.Equal(manifest.Hash()):
l.Debug().Msg("previous block of init voteproof does tno match with last manifest; moves to syncing state")
return newSyncingSwitchContext(StateJoining, ivp.Point().Height()-1)
default:
l.Debug().Msg("found valid init voteproof; moves to consensus state")
sctx, err := newConsensusSwitchContext(StateJoining, ivp)
if err != nil {
return err
}
return sctx
}
}
func (st *JoiningHandler) newACCEPTVoteproof(avp base.ACCEPTVoteproof, manifest base.Manifest) error {
l := st.Log().With().Dict("voteproof", base.VoteproofLog(avp)).Logger()
switch lastheight := manifest.Height(); {
case avp.Point().Height() < lastheight+1: // NOTE lower height; ignore
return nil
case avp.Point().Height() > lastheight+1,
avp.Point().Height() == lastheight+1 && avp.Result() == base.VoteResultMajority:
l.Debug().Msg("new accept voteproof found; moves to syncing")
height := avp.Point().Height()
if avp.Result() != base.VoteResultMajority {
height = avp.Point().Height() - 1
}
return newSyncingSwitchContext(StateJoining, height)
default:
l.Debug().Msg("found valid accept voteproof; moves to consensus state")
sctx, err := newConsensusSwitchContext(StateJoining, avp)
if err != nil {
return err
}
return sctx
}
}
func (st *JoiningHandler) checkSuffrage(height base.Height) (base.Suffrage, error) {
suf, found, err := st.args.NodeInConsensusNodesFunc(st.local, height)
switch {
case err != nil:
case !found:
if lerr := st.args.LeaveMemberlistFunc(time.Second); lerr != nil {
st.Log().Error().Err(lerr).Msg("failed to leave memberilst; ignored")
}
st.Log().Debug().Msg("local not in consensus nodes; moves to syncing")
return nil, newSyncingSwitchContext(StateJoining, height)
case suf == nil:
return nil, newBrokenSwitchContext(StateJoining, errors.Errorf("empty suffrage"))
}
switch {
case errors.Is(err, storage.ErrNotFound):
st.Log().Debug().Interface("height", height+1).Msg("suffrage not found; moves to syncing")
return nil, newSyncingSwitchContext(StateJoining, height)
case err != nil:
return nil, err
default:
return suf, nil
}
}
// firstVoteproof handles the voteproof, which is received before joining
// handler. It will help to prevent voting stuck. It waits for given
// time, if no incoming voteproof, process last voteproof.
func (st *JoiningHandler) firstVoteproof(lvp base.Voteproof, manifest base.Manifest) {
if lvp == nil {
return
}
st.Log().Debug().Dur("wait", st.waitFirstVoteproof).Msg("will wait new voteproof")
select {
case <-st.ctx.Done():
return
case <-time.After(st.waitFirstVoteproof):
}
switch nlvp := st.lastVoteproofs().Cap(); {
case nlvp == nil:
case nlvp.Point().Compare(lvp.Point()) > 0:
return
}
st.Log().Debug().Msg("last voteproof found for firstVoteproof")
// NOTE if no new voteproof and last accept voteproof looks good, broadcast
// next init ballot
switch avp, ok := lvp.(base.ACCEPTVoteproof); {
case !ok:
case avp.Result() != base.VoteResultMajority:
case avp.Point().Height() != manifest.Height():
default:
st.Log().Debug().Msg("no more new voteproof; prepare next block")
go st.nextBlock(avp)
return
}
var dsctx switchContext
switch err := st.handleNewVoteproof(lvp); {
case err == nil:
case !errors.As(err, &dsctx):
st.Log().Error().Err(err).Dict("voteproof", base.VoteproofLog(lvp)).
Msg("failed last voteproof after enter; ignore")
default:
go st.switchState(dsctx)
}
}
func (st *JoiningHandler) nextBlock(avp base.ACCEPTVoteproof) {
point := avp.Point().Point.NextHeight()
l := st.Log().With().Dict("voteproof", base.VoteproofLog(avp)).Object("point", point).Logger()
var sctx switchContext
var bl base.INITBallot
switch i, err := st.makeNextBlockBallot(avp, st.args.NodeInConsensusNodesFunc); {
case err == nil:
if i == nil {
return
}
bl = i
case errors.As(err, &sctx):
go st.switchState(sctx)
return
default:
l.Debug().Err(err).Msg("failed to prepare next block; moves to broken state")
go st.switchState(newBrokenSwitchContext(StateJoining, err))
return
}
switch _, err := st.vote(bl); {
case err == nil:
case errors.Is(err, errFailedToVoteNotInConsensus):
l.Error().Err(err).Msg("failed to vote init ballot for next round; moves to syncing state")
go st.switchState(newSyncingSwitchContext(StateJoining, avp.Point().Height()-1))
return
default:
l.Error().Err(err).Msg("failed to vote init ballot for next block; moves to broken")
go st.switchState(newBrokenSwitchContext(StateJoining, err))
return
}
if err := st.broadcastINITBallot(
bl,
func(i int, _ time.Duration) time.Duration {
if i < 1 {
return time.Nanosecond
}
return st.params.IntervalBroadcastBallot()
},
); err != nil {
l.Error().Err(err).Msg("failed to broadcast init ballot for next block")
return
}
if err := st.timers.StartTimers([]util.TimerID{
timerIDBroadcastINITBallot,
timerIDBroadcastACCEPTBallot,
}, true); err != nil {
l.Error().Err(err).Msg("failed to start timers for broadcasting init ballot for next block")
return
}
l.Debug().Interface("ballot", bl).Msg("next init ballot broadcasted")
}
func (st *JoiningHandler) joinMemberlist(suf base.Suffrage) error {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-st.ctx.Done():
return st.ctx.Err()
case <-ticker.C:
switch err := st.args.JoinMemberlistFunc(st.ctx, suf); {
case err == nil:
return nil
case errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled):
return nil
}
}
}
}
func (st *JoiningHandler) checkStuckVoteproof(
vp base.Voteproof,
lastManifest base.Manifest,
) (bool, error) {
if _, ok := vp.(base.StuckVoteproof); !ok {
return true, nil
}
l := st.Log().With().
Dict("init_voteproof", base.VoteproofLog(vp)).
Interface("last_manifest", lastManifest).
Logger()
lastHeight := lastManifest.Height()
switch {
case vp.Point().Height() == lastHeight+1:
l.Debug().Msg("found valid stuck voteproof; moves to consensus state")
sctx, err := newConsensusSwitchContext(StateJoining, vp)
if err != nil {
return false, err
}
return false, sctx
case vp.Point().Height() > lastHeight+1:
l.Debug().Msg("higher init stuck voteproof; moves to syncing state")
return false, newSyncingSwitchContext(StateConsensus, vp.Point().Height()-1)
default:
return false, nil
}
}
type joiningSwitchContext struct {
vp base.Voteproof
baseSwitchContext
}
func newJoiningSwitchContext(from StateType, vp base.Voteproof) joiningSwitchContext {
return joiningSwitchContext{
baseSwitchContext: newBaseSwitchContext(StateJoining, switchContextOKFuncCheckFrom(from)),
vp: vp,
}
}