state_transition.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // Copyright 2014 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 core
  17. import (
  18. "errors"
  19. "fmt"
  20. "math"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/state"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/core/vm"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/multitenancy"
  28. "github.com/ethereum/go-ethereum/params"
  29. "github.com/ethereum/go-ethereum/private"
  30. )
  31. /*
  32. The State Transitioning Model
  33. A state transition is a change made when a transaction is applied to the current world state
  34. The state transitioning model does all the necessary work to work out a valid new state root.
  35. 1) Nonce handling
  36. 2) Pre pay gas
  37. 3) Create a new state object if the recipient is \0*32
  38. 4) Value transfer
  39. == If contract creation ==
  40. 4a) Attempt to run transaction data
  41. 4b) If valid, use result as code for the new state object
  42. == end ==
  43. 5) Run Script section
  44. 6) Derive new state root
  45. */
  46. type StateTransition struct {
  47. gp *GasPool
  48. msg Message
  49. gas uint64
  50. gasPrice *big.Int
  51. initialGas uint64
  52. value *big.Int
  53. data []byte
  54. state vm.StateDB
  55. evm *vm.EVM
  56. }
  57. // Message represents a message sent to a contract.
  58. type Message interface {
  59. From() common.Address
  60. To() *common.Address
  61. GasPrice() *big.Int
  62. Gas() uint64
  63. Value() *big.Int
  64. Nonce() uint64
  65. CheckNonce() bool
  66. Data() []byte
  67. AccessList() types.AccessList
  68. }
  69. // ExecutionResult includes all output after executing given evm
  70. // message no matter the execution itself is successful or not.
  71. type ExecutionResult struct {
  72. UsedGas uint64 // Total used gas but include the refunded gas
  73. Err error // Any error encountered during the execution(listed in core/vm/errors.go)
  74. ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode)
  75. }
  76. // Unwrap returns the internal evm error which allows us for further
  77. // analysis outside.
  78. func (result *ExecutionResult) Unwrap() error {
  79. return result.Err
  80. }
  81. // Failed returns the indicator whether the execution is successful or not
  82. func (result *ExecutionResult) Failed() bool { return result.Err != nil }
  83. // Return is a helper function to help caller distinguish between revert reason
  84. // and function return. Return returns the data after execution if no error occurs.
  85. func (result *ExecutionResult) Return() []byte {
  86. if result.Err != nil {
  87. return nil
  88. }
  89. return common.CopyBytes(result.ReturnData)
  90. }
  91. // Revert returns the concrete revert reason if the execution is aborted by `REVERT`
  92. // opcode. Note the reason can be nil if no data supplied with revert opcode.
  93. func (result *ExecutionResult) Revert() []byte {
  94. if result.Err != vm.ErrExecutionReverted {
  95. return nil
  96. }
  97. return common.CopyBytes(result.ReturnData)
  98. }
  99. // PrivateMessage implements a private message
  100. type PrivateMessage interface {
  101. Message
  102. IsPrivate() bool
  103. IsInnerPrivate() bool
  104. }
  105. // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
  106. func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool, isHomestead, isEIP2028 bool) (uint64, error) {
  107. // Set the starting gas for the raw transaction
  108. var gas uint64
  109. if isContractCreation && isHomestead {
  110. gas = params.TxGasContractCreation
  111. } else {
  112. gas = params.TxGas
  113. }
  114. // Bump the required gas by the amount of transactional data
  115. if len(data) > 0 {
  116. // Zero and non-zero bytes are priced differently
  117. var nz uint64
  118. for _, byt := range data {
  119. if byt != 0 {
  120. nz++
  121. }
  122. }
  123. // Make sure we don't exceed uint64 for all data combinations
  124. nonZeroGas := params.TxDataNonZeroGasFrontier
  125. if isEIP2028 {
  126. nonZeroGas = params.TxDataNonZeroGasEIP2028
  127. }
  128. if (math.MaxUint64-gas)/nonZeroGas < nz {
  129. return 0, ErrGasUintOverflow
  130. }
  131. gas += nz * nonZeroGas
  132. z := uint64(len(data)) - nz
  133. if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
  134. return 0, ErrGasUintOverflow
  135. }
  136. gas += z * params.TxDataZeroGas
  137. }
  138. if accessList != nil {
  139. gas += uint64(len(accessList)) * params.TxAccessListAddressGas
  140. gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas
  141. }
  142. return gas, nil
  143. }
  144. // NewStateTransition initialises and returns a new state transition object.
  145. func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
  146. return &StateTransition{
  147. gp: gp,
  148. evm: evm,
  149. msg: msg,
  150. gasPrice: msg.GasPrice(),
  151. value: msg.Value(),
  152. data: msg.Data(),
  153. state: evm.PublicState(),
  154. }
  155. }
  156. // ApplyMessage computes the new state by applying the given message
  157. // against the old state within the environment.
  158. //
  159. // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
  160. // the gas used (which includes gas refunds) and an error if it failed. An error always
  161. // indicates a core error meaning that the message would always fail for that particular
  162. // state and would never be accepted within a block.
  163. func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) {
  164. return NewStateTransition(evm, msg, gp).TransitionDb()
  165. }
  166. // to returns the recipient of the message.
  167. func (st *StateTransition) to() common.Address {
  168. if st.msg == nil || st.msg.To() == nil /* contract creation */ {
  169. return common.Address{}
  170. }
  171. return *st.msg.To()
  172. }
  173. func (st *StateTransition) buyGas() error {
  174. mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
  175. if have, want := st.state.GetBalance(st.msg.From()), mgval; have.Cmp(want) < 0 {
  176. return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want)
  177. }
  178. if err := st.gp.SubGas(st.msg.Gas()); err != nil {
  179. return err
  180. }
  181. st.gas += st.msg.Gas()
  182. st.initialGas = st.msg.Gas()
  183. st.state.SubBalance(st.msg.From(), mgval)
  184. return nil
  185. }
  186. func (st *StateTransition) preCheck() error {
  187. // Make sure this transaction's nonce is correct.
  188. if st.msg.CheckNonce() {
  189. stNonce := st.state.GetNonce(st.msg.From())
  190. if msgNonce := st.msg.Nonce(); stNonce < msgNonce {
  191. return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh,
  192. st.msg.From().Hex(), msgNonce, stNonce)
  193. } else if stNonce > msgNonce {
  194. return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow,
  195. st.msg.From().Hex(), msgNonce, stNonce)
  196. }
  197. }
  198. return st.buyGas()
  199. }
  200. // TransitionDb will transition the state by applying the current message and
  201. // returning the evm execution result with following fields.
  202. //
  203. // - used gas:
  204. // total gas used (including gas being refunded)
  205. // - returndata:
  206. // the returned data from evm
  207. // - concrete execution error:
  208. // various **EVM** error which aborts the execution,
  209. // e.g. ErrOutOfGas, ErrExecutionReverted
  210. //
  211. // However if any consensus issue encountered, return the error directly with
  212. // nil evm execution result.
  213. //
  214. // Quorum:
  215. // 1. Intrinsic gas is calculated based on the encrypted payload hash
  216. // and NOT the actual private payload.
  217. // 2. For private transactions, we only deduct intrinsic gas from the gas pool
  218. // regardless the current node is party to the transaction or not.
  219. // 3. For privacy marker transactions, we only deduct the PMT gas from the gas pool. No gas is deducted
  220. // for the internal private transaction, regardless of whether the current node is a party.
  221. // 4. With multitenancy support, we enforce the party set in the contract index must contain all
  222. // parties from the transaction. This is to detect unauthorized access from a legit proxy contract
  223. // to an unauthorized contract.
  224. func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
  225. // First check this message satisfies all consensus rules before
  226. // applying the message. The rules include these clauses
  227. //
  228. // 1. the nonce of the message caller is correct
  229. // 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
  230. // 3. the amount of gas required is available in the block
  231. // 4. the purchased gas is enough to cover intrinsic usage
  232. // 5. there is no overflow when calculating intrinsic gas
  233. // 6. caller has enough balance to cover asset transfer for **topmost** call
  234. // Check clauses 1-3, buy gas if everything is correct
  235. var err error
  236. if err = st.preCheck(); err != nil {
  237. return nil, err
  238. }
  239. msg := st.msg
  240. sender := vm.AccountRef(msg.From())
  241. homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber)
  242. istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber)
  243. contractCreation := msg.To() == nil
  244. isQuorum := st.evm.ChainConfig().IsQuorum
  245. snapshot := st.evm.StateDB.Snapshot()
  246. var data []byte
  247. isPrivate := false
  248. publicState := st.state
  249. pmh := newPMH(st)
  250. if msg, ok := msg.(PrivateMessage); ok && isQuorum && msg.IsPrivate() {
  251. isPrivate = true
  252. pmh.snapshot = snapshot
  253. pmh.eph = common.BytesToEncryptedPayloadHash(st.data)
  254. _, _, data, pmh.receivedPrivacyMetadata, err = private.P.Receive(pmh.eph)
  255. // Increment the public account nonce if:
  256. // 1. Tx is private and *not* a participant of the group and either call or create
  257. // 2. Tx is private we are part of the group and is a call
  258. if err != nil || !contractCreation {
  259. publicState.SetNonce(sender.Address(), publicState.GetNonce(sender.Address())+1)
  260. }
  261. if err != nil {
  262. return &ExecutionResult{
  263. UsedGas: 0,
  264. Err: nil,
  265. ReturnData: nil,
  266. }, nil
  267. }
  268. pmh.hasPrivatePayload = data != nil
  269. vmErr, consensusErr := pmh.prepare()
  270. if consensusErr != nil || vmErr != nil {
  271. return &ExecutionResult{
  272. UsedGas: 0,
  273. Err: vmErr,
  274. ReturnData: nil,
  275. }, consensusErr
  276. }
  277. } else {
  278. data = st.data
  279. }
  280. // Pay intrinsic gas. For a private contract this is done using the public hash passed in,
  281. // not the private data retrieved above. This is because we need any (participant) validator
  282. // node to get the same result as a (non-participant) minter node, to avoid out-of-gas issues.
  283. // Check clauses 4-5, subtract intrinsic gas if everything is correct
  284. gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation, homestead, istanbul)
  285. if err != nil {
  286. return nil, err
  287. }
  288. if st.gas < gas {
  289. return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas)
  290. }
  291. st.gas -= gas
  292. // Check clause 6
  293. if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) {
  294. return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex())
  295. }
  296. // Set up the initial access list.
  297. if rules := st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber); rules.IsBerlin {
  298. st.state.PrepareAccessList(msg.From(), msg.To(), vm.ActivePrecompiles(rules), msg.AccessList())
  299. }
  300. var (
  301. leftoverGas uint64
  302. evm = st.evm
  303. ret []byte
  304. // vm errors do not effect consensus and are therefor
  305. // not assigned to err, except for insufficient balance
  306. // error.
  307. vmerr error
  308. )
  309. if contractCreation {
  310. ret, _, leftoverGas, vmerr = evm.Create(sender, data, st.gas, st.value)
  311. } else {
  312. // Increment the account nonce only if the transaction isn't private.
  313. // If the transaction is private it has already been incremented on
  314. // the public state.
  315. if !isPrivate {
  316. publicState.SetNonce(msg.From(), publicState.GetNonce(sender.Address())+1)
  317. }
  318. var to common.Address
  319. if isQuorum {
  320. to = *st.msg.To()
  321. } else {
  322. to = st.to()
  323. }
  324. //if input is empty for the smart contract call, return (refunding any gas deducted)
  325. if len(data) == 0 && isPrivate {
  326. st.refundGas()
  327. st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
  328. return &ExecutionResult{
  329. UsedGas: 0,
  330. Err: nil,
  331. ReturnData: nil,
  332. }, nil
  333. }
  334. ret, leftoverGas, vmerr = evm.Call(sender, to, data, st.gas, st.value)
  335. }
  336. if vmerr != nil {
  337. log.Debug("VM returned with error", "err", vmerr)
  338. // The only possible consensus-error would be if there wasn't
  339. // sufficient balance to make the transfer happen. The first
  340. // balance transfer may never fail.
  341. if vmerr == vm.ErrInsufficientBalance {
  342. return nil, vmerr
  343. }
  344. if errors.Is(vmerr, multitenancy.ErrNotAuthorized) {
  345. return nil, vmerr
  346. }
  347. }
  348. // Quorum - Privacy Enhancements
  349. // perform privacy enhancements checks
  350. if pmh.mustVerify() {
  351. var exitEarly bool
  352. exitEarly, err = pmh.verify(vmerr)
  353. if exitEarly {
  354. return &ExecutionResult{
  355. UsedGas: 0,
  356. Err: ErrPrivateContractInteractionVerificationFailed,
  357. ReturnData: nil,
  358. }, err
  359. }
  360. }
  361. // End Quorum - Privacy Enhancements
  362. // Pay gas used during contract creation or execution (st.gas tracks remaining gas)
  363. // However, if private contract then we don't want to do this else we can get
  364. // a mismatch between a (non-participant) minter and (participant) validator,
  365. // which can cause a 'BAD BLOCK' crash.
  366. if !isPrivate {
  367. st.gas = leftoverGas
  368. }
  369. // Quorum with gas enabled we can specify if it goes to coinbase(ie validators) or a fixed beneficiary
  370. // Note the rewards here are only for transitions, any additional block rewards must go
  371. rewardAccount, err := st.evm.ChainConfig().GetRewardAccount(st.evm.Context.BlockNumber, st.evm.Context.Coinbase)
  372. if err != nil {
  373. return nil, err
  374. }
  375. st.refundGas()
  376. st.state.AddBalance(rewardAccount, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
  377. if isPrivate {
  378. return &ExecutionResult{
  379. UsedGas: 0,
  380. Err: vmerr,
  381. ReturnData: ret,
  382. }, err
  383. }
  384. // End Quorum
  385. return &ExecutionResult{
  386. UsedGas: st.gasUsed(),
  387. Err: vmerr,
  388. ReturnData: ret,
  389. }, nil
  390. }
  391. func (st *StateTransition) refundGas() {
  392. // Quorum
  393. if msg, ok := st.msg.(PrivateMessage); ok && msg.IsInnerPrivate() {
  394. // Quorum
  395. // This is the inner private transaction of a PMT, need to ensure that ALL gas is refunded to prevent
  396. // a mismatch between a (non-participant) minter and (participant) validator.
  397. st.gas += st.gasUsed()
  398. } else { // run original code
  399. // Apply refund counter, capped to half of the used gas.
  400. refund := st.gasUsed() / 2
  401. if refund > st.state.GetRefund() {
  402. refund = st.state.GetRefund()
  403. }
  404. st.gas += refund
  405. }
  406. // Return ETH for remaining gas, exchanged at the original rate.
  407. remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
  408. st.state.AddBalance(st.msg.From(), remaining)
  409. // Also return remaining gas to the block gas counter so it is
  410. // available for the next transaction.
  411. st.gp.AddGas(st.gas)
  412. }
  413. // gasUsed returns the amount of gas used up by the state transition.
  414. func (st *StateTransition) gasUsed() uint64 {
  415. return st.initialGas - st.gas
  416. }
  417. // Quorum - Privacy Enhancements - implement the pmcStateTransitionAPI interface
  418. func (st *StateTransition) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) {
  419. st.evm.SetTxPrivacyMetadata(pm)
  420. }
  421. func (st *StateTransition) IsPrivacyEnhancementsEnabled() bool {
  422. return st.evm.ChainConfig().IsPrivacyEnhancementsEnabled(st.evm.Context.BlockNumber)
  423. }
  424. func (st *StateTransition) RevertToSnapshot(snapshot int) {
  425. st.evm.StateDB.RevertToSnapshot(snapshot)
  426. }
  427. func (st *StateTransition) GetStatePrivacyMetadata(addr common.Address) (*state.PrivacyMetadata, error) {
  428. return st.evm.StateDB.GetPrivacyMetadata(addr)
  429. }
  430. func (st *StateTransition) CalculateMerkleRoot() (common.Hash, error) {
  431. return st.evm.CalculateMerkleRoot()
  432. }
  433. func (st *StateTransition) AffectedContracts() []common.Address {
  434. return st.evm.AffectedContracts()
  435. }
  436. // End Quorum - Privacy Enhancements