execution.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package core
  2. import (
  3. "fmt"
  4. "math/big"
  5. "time"
  6. "github.com/ethereum/go-ethereum/state"
  7. "github.com/ethereum/go-ethereum/vm"
  8. )
  9. type Execution struct {
  10. env vm.Environment
  11. address, input []byte
  12. Gas, price, value *big.Int
  13. SkipTransfer bool
  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.New(env, vm.DebugVmTy)
  29. if env.Depth() == vm.MaxCallDepth {
  30. // Consume all gas (by not returning it) and return a depth error
  31. return nil, vm.DepthError{}
  32. }
  33. from, to := env.State().GetStateObject(caller.Address()), env.State().GetOrNewStateObject(self.address)
  34. // Skipping transfer is used on testing for the initial call
  35. if !self.SkipTransfer {
  36. err = env.Transfer(from, to, self.value)
  37. if err != nil {
  38. caller.ReturnGas(self.Gas, self.price)
  39. err = fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, from.Balance)
  40. return
  41. }
  42. }
  43. snapshot := env.State().Copy()
  44. start := time.Now()
  45. ret, err = evm.Run(to, caller, code, self.value, self.Gas, self.price, self.input)
  46. if err != nil {
  47. env.State().Set(snapshot)
  48. }
  49. chainlogger.Debugf("vm took %v\n", time.Since(start))
  50. return
  51. }
  52. func (self *Execution) Create(caller vm.ContextRef) (ret []byte, err error, account *state.StateObject) {
  53. ret, err = self.exec(self.input, nil, caller)
  54. account = self.env.State().GetStateObject(self.address)
  55. return
  56. }