context.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package vm
  2. import (
  3. "math"
  4. "math/big"
  5. "github.com/ethereum/go-ethereum/common"
  6. )
  7. type ContextRef interface {
  8. ReturnGas(*big.Int, *big.Int)
  9. Address() common.Address
  10. SetCode([]byte)
  11. }
  12. type Context struct {
  13. caller ContextRef
  14. self ContextRef
  15. Code []byte
  16. CodeAddr *common.Address
  17. value, Gas, UsedGas, Price *big.Int
  18. Args []byte
  19. }
  20. // Create a new context for the given data items
  21. func NewContext(caller ContextRef, object ContextRef, value, gas, price *big.Int) *Context {
  22. c := &Context{caller: caller, self: object, Args: nil}
  23. // Gas should be a pointer so it can safely be reduced through the run
  24. // This pointer will be off the state transition
  25. c.Gas = gas //new(big.Int).Set(gas)
  26. c.value = new(big.Int).Set(value)
  27. // In most cases price and value are pointers to transaction objects
  28. // and we don't want the transaction's values to change.
  29. c.Price = new(big.Int).Set(price)
  30. c.UsedGas = new(big.Int)
  31. return c
  32. }
  33. func (c *Context) GetOp(n uint64) OpCode {
  34. return OpCode(c.GetByte(n))
  35. }
  36. func (c *Context) GetByte(n uint64) byte {
  37. if n < uint64(len(c.Code)) {
  38. return c.Code[n]
  39. }
  40. return 0
  41. }
  42. func (c *Context) GetBytes(x, y int) []byte {
  43. return c.GetRangeValue(uint64(x), uint64(y))
  44. }
  45. func (c *Context) GetRangeValue(x, size uint64) []byte {
  46. x = uint64(math.Min(float64(x), float64(len(c.Code))))
  47. y := uint64(math.Min(float64(x+size), float64(len(c.Code))))
  48. return common.RightPadBytes(c.Code[x:y], int(size))
  49. }
  50. func (c *Context) Return(ret []byte) []byte {
  51. // Return the remaining gas to the caller
  52. c.caller.ReturnGas(c.Gas, c.Price)
  53. return ret
  54. }
  55. /*
  56. * Gas functions
  57. */
  58. func (c *Context) UseGas(gas *big.Int) (ok bool) {
  59. ok = UseGas(c.Gas, gas)
  60. if ok {
  61. c.UsedGas.Add(c.UsedGas, gas)
  62. }
  63. return
  64. }
  65. // Implement the caller interface
  66. func (c *Context) ReturnGas(gas, price *big.Int) {
  67. // Return the gas to the context
  68. c.Gas.Add(c.Gas, gas)
  69. c.UsedGas.Sub(c.UsedGas, gas)
  70. }
  71. /*
  72. * Set / Get
  73. */
  74. func (c *Context) Address() common.Address {
  75. return c.self.Address()
  76. }
  77. func (self *Context) SetCode(code []byte) {
  78. self.Code = code
  79. }
  80. func (self *Context) SetCallCode(addr *common.Address, code []byte) {
  81. self.Code = code
  82. self.CodeAddr = addr
  83. }