context.go 2.3 KB

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