Optimism 백서

Optimism

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 42쪽

single smart contract, adding one new file to `op-node`, and modifying one existing file inside `op-node`. It'll be painless. Let's go! ## Deploy the burn contract You're going to use a smart contract on your Rollup to store the reports that the `op-node` makes about the L1 burn. Here's the code for your smart contract: ```solidity theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title L1Burn * @notice L1Burn keeps track of the total amount of ETH burned on L1. */ contract L1Burn { /** * @notice Total amount of ETH burned on L1. */ uint256 public total; /** * @notice Mapping of block numbers to total burn. */ mapping (uint64 => uint256) public reports; /** * @notice Allows the system address to submit a report. * * @param _blocknum L1 block number the report corresponds to. * @param _burn Amount of ETH burned in the block. */ function report(uint64 _blocknum, uint64 _burn) external { require( msg.sender == 0xDeaDDEaDDeAdDeAdDEAdDEaddeAddEAdDEAd0001, "L1Burn: reports can only be made from system address" ); total += _burn; reports[_blocknum] = total; } /** * @notice Tallies up the total burn since a given block number. * * @param _blocknum L1 block number to tally from. * * @return Total amount of ETH burned since the given block number; */ function tally(uint64 _blocknum) external view returns (uint256) { return total - reports[_blocknum]; } } ``` Deploy this smart contract to your L2 (using any tool you find convenient). Make a note of the address that the contract is deployed to because you'll need it in a minute. Simple! ## Add the burn transaction Now you need to add logic to the `op-node` to automatically submit a burn report whenever an L1 block is produced. Since this transaction is very similar to the system transaction that reports other L1 block info (found in [l1\_block\_info.go](https://github.com/ethereum-optimism/optimism/blob/develop/op-node/rollup/derive/l1_block_info.go)), you'll use that transaction as a jumping-off point. <Steps> <Step title="Navigate to the `op-node` package:"> ```bash theme={null} cd ~/optimism/op-node ``` </Step> <Step title="Inside of the folder `rollup/derive`, create a new file called `l1_burn_info.go`:"> ```bash theme={null} touch rollup/derive/l1_burn_info.go ``` </Step> <Step title="Paste the following into `l1_burn_info.go`, and make sure to replace `YOUR_BURN_CONTRACT_HERE` with the address of the `L1Burn` contract you just deployed."> ```go theme={null} package derive import ( "bytes" "encoding/binary" "fmt" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum-optimism/optimism/op-node/eth" ) const ( L1BurnFuncSignature = "report(uint64,uint64)" L1BurnArguments = 2 L1BurnLen = 4 + 32*L1BurnArguments ) var ( L1BurnFuncBytes4 = crypto.Keccak256([]byte(L1BurnFuncSignature))[:4] L1BurnAddress = common.HexToAddress("YOUR_BURN_CONTRACT_HERE") ) type L1BurnInfo struct { Number uint64 Burn uint64 } func (info *L1BurnInfo) MarshalBinary() ([]byte, error) { data := make([]byte, L1BurnLen) offset := 0 copy(data[offset:4], L1BurnFuncBytes4) offset += 4 binary.BigEndian.PutUint64(data[offset+24:offset+32], info.Number) offset += 32 binary.BigEndian.PutUint64(data[offset+24:offset+32], info.Burn) return data, nil } func (info *L1BurnInfo) UnmarshalBinary(data []byte) error { if len(data) != L1InfoLen { return fmt.Errorf("data is unexpected length: %d", len(data)) } var padding [24]byte offset := 4 info.Number = binary.BigEndian.Uint64(data[offset+24 : offset+32]) if !bytes.Equal(data[offset:offset+24], padding[:]) { return fmt.Errorf("l1 burn tx number exceeds uint64 bounds: %x", data[offset:offset+32]) } offset += 32 info.Burn = binary.BigEndian.Uint64(data[offset+24 : offset+32]) if !bytes.Equal(data[offset:offset+24], padding[:]) { return fmt.Errorf("l1 burn tx burn exceeds uint64 bounds: %x", data[offset:offset+32]) } return nil } func L1BurnDepositTxData(data []byte) (L1BurnInfo, error) { var info L1BurnInfo err := info.UnmarshalBinary(data) return info, err } func L1BurnDeposit(seqNumber uint64, block eth.BlockInfo, sysCfg eth.SystemConfig) (*types.DepositTx, error) { infoDat := L1BurnInfo{ Number: block.NumberU64(), Burn: block.BaseFee().Uint64() * block.GasUsed(), } data, err := infoDat.MarshalBinary() if err != nil { return nil, err } source := L1InfoDepositSource{ L1BlockHash: block.Hash(), SeqNumber: seqNumber, } return &types.DepositTx{ SourceHash: source.SourceHash(), From: L1InfoDepositerAddress, To: &L1BurnAddress, Mint: nil, Value: big.NewInt(0), Gas: 150_000_000, IsSystemTransaction: true, Data: data, }, nil } func L1BurnDepositBytes(seqNumber uint64, l1Info eth.BlockInfo, sysCfg eth.SystemConfig) ([]byte, error) { dep, err := L1BurnDeposit(seqNumber, l1Info, sysCfg) if err != nil { return nil, fmt.Errorf("failed to create L1 burn tx: %w", err) } l1Tx := types.NewTx(dep) opaqueL1Tx, err := l1Tx.MarshalBinary() if err != nil { return nil, fmt.Errorf("failed to encode L1 burn tx: %w", err) } return opaqueL1Tx, nil } ``` Feel free to take a look at this file if you're interested. It's relatively simple, mainly just defining a new transaction type and describing how the transaction should be encoded. </Step> </Steps> ## Insert the burn transactions Finally, you'll need to update `~/optimism/op-node/rollup/derive/attributes.go` to insert the new burn transaction into every block. You'll need to make the following changes: <Steps> <Step title="Find these lines:"> ```go theme={null} l1InfoTx, err := L1InfoDepositBytes(seqNumber, l1Info, sysConfig) if err != nil { return nil, NewCriticalError(fmt.Errorf("failed to create l1InfoTx: %w", err)) } ``` </Step> <Step title="After those lines, add this code fragment:"> ```go theme={null} l1BurnTx, err := L1BurnDepositBytes(seqNumber, l1Info, sysConfig) if err != nil { return nil, NewCriticalError(fmt.Errorf("failed to create l1InfoTx: %w", err)) } ``` </Step> <Step title="Immediately following, change these lines:"> ```go theme={null} txs := make([]hexutil.Bytes, 0, 1+len(depositTxs)) txs = append(txs, l1InfoTx) ``` to ```go theme={null} txs := make([]hexutil.Bytes, 0, 2+len(depositTxs)) txs = append(txs, l1InfoTx) txs = append(txs, l1BurnTx) ``` All you're doing here is creating a new burn transaction after every `l1InfoTx` and inserting it into every block. </Step> </Steps> ## Rebuild your op-node Before you can see this change take effect, you'll need to rebuild your `op-node`: ```bash theme={null} cd ~/optimism/op-node make op-node ``` Now start your `op-node` if it isn't running or restart your `op-node` if it's already running. You should see the change immediately — new blocks will contain two system transactions instead of just one! ## Checking the result Query the `total` function of your contract, you should also start to see the total slowly increasing. Play around with the `tally` function to grab the amount of gas burned since a given L2 block. You could use this to implement a version of [ultrasound.money](http://ultrasound.money) that keeps track of things with an OP Stack as a backend. One way to get the total is to run these commands: ```bash theme={null} export ETH_RPC_URL=http://localhost:8545 cast call <YOUR_BURN_CONTRACT_HERE> "total()" | cast --from-wei ``` ## Conclusion With just a few tiny changes to the `op-node`, you were just able to implement a change to the OP Stack that allows you to keep track of the L1 ETH burn on L2. With a live Cannon Fault Proof System, you should not only be able to track the L1 burn on L2, you should be able to *prove* the burn to contracts back on L1. That's crazy! The OP Stack is an extremely powerful platform that allows you to perform a large amount of computation trustlessly. It's a superpower for smart contracts. Tracking the L1 burn is just one of the many, many wild things you can do with the OP Stack. If you're looking for inspiration or you want to see what others are building on the OP Stack, check out the OP Stack Hacks page. Maybe you'll find a project you want to work on, or maybe you'll get the inspiration you need to build the next killer smart contract. # Adding a precompile Source: https://docs.optimism.io/chain-operators/tutorials/adding-precompiles Learn how to run an EVM with a new precompile for OP Stack chain operations to speed up calculations that are not currently supported. <Info> OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use. OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks. Be prepared to get your hands dirty and to work without support. </Info> One possible use of OP Stack is to run an EVM with a new precompile for operations to speed up calculations that are not currently supported. In this tutorial, you'll make a simple precompile that returns a constant value if it's called with four or less bytes, or an error if it is called with more than that. To create a new precompile, the file to modify is [`op-geth/core/vm/contracts.go`](https://github.com/ethereum-optimism/op-geth/blob/optimism-history/core/vm/contracts.go). <Steps> <Step title="Add to `PrecompiledContractsBerlin` on line 82 (or a later fork, if the list of precompiles changes again)"> * add a structure named after your new precompile, and * use an address that is unlikely to ever clash with a standard precompile and avoids the [EIP-7587](https://eips.ethereum.org/EIPS/eip-7587) reserved range (0x1337, for example): ```go theme={null} common.BytesToAddress([]byte{0x13,0x37}): &retConstant{}, ``` </Step> <Step title="Add the lines for the precompile"> ```go theme={null} type retConstant struct{} func (c *retConstant) RequiredGas(input []byte) uint64 { return uint64(1024) } var ( errConstInvalidInputLength = errors.New("invalid input length") ) func (c *retConstant) Run(input []byte) ([]byte, error) { // Only allow input up to four bytes (function signature) if len(input) > 4 { return nil, errConstInvalidInputLength } output := make([]byte, 6) for i := 0; i < 6; i++ { output[i] = byte(64+i) } return output, nil } ``` </Step> <Step title="Stop `op-geth` and recompile:"> ```bash theme={null} cd ~/op-geth make geth ``` </Step> <Step title="Restart `op-geth`" /> <Step title="Run these commands to see the result of calling the precompile successfully, and the result of an error:"> ```bash theme={null} cast call 0x0000000000000000000000000000000000001337 "whatever()" cast call 0x0000000000000000000000000000000000001337 "whatever(string)" "fail" ``` </Step> </Steps> ## How does it work? This is the precompile interface definition: ```go theme={null} type PrecompiledContract interface { RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use Run(input []byte) ([]byte, error) // Run runs the precompiled contract } ``` It means that for every precompile you need two functions: * `RequiredGas` which returns the gas cost for the call. This function takes an array of bytes as input, and returns a single value, the gas cost. * `Run` which runs the actual precompile. This function also takes an array of bytes, but it returns two values: the call's output (a byte array) and an error. For every fork that changes the precompiles you have a [`map`](https://www.w3schools.com/go/go_maps.php) from addresses to the `PrecompiledContract` definitions: ```go theme={null} // PrecompiledContractsBerlin contains the default set of pre-compiled Ethereum // contracts used in the Berlin release. var PrecompiledContractsBerlin = map[common.Address]PrecompiledContract{ common.BytesToAddress([]byte{1}): &ecrecover{}, . . . common.BytesToAddress([]byte{9}): &blake2F{}, common.BytesToAddress([]byte{0x13,0x37}): &retConstant{}, } ``` The key of the map is an address. You create those from bytes using `common.BytesToAddress([]byte{<bytes to convert to address go here>})`. In this case you have two bytes, `0x13` and `0x37`. Together you get the address `0x0…1337`. The syntax for a precompiled contract interface is `&<variable name>{}`. The next step is to define the precompiled contract itself. ```go theme={null} type retConstant struct{} ``` First you create a structure for the precompile. ```go theme={null} func (c *retConstant) RequiredGas(input []byte) uint64 { return uint64(1024) } ``` Then you define a function as part of that structure. Here you just require a constant amount of gas, but of course the calculation can be a lot more sophisticated. ```go theme={null} var ( errConstInvalidInputLength = errors.New("invalid input length") ) ``` Next you define a variable for the error. ```go theme={null} func (c *retConstant) Run(input []byte) ([]byte, error) { ``` This is the function that actually executes the precompile. ```go theme={null} // Only allow input up to four bytes (function signature) if len(input) > 4 { return nil, errConstInvalidInputLength } ``` Return an error if warranted. The reason this precompile allows up to four bytes of input is that any standard call (for example, using `cast`) is going to have at least four bytes for the function signature. `return a, b` is the way we return two values from a function in Go. The normal output is `nil`, nothing, because we return an error. ```go theme={null} output := make([]byte, 6) for i := 0; i < 6; i++ { output[i] = byte(64+i) } return output, nil } ``` Finally, you create the output buffer, fill it, and then return it. ## Conclusion An OP Stack chain with additional precompiles can be useful, for example, to further reduce the computational effort required for cryptographic operations by moving them from interpreted EVM code to compiled Go code. # Generating an op-program absolute prestate (archived) Source: https://docs.optimism.io/chain-operators/tutorials/archive/op-program-prestate Archived: legacy op-program prestate generation flow for chains resolving in-flight CANNON game type 1 disputes. <Warning> **Archived.** As of [Upgrade 19](/notices/archive/upgrade-19), `CANNON_KONA` (game type `8`) is the respected game type for permissionless fault proofs and `op-program` (game type `0`, `CANNON`) is no longer supported for new fault proofs. This page is retained only for chains that still need to resolve in-flight `CANNON` games created before Upgrade 19. For all current work, see [Generating absolute prestate and preimage files](/chain-operators/tutorials/absolute-prestate) (kona-client) and, if your chain is not yet in the Superchain Registry, [Generating a custom kona-client absolute prestate](/chain-operators/tutorials/kona-custom-prestate). </Warning> ## Overview Permissionless fault proofs are a critical component of the OP Stack's security model. They allow anyone to challenge invalid state proposals, ensuring the correctness of L2 to L1 withdrawals without relying on trusted third parties. To enable this functionality, chain operators must generate and maintain the necessary absolute prestate and preimage files. The absolute prestate is a commitment to the initial state of the fault proof program, and the preimage is the serialized binary representation of this program state. These files are essential for the op-challenger tool to participate in dispute games when challenging invalid claims. ## Prerequisites Before starting, ensure you have: * [Docker](https://docs.docker.com/engine/install/) running ## Official prestate hashes for superchain-registry chains The superchain-registry maintains official absolute prestate hashes for chains that are part of the registry. These prestates include the configurations of chains that were in the superchain-registry at the time the prestate was created. <Info> Important: A prestate listed in the superchain-registry may not be suitable for your chain if: * Your chain was added to the registry after the prestate was created * The configuration for your chain has been updated since the prestate was created Before using a prestate from the registry, verify that it contains the latest configuration for your chain. When in doubt, generating your own prestate with your specific chain configuration is the safest approach. </Info> You can find the latest prestate tags in the [Superchain registry](https://github.com/ethereum-optimism/superchain-registry/blob/main/validation/standard/standard-prestates.toml). ## Generating the absolute prestate <Steps> <Step title="Clone and checkout the tagged version"> First, clone the Optimism monorepo and check out the appropriate [release tag](https://github.com/ethereum-optimism/optimism/tags) for op-program: ```bash theme={null} git clone https://github.com/ethereum-optimism/optimism.git cd optimism # Check out the op-program version that matches the in-flight CANNON game you # need to resolve. Use the version the game's original prestate was generated with. git checkout op-program/v1.6.1 ``` </Step> <Step title="(Optional) Provide chain configuration and genesis files"> For chains that are not included in the superchain-registry, you'll need to provide the chain rollup configuration file and the L2 genesis file. Add the `rollup.json` and `l2-genesis.json` to the monorepo at `optimism/op-program/chainconfig/configs/<L2_CHAIN_ID>-rollup.json` and `optimism/op-program/chainconfig/configs/<L2_CHAIN_ID>-genesis-l2.json` respectively. </Step> <Step title="Generate the absolute prestate"> Run the following command from the root of the monorepo: ```bash theme={null} make reproducible-prestate ``` You should see the following logs at the end of the command’s output: ```log theme={null} -------------------- Production Prestates -------------------- Cannon64 Absolute prestate hash: 0x03eb07101fbdeaf3f04d9fb76526362c1eea2824e4c6e970bdb19675b72e4fc8 -------------------- Experimental Prestates -------------------- CannonInterop Absolute prestate hash: 0x03fc3b4d091527d53f1ff369ea8ed65e5e17cc7fc98ebf75380238151cdc949c Cannon64Next Absolute prestate hash: 0x03eb07101fbdeaf3f04d9fb76526362c1eea2824e4c6e970bdb19675b72e4fc8 ``` The output will display production and experimental prestate hashes: * **Production prestates**: Contains the `Cannon64` prestate, which is the current production absolute prestate hash for the 64-bit version of Cannon. This is the hash you should use for permissionless fault proofs. * **Experimental prestates**: These contain prestates for versions that are in development and not yet ready for production use. </Step> <Step title="Prepare the preimage file"> After generating the prestate, the preimage file will be located in `op-program/bin/prestate-mt64.bin.gz`. The exact name might vary based on the version. Rename this file to include the prestate hash: ```bash theme={null} cd op-program/bin mv prestate-mt64.bin.gz <cannon64-prestate-hash>.bin.gz ``` Replace `<cannon64-prestate-hash>` with the actual `Cannon64` absolute prestate hash value from the output. This file needs to be uploaded to a location that's accessible by your op-challenger instances. </Step> </Steps> ## Deploying and configuring with the absolute prestate After generating the absolute prestate and preimage files, you'll need to: <Steps> <Step title="Upload preimage file"> Upload the preimage file to a location accessible by your op-challenger instances </Step> <Step title="Configure op-challenger"> Configure the op-challenger to use the generated prestate. There are two ways to provide prestates: </Step> </Steps> <Steps> <Step title="Option 1: Using HTTP URL"> If your prestate files are
프로젝트로 돌아가기