execution.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package core
  2. import (
  3. "math/big"
  4. "time"
  5. "github.com/ethereum/go-ethereum/common"
  6. "github.com/ethereum/go-ethereum/core/state"
  7. "github.com/ethereum/go-ethereum/core/vm"
  8. "github.com/ethereum/go-ethereum/crypto"
  9. )
  10. type Execution struct {
  11. env vm.Environment
  12. address *common.Address
  13. input []byte
  14. Gas, price, value *big.Int
  15. }
  16. func NewExecution(env vm.Environment, address *common.Address, input []byte, gas, gasPrice, value *big.Int) *Execution {
  17. return &Execution{env: env, address: address, input: input, Gas: gas, price: gasPrice, value: value}
  18. }
  19. func (self *Execution) Call(codeAddr common.Address, caller vm.ContextRef) ([]byte, error) {
  20. // Retrieve the executing code
  21. code := self.env.State().GetCode(codeAddr)
  22. return self.exec(&codeAddr, code, caller)
  23. }
  24. func (self *Execution) exec(contextAddr *common.Address, code []byte, caller vm.ContextRef) (ret []byte, err error) {
  25. start := time.Now()
  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. snapshot := env.State().Copy()
  33. if self.address == nil {
  34. // Generate a new address
  35. nonce := env.State().GetNonce(caller.Address())
  36. addr := crypto.CreateAddress(caller.Address(), nonce)
  37. self.address = &addr
  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(snapshot)
  44. //caller.ReturnGas(self.Gas, self.price)
  45. return nil, ValueTransferErr("insufficient funds to transfer value. Req %v, has %v", self.value, from.Balance())
  46. }
  47. context := vm.NewContext(caller, to, self.value, self.Gas, self.price)
  48. context.SetCallCode(contextAddr, code)
  49. ret, err = evm.Run(context, self.input)
  50. evm.Printf("message call took %v", time.Since(start)).Endl()
  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(nil, self.input, caller)
  58. account = self.env.State().GetStateObject(*self.address)
  59. return
  60. }