/
dpos.go
329 lines (300 loc) · 9.57 KB
/
dpos.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
package dpos
import (
"errors"
"fmt"
"github.com/Futuremine-chain/future/common/blockchain"
"github.com/Futuremine-chain/future/common/config"
"github.com/Futuremine-chain/future/common/dpos"
"github.com/Futuremine-chain/future/common/param"
"github.com/Futuremine-chain/future/future/common/kit/message"
fmctypes "github.com/Futuremine-chain/future/future/types"
"github.com/Futuremine-chain/future/tools/arry"
"github.com/Futuremine-chain/future/tools/utils"
"github.com/Futuremine-chain/future/types"
)
type DPos struct {
cycle *Cycle
confirmed uint64
}
func NewDPos(dPosStatus dpos.IDPosStatus) *DPos {
return &DPos{cycle: &Cycle{DPosStatus: dPosStatus}}
}
func (d *DPos) GenesisBlock() types.IBlock {
block := &fmctypes.Block{
Header: fmctypes.NewHeader(arry.Hash{},
arry.Hash{},
arry.Hash{},
arry.Hash{},
arry.Hash{},
0,
config.Param.GenesisTime,
arry.Address{},
),
Body: &fmctypes.Body{Messages: make([]types.IMessage, 0)},
}
for _, super := range genesisSuperList.Members {
var peerId fmctypes.Peer
copy(peerId[:], super.PeerId)
msg := &fmctypes.Message{
Header: &fmctypes.MsgHeader{
Type: fmctypes.Candidate,
Nonce: 1,
From: super.Signer,
Time: config.Param.GenesisTime,
Signature: &fmctypes.Signature{},
},
Body: &fmctypes.CandidateBody{Peer: peerId},
}
msg.SetHash()
block.Body.Messages = append(block.Body.Messages, msg)
}
for _, e := range param.PreCirculations {
tx := message.NewTransaction("", e.Address, config.Param.MainToken.String(), e.Amount, 0, 0, config.Param.GenesisTime)
block.Body.Messages = append(block.Body.Messages, tx)
}
block.SetHash()
return block
}
func (d *DPos) CheckTime(header types.IHeader, chain blockchain.IChain) error {
preHeader, err := chain.GetBlockHash(header.GetPreHash())
if err != nil {
return err
}
if err := d.cycle.CheckCycle(chain, preHeader.GetTime(), header.GetTime()); err != Err_Elected {
if err := d.cycle.Elect(header.GetTime(), preHeader.GetHash(), chain); err != nil {
return err
}
}
// Check if the time of block production is correct
if err := d.checkTime(preHeader, header); err != nil {
return err
}
return nil
}
func (d *DPos) CheckSigner(header types.IHeader, chain blockchain.IChain) error {
// Find the block address at that time
super, err := d.lookupSuper(header.GetTime())
if err != nil {
return err
}
if !super.IsEqual(header.GetSigner()) {
return errors.New("it's not the miner's turn")
}
return nil
}
func (d *DPos) CheckHeader(header types.IHeader, parent types.IHeader, chain blockchain.IChain) error {
// If the block time is in the future, it will fail
if header.GetTime() > uint64(utils.NowUnix()) {
return errors.New("block in the future")
}
// Verify whether it is the time point of block generation
if err := d.checkTime(parent, header); err != nil {
return errors.New("time check failed")
}
if header.GetSignature() == nil {
return errors.New("no signature")
}
if parent.GetTime()+param.BlockInterval > header.GetTime() {
return errors.New("invalid timestamp")
}
return nil
}
func (d *DPos) CheckSeal(header types.IHeader, parent types.IHeader, chain blockchain.IChain) error {
// Verifying the genesis block is not supported
if header.GetHeight() == 0 {
return errors.New("unknown block")
}
if header.GetHeight() <= d.confirmed {
return errors.New("height error")
}
lastCycleHeader, err := d.preCycleLastHash(header, chain)
if err != nil {
return err
}
// Verify the block node
if err := d.CheckCreator(header, lastCycleHeader, chain); err != nil {
return err
}
// Update the height of the confirmed block
return d.updateConfirmed(chain)
}
func (d *DPos) CheckCreator(header types.IHeader, parent types.IHeader, chain blockchain.IChain) error {
signer, err := d.setAndLookupSuper(header.GetTime(), parent, chain)
if err != nil {
return err
}
if err := d.checkSigner(signer, header); err != nil {
return err
}
return nil
}
func (d *DPos) SuperIds() []string {
return nil
}
func (d *DPos) Confirmed() uint64 {
if d.confirmed == 0 {
d.confirmed, _ = d.cycle.DPosStatus.Confirmed()
}
return d.confirmed
}
func (d *DPos) SetConfirmed(confirmed uint64) {
d.confirmed = confirmed
d.cycle.DPosStatus.SetConfirmed(confirmed)
}
func (d *DPos) checkTime(lastHeader types.IHeader, header types.IHeader) error {
nextTime := nextTime(header.GetTime())
if lastHeader.GetTime() >= nextTime {
return errors.New("create the future block")
}
if nextTime-header.GetTime() >= 1 {
return fmt.Errorf("wait for last block arrived, next slot = %d, block time = %d ", nextTime, header.GetTime)
}
if header.GetTime() == nextTime {
return nil
}
return fmt.Errorf("wait for last block arrived, next slot = %d, block time = %d ", nextTime, header.GetTime)
}
func (d *DPos) lookupSuper(now uint64) (arry.Address, error) {
offset := now % param.CycleInterval
if offset%param.BlockInterval != 0 {
return arry.Address{}, errors.New("invalid time to mint the block")
}
offset /= param.BlockInterval
supers, err := d.cycle.DPosStatus.CycleSupers(now / param.CycleInterval)
if err != nil {
return arry.Address{}, err
}
if supers.Len() == 0 {
return arry.Address{}, errors.New("no super to be found in storage")
}
offset %= uint64(supers.Len())
candidate := supers.Get(int(offset))
return candidate.GetSinger(), nil
}
func (d *DPos) setAndLookupSuper(now uint64, parent types.IHeader, chain blockchain.IChain) (arry.Address, error) {
offset := now % param.CycleInterval
if offset%param.BlockInterval != 0 {
return arry.Address{}, errors.New("invalid time to mint the block")
}
offset /= param.BlockInterval
supers, err := d.setSupers(now, parent, chain)
if err != nil {
return arry.Address{}, err
}
if supers.Len() == 0 {
return arry.Address{}, errors.New("no winner to be found in storage")
}
offset %= uint64(supers.Len())
super := supers.Get(int(offset))
return super.GetSinger(), nil
}
func (d *DPos) setSupers(time uint64, parent types.IHeader, chain blockchain.IChain) (types.ICandidates, error) {
cycle := time / param.CycleInterval
supers, err := d.cycle.DPosStatus.CycleSupers(cycle)
// If the election result of the current cycle does not
// exist, the current cycle of elections is conducted
if err != nil || supers == nil || !parent.GetHash().IsEqual(supers.GetPreHash()) {
if err := d.cycle.Elect(time, parent.GetHash(), chain); err != nil {
return nil, err
}
if supers, err = d.cycle.DPosStatus.CycleSupers(cycle); err != nil {
return nil, err
}
}
return supers, nil
}
// Get the hash of the last block of the previous cycle
// as the random number seed of the new cycle.
func (d *DPos) preCycleLastHash(current types.IHeader, chain blockchain.IChain) (types.IHeader, error) {
preTermLastHash, err := chain.CycleLastHash(current.GetCycle() - 1)
if err == nil {
header, _ := chain.GetBlockHash(preTermLastHash)
tHeader, _ := chain.GetHeaderHeight(header.GetHeight())
if header.GetHeight() < current.GetHeight() && header.GetHash().IsEqual(tHeader.GetHash()) {
return header, nil
}
}
// If the last block header of the last cycle cannot be obtained directly
// from the chain, then look forward from the current block
genesis, err := chain.GetHeaderHeight(0)
if err != nil {
return nil, err
}
header, err := chain.GetHeaderHeight(1)
if err != nil {
return genesis, nil
}
if header.GetCycle() >= current.GetCycle() {
return genesis, nil
}
height := current.GetHeight()
for height > 0 {
height--
header, err := chain.GetHeaderHeight(height)
if err != nil {
continue
}
if header.GetCycle() < current.GetCycle() {
return header, nil
}
}
return nil, errors.New("not found")
}
func (d *DPos) checkSigner(super arry.Address, header types.IHeader) error {
if !fmctypes.VerifySigner(config.Param.Name, super, header.GetSignature().PubicKey()) {
return errors.New("not the signature of the address")
}
if !fmctypes.Verify(header.GetHash(), header.GetSignature()) {
return errors.New("verify seal failed")
}
return nil
}
// updateConfirmedBlockHeader Update the final confirmation block
func (d *DPos) updateConfirmed(chain blockchain.IChain) error {
if d.confirmed == 0 {
height, err := d.cycle.DPosStatus.Confirmed()
if err != nil {
header, err := chain.GetHeaderHeight(0)
if err != nil {
return err
}
height = header.GetHeight()
}
d.confirmed = height
}
curHeader, err := chain.LastHeader()
if err != nil {
return err
}
// If there are already more than two-thirds of different nodes generating blocks,
// it means that the blocks before these blocks have been confirmed
cycle := uint64(0)
superMap := make(map[string]int)
for d.confirmed < curHeader.GetHeight() {
curCycle := curHeader.GetTime() / param.CycleInterval
if curCycle != cycle {
cycle = curCycle
superMap = make(map[string]int)
}
// fast return
// if block number difference less consensusSize-witnessNum
// there is no need to check block is confirmed
count := superMap[curHeader.GetSigner().String()]
superMap[curHeader.GetSigner().String()] = count + 1
if len(superMap) >= param.DPosSize /*dpos.checkWinnerMapCount(winnerMap, 1)*/ {
d.cycle.DPosStatus.SetConfirmed(curHeader.GetHeight())
d.confirmed = curHeader.GetHeight()
chain.SetConfirmed(curHeader.GetHeight())
//log.Info("DPos set confirmed block header", "currentHeader", curHeader.Height)
return nil
}
curHeader, err = chain.GetHeaderHash(curHeader.GetPreHash())
if err != nil {
return errors.New("nil block header returned")
}
}
return nil
}
func nextTime(now uint64) uint64 {
return (now + param.BlockInterval - 1) / param.BlockInterval * param.BlockInterval
}