api.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. // Package catalyst implements the temporary eth1/eth2 RPC integration.
  17. package catalyst
  18. import (
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/state"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/eth"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/node"
  30. chainParams "github.com/ethereum/go-ethereum/params"
  31. "github.com/ethereum/go-ethereum/rpc"
  32. "github.com/ethereum/go-ethereum/trie"
  33. )
  34. // Register adds catalyst APIs to the node.
  35. func Register(stack *node.Node, backend *eth.Ethereum) error {
  36. chainconfig := backend.BlockChain().Config()
  37. if chainconfig.CatalystBlock == nil {
  38. return errors.New("catalystBlock is not set in genesis config")
  39. } else if chainconfig.CatalystBlock.Sign() != 0 {
  40. return errors.New("catalystBlock of genesis config must be zero")
  41. }
  42. log.Warn("Catalyst mode enabled")
  43. stack.RegisterAPIs([]rpc.API{
  44. {
  45. Namespace: "consensus",
  46. Version: "1.0",
  47. Service: newConsensusAPI(backend),
  48. Public: true,
  49. },
  50. })
  51. return nil
  52. }
  53. type consensusAPI struct {
  54. eth *eth.Ethereum
  55. }
  56. func newConsensusAPI(eth *eth.Ethereum) *consensusAPI {
  57. return &consensusAPI{eth: eth}
  58. }
  59. // blockExecutionEnv gathers all the data required to execute
  60. // a block, either when assembling it or when inserting it.
  61. type blockExecutionEnv struct {
  62. chain *core.BlockChain
  63. state *state.StateDB
  64. tcount int
  65. gasPool *core.GasPool
  66. header *types.Header
  67. txs []*types.Transaction
  68. receipts []*types.Receipt
  69. }
  70. func (env *blockExecutionEnv) commitTransaction(tx *types.Transaction, coinbase common.Address) error {
  71. vmconfig := *env.chain.GetVMConfig()
  72. receipt, err := core.ApplyTransaction(env.chain.Config(), env.chain, &coinbase, env.gasPool, env.state, env.header, tx, &env.header.GasUsed, vmconfig)
  73. if err != nil {
  74. return err
  75. }
  76. env.txs = append(env.txs, tx)
  77. env.receipts = append(env.receipts, receipt)
  78. return nil
  79. }
  80. func (api *consensusAPI) makeEnv(parent *types.Block, header *types.Header) (*blockExecutionEnv, error) {
  81. state, err := api.eth.BlockChain().StateAt(parent.Root())
  82. if err != nil {
  83. return nil, err
  84. }
  85. env := &blockExecutionEnv{
  86. chain: api.eth.BlockChain(),
  87. state: state,
  88. header: header,
  89. gasPool: new(core.GasPool).AddGas(header.GasLimit),
  90. }
  91. return env, nil
  92. }
  93. // AssembleBlock creates a new block, inserts it into the chain, and returns the "execution
  94. // data" required for eth2 clients to process the new block.
  95. func (api *consensusAPI) AssembleBlock(params assembleBlockParams) (*executableData, error) {
  96. log.Info("Producing block", "parentHash", params.ParentHash)
  97. bc := api.eth.BlockChain()
  98. parent := bc.GetBlockByHash(params.ParentHash)
  99. if parent == nil {
  100. log.Warn("Cannot assemble block with parent hash to unknown block", "parentHash", params.ParentHash)
  101. return nil, fmt.Errorf("cannot assemble block with unknown parent %s", params.ParentHash)
  102. }
  103. pool := api.eth.TxPool()
  104. if parent.Time() >= params.Timestamp {
  105. return nil, fmt.Errorf("child timestamp lower than parent's: %d >= %d", parent.Time(), params.Timestamp)
  106. }
  107. if now := uint64(time.Now().Unix()); params.Timestamp > now+1 {
  108. wait := time.Duration(params.Timestamp-now) * time.Second
  109. log.Info("Producing block too far in the future", "wait", common.PrettyDuration(wait))
  110. time.Sleep(wait)
  111. }
  112. pending, err := pool.Pending()
  113. if err != nil {
  114. return nil, err
  115. }
  116. coinbase, err := api.eth.Etherbase()
  117. if err != nil {
  118. return nil, err
  119. }
  120. num := parent.Number()
  121. header := &types.Header{
  122. ParentHash: parent.Hash(),
  123. Number: num.Add(num, common.Big1),
  124. Coinbase: coinbase,
  125. GasLimit: parent.GasLimit(), // Keep the gas limit constant in this prototype
  126. Extra: []byte{},
  127. Time: params.Timestamp,
  128. }
  129. err = api.eth.Engine().Prepare(bc, header)
  130. if err != nil {
  131. return nil, err
  132. }
  133. env, err := api.makeEnv(parent, header)
  134. if err != nil {
  135. return nil, err
  136. }
  137. var (
  138. signer = types.MakeSigner(bc.Config(), header.Number)
  139. txHeap = types.NewTransactionsByPriceAndNonce(signer, pending)
  140. transactions []*types.Transaction
  141. )
  142. for {
  143. if env.gasPool.Gas() < chainParams.TxGas {
  144. log.Trace("Not enough gas for further transactions", "have", env.gasPool, "want", chainParams.TxGas)
  145. break
  146. }
  147. tx := txHeap.Peek()
  148. if tx == nil {
  149. break
  150. }
  151. // The sender is only for logging purposes, and it doesn't really matter if it's correct.
  152. from, _ := types.Sender(signer, tx)
  153. // Execute the transaction
  154. env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount)
  155. err = env.commitTransaction(tx, coinbase)
  156. switch err {
  157. case core.ErrGasLimitReached:
  158. // Pop the current out-of-gas transaction without shifting in the next from the account
  159. log.Trace("Gas limit exceeded for current block", "sender", from)
  160. txHeap.Pop()
  161. case core.ErrNonceTooLow:
  162. // New head notification data race between the transaction pool and miner, shift
  163. log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  164. txHeap.Shift()
  165. case core.ErrNonceTooHigh:
  166. // Reorg notification data race between the transaction pool and miner, skip account =
  167. log.Trace("Skipping account with high nonce", "sender", from, "nonce", tx.Nonce())
  168. txHeap.Pop()
  169. case nil:
  170. // Everything ok, collect the logs and shift in the next transaction from the same account
  171. env.tcount++
  172. txHeap.Shift()
  173. transactions = append(transactions, tx)
  174. default:
  175. // Strange error, discard the transaction and get the next in line (note, the
  176. // nonce-too-high clause will prevent us from executing in vain).
  177. log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  178. txHeap.Shift()
  179. }
  180. }
  181. // Create the block.
  182. block, _, err := api.eth.Engine().FinalizeAndAssemble(bc, header, env.state, transactions, nil /* uncles */, env.receipts)
  183. if err != nil {
  184. return nil, err
  185. }
  186. return &executableData{
  187. BlockHash: block.Hash(),
  188. ParentHash: block.ParentHash(),
  189. Miner: block.Coinbase(),
  190. StateRoot: block.Root(),
  191. Number: block.NumberU64(),
  192. GasLimit: block.GasLimit(),
  193. GasUsed: block.GasUsed(),
  194. Timestamp: block.Time(),
  195. ReceiptRoot: block.ReceiptHash(),
  196. LogsBloom: block.Bloom().Bytes(),
  197. Transactions: encodeTransactions(block.Transactions()),
  198. }, nil
  199. }
  200. func encodeTransactions(txs []*types.Transaction) [][]byte {
  201. var enc = make([][]byte, len(txs))
  202. for i, tx := range txs {
  203. enc[i], _ = tx.MarshalBinary()
  204. }
  205. return enc
  206. }
  207. func decodeTransactions(enc [][]byte) ([]*types.Transaction, error) {
  208. var txs = make([]*types.Transaction, len(enc))
  209. for i, encTx := range enc {
  210. var tx types.Transaction
  211. if err := tx.UnmarshalBinary(encTx); err != nil {
  212. return nil, fmt.Errorf("invalid transaction %d: %v", i, err)
  213. }
  214. txs[i] = &tx
  215. }
  216. return txs, nil
  217. }
  218. func insertBlockParamsToBlock(params executableData) (*types.Block, error) {
  219. txs, err := decodeTransactions(params.Transactions)
  220. if err != nil {
  221. return nil, err
  222. }
  223. number := big.NewInt(0)
  224. number.SetUint64(params.Number)
  225. header := &types.Header{
  226. ParentHash: params.ParentHash,
  227. UncleHash: types.EmptyUncleHash,
  228. Coinbase: params.Miner,
  229. Root: params.StateRoot,
  230. TxHash: types.DeriveSha(types.Transactions(txs), trie.NewStackTrie(nil)),
  231. ReceiptHash: params.ReceiptRoot,
  232. Bloom: types.BytesToBloom(params.LogsBloom),
  233. Difficulty: big.NewInt(1),
  234. Number: number,
  235. GasLimit: params.GasLimit,
  236. GasUsed: params.GasUsed,
  237. Time: params.Timestamp,
  238. }
  239. block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */)
  240. return block, nil
  241. }
  242. // NewBlock creates an Eth1 block, inserts it in the chain, and either returns true,
  243. // or false + an error. This is a bit redundant for go, but simplifies things on the
  244. // eth2 side.
  245. func (api *consensusAPI) NewBlock(params executableData) (*newBlockResponse, error) {
  246. parent := api.eth.BlockChain().GetBlockByHash(params.ParentHash)
  247. if parent == nil {
  248. return &newBlockResponse{false}, fmt.Errorf("could not find parent %x", params.ParentHash)
  249. }
  250. block, err := insertBlockParamsToBlock(params)
  251. if err != nil {
  252. return nil, err
  253. }
  254. _, err = api.eth.BlockChain().InsertChainWithoutSealVerification(block)
  255. return &newBlockResponse{err == nil}, err
  256. }
  257. // Used in tests to add a the list of transactions from a block to the tx pool.
  258. func (api *consensusAPI) addBlockTxs(block *types.Block) error {
  259. for _, tx := range block.Transactions() {
  260. api.eth.TxPool().AddLocal(tx)
  261. }
  262. return nil
  263. }
  264. // FinalizeBlock is called to mark a block as synchronized, so
  265. // that data that is no longer needed can be removed.
  266. func (api *consensusAPI) FinalizeBlock(blockHash common.Hash) (*genericResponse, error) {
  267. return &genericResponse{true}, nil
  268. }
  269. // SetHead is called to perform a force choice.
  270. func (api *consensusAPI) SetHead(newHead common.Hash) (*genericResponse, error) {
  271. return &genericResponse{true}, nil
  272. }