-
Notifications
You must be signed in to change notification settings - Fork 521
/
dev.go
244 lines (188 loc) · 5.1 KB
/
dev.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
package dev
import (
"fmt"
"time"
"github.com/0xPolygon/polygon-edge/blockchain"
"github.com/0xPolygon/polygon-edge/consensus"
"github.com/0xPolygon/polygon-edge/helper/progress"
"github.com/0xPolygon/polygon-edge/state"
"github.com/0xPolygon/polygon-edge/txpool"
"github.com/0xPolygon/polygon-edge/types"
"github.com/hashicorp/go-hclog"
)
const (
devConsensus = "dev-consensus"
)
// Dev consensus protocol seals any new transaction immediately
type Dev struct {
logger hclog.Logger
notifyCh chan struct{}
closeCh chan struct{}
interval uint64
txpool *txpool.TxPool
blockchain *blockchain.Blockchain
executor *state.Executor
}
// Factory implements the base factory method
func Factory(
params *consensus.Params,
) (consensus.Consensus, error) {
logger := params.Logger.Named("dev")
d := &Dev{
logger: logger,
notifyCh: make(chan struct{}),
closeCh: make(chan struct{}),
blockchain: params.Blockchain,
executor: params.Executor,
txpool: params.TxPool,
}
rawInterval, ok := params.Config.Config["interval"]
if ok {
interval, ok := rawInterval.(uint64)
if !ok {
return nil, fmt.Errorf("interval expected int")
}
d.interval = interval
}
return d, nil
}
// Initialize initializes the consensus
func (d *Dev) Initialize() error {
d.txpool.SetSealing(true)
return nil
}
// Start starts the consensus mechanism
func (d *Dev) Start() error {
go d.run()
return nil
}
func (d *Dev) nextNotify() chan struct{} {
if d.interval == 0 {
d.interval = 1
}
go func() {
<-time.After(time.Duration(d.interval) * time.Second)
d.notifyCh <- struct{}{}
}()
return d.notifyCh
}
func (d *Dev) run() {
d.logger.Info("consensus started")
for {
// wait until there is a new txn
select {
case <-d.nextNotify():
case <-d.closeCh:
return
}
// There are new transactions in the pool, try to seal them
header := d.blockchain.Header()
if err := d.writeNewBlock(header); err != nil {
d.logger.Error("failed to mine block", "err", err)
}
}
}
type transitionInterface interface {
Write(txn *types.Transaction) error
}
func (d *Dev) writeTransactions(gasLimit uint64, transition transitionInterface) []*types.Transaction {
var successful []*types.Transaction
d.txpool.Prepare()
for {
tx := d.txpool.Peek()
if tx == nil {
break
}
if tx.ExceedsBlockGasLimit(gasLimit) {
d.txpool.Drop(tx)
continue
}
if err := transition.Write(tx); err != nil {
if _, ok := err.(*state.GasLimitReachedTransitionApplicationError); ok { //nolint:errorlint
break
} else if appErr, ok := err.(*state.TransitionApplicationError); ok && appErr.IsRecoverable { //nolint:errorlint
d.txpool.Demote(tx)
} else {
d.txpool.Drop(tx)
}
continue
}
// no errors, pop the tx from the pool
d.txpool.Pop(tx)
successful = append(successful, tx)
}
d.logger.Info("picked out txns from pool", "num", len(successful), "remaining", d.txpool.Length())
return successful
}
// writeNewBLock generates a new block based on transactions from the pool,
// and writes them to the blockchain
func (d *Dev) writeNewBlock(parent *types.Header) error {
// Generate the base block
num := parent.Number
header := &types.Header{
ParentHash: parent.Hash,
Number: num + 1,
GasLimit: parent.GasLimit, // Inherit from parent for now, will need to adjust dynamically later.
Timestamp: uint64(time.Now().Unix()),
}
// calculate gas limit based on parent header
gasLimit, err := d.blockchain.CalculateGasLimit(header.Number)
if err != nil {
return err
}
header.GasLimit = gasLimit
miner, err := d.GetBlockCreator(header)
if err != nil {
return err
}
transition, err := d.executor.BeginTxn(parent.StateRoot, header, miner)
if err != nil {
return err
}
txns := d.writeTransactions(gasLimit, transition)
// Commit the changes
_, root := transition.Commit()
// Update the header
header.StateRoot = root
header.GasUsed = transition.TotalGas()
// Build the actual block
// The header hash is computed inside buildBlock
block := consensus.BuildBlock(consensus.BuildBlockParams{
Header: header,
Txns: txns,
Receipts: transition.Receipts(),
})
if err := d.blockchain.VerifyFinalizedBlock(block); err != nil {
return err
}
// Write the block to the blockchain
if err := d.blockchain.WriteBlock(block, devConsensus); err != nil {
return err
}
// after the block has been written we reset the txpool so that
// the old transactions are removed
d.txpool.ResetWithHeaders(block.Header)
return nil
}
// REQUIRED BASE INTERFACE METHODS //
func (d *Dev) VerifyHeader(header *types.Header) error {
// All blocks are valid
return nil
}
func (d *Dev) ProcessHeaders(headers []*types.Header) error {
return nil
}
func (d *Dev) GetBlockCreator(header *types.Header) (types.Address, error) {
return header.Miner, nil
}
// PreStateCommit a hook to be called before finalizing state transition on inserting block
func (d *Dev) PreStateCommit(_header *types.Header, _txn *state.Transition) error {
return nil
}
func (d *Dev) GetSyncProgression() *progress.Progression {
return nil
}
func (d *Dev) Close() error {
close(d.closeCh)
return nil
}