execution.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. ret, err = evm.Run(to, caller, code, self.value, self.Gas, self.price, self.input)
  49. chainlogger.Debugf("vm took %v\n", time.Since(start))
  50. if err != nil {
  51. env.State().Set(snapshot)
  52. }
  53. return
  54. }
  55. func (self *Execution) Create(caller vm.ContextRef) (ret []byte, err error, account *state.StateObject) {
  56. ret, err = self.exec(self.input, nil, caller)
  57. account = self.env.State().GetStateObject(self.address)
  58. return
  59. }