/
layer_one.go
488 lines (445 loc) · 12.8 KB
/
layer_one.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package genesis
import (
"context"
"errors"
"fmt"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie"
"github.com/sliceledger-blockchain/slice-ledger/op-bindings/bindings"
"github.com/sliceledger-blockchain/slice-ledger/op-bindings/predeploys"
"github.com/sliceledger-blockchain/slice-ledger/op-chain-ops/deployer"
"github.com/sliceledger-blockchain/slice-ledger/op-chain-ops/state"
)
var (
// proxies represents the set of proxies in front of contracts.
proxies = []string{
"SystemConfigProxy",
"L2OutputOracleProxy",
"L1CrossDomainMessengerProxy",
"L1StandardBridgeProxy",
"SlicePortalProxy",
"SliceMintableERC20FactoryProxy",
}
// portalMeteringSlot is the storage slot containing the metering params.
portalMeteringSlot = common.Hash{31: 0x01}
// zeroHash represents the zero value for a hash.
zeroHash = common.Hash{}
// uint128Max is type(uint128).max and is set in the init function.
uint128Max = new(big.Int)
// The default values for the ResourceConfig, used as part of
// an EIP-1559 curve for deposit gas.
defaultResourceConfig = bindings.ResourceMeteringResourceConfig{
MaxResourceLimit: 20_000_000,
ElasticityMultiplier: 10,
BaseFeeMaxChangeDenominator: 8,
MinimumBaseFee: params.GWei,
SystemTxMaxGas: 1_000_000,
}
)
func init() {
var ok bool
uint128Max, ok = new(big.Int).SetString("ffffffffffffffffffffffffffffffff", 16)
if !ok {
panic("bad uint128Max")
}
// Set the maximum base fee on the default config.
defaultResourceConfig.MaximumBaseFee = uint128Max
}
// BuildL1DeveloperGenesis will create a L1 genesis block after creating
// all of the state required for an Slice network to function.
func BuildL1DeveloperGenesis(config *DeployConfig) (*core.Genesis, error) {
if config.L2OutputOracleStartingTimestamp != -1 {
return nil, errors.New("l2oo starting timestamp must be -1")
}
if config.L1GenesisBlockTimestamp == 0 {
return nil, errors.New("must specify l1 genesis block timestamp")
}
genesis, err := NewL1Genesis(config)
if err != nil {
return nil, err
}
backend := deployer.NewBackendWithGenesisTimestamp(uint64(config.L1GenesisBlockTimestamp))
deployments, err := deployL1Contracts(config, backend)
if err != nil {
return nil, err
}
depsByName := make(map[string]deployer.Deployment)
depsByAddr := make(map[common.Address]deployer.Deployment)
for _, dep := range deployments {
depsByName[dep.Name] = dep
depsByAddr[dep.Address] = dep
}
opts, err := bind.NewKeyedTransactorWithChainID(deployer.TestKey, deployer.ChainID)
if err != nil {
return nil, err
}
portalABI, err := bindings.SlicePortalMetaData.GetAbi()
if err != nil {
return nil, err
}
// Initialize the SlicePortal without being paused
data, err := portalABI.Pack("initialize", false)
if err != nil {
return nil, fmt.Errorf("cannot abi encode initialize for SlicePortal: %w", err)
}
if _, err := upgradeProxy(
backend,
opts,
depsByName["SlicePortalProxy"].Address,
depsByName["SlicePortal"].Address,
data,
); err != nil {
return nil, fmt.Errorf("cannot upgrade SlicePortalProxy: %w", err)
}
sysCfgABI, err := bindings.SystemConfigMetaData.GetAbi()
if err != nil {
return nil, err
}
gasLimit := uint64(config.L2GenesisBlockGasLimit)
if gasLimit == 0 {
gasLimit = defaultL2GasLimit
}
data, err = sysCfgABI.Pack(
"initialize",
config.FinalSystemOwner,
uint642Big(config.GasPriceOracleOverhead),
uint642Big(config.GasPriceOracleScalar),
config.BatchSenderAddress.Hash(),
gasLimit,
config.P2PSequencerAddress,
defaultResourceConfig,
)
if err != nil {
return nil, fmt.Errorf("cannot abi encode initialize for SystemConfig: %w", err)
}
if _, err := upgradeProxy(
backend,
opts,
depsByName["SystemConfigProxy"].Address,
depsByName["SystemConfig"].Address,
data,
); err != nil {
return nil, fmt.Errorf("cannot upgrade SystemConfigProxy: %w", err)
}
l2ooABI, err := bindings.L2OutputOracleMetaData.GetAbi()
if err != nil {
return nil, err
}
data, err = l2ooABI.Pack(
"initialize",
big.NewInt(0),
uint642Big(uint64(config.L1GenesisBlockTimestamp)),
)
if err != nil {
return nil, fmt.Errorf("cannot abi encode initialize for L2OutputOracle: %w", err)
}
if _, err := upgradeProxy(
backend,
opts,
depsByName["L2OutputOracleProxy"].Address,
depsByName["L2OutputOracle"].Address,
data,
); err != nil {
return nil, err
}
l1XDMABI, err := bindings.L1CrossDomainMessengerMetaData.GetAbi()
if err != nil {
return nil, err
}
data, err = l1XDMABI.Pack("initialize")
if err != nil {
return nil, fmt.Errorf("cannot abi encode initialize for L1CrossDomainMessenger: %w", err)
}
if _, err := upgradeProxy(
backend,
opts,
depsByName["L1CrossDomainMessengerProxy"].Address,
depsByName["L1CrossDomainMessenger"].Address,
data,
); err != nil {
return nil, err
}
if _, err := upgradeProxy(
backend,
opts,
depsByName["L1StandardBridgeProxy"].Address,
depsByName["L1StandardBridge"].Address,
nil,
); err != nil {
return nil, err
}
var lastUpgradeTx *types.Transaction
if lastUpgradeTx, err = upgradeProxy(
backend,
opts,
depsByName["SliceMintableERC20FactoryProxy"].Address,
depsByName["SliceMintableERC20Factory"].Address,
nil,
); err != nil {
return nil, err
}
// Commit all the upgrades at once, then wait for the last
// transaction to be mined. The simulator performs async
// processing, and as such we need to wait for the transaction
// receipt to appear before considering the above transactions
// committed to the chain.
backend.Commit()
if _, err := bind.WaitMined(context.Background(), backend, lastUpgradeTx); err != nil {
return nil, err
}
memDB := state.NewMemoryStateDB(genesis)
if err := SetL1Proxies(memDB, predeploys.DevProxyAdminAddr); err != nil {
return nil, err
}
FundDevAccounts(memDB)
SetPrecompileBalances(memDB)
for name, proxyAddr := range predeploys.DevPredeploys {
memDB.SetState(*proxyAddr, ImplementationSlot, depsByName[name].Address.Hash())
// Special case for WETH since it was not designed to be behind a proxy
if name == "WETH9" {
name, _ := state.EncodeStringValue("Wrapped Ether", 0)
symbol, _ := state.EncodeStringValue("WETH", 0)
decimals, _ := state.EncodeUintValue(18, 0)
memDB.SetState(*proxyAddr, common.Hash{}, name)
memDB.SetState(*proxyAddr, common.Hash{31: 0x01}, symbol)
memDB.SetState(*proxyAddr, common.Hash{31: 0x02}, decimals)
}
}
if config.FundDevAccounts {
FundDevAccounts(memDB)
SetPrecompileBalances(memDB)
}
stateDB, err := backend.Blockchain().State()
if err != nil {
return nil, err
}
for _, dep := range deployments {
st, err := stateDB.StorageTrie(dep.Address)
if err != nil {
return nil, fmt.Errorf("failed to open storage trie of %s: %w", dep.Address, err)
}
if st == nil {
return nil, fmt.Errorf("missing account %s in state, address: %s", dep.Name, dep.Address)
}
iter := trie.NewIterator(st.NodeIterator(nil))
depAddr := dep.Address
if strings.HasSuffix(dep.Name, "Proxy") {
depAddr = *predeploys.DevPredeploys[strings.TrimSuffix(dep.Name, "Proxy")]
}
memDB.CreateAccount(depAddr)
memDB.SetCode(depAddr, dep.Bytecode)
for iter.Next() {
_, data, _, err := rlp.Split(iter.Value)
if err != nil {
return nil, err
}
key := common.BytesToHash(st.GetKey(iter.Key))
value := common.BytesToHash(data)
if depAddr == predeploys.DevSlicePortalAddr && key == portalMeteringSlot {
// We need to manually set the block number in the resource
// metering storage slot to zero. Otherwise, deposits will
// revert.
copy(value[:24], zeroHash[:])
}
memDB.SetState(depAddr, key, value)
}
}
return memDB.Genesis(), nil
}
func deployL1Contracts(config *DeployConfig, backend *backends.SimulatedBackend) ([]deployer.Deployment, error) {
constructors := make([]deployer.Constructor, 0)
for _, proxy := range proxies {
constructors = append(constructors, deployer.Constructor{
Name: proxy,
})
}
gasLimit := uint64(config.L2GenesisBlockGasLimit)
if gasLimit == 0 {
gasLimit = defaultL2GasLimit
}
constructors = append(constructors, []deployer.Constructor{
{
Name: "SystemConfig",
Args: []interface{}{
config.FinalSystemOwner,
uint642Big(config.GasPriceOracleOverhead),
uint642Big(config.GasPriceOracleScalar),
config.BatchSenderAddress.Hash(), // left-padded 32 bytes value, version is zero anyway
gasLimit,
config.P2PSequencerAddress,
defaultResourceConfig,
},
},
{
Name: "L2OutputOracle",
Args: []interface{}{
uint642Big(config.L2OutputOracleSubmissionInterval),
uint642Big(config.L2BlockTime),
big.NewInt(0),
uint642Big(uint64(config.L1GenesisBlockTimestamp)),
config.L2OutputOracleProposer,
config.L2OutputOracleChallenger,
uint642Big(config.FinalizationPeriodSeconds),
},
},
{
// The implementation of the SlicePortal is deployed
// as being paused to prevent invalid usage of the network
// as only the proxy should be used
Name: "SlicePortal",
Args: []interface{}{
predeploys.DevL2OutputOracleAddr,
config.PortalGuardian,
true, // _paused
predeploys.DevSystemConfigAddr,
},
},
{
Name: "L1CrossDomainMessenger",
},
{
Name: "L1StandardBridge",
},
{
Name: "L1ERC721Bridge",
},
{
Name: "SliceMintableERC20Factory",
},
{
Name: "AddressManager",
},
{
Name: "ProxyAdmin",
Args: []interface{}{
common.Address{19: 0x01},
},
},
{
Name: "WETH9",
},
}...)
return deployer.Deploy(backend, constructors, l1Deployer)
}
func l1Deployer(backend *backends.SimulatedBackend, opts *bind.TransactOpts, deployment deployer.Constructor) (*types.Transaction, error) {
var tx *types.Transaction
var err error
switch deployment.Name {
case "SystemConfig":
_, tx, _, err = bindings.DeploySystemConfig(
opts,
backend,
deployment.Args[0].(common.Address),
deployment.Args[1].(*big.Int),
deployment.Args[2].(*big.Int),
deployment.Args[3].(common.Hash),
deployment.Args[4].(uint64),
deployment.Args[5].(common.Address),
deployment.Args[6].(bindings.ResourceMeteringResourceConfig),
)
case "L2OutputOracle":
_, tx, _, err = bindings.DeployL2OutputOracle(
opts,
backend,
deployment.Args[0].(*big.Int),
deployment.Args[1].(*big.Int),
deployment.Args[2].(*big.Int),
deployment.Args[3].(*big.Int),
deployment.Args[4].(common.Address),
deployment.Args[5].(common.Address),
deployment.Args[6].(*big.Int),
)
case "SlicePortal":
_, tx, _, err = bindings.DeploySlicePortal(
opts,
backend,
deployment.Args[0].(common.Address),
deployment.Args[1].(common.Address),
deployment.Args[2].(bool),
deployment.Args[3].(common.Address),
)
case "L1CrossDomainMessenger":
_, tx, _, err = bindings.DeployL1CrossDomainMessenger(
opts,
backend,
predeploys.DevSlicePortalAddr,
)
case "L1StandardBridge":
_, tx, _, err = bindings.DeployL1StandardBridge(
opts,
backend,
predeploys.DevL1CrossDomainMessengerAddr,
)
case "SliceMintableERC20Factory":
_, tx, _, err = bindings.DeploySliceMintableERC20Factory(
opts,
backend,
predeploys.DevL1StandardBridgeAddr,
)
case "AddressManager":
_, tx, _, err = bindings.DeployAddressManager(
opts,
backend,
)
case "ProxyAdmin":
_, tx, _, err = bindings.DeployProxyAdmin(
opts,
backend,
common.Address{},
)
case "WETH9":
_, tx, _, err = bindings.DeployWETH9(
opts,
backend,
)
case "L1ERC721Bridge":
_, tx, _, err = bindings.DeployL1ERC721Bridge(
opts,
backend,
predeploys.DevL1CrossDomainMessengerAddr,
predeploys.L2ERC721BridgeAddr,
)
default:
if strings.HasSuffix(deployment.Name, "Proxy") {
_, tx, _, err = bindings.DeployProxy(opts, backend, deployer.TestAddress)
} else {
err = fmt.Errorf("unknown contract %s", deployment.Name)
}
}
if err != nil {
err = fmt.Errorf("cannot deploy %s: %w", deployment.Name, err)
}
return tx, err
}
func upgradeProxy(backend *backends.SimulatedBackend, opts *bind.TransactOpts, proxyAddr common.Address, implAddr common.Address, callData []byte) (*types.Transaction, error) {
var tx *types.Transaction
code, err := backend.CodeAt(context.Background(), implAddr, nil)
if err != nil {
return nil, err
}
if len(code) == 0 {
return nil, fmt.Errorf("no code at %s", implAddr)
}
proxy, err := bindings.NewProxy(proxyAddr, backend)
if err != nil {
return nil, err
}
if callData == nil {
tx, err = proxy.UpgradeTo(opts, implAddr)
} else {
tx, err = proxy.UpgradeToAndCall(
opts,
implAddr,
callData,
)
}
return tx, err
}