-
Notifications
You must be signed in to change notification settings - Fork 1
/
bihs.go
213 lines (177 loc) · 4.62 KB
/
bihs.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
package bihs
import (
"context"
"fmt"
"io/ioutil"
"os"
"sync"
"sync/atomic"
"time"
"github.com/ontio/ontology/common"
"github.com/zhiqiangxu/util"
"github.com/zhiqiangxu/util/wm"
)
// HotStuff ...
type HotStuff struct {
ConsensusState
status int32
proposeCh chan Block
closeCh chan struct{}
heightChangeCh chan struct{}
p2p P2P
store StateDB
conf Config
relayTimer *time.Timer
nvInterrupt *time.Timer
waiter *wm.Offset
wg sync.WaitGroup
waitBlock func(ID, *Msg)
lastBlockTime uint64
createMsg func(mt MsgType, justify *QC, node *BlockOrHash) *Msg
sign func([]byte) []byte
tcombine func(msg *Msg, votes map[int][]byte) []byte
validateQC func(qc *QC) error
verify func(msg *Msg) (voter ID, err error)
generateBitmap func(votes map[int][]byte) []byte
}
func New(store StateDB, p2p P2P, conf Config) *HotStuff {
err := conf.validate()
if err != nil {
panic(fmt.Sprintf("Config.Validate failed:%v", err))
}
hs := &HotStuff{
proposeCh: make(chan Block),
closeCh: make(chan struct{}),
heightChangeCh: make(chan struct{}, 1),
p2p: p2p,
store: store,
conf: conf,
waiter: wm.NewOffset(),
}
if conf.BlsSigner != nil {
hs.sign = hs.signBls
hs.tcombine = hs.tcombineBls
hs.validateQC = hs.validateQCBls
hs.verify = hs.verifyBls
hs.createMsg = hs.createMsgBls
hs.generateBitmap = hs.generateBitmapBls
} else {
hs.sign = hs.signEc
hs.tcombine = hs.tcombineEc
hs.validateQC = hs.validateQCEc
hs.verify = hs.verifyEc
hs.createMsg = hs.createMsgEc
hs.generateBitmap = hs.generateBitmapEc
}
return hs
}
func (hs *HotStuff) Start() (err error) {
swapped := atomic.CompareAndSwapInt32(&hs.status, 0, 1)
if !swapped {
err = fmt.Errorf("already started")
return
}
hs.store.SubscribeHeightChange(hs)
err = hs.initConsensusState()
if err != nil {
return
}
hs.enterHeightView(hs.height, hs.view)
util.GoFunc(&hs.wg, hs.loop)
return
}
const consensusFile = "/consensus.dat"
func (hs *HotStuff) initConsensusState() (err error) {
fullPath := hs.conf.DataDir + consensusFile
if _, err = os.Stat(fullPath); os.IsNotExist(err) {
err = nil
hs.advanceToHeight(hs.store.Height()+1, hs)
hs.conf.Logger.Infof("initConsensusState height=%d view=0", hs.store.Height()+1)
return
}
data, err := ioutil.ReadFile(fullPath)
if err != nil {
hs.conf.Logger.Error("initConsensusState failed:%v", err)
return
}
cs := ConsensusState{}
err = cs.Deserialize(common.NewZeroCopySource(data))
if err != nil {
hs.conf.Logger.Error("initConsensusState cs.Deserialize failed:%v", err)
return
}
if cs.height > hs.store.Height()+1 {
err = fmt.Errorf("inconsistent state found")
return
}
if cs.height < hs.store.Height()+1 {
hs.advanceToHeight(hs.store.Height()+1, hs)
hs.conf.Logger.Infof("initConsensusState height=%d view=0", hs.store.Height()+1)
return
}
hs.ConsensusState = cs
hs.conf.Logger.Infof("initConsensusState height=%d view=%d", hs.height, hs.view)
return
}
func (hs *HotStuff) restoreConsensusState() {
cs := hs.ConsensusState
sink := common.NewZeroCopySink(nil)
cs.Serialize(sink)
csBytes := sink.Bytes()
util.TryUntilSuccess(func() bool {
err := ioutil.WriteFile(hs.conf.DataDir+consensusFile, csBytes, 0777)
if err != nil {
hs.conf.Logger.Error("restoreConsensusState failed:%v", err)
return false
}
hs.conf.Logger.Infof("consensus state stored at %s #len %d", hs.conf.DataDir+consensusFile, len(csBytes))
return true
}, time.Second)
}
func (hs *HotStuff) Stop() (err error) {
swapped := atomic.CompareAndSwapInt32(&hs.status, 1, 2)
if !swapped {
status := atomic.LoadInt32(&hs.status)
switch status {
case 2:
err = fmt.Errorf("already stopped")
case 0:
err = fmt.Errorf("not started")
default:
err = fmt.Errorf("unknown error")
}
return
}
close(hs.closeCh)
hs.store.UnSubscribeHeightChange(hs)
hs.wg.Wait()
return
}
func (hs *HotStuff) Propose(ctx context.Context, blk Block) (err error) {
err = hs.store.Validate(blk)
if err != nil {
return
}
height := blk.Height()
if height <= hs.store.Height() {
err = fmt.Errorf("block for specified height already exists")
return
}
go func() {
select {
case hs.proposeCh <- blk:
case <-ctx.Done():
case <-hs.closeCh:
}
}()
return
}
func (hs *HotStuff) Wait(ctx context.Context, height uint64) error {
return hs.waiter.Wait(ctx, int64(height))
}
func (hs *HotStuff) ConsensusHeight() uint64 {
return atomic.LoadUint64(&hs.height)
}
func (hs *HotStuff) ConsensusView() uint64 {
return atomic.LoadUint64(&hs.view)
}