execution.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package core
  2. import (
  3. "fmt"
  4. "math/big"
  5. "github.com/ethereum/go-ethereum/ethutil"
  6. "github.com/ethereum/go-ethereum/state"
  7. "github.com/ethereum/go-ethereum/vm"
  8. )
  9. type Execution struct {
  10. vm vm.VirtualMachine
  11. address, input []byte
  12. Gas, price, value *big.Int
  13. object *state.StateObject
  14. SkipTransfer bool
  15. }
  16. func NewExecution(vm vm.VirtualMachine, address, input []byte, gas, gasPrice, value *big.Int) *Execution {
  17. return &Execution{vm: vm, address: address, input: input, Gas: gas, price: gasPrice, value: value}
  18. }
  19. func (self *Execution) Addr() []byte {
  20. return self.address
  21. }
  22. func (self *Execution) Call(codeAddr []byte, caller vm.ClosureRef) ([]byte, error) {
  23. // Retrieve the executing code
  24. code := self.vm.Env().State().GetCode(codeAddr)
  25. return self.exec(code, codeAddr, caller)
  26. }
  27. func (self *Execution) exec(code, caddr []byte, caller vm.ClosureRef) (ret []byte, err error) {
  28. env := self.vm.Env()
  29. chainlogger.Debugf("pre state %x\n", env.State().Root())
  30. snapshot := env.State().Copy()
  31. defer func() {
  32. if vm.IsDepthErr(err) || vm.IsOOGErr(err) {
  33. env.State().Set(snapshot)
  34. }
  35. chainlogger.Debugf("post state %x\n", env.State().Root())
  36. }()
  37. from, to := env.State().GetStateObject(caller.Address()), env.State().GetOrNewStateObject(self.address)
  38. // Skipping transfer is used on testing for the initial call
  39. if !self.SkipTransfer {
  40. err = env.Transfer(from, to, self.value)
  41. }
  42. if err != nil {
  43. caller.ReturnGas(self.Gas, self.price)
  44. err = fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, from.Balance)
  45. } else {
  46. self.object = to
  47. // Pre-compiled contracts (address.go) 1, 2 & 3.
  48. naddr := ethutil.BigD(caddr).Uint64()
  49. if p := vm.Precompiled[naddr]; p != nil {
  50. if self.Gas.Cmp(p.Gas) >= 0 {
  51. ret = p.Call(self.input)
  52. self.vm.Printf("NATIVE_FUNC(%x) => %x", naddr, ret)
  53. self.vm.Endl()
  54. }
  55. } else {
  56. ret, err = self.vm.Run(to, caller, code, self.value, self.Gas, self.price, self.input)
  57. }
  58. }
  59. return
  60. }
  61. func (self *Execution) Create(caller vm.ClosureRef) (ret []byte, err error, account *state.StateObject) {
  62. ret, err = self.exec(self.input, nil, caller)
  63. account = self.vm.Env().State().GetStateObject(self.address)
  64. return
  65. }