forked from taikoxyz/taiko-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver.go
275 lines (236 loc) · 6.63 KB
/
driver.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
package driver
import (
"context"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/beacon/engine"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log"
chainSyncer "github.com/taikoxyz/taiko-client/driver/chain_syncer"
"github.com/taikoxyz/taiko-client/driver/state"
"github.com/taikoxyz/taiko-client/pkg/rpc"
"github.com/urfave/cli/v2"
)
const (
protocolStatusReportInterval = 30 * time.Second
exchangeTransitionConfigInterval = 1 * time.Minute
)
// Driver keeps the L2 execution engine's local block chain in sync with the TaikoL1
// contract.
type Driver struct {
rpc *rpc.Client
l2ChainSyncer *chainSyncer.L2ChainSyncer
state *state.State
l1HeadCh chan *types.Header
l1HeadSub event.Subscription
syncNotify chan struct{}
backOffRetryInterval time.Duration
ctx context.Context
wg sync.WaitGroup
}
// New initializes the given driver instance based on the command line flags.
func (d *Driver) InitFromCli(ctx context.Context, c *cli.Context) error {
cfg, err := NewConfigFromCliContext(c)
if err != nil {
return err
}
return InitFromConfig(ctx, d, cfg)
}
// InitFromConfig initializes the driver instance based on the given configurations.
func InitFromConfig(ctx context.Context, d *Driver, cfg *Config) (err error) {
d.l1HeadCh = make(chan *types.Header, 1024)
d.wg = sync.WaitGroup{}
d.syncNotify = make(chan struct{}, 1)
d.ctx = ctx
d.backOffRetryInterval = cfg.BackOffRetryInterval
if d.rpc, err = rpc.NewClient(d.ctx, &rpc.ClientConfig{
L1Endpoint: cfg.L1Endpoint,
L2Endpoint: cfg.L2Endpoint,
L2CheckPoint: cfg.L2CheckPoint,
TaikoL1Address: cfg.TaikoL1Address,
TaikoL2Address: cfg.TaikoL2Address,
L2EngineEndpoint: cfg.L2EngineEndpoint,
JwtSecret: cfg.JwtSecret,
RetryInterval: cfg.BackOffRetryInterval,
Timeout: cfg.RPCTimeout,
}); err != nil {
return err
}
if d.state, err = state.New(d.ctx, d.rpc); err != nil {
return err
}
peers, err := d.rpc.L2.PeerCount(d.ctx)
if err != nil {
return err
}
if cfg.P2PSyncVerifiedBlocks && peers == 0 {
log.Warn("P2P syncing verified blocks enabled, but no connected peer found in L2 execution engine")
}
signalServiceAddress, err := d.rpc.TaikoL1.Resolve0(
&bind.CallOpts{Context: ctx},
rpc.StringToBytes32("signal_service"),
false,
)
if err != nil {
return err
}
if d.l2ChainSyncer, err = chainSyncer.New(
d.ctx,
d.rpc,
d.state,
cfg.P2PSyncVerifiedBlocks,
cfg.P2PSyncTimeout,
signalServiceAddress,
); err != nil {
return err
}
d.l1HeadSub = d.state.SubL1HeadsFeed(d.l1HeadCh)
return nil
}
// Start starts the driver instance.
func (d *Driver) Start() error {
d.wg.Add(3)
go d.eventLoop()
go d.reportProtocolStatus()
go d.exchangeTransitionConfigLoop()
return nil
}
// Close closes the driver instance.
func (d *Driver) Close(ctx context.Context) {
d.state.Close()
d.wg.Wait()
}
// eventLoop starts the main loop of a L2 execution engine's driver.
func (d *Driver) eventLoop() {
defer d.wg.Done()
// reqSync requests performing a synchronising operation, won't block
// if we are already synchronising.
reqSync := func() {
select {
case d.syncNotify <- struct{}{}:
default:
}
}
// doSyncWithBackoff performs a synchronising operation with a backoff strategy.
doSyncWithBackoff := func() {
if err := backoff.Retry(d.doSync, backoff.NewConstantBackOff(d.backOffRetryInterval)); err != nil {
log.Error("Sync L2 execution engine's block chain error", "error", err)
}
}
// Call doSync() right away to catch up with the latest known L1 head.
doSyncWithBackoff()
for {
select {
case <-d.ctx.Done():
return
case <-d.syncNotify:
doSyncWithBackoff()
case <-d.l1HeadCh:
reqSync()
}
}
}
// doSync fetches all `BlockProposed` events emitted from local
// L1 sync cursor to the L1 head, and then applies all corresponding
// L2 blocks into node's local block chain.
func (d *Driver) doSync() error {
// Check whether the application is closing.
if d.ctx.Err() != nil {
log.Warn("Driver context error", "error", d.ctx.Err())
return nil
}
l1Head := d.state.GetL1Head()
if err := d.l2ChainSyncer.Sync(l1Head); err != nil {
log.Error("Process new L1 blocks error", "error", err)
return err
}
return nil
}
// ChainSyncer returns the driver's chain syncer.
func (d *Driver) ChainSyncer() *chainSyncer.L2ChainSyncer {
return d.l2ChainSyncer
}
// reportProtocolStatus reports some protocol status intervally.
func (d *Driver) reportProtocolStatus() {
ticker := time.NewTicker(protocolStatusReportInterval)
defer func() {
ticker.Stop()
d.wg.Done()
}()
var maxNumBlocks uint64
if err := backoff.Retry(
func() error {
if d.ctx.Err() != nil {
return nil
}
configs, err := d.rpc.TaikoL1.GetConfig(&bind.CallOpts{Context: d.ctx})
if err != nil {
return err
}
maxNumBlocks = configs.BlockMaxProposals
return nil
},
backoff.NewConstantBackOff(d.backOffRetryInterval),
); err != nil {
log.Error("Failed to get protocol state variables", "error", err)
return
}
for {
select {
case <-d.ctx.Done():
return
case <-ticker.C:
vars, err := d.rpc.GetProtocolStateVariables(&bind.CallOpts{Context: d.ctx})
if err != nil {
log.Error("Failed to get protocol state variables", "error", err)
continue
}
log.Info(
"📖 Protocol status",
"lastVerifiedBlockId", vars.B.LastVerifiedBlockId,
"pendingBlocks", vars.B.NumBlocks-vars.B.LastVerifiedBlockId-1,
"availableSlots", vars.B.LastVerifiedBlockId+maxNumBlocks-vars.B.NumBlocks,
)
}
}
}
// exchangeTransitionConfigLoop keeps exchanging transition configs with the
// L2 execution engine.
func (d *Driver) exchangeTransitionConfigLoop() {
ticker := time.NewTicker(exchangeTransitionConfigInterval)
defer func() {
ticker.Stop()
d.wg.Done()
}()
for {
select {
case <-d.ctx.Done():
return
case <-ticker.C:
func() {
tc, err := d.rpc.L2Engine.ExchangeTransitionConfiguration(d.ctx, &engine.TransitionConfigurationV1{
TerminalTotalDifficulty: (*hexutil.Big)(common.Big0),
TerminalBlockHash: common.Hash{},
TerminalBlockNumber: 0,
})
if err != nil {
log.Error("Failed to exchange Transition Configuration", "error", err)
return
}
log.Debug(
"Exchanged transition config",
"transitionConfig", tc,
)
}()
}
}
}
// Name returns the application name.
func (d *Driver) Name() string {
return "driver"
}