parsing.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package ethutil
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/big"
  6. "strconv"
  7. "strings"
  8. )
  9. // Op codes
  10. var OpCodes = map[string]string{
  11. "STOP": "0",
  12. "ADD": "1",
  13. "MUL": "2",
  14. "SUB": "3",
  15. "DIV": "4",
  16. "SDIV": "5",
  17. "MOD": "6",
  18. "SMOD": "7",
  19. "EXP": "8",
  20. "NEG": "9",
  21. "LT": "10",
  22. "LE": "11",
  23. "GT": "12",
  24. "GE": "13",
  25. "EQ": "14",
  26. "NOT": "15",
  27. "MYADDRESS": "16",
  28. "TXSENDER": "17",
  29. "PUSH": "48",
  30. "POP": "49",
  31. "LOAD": "54",
  32. }
  33. func CompileInstr(s string) (string, error) {
  34. tokens := strings.Split(s, " ")
  35. if OpCodes[tokens[0]] == "" {
  36. return s, errors.New(fmt.Sprintf("OP not found: %s", tokens[0]))
  37. }
  38. code := OpCodes[tokens[0]] // Replace op codes with the proper numerical equivalent
  39. op := new(big.Int)
  40. op.SetString(code, 0)
  41. args := make([]*big.Int, 6)
  42. for i, val := range tokens[1:len(tokens)] {
  43. num := new(big.Int)
  44. num.SetString(val, 0)
  45. args[i] = num
  46. }
  47. // Big int equation = op + x * 256 + y * 256**2 + z * 256**3 + a * 256**4 + b * 256**5 + c * 256**6
  48. base := new(big.Int)
  49. x := new(big.Int)
  50. y := new(big.Int)
  51. z := new(big.Int)
  52. a := new(big.Int)
  53. b := new(big.Int)
  54. c := new(big.Int)
  55. if args[0] != nil {
  56. x.Mul(args[0], big.NewInt(256))
  57. }
  58. if args[1] != nil {
  59. y.Mul(args[1], BigPow(256, 2))
  60. }
  61. if args[2] != nil {
  62. z.Mul(args[2], BigPow(256, 3))
  63. }
  64. if args[3] != nil {
  65. a.Mul(args[3], BigPow(256, 4))
  66. }
  67. if args[4] != nil {
  68. b.Mul(args[4], BigPow(256, 5))
  69. }
  70. if args[5] != nil {
  71. c.Mul(args[5], BigPow(256, 6))
  72. }
  73. base.Add(op, x)
  74. base.Add(base, y)
  75. base.Add(base, z)
  76. base.Add(base, a)
  77. base.Add(base, b)
  78. base.Add(base, c)
  79. return base.String(), nil
  80. }
  81. func Instr(instr string) (int, []string, error) {
  82. base := new(big.Int)
  83. base.SetString(instr, 0)
  84. args := make([]string, 7)
  85. for i := 0; i < 7; i++ {
  86. // int(int(val) / int(math.Pow(256,float64(i)))) % 256
  87. exp := BigPow(256, i)
  88. num := new(big.Int)
  89. num.Div(base, exp)
  90. args[i] = num.Mod(num, big.NewInt(256)).String()
  91. }
  92. op, _ := strconv.Atoi(args[0])
  93. return op, args[1:7], nil
  94. }