github.com/hardtosaygoodbye/go-ethereum@v1.10.16-0.20220122011429-97003b9e6c15/eth/catalyst/api.go (about) 1 // Copyright 2020 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package catalyst implements the temporary eth1/eth2 RPC integration. 18 package catalyst 19 20 import ( 21 "crypto/sha256" 22 "encoding/binary" 23 "errors" 24 "fmt" 25 "math/big" 26 "time" 27 28 "github.com/hardtosaygoodbye/go-ethereum/common" 29 "github.com/hardtosaygoodbye/go-ethereum/consensus" 30 "github.com/hardtosaygoodbye/go-ethereum/consensus/beacon" 31 "github.com/hardtosaygoodbye/go-ethereum/consensus/misc" 32 "github.com/hardtosaygoodbye/go-ethereum/core" 33 "github.com/hardtosaygoodbye/go-ethereum/core/state" 34 "github.com/hardtosaygoodbye/go-ethereum/core/types" 35 "github.com/hardtosaygoodbye/go-ethereum/eth" 36 "github.com/hardtosaygoodbye/go-ethereum/les" 37 "github.com/hardtosaygoodbye/go-ethereum/log" 38 "github.com/hardtosaygoodbye/go-ethereum/node" 39 chainParams "github.com/hardtosaygoodbye/go-ethereum/params" 40 "github.com/hardtosaygoodbye/go-ethereum/rpc" 41 "github.com/hardtosaygoodbye/go-ethereum/trie" 42 ) 43 44 var ( 45 VALID = GenericStringResponse{"VALID"} 46 SUCCESS = GenericStringResponse{"SUCCESS"} 47 INVALID = ForkChoiceResponse{Status: "INVALID", PayloadID: nil} 48 SYNCING = ForkChoiceResponse{Status: "SYNCING", PayloadID: nil} 49 GenericServerError = rpc.CustomError{Code: -32000, ValidationError: "Server error"} 50 UnknownPayload = rpc.CustomError{Code: -32001, ValidationError: "Unknown payload"} 51 InvalidTB = rpc.CustomError{Code: -32002, ValidationError: "Invalid terminal block"} 52 ) 53 54 // Register adds catalyst APIs to the full node. 55 func Register(stack *node.Node, backend *eth.Ethereum) error { 56 log.Warn("Catalyst mode enabled", "protocol", "eth") 57 stack.RegisterAPIs([]rpc.API{ 58 { 59 Namespace: "engine", 60 Version: "1.0", 61 Service: NewConsensusAPI(backend, nil), 62 Public: true, 63 }, 64 }) 65 return nil 66 } 67 68 // RegisterLight adds catalyst APIs to the light client. 69 func RegisterLight(stack *node.Node, backend *les.LightEthereum) error { 70 log.Warn("Catalyst mode enabled", "protocol", "les") 71 stack.RegisterAPIs([]rpc.API{ 72 { 73 Namespace: "engine", 74 Version: "1.0", 75 Service: NewConsensusAPI(nil, backend), 76 Public: true, 77 }, 78 }) 79 return nil 80 } 81 82 type ConsensusAPI struct { 83 light bool 84 eth *eth.Ethereum 85 les *les.LightEthereum 86 engine consensus.Engine // engine is the post-merge consensus engine, only for block creation 87 preparedBlocks *payloadQueue // preparedBlocks caches payloads (*ExecutableDataV1) by payload ID (PayloadID) 88 } 89 90 func NewConsensusAPI(eth *eth.Ethereum, les *les.LightEthereum) *ConsensusAPI { 91 var engine consensus.Engine 92 if eth == nil { 93 if les.BlockChain().Config().TerminalTotalDifficulty == nil { 94 panic("Catalyst started without valid total difficulty") 95 } 96 if b, ok := les.Engine().(*beacon.Beacon); ok { 97 engine = beacon.New(b.InnerEngine()) 98 } else { 99 engine = beacon.New(les.Engine()) 100 } 101 } else { 102 if eth.BlockChain().Config().TerminalTotalDifficulty == nil { 103 panic("Catalyst started without valid total difficulty") 104 } 105 if b, ok := eth.Engine().(*beacon.Beacon); ok { 106 engine = beacon.New(b.InnerEngine()) 107 } else { 108 engine = beacon.New(eth.Engine()) 109 } 110 } 111 112 return &ConsensusAPI{ 113 light: eth == nil, 114 eth: eth, 115 les: les, 116 engine: engine, 117 preparedBlocks: newPayloadQueue(), 118 } 119 } 120 121 // blockExecutionEnv gathers all the data required to execute 122 // a block, either when assembling it or when inserting it. 123 type blockExecutionEnv struct { 124 chain *core.BlockChain 125 state *state.StateDB 126 tcount int 127 gasPool *core.GasPool 128 129 header *types.Header 130 txs []*types.Transaction 131 receipts []*types.Receipt 132 } 133 134 func (env *blockExecutionEnv) commitTransaction(tx *types.Transaction, coinbase common.Address) error { 135 vmConfig := *env.chain.GetVMConfig() 136 snap := env.state.Snapshot() 137 receipt, err := core.ApplyTransaction(env.chain.Config(), env.chain, &coinbase, env.gasPool, env.state, env.header, tx, &env.header.GasUsed, vmConfig) 138 if err != nil { 139 env.state.RevertToSnapshot(snap) 140 return err 141 } 142 env.txs = append(env.txs, tx) 143 env.receipts = append(env.receipts, receipt) 144 return nil 145 } 146 147 func (api *ConsensusAPI) makeEnv(parent *types.Block, header *types.Header) (*blockExecutionEnv, error) { 148 // The parent state might be missing. It can be the special scenario 149 // that consensus layer tries to build a new block based on the very 150 // old side chain block and the relevant state is already pruned. So 151 // try to retrieve the live state from the chain, if it's not existent, 152 // do the necessary recovery work. 153 var ( 154 err error 155 state *state.StateDB 156 ) 157 if api.eth.BlockChain().HasState(parent.Root()) { 158 state, err = api.eth.BlockChain().StateAt(parent.Root()) 159 } else { 160 // The maximum acceptable reorg depth can be limited by the 161 // finalised block somehow. TODO(rjl493456442) fix the hard- 162 // coded number here later. 163 state, err = api.eth.StateAtBlock(parent, 1000, nil, false, false) 164 } 165 if err != nil { 166 return nil, err 167 } 168 env := &blockExecutionEnv{ 169 chain: api.eth.BlockChain(), 170 state: state, 171 header: header, 172 gasPool: new(core.GasPool).AddGas(header.GasLimit), 173 } 174 return env, nil 175 } 176 177 func (api *ConsensusAPI) GetPayloadV1(payloadID PayloadID) (*ExecutableDataV1, error) { 178 log.Trace("Engine API request received", "method", "GetPayload", "id", payloadID) 179 data := api.preparedBlocks.get(payloadID) 180 if data == nil { 181 return nil, &UnknownPayload 182 } 183 return data, nil 184 } 185 186 func (api *ConsensusAPI) ForkchoiceUpdatedV1(heads ForkchoiceStateV1, PayloadAttributes *PayloadAttributesV1) (ForkChoiceResponse, error) { 187 log.Trace("Engine API request received", "method", "ForkChoiceUpdated", "head", heads.HeadBlockHash, "finalized", heads.FinalizedBlockHash, "safe", heads.SafeBlockHash) 188 if heads.HeadBlockHash == (common.Hash{}) { 189 return ForkChoiceResponse{Status: SUCCESS.Status, PayloadID: nil}, nil 190 } 191 if err := api.checkTerminalTotalDifficulty(heads.HeadBlockHash); err != nil { 192 if block := api.eth.BlockChain().GetBlockByHash(heads.HeadBlockHash); block == nil { 193 // TODO (MariusVanDerWijden) trigger sync 194 return SYNCING, nil 195 } 196 return INVALID, err 197 } 198 // If the finalized block is set, check if it is in our blockchain 199 if heads.FinalizedBlockHash != (common.Hash{}) { 200 if block := api.eth.BlockChain().GetBlockByHash(heads.FinalizedBlockHash); block == nil { 201 // TODO (MariusVanDerWijden) trigger sync 202 return SYNCING, nil 203 } 204 } 205 // SetHead 206 if err := api.setHead(heads.HeadBlockHash); err != nil { 207 return INVALID, err 208 } 209 // Assemble block (if needed) 210 if PayloadAttributes != nil { 211 data, err := api.assembleBlock(heads.HeadBlockHash, PayloadAttributes) 212 if err != nil { 213 return INVALID, err 214 } 215 id := computePayloadId(heads.HeadBlockHash, PayloadAttributes) 216 api.preparedBlocks.put(id, data) 217 log.Info("Created payload", "payloadID", id) 218 return ForkChoiceResponse{Status: SUCCESS.Status, PayloadID: &id}, nil 219 } 220 return ForkChoiceResponse{Status: SUCCESS.Status, PayloadID: nil}, nil 221 } 222 223 func computePayloadId(headBlockHash common.Hash, params *PayloadAttributesV1) PayloadID { 224 // Hash 225 hasher := sha256.New() 226 hasher.Write(headBlockHash[:]) 227 binary.Write(hasher, binary.BigEndian, params.Timestamp) 228 hasher.Write(params.Random[:]) 229 hasher.Write(params.SuggestedFeeRecipient[:]) 230 var out PayloadID 231 copy(out[:], hasher.Sum(nil)[:8]) 232 return out 233 } 234 235 func (api *ConsensusAPI) invalid() ExecutePayloadResponse { 236 if api.light { 237 return ExecutePayloadResponse{Status: INVALID.Status, LatestValidHash: api.les.BlockChain().CurrentHeader().Hash()} 238 } 239 return ExecutePayloadResponse{Status: INVALID.Status, LatestValidHash: api.eth.BlockChain().CurrentHeader().Hash()} 240 } 241 242 // ExecutePayloadV1 creates an Eth1 block, inserts it in the chain, and returns the status of the chain. 243 func (api *ConsensusAPI) ExecutePayloadV1(params ExecutableDataV1) (ExecutePayloadResponse, error) { 244 log.Trace("Engine API request received", "method", "ExecutePayload", params.BlockHash, "number", params.Number) 245 block, err := ExecutableDataToBlock(params) 246 if err != nil { 247 return api.invalid(), err 248 } 249 if api.light { 250 parent := api.les.BlockChain().GetHeaderByHash(params.ParentHash) 251 if parent == nil { 252 return api.invalid(), fmt.Errorf("could not find parent %x", params.ParentHash) 253 } 254 if err = api.les.BlockChain().InsertHeader(block.Header()); err != nil { 255 return api.invalid(), err 256 } 257 return ExecutePayloadResponse{Status: VALID.Status, LatestValidHash: block.Hash()}, nil 258 } 259 if !api.eth.BlockChain().HasBlock(block.ParentHash(), block.NumberU64()-1) { 260 /* 261 TODO (MariusVanDerWijden) reenable once sync is merged 262 if err := api.eth.Downloader().BeaconSync(api.eth.SyncMode(), block.Header()); err != nil { 263 return SYNCING, err 264 } 265 */ 266 // TODO (MariusVanDerWijden) we should return nil here not empty hash 267 return ExecutePayloadResponse{Status: SYNCING.Status, LatestValidHash: common.Hash{}}, nil 268 } 269 parent := api.eth.BlockChain().GetBlockByHash(params.ParentHash) 270 td := api.eth.BlockChain().GetTd(parent.Hash(), block.NumberU64()-1) 271 ttd := api.eth.BlockChain().Config().TerminalTotalDifficulty 272 if td.Cmp(ttd) < 0 { 273 return api.invalid(), fmt.Errorf("can not execute payload on top of block with low td got: %v threshold %v", td, ttd) 274 } 275 log.Trace("Inserting block without head", "hash", block.Hash(), "number", block.Number) 276 if err := api.eth.BlockChain().InsertBlockWithoutSetHead(block); err != nil { 277 return api.invalid(), err 278 } 279 280 if merger := api.merger(); !merger.TDDReached() { 281 merger.ReachTTD() 282 } 283 return ExecutePayloadResponse{Status: VALID.Status, LatestValidHash: block.Hash()}, nil 284 } 285 286 // AssembleBlock creates a new block, inserts it into the chain, and returns the "execution 287 // data" required for eth2 clients to process the new block. 288 func (api *ConsensusAPI) assembleBlock(parentHash common.Hash, params *PayloadAttributesV1) (*ExecutableDataV1, error) { 289 if api.light { 290 return nil, errors.New("not supported") 291 } 292 log.Info("Producing block", "parentHash", parentHash) 293 294 bc := api.eth.BlockChain() 295 parent := bc.GetBlockByHash(parentHash) 296 if parent == nil { 297 log.Warn("Cannot assemble block with parent hash to unknown block", "parentHash", parentHash) 298 return nil, fmt.Errorf("cannot assemble block with unknown parent %s", parentHash) 299 } 300 301 if params.Timestamp <= parent.Time() { 302 return nil, fmt.Errorf("invalid timestamp: child's %d <= parent's %d", params.Timestamp, parent.Time()) 303 } 304 if now := uint64(time.Now().Unix()); params.Timestamp > now+1 { 305 diff := time.Duration(params.Timestamp-now) * time.Second 306 log.Warn("Producing block too far in the future", "diff", common.PrettyDuration(diff)) 307 } 308 pending := api.eth.TxPool().Pending(true) 309 coinbase := params.SuggestedFeeRecipient 310 num := parent.Number() 311 header := &types.Header{ 312 ParentHash: parent.Hash(), 313 Number: num.Add(num, common.Big1), 314 Coinbase: coinbase, 315 GasLimit: parent.GasLimit(), // Keep the gas limit constant in this prototype 316 Extra: []byte{}, // TODO (MariusVanDerWijden) properly set extra data 317 Time: params.Timestamp, 318 MixDigest: params.Random, 319 } 320 if config := api.eth.BlockChain().Config(); config.IsLondon(header.Number) { 321 header.BaseFee = misc.CalcBaseFee(config, parent.Header()) 322 } 323 if err := api.engine.Prepare(bc, header); err != nil { 324 return nil, err 325 } 326 env, err := api.makeEnv(parent, header) 327 if err != nil { 328 return nil, err 329 } 330 var ( 331 signer = types.MakeSigner(bc.Config(), header.Number) 332 txHeap = types.NewTransactionsByPriceAndNonce(signer, pending, nil) 333 transactions []*types.Transaction 334 ) 335 for { 336 if env.gasPool.Gas() < chainParams.TxGas { 337 log.Trace("Not enough gas for further transactions", "have", env.gasPool, "want", chainParams.TxGas) 338 break 339 } 340 tx := txHeap.Peek() 341 if tx == nil { 342 break 343 } 344 345 // The sender is only for logging purposes, and it doesn't really matter if it's correct. 346 from, _ := types.Sender(signer, tx) 347 348 // Execute the transaction 349 env.state.Prepare(tx.Hash(), env.tcount) 350 err = env.commitTransaction(tx, coinbase) 351 switch err { 352 case core.ErrGasLimitReached: 353 // Pop the current out-of-gas transaction without shifting in the next from the account 354 log.Trace("Gas limit exceeded for current block", "sender", from) 355 txHeap.Pop() 356 357 case core.ErrNonceTooLow: 358 // New head notification data race between the transaction pool and miner, shift 359 log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce()) 360 txHeap.Shift() 361 362 case core.ErrNonceTooHigh: 363 // Reorg notification data race between the transaction pool and miner, skip account = 364 log.Trace("Skipping account with high nonce", "sender", from, "nonce", tx.Nonce()) 365 txHeap.Pop() 366 367 case nil: 368 // Everything ok, collect the logs and shift in the next transaction from the same account 369 env.tcount++ 370 txHeap.Shift() 371 transactions = append(transactions, tx) 372 373 default: 374 // Strange error, discard the transaction and get the next in line (note, the 375 // nonce-too-high clause will prevent us from executing in vain). 376 log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err) 377 txHeap.Shift() 378 } 379 } 380 // Create the block. 381 block, err := api.engine.FinalizeAndAssemble(bc, header, env.state, transactions, nil /* uncles */, env.receipts) 382 if err != nil { 383 return nil, err 384 } 385 return BlockToExecutableData(block, params.Random), nil 386 } 387 388 func encodeTransactions(txs []*types.Transaction) [][]byte { 389 var enc = make([][]byte, len(txs)) 390 for i, tx := range txs { 391 enc[i], _ = tx.MarshalBinary() 392 } 393 return enc 394 } 395 396 func decodeTransactions(enc [][]byte) ([]*types.Transaction, error) { 397 var txs = make([]*types.Transaction, len(enc)) 398 for i, encTx := range enc { 399 var tx types.Transaction 400 if err := tx.UnmarshalBinary(encTx); err != nil { 401 return nil, fmt.Errorf("invalid transaction %d: %v", i, err) 402 } 403 txs[i] = &tx 404 } 405 return txs, nil 406 } 407 408 func ExecutableDataToBlock(params ExecutableDataV1) (*types.Block, error) { 409 txs, err := decodeTransactions(params.Transactions) 410 if err != nil { 411 return nil, err 412 } 413 if len(params.ExtraData) > 32 { 414 return nil, fmt.Errorf("invalid extradata length: %v", len(params.ExtraData)) 415 } 416 number := big.NewInt(0) 417 number.SetUint64(params.Number) 418 header := &types.Header{ 419 ParentHash: params.ParentHash, 420 UncleHash: types.EmptyUncleHash, 421 Coinbase: params.FeeRecipient, 422 Root: params.StateRoot, 423 TxHash: types.DeriveSha(types.Transactions(txs), trie.NewStackTrie(nil)), 424 ReceiptHash: params.ReceiptsRoot, 425 Bloom: types.BytesToBloom(params.LogsBloom), 426 Difficulty: common.Big0, 427 Number: number, 428 GasLimit: params.GasLimit, 429 GasUsed: params.GasUsed, 430 Time: params.Timestamp, 431 BaseFee: params.BaseFeePerGas, 432 Extra: params.ExtraData, 433 MixDigest: params.Random, 434 } 435 block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */) 436 if block.Hash() != params.BlockHash { 437 return nil, fmt.Errorf("blockhash mismatch, want %x, got %x", params.BlockHash, block.Hash()) 438 } 439 return block, nil 440 } 441 442 func BlockToExecutableData(block *types.Block, random common.Hash) *ExecutableDataV1 { 443 return &ExecutableDataV1{ 444 BlockHash: block.Hash(), 445 ParentHash: block.ParentHash(), 446 FeeRecipient: block.Coinbase(), 447 StateRoot: block.Root(), 448 Number: block.NumberU64(), 449 GasLimit: block.GasLimit(), 450 GasUsed: block.GasUsed(), 451 BaseFeePerGas: block.BaseFee(), 452 Timestamp: block.Time(), 453 ReceiptsRoot: block.ReceiptHash(), 454 LogsBloom: block.Bloom().Bytes(), 455 Transactions: encodeTransactions(block.Transactions()), 456 Random: random, 457 ExtraData: block.Extra(), 458 } 459 } 460 461 // Used in tests to add a the list of transactions from a block to the tx pool. 462 func (api *ConsensusAPI) insertTransactions(txs types.Transactions) error { 463 for _, tx := range txs { 464 api.eth.TxPool().AddLocal(tx) 465 } 466 return nil 467 } 468 469 func (api *ConsensusAPI) checkTerminalTotalDifficulty(head common.Hash) error { 470 // shortcut if we entered PoS already 471 if api.merger().PoSFinalized() { 472 return nil 473 } 474 // make sure the parent has enough terminal total difficulty 475 newHeadBlock := api.eth.BlockChain().GetBlockByHash(head) 476 if newHeadBlock == nil { 477 return &GenericServerError 478 } 479 td := api.eth.BlockChain().GetTd(newHeadBlock.Hash(), newHeadBlock.NumberU64()) 480 if td != nil && td.Cmp(api.eth.BlockChain().Config().TerminalTotalDifficulty) < 0 { 481 return &InvalidTB 482 } 483 return nil 484 } 485 486 // setHead is called to perform a force choice. 487 func (api *ConsensusAPI) setHead(newHead common.Hash) error { 488 log.Info("Setting head", "head", newHead) 489 if api.light { 490 headHeader := api.les.BlockChain().CurrentHeader() 491 if headHeader.Hash() == newHead { 492 return nil 493 } 494 newHeadHeader := api.les.BlockChain().GetHeaderByHash(newHead) 495 if newHeadHeader == nil { 496 return &GenericServerError 497 } 498 if err := api.les.BlockChain().SetChainHead(newHeadHeader); err != nil { 499 return err 500 } 501 // Trigger the transition if it's the first `NewHead` event. 502 merger := api.merger() 503 if !merger.PoSFinalized() { 504 merger.FinalizePoS() 505 } 506 return nil 507 } 508 headBlock := api.eth.BlockChain().CurrentBlock() 509 if headBlock.Hash() == newHead { 510 return nil 511 } 512 newHeadBlock := api.eth.BlockChain().GetBlockByHash(newHead) 513 if newHeadBlock == nil { 514 return &GenericServerError 515 } 516 if err := api.eth.BlockChain().SetChainHead(newHeadBlock); err != nil { 517 return err 518 } 519 // Trigger the transition if it's the first `NewHead` event. 520 if merger := api.merger(); !merger.PoSFinalized() { 521 merger.FinalizePoS() 522 } 523 // TODO (MariusVanDerWijden) are we really synced now? 524 api.eth.SetSynced() 525 return nil 526 } 527 528 // Helper function, return the merger instance. 529 func (api *ConsensusAPI) merger() *consensus.Merger { 530 if api.light { 531 return api.les.Merger() 532 } 533 return api.eth.Merger() 534 }