execution.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package core
  2. import (
  3. "fmt"
  4. "math/big"
  5. "time"
  6. "github.com/ethereum/go-ethereum/crypto"
  7. "github.com/ethereum/go-ethereum/state"
  8. "github.com/ethereum/go-ethereum/vm"
  9. )
  10. type Execution struct {
  11. env vm.Environment
  12. address, input []byte
  13. Gas, price, value *big.Int
  14. }
  15. func NewExecution(env vm.Environment, address, input []byte, gas, gasPrice, value *big.Int) *Execution {
  16. return &Execution{env: env, address: address, input: input, Gas: gas, price: gasPrice, value: value}
  17. }
  18. func (self *Execution) Addr() []byte {
  19. return self.address
  20. }
  21. func (self *Execution) Call(codeAddr []byte, caller vm.ContextRef) ([]byte, error) {
  22. // Retrieve the executing code
  23. code := self.env.State().GetCode(codeAddr)
  24. return self.exec(code, codeAddr, caller)
  25. }
  26. func (self *Execution) exec(code, contextAddr []byte, caller vm.ContextRef) (ret []byte, err error) {
  27. env := self.env
  28. evm := vm.NewVm(env)
  29. if env.Depth() == vm.MaxCallDepth {
  30. caller.ReturnGas(self.Gas, self.price)
  31. return nil, vm.DepthError{}
  32. }
  33. vsnapshot := env.State().Copy()
  34. if len(self.address) == 0 {
  35. // Generate a new address
  36. nonce := env.State().GetNonce(caller.Address())
  37. self.address = crypto.CreateAddress(caller.Address(), nonce)
  38. env.State().SetNonce(caller.Address(), nonce+1)
  39. }
  40. from, to := env.State().GetStateObject(caller.Address()), env.State().GetOrNewStateObject(self.address)
  41. err = env.Transfer(from, to, self.value)
  42. if err != nil {
  43. env.State().Set(vsnapshot)
  44. caller.ReturnGas(self.Gas, self.price)
  45. return nil, fmt.Errorf("insufficient funds to transfer value. Req %v, has %v", self.value, from.Balance())
  46. }
  47. snapshot := env.State().Copy()
  48. start := time.Now()
  49. ret, err = evm.Run(to, caller, code, self.value, self.Gas, self.price, self.input)
  50. chainlogger.Debugf("vm took %v\n", time.Since(start))
  51. if err != nil {
  52. env.State().Set(snapshot)
  53. }
  54. return
  55. }
  56. func (self *Execution) Create(caller vm.ContextRef) (ret []byte, err error, account *state.StateObject) {
  57. ret, err = self.exec(self.input, nil, caller)
  58. account = self.env.State().GetStateObject(self.address)
  59. return
  60. }