/
consensus_backend.go
396 lines (317 loc) · 8.9 KB
/
consensus_backend.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
package ibft
import (
"context"
"fmt"
"math"
"time"
"github.com/0xDaoChain/go-ibft/messages"
"github.com/0xDaoChain/dao-chain/consensus"
"github.com/0xDaoChain/dao-chain/consensus/ibft/signer"
"github.com/0xDaoChain/dao-chain/state"
"github.com/0xDaoChain/dao-chain/types"
)
func (i *backendIBFT) BuildProposal(blockNumber uint64) []byte {
var (
latestHeader = i.blockchain.Header()
latestBlockNumber = latestHeader.Number
)
if latestBlockNumber+1 != blockNumber {
i.logger.Error(
"unable to build block, due to lack of parent block",
"num",
latestBlockNumber,
)
return nil
}
block, err := i.buildBlock(latestHeader)
if err != nil {
i.logger.Error("cannot build block", "num", blockNumber, "err", err)
return nil
}
return block.MarshalRLP()
}
func (i *backendIBFT) InsertBlock(
proposal []byte,
committedSeals []*messages.CommittedSeal,
) {
newBlock := &types.Block{}
if err := newBlock.UnmarshalRLP(proposal); err != nil {
i.logger.Error("cannot unmarshal proposal", "err", err)
return
}
committedSealsMap := make(map[types.Address][]byte, len(committedSeals))
for _, cm := range committedSeals {
committedSealsMap[types.BytesToAddress(cm.Signer)] = cm.Signature
}
// Push the committed seals to the header
header, err := i.currentSigner.WriteCommittedSeals(newBlock.Header, committedSealsMap)
if err != nil {
i.logger.Error("cannot write committed seals", "err", err)
return
}
newBlock.Header = header
// Save the block locally
if err := i.blockchain.WriteBlock(newBlock, "consensus"); err != nil {
i.logger.Error("cannot write block", "err", err)
return
}
i.updateMetrics(newBlock)
i.logger.Info(
"block committed",
"number", newBlock.Number(),
"hash", newBlock.Hash(),
"validation_type", i.currentSigner.Type(),
"validators", i.currentValidators.Len(),
"committed", len(committedSeals),
)
if err := i.currentHooks.PostInsertBlock(newBlock); err != nil {
i.logger.Error(
"failed to call PostInsertBlock hook",
"height", newBlock.Number(),
"hash", newBlock.Hash(),
"err", err,
)
return
}
// after the block has been written we reset the txpool so that
// the old transactions are removed
i.txpool.ResetWithHeaders(newBlock.Header)
}
func (i *backendIBFT) ID() []byte {
return i.currentSigner.Address().Bytes()
}
func (i *backendIBFT) MaximumFaultyNodes() uint64 {
return uint64(CalcMaxFaultyNodes(i.currentValidators))
}
func (i *backendIBFT) Quorum(blockNumber uint64) uint64 {
validators, err := i.forkManager.GetValidators(blockNumber)
if err != nil {
i.logger.Error(
"failed to get validators when calculation quorum",
"height", blockNumber,
"err", err,
)
// return Math.MaxInt32 to prevent overflow when casting to int in go-ibft package
return math.MaxInt32
}
quorumFn := i.quorumSize(blockNumber)
return uint64(quorumFn(validators))
}
// buildBlock builds the block, based on the passed in snapshot and parent header
func (i *backendIBFT) buildBlock(parent *types.Header) (*types.Block, error) {
header := &types.Header{
ParentHash: parent.Hash,
Number: parent.Number + 1,
Miner: types.ZeroAddress.Bytes(),
Nonce: types.Nonce{},
MixHash: signer.IstanbulDigest,
// this is required because blockchain needs difficulty to organize blocks and forks
Difficulty: parent.Number + 1,
StateRoot: types.EmptyRootHash, // this avoids needing state for now
Sha3Uncles: types.EmptyUncleHash,
GasLimit: parent.GasLimit, // Inherit from parent for now, will need to adjust dynamically later.
}
// calculate gas limit based on parent header
gasLimit, err := i.blockchain.CalculateGasLimit(header.Number)
if err != nil {
return nil, err
}
header.GasLimit = gasLimit
if err := i.currentHooks.ModifyHeader(header, i.currentSigner.Address()); err != nil {
return nil, err
}
// Set the header timestamp
potentialTimestamp := i.calcHeaderTimestamp(parent.Timestamp, time.Now())
header.Timestamp = uint64(potentialTimestamp.Unix())
parentCommittedSeals, err := i.extractParentCommittedSeals(parent)
if err != nil {
return nil, err
}
i.currentSigner.InitIBFTExtra(header, i.currentValidators, parentCommittedSeals)
transition, err := i.executor.BeginTxn(parent.StateRoot, header, i.currentSigner.Address())
if err != nil {
return nil, err
}
// Get the block transactions
writeCtx, cancelFn := context.WithDeadline(context.Background(), potentialTimestamp)
defer cancelFn()
txs := i.writeTransactions(
writeCtx,
gasLimit,
header.Number,
transition,
)
if err := i.PreCommitState(header, transition); err != nil {
return nil, err
}
_, root := transition.Commit()
header.StateRoot = root
header.GasUsed = transition.TotalGas()
// build the block
block := consensus.BuildBlock(consensus.BuildBlockParams{
Header: header,
Txns: txs,
Receipts: transition.Receipts(),
})
// write the seal of the block after all the fields are completed
header, err = i.currentSigner.WriteProposerSeal(header)
if err != nil {
return nil, err
}
block.Header = header
// compute the hash, this is only a provisional hash since the final one
// is sealed after all the committed seals
block.Header.ComputeHash()
i.logger.Info("build block", "number", header.Number, "txs", len(txs))
return block, nil
}
// calcHeaderTimestamp calculates the new block timestamp, based
// on the block time and parent timestamp
func (i *backendIBFT) calcHeaderTimestamp(parentUnix uint64, currentTime time.Time) time.Time {
var (
parentTimestamp = time.Unix(int64(parentUnix), 0)
potentialTimestamp = parentTimestamp.Add(i.blockTime)
)
if potentialTimestamp.Before(currentTime) {
// The deadline for creating this next block
// has passed, round it to the nearest
// multiple of block time
// t........t+blockT...x (t+blockT.x; now).....t+blockT (potential)
potentialTimestamp = roundUpTime(currentTime, i.blockTime)
}
return potentialTimestamp
}
// roundUpTime rounds up the specified time to the
// nearest higher multiple
func roundUpTime(t time.Time, roundOn time.Duration) time.Time {
return t.Add(roundOn / 2).Round(roundOn)
}
type status uint8
const (
success status = iota
fail
skip
)
type txExeResult struct {
tx *types.Transaction
status status
}
type transitionInterface interface {
Write(txn *types.Transaction) error
WriteFailedReceipt(txn *types.Transaction) error
}
func (i *backendIBFT) writeTransactions(
writeCtx context.Context,
gasLimit,
blockNumber uint64,
transition transitionInterface,
) (executed []*types.Transaction) {
executed = make([]*types.Transaction, 0)
if !i.currentHooks.ShouldWriteTransactions(blockNumber) {
return
}
var (
successful = 0
failed = 0
skipped = 0
)
defer func() {
i.logger.Info(
"executed txs",
"successful", successful,
"failed", failed,
"skipped", skipped,
"remaining", i.txpool.Length(),
)
}()
i.txpool.Prepare()
write:
for {
select {
case <-writeCtx.Done():
return
default:
// execute transactions one by one
result, ok := i.writeTransaction(
i.txpool.Peek(),
transition,
gasLimit,
)
if !ok {
break write
}
tx := result.tx
switch result.status {
case success:
executed = append(executed, tx)
successful++
case fail:
failed++
case skip:
skipped++
}
}
}
// wait for the timer to expire
<-writeCtx.Done()
return
}
func (i *backendIBFT) writeTransaction(
tx *types.Transaction,
transition transitionInterface,
gasLimit uint64,
) (*txExeResult, bool) {
if tx == nil {
return nil, false
}
if tx.ExceedsBlockGasLimit(gasLimit) {
i.txpool.Drop(tx)
if err := transition.WriteFailedReceipt(tx); err != nil {
i.logger.Error(
fmt.Sprintf(
"unable to write failed receipt for transaction %s",
tx.Hash,
),
)
}
// continue processing
return &txExeResult{tx, fail}, true
}
if err := transition.Write(tx); err != nil {
if _, ok := err.(*state.GasLimitReachedTransitionApplicationError); ok { //nolint:errorlint
// stop processing
return nil, false
} else if appErr, ok := err.(*state.TransitionApplicationError); ok && appErr.IsRecoverable { //nolint:errorlint
i.txpool.Demote(tx)
return &txExeResult{tx, skip}, true
} else {
i.txpool.Drop(tx)
return &txExeResult{tx, fail}, true
}
}
i.txpool.Pop(tx)
return &txExeResult{tx, success}, true
}
// extractCommittedSeals extracts CommittedSeals from header
func (i *backendIBFT) extractCommittedSeals(
header *types.Header,
) (signer.Seals, error) {
signer, err := i.forkManager.GetSigner(header.Number)
if err != nil {
return nil, err
}
extra, err := signer.GetIBFTExtra(header)
if err != nil {
return nil, err
}
return extra.CommittedSeals, nil
}
// extractParentCommittedSeals extracts ParentCommittedSeals from header
func (i *backendIBFT) extractParentCommittedSeals(
header *types.Header,
) (signer.Seals, error) {
if header.Number == 0 {
return nil, nil
}
return i.extractCommittedSeals(header)
}