api.go 10 KB

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