-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
remote_handlers.go
444 lines (379 loc) · 16.9 KB
/
remote_handlers.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
package bindgen
import (
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/ethereum-optimism/optimism/op-bindings/etherscan"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)
type ContractData struct {
Abi string
DeployedBin string
DeploymentTx etherscan.Transaction
}
func (generator *BindGenGeneratorRemote) standardHandler(contractMetadata *RemoteContractMetadata) error {
fetchedData, err := generator.FetchContractData(contractMetadata.Verified, "eth", contractMetadata.Deployments.Eth.Hex())
if err != nil {
return err
}
contractMetadata.DeployedBin = fetchedData.DeployedBin
if err = generator.CompareDeployedBytecodeWithRpc(contractMetadata, "eth"); err != nil {
return err
}
if err = generator.CompareDeployedBytecodeWithRpc(contractMetadata, "op"); err != nil {
return err
}
// If ABI was explicitly provided by config, don't overwrite
if contractMetadata.ABI == "" {
contractMetadata.ABI = fetchedData.Abi
} else if fetchedData.Abi != "" && contractMetadata.ABI != fetchedData.Abi {
generator.Logger.Debug("ABIs", "given", contractMetadata.ABI, "fetched", fetchedData.Abi)
return fmt.Errorf("the given ABI for %s differs from what was fetched from Etherscan", contractMetadata.Name)
}
if contractMetadata.InitBin, err = generator.removeDeploymentSalt(fetchedData.DeploymentTx.Input, contractMetadata.DeploymentSalt); err != nil {
return err
}
if err := generator.CompareInitBytecodeWithOp(contractMetadata, true); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
if err := generator.CompareDeployedBytecodeWithOp(contractMetadata, true); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
return generator.writeAllOutputs(contractMetadata, remoteContractMetadataTemplate)
}
func (generator *BindGenGeneratorRemote) create2DeployerHandler(contractMetadata *RemoteContractMetadata) error {
fetchedData, err := generator.FetchContractData(contractMetadata.Verified, "eth", contractMetadata.Deployments.Eth.Hex())
if err != nil {
return err
}
contractMetadata.ABI = fetchedData.Abi
contractMetadata.DeployedBin = fetchedData.DeployedBin
if contractMetadata.InitBin, err = generator.removeDeploymentSalt(fetchedData.DeploymentTx.Input, contractMetadata.DeploymentSalt); err != nil {
return err
}
// We're expecting the initialization bytecode for Create2Deployer to not match the init code on OP,
// because the deployment on OP has been overwritten by the Canyon hardfork, and the init code
// Etherscan returns for the OP deployment is from the initial outdated deployment.
// For context: https:/ethereum-optimism/op-geth/pull/126
if err := generator.CompareInitBytecodeWithOp(contractMetadata, false); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
if err := generator.CompareDeployedBytecodeWithOp(contractMetadata, true); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
return generator.writeAllOutputs(contractMetadata, remoteContractMetadataTemplate)
}
func (generator *BindGenGeneratorRemote) multiSendHandler(contractMetadata *RemoteContractMetadata) error {
// MultiSend has an immutable that resolves to this(address).
// Because we're predeploying MultiSend to the same address as on OP,
// we can use the deployed bytecode directly for the predeploy
fetchedData, err := generator.FetchContractData(contractMetadata.Verified, "op", contractMetadata.Deployments.Op.Hex())
if err != nil {
return err
}
contractMetadata.ABI = fetchedData.Abi
contractMetadata.DeployedBin = fetchedData.DeployedBin
if err = generator.CompareDeployedBytecodeWithRpc(contractMetadata, "op"); err != nil {
return err
}
if contractMetadata.InitBin, err = generator.removeDeploymentSalt(fetchedData.DeploymentTx.Input, contractMetadata.DeploymentSalt); err != nil {
return err
}
return generator.writeAllOutputs(contractMetadata, remoteContractMetadataTemplate)
}
func (generator *BindGenGeneratorRemote) senderCreatorHandler(contractMetadata *RemoteContractMetadata) error {
var err error
contractMetadata.DeployedBin, err = generator.ContractDataClients.Eth.FetchDeployedBytecode(context.Background(), contractMetadata.Deployments.Eth.Hex())
if err != nil {
return fmt.Errorf("error fetching deployed bytecode: %w", err)
}
if err = generator.CompareDeployedBytecodeWithRpc(contractMetadata, "eth"); err != nil {
return err
}
if err = generator.CompareDeployedBytecodeWithRpc(contractMetadata, "op"); err != nil {
return err
}
// The SenderCreator contract is deployed by EntryPoint, so the transaction data
// from the deployment transaction is for the entire EntryPoint deployment.
// So, we're manually providing the initialization bytecode and therefore it isn't being compared here
if err := generator.CompareInitBytecodeWithOp(contractMetadata, false); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
if err := generator.CompareDeployedBytecodeWithOp(contractMetadata, true); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
return generator.writeAllOutputs(contractMetadata, remoteContractMetadataTemplate)
}
func (generator *BindGenGeneratorRemote) permit2Handler(contractMetadata *RemoteContractMetadata) error {
fetchedData, err := generator.FetchContractData(contractMetadata.Verified, "eth", contractMetadata.Deployments.Eth.Hex())
if err != nil {
return err
}
contractMetadata.ABI = fetchedData.Abi
contractMetadata.DeployedBin = fetchedData.DeployedBin
if contractMetadata.InitBin, err = generator.removeDeploymentSalt(fetchedData.DeploymentTx.Input, contractMetadata.DeploymentSalt); err != nil {
return err
}
if !strings.EqualFold(contractMetadata.Deployer.Hex(), fetchedData.DeploymentTx.To) {
return fmt.Errorf(
"expected deployer address: %s doesn't match the to address: %s for Permit2's proxy deployment transaction",
contractMetadata.Deployer.Hex(),
fetchedData.DeploymentTx.To,
)
}
if err := generator.CompareInitBytecodeWithOp(contractMetadata, true); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
// We're asserting the deployed bytecode doesn't match, because Permit2 has immutable Solidity variables that
// are dependent on block.chainid
if err := generator.CompareDeployedBytecodeWithOp(contractMetadata, false); err != nil {
return fmt.Errorf("%s: %w", contractMetadata.Name, err)
}
return generator.writeAllOutputs(contractMetadata, permit2MetadataTemplate)
}
func (generator *BindGenGeneratorRemote) FetchContractData(contractVerified bool, chain, deploymentAddress string) (ContractData, error) {
var data ContractData
var err error
var client contractDataClient
switch chain {
case "eth":
client = generator.ContractDataClients.Eth
case "op":
client = generator.ContractDataClients.Op
default:
return data, fmt.Errorf("unknown chain, unable to retrieve a contract data client for chain: %s", chain)
}
if contractVerified {
data.Abi, err = client.FetchAbi(context.Background(), deploymentAddress)
if err != nil {
return ContractData{}, fmt.Errorf("error fetching ABI: %w", err)
}
}
data.DeployedBin, err = client.FetchDeployedBytecode(context.Background(), deploymentAddress)
if err != nil {
return ContractData{}, fmt.Errorf("error fetching deployed bytecode: %w", err)
}
deploymentTxHash, err := client.FetchDeploymentTxHash(context.Background(), deploymentAddress)
if err != nil {
return ContractData{}, fmt.Errorf("error fetching deployment transaction hash: %w", err)
}
data.DeploymentTx, err = client.FetchDeploymentTx(context.Background(), deploymentTxHash)
if err != nil {
return ContractData{}, fmt.Errorf("error fetching deployment transaction data: %w", err)
}
return data, nil
}
func (generator *BindGenGeneratorRemote) removeDeploymentSalt(deploymentData, deploymentSalt string) (string, error) {
if deploymentSalt == "" {
return deploymentData, nil
}
re, err := regexp.Compile(fmt.Sprintf("^0x(%s)", deploymentSalt))
if err != nil {
return "", fmt.Errorf("failed to compile regular expression: %w", err)
}
if !re.MatchString(deploymentData) {
return "", fmt.Errorf(
"expected salt: %s to be at the beginning of the contract initialization code: %s, but it wasn't",
deploymentSalt, deploymentData,
)
}
return re.ReplaceAllString(deploymentData, ""), nil
}
func (generator *BindGenGeneratorRemote) CompareInitBytecodeWithOp(contractMetadataEth *RemoteContractMetadata, initCodeShouldMatch bool) error {
if contractMetadataEth.InitBin == "" {
return fmt.Errorf("no initialization bytecode provided for ETH deployment for comparison")
}
var zeroAddress common.Address
if contractMetadataEth.Deployments.Op == zeroAddress {
return fmt.Errorf("no deployment address on Optimism provided for %s", contractMetadataEth.Name)
}
// Passing false here, because true will retrieve contract's ABI, but we don't need it for bytecode comparison
opContractData, err := generator.FetchContractData(false, "op", contractMetadataEth.Deployments.Op.Hex())
if err != nil {
return err
}
if opContractData.DeploymentTx.Input, err = generator.removeDeploymentSalt(opContractData.DeploymentTx.Input, contractMetadataEth.DeploymentSalt); err != nil {
return err
}
initCodeComparison := strings.EqualFold(contractMetadataEth.InitBin, opContractData.DeploymentTx.Input)
if initCodeShouldMatch && !initCodeComparison {
return fmt.Errorf(
"expected initialization bytecode to match on Ethereum and Optimism, but it doesn't. contract=%s bytecodeEth=%s bytecodeOp=%s",
contractMetadataEth.Name,
contractMetadataEth.InitBin,
opContractData.DeploymentTx.Input,
)
} else if !initCodeShouldMatch && initCodeComparison {
return fmt.Errorf(
"expected initialization bytecode on Ethereum to not match on Optimism, but it did. contract=%s bytecodeEth=%s bytecodeOp=%s",
contractMetadataEth.Name,
contractMetadataEth.InitBin,
opContractData.DeploymentTx.Input,
)
}
return nil
}
func (generator *BindGenGeneratorRemote) CompareDeployedBytecodeWithOp(contractMetadataEth *RemoteContractMetadata, deployedCodeShouldMatch bool) error {
if contractMetadataEth.DeployedBin == "" {
return fmt.Errorf("no deployed bytecode provided for ETH deployment for comparison")
}
var zeroAddress common.Address
if contractMetadataEth.Deployments.Op == zeroAddress {
return fmt.Errorf("no deployment address on Optimism provided for %s", contractMetadataEth.Name)
}
// Passing false here, because true will retrieve contract's ABI, but we don't need it for bytecode comparison
opContractData, err := generator.FetchContractData(false, "op", contractMetadataEth.Deployments.Op.Hex())
if err != nil {
return err
}
deployedCodeComparison := strings.EqualFold(contractMetadataEth.DeployedBin, opContractData.DeployedBin)
if deployedCodeShouldMatch && !deployedCodeComparison {
return fmt.Errorf(
"expected deployed bytecode to match on Ethereum and Optimism, but it doesn't. contract=%s bytecodeEth=%s bytecodeOp=%s",
contractMetadataEth.Name,
contractMetadataEth.DeployedBin,
opContractData.DeployedBin,
)
} else if !deployedCodeShouldMatch && deployedCodeComparison {
return fmt.Errorf(
"expected deployed bytecode on Ethereum to not match on Optimism, but it does. contract=%s bytecodeEth=%s bytecodeOp=%s",
contractMetadataEth.Name,
contractMetadataEth.DeployedBin,
opContractData.DeployedBin,
)
}
return nil
}
func (generator *BindGenGeneratorRemote) CompareDeployedBytecodeWithRpc(contractMetadata *RemoteContractMetadata, chain string) error {
var client *ethclient.Client
switch chain {
case "eth":
client = generator.RpcClients.Eth
case "op":
client = generator.RpcClients.Op
default:
return fmt.Errorf("unknown chain: %s, unable to retrieve a RPC client", chain)
}
var deployment common.Address
switch chain {
case "eth":
deployment = contractMetadata.Deployments.Eth
case "op":
deployment = contractMetadata.Deployments.Op
default:
generator.Logger.Warn("Unable to compare bytecode from Etherscan against RPC client, no deployment address provided for chain", "chain", chain)
}
if deployment != (common.Address{}) {
bytecode, err := client.CodeAt(context.Background(), common.HexToAddress(deployment.Hex()), nil)
if err != nil {
return fmt.Errorf("error getting deployed bytecode from RPC on chain: %s err: %w", chain, err)
}
bytecodeHex := common.Bytes2Hex(bytecode)
if !strings.EqualFold(strings.TrimPrefix(contractMetadata.DeployedBin, "0x"), bytecodeHex) {
return fmt.Errorf("%s deployment bytecode from RPC doesn't match bytecode from Etherscan. rpcBytecode: %s etherscanBytecode: %s", contractMetadata.Name, bytecodeHex, contractMetadata.DeployedBin)
}
}
return nil
}
func (generator *BindGenGeneratorRemote) writeAllOutputs(contractMetadata *RemoteContractMetadata, fileTemplate string) error {
abiFilePath, bytecodeFilePath, err := writeContractArtifacts(
generator.Logger, generator.tempArtifactsDir, contractMetadata.Name,
[]byte(contractMetadata.ABI), []byte(contractMetadata.InitBin),
)
if err != nil {
return err
}
err = genContractBindings(generator.Logger, generator.MonorepoBasePath, abiFilePath, bytecodeFilePath, generator.BindingsPackageName, contractMetadata.Name)
if err != nil {
return err
}
return generator.writeContractMetadata(
contractMetadata,
template.Must(template.New("RemoteContractMetadata").Parse(fileTemplate)),
)
}
func (generator *BindGenGeneratorRemote) writeContractMetadata(contractMetadata *RemoteContractMetadata, fileTemplate *template.Template) error {
metadataFilePath := filepath.Join(generator.MetadataOut, strings.ToLower(contractMetadata.Name)+"_more.go")
var existingOutput []byte
if _, err := os.Stat(metadataFilePath); err == nil {
existingOutput, err = os.ReadFile(metadataFilePath)
if err != nil {
return fmt.Errorf("error reading existing metadata output file, metadataFilePath: %s err: %w", metadataFilePath, err)
}
}
metadataFile, err := os.OpenFile(
metadataFilePath,
os.O_RDWR|os.O_CREATE|os.O_TRUNC,
0o600,
)
if err != nil {
return fmt.Errorf("error opening %s's metadata file at %s: %w", contractMetadata.Name, metadataFilePath, err)
}
defer metadataFile.Close()
if err := fileTemplate.Execute(metadataFile, contractMetadata); err != nil {
return fmt.Errorf("error writing %s's contract metadata at %s: %w", contractMetadata.Name, metadataFilePath, err)
}
if len(existingOutput) != 0 {
var newOutput []byte
newOutput, err = os.ReadFile(metadataFilePath)
if err != nil {
return fmt.Errorf("error reading new file: %w", err)
}
if bytes.Equal(existingOutput, newOutput) {
generator.Logger.Debug("No changes detected in the contract metadata", "contract", contractMetadata.Name)
} else {
generator.Logger.Warn("Changes detected in the contract metadata, old metadata has been overwritten", "contract", contractMetadata.Name)
}
} else {
generator.Logger.Debug("No existing contract metadata found, skipping comparison", "contract", contractMetadata.Name)
}
generator.Logger.Debug("Successfully wrote contract metadata", "contract", contractMetadata.Name, "path", metadataFilePath)
return nil
}
// remoteContractMetadataTemplate is a Go text template for generating the metadata
// associated with a remotely sourced contracts.
//
// The template expects the following data to be provided:
// - .Package: the name of the Go package.
// - .Name: the name of the contract.
// - .DeployedBin: the binary (hex-encoded) of the deployed contract.
var remoteContractMetadataTemplate = `// Code generated - DO NOT EDIT.
// This file is a generated binding and any manual changes will be lost.
package {{.Package}}
var {{.Name}}DeployedBin = "{{.DeployedBin}}"
func init() {
deployedBytecodes["{{.Name}}"] = {{.Name}}DeployedBin
}
`
// permit2MetadataTemplate is a Go text template used to generate metadata
// for remotely sourced Permit2 contract. Because Permit2 has an immutable
// Solidity variables that depends on block.chainid, we can't use the deployed
// bytecode, but instead need to generate it specifically for each chain.
// To help with this, the metadata contains the initialization bytecode, the
// deployer address, and the CREATE2 salt, so that deployment can be
// replicated as closely as possible.
//
// The template expects the following data to be provided:
// - .Package: the name of the Go package.
// - .Name: the name of the contract.
// - .InitBin: the binary (hex-encoded) of the contract's initialization code.
// - .DeploymentSalt: the salt used during the contract's deployment.
// - .Deployer: the Ethereum address of the contract's deployer.
var permit2MetadataTemplate = `// Code generated - DO NOT EDIT.
// This file is a generated binding and any manual changes will be lost.
package {{.Package}}
var {{.Name}}InitBin = "{{.InitBin}}"
var {{.Name}}DeploymentSalt = "{{.DeploymentSalt}}"
var {{.Name}}Deployer = "{{.Deployer}}"
func init() {
initBytecodes["{{.Name}}"] = {{.Name}}InitBin
deploymentSalts["{{.Name}}"] = {{.Name}}DeploymentSalt
deployers["{{.Name}}"] = {{.Name}}Deployer
}
`