execution.go 2.2 KB

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