abi_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package abi
  17. import (
  18. "bytes"
  19. "fmt"
  20. "log"
  21. "math/big"
  22. "reflect"
  23. "strings"
  24. "testing"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. )
  28. // formatSilceOutput add padding to the value and adds a size
  29. func formatSliceOutput(v ...[]byte) []byte {
  30. off := common.LeftPadBytes(big.NewInt(int64(len(v))).Bytes(), 32)
  31. output := append(off, make([]byte, 0, len(v)*32)...)
  32. for _, value := range v {
  33. output = append(output, common.LeftPadBytes(value, 32)...)
  34. }
  35. return output
  36. }
  37. // quick helper padding
  38. func pad(input []byte, size int, left bool) []byte {
  39. if left {
  40. return common.LeftPadBytes(input, size)
  41. }
  42. return common.RightPadBytes(input, size)
  43. }
  44. const jsondata = `
  45. [
  46. { "type" : "function", "name" : "balance", "constant" : true },
  47. { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] }
  48. ]`
  49. const jsondata2 = `
  50. [
  51. { "type" : "function", "name" : "balance", "constant" : true },
  52. { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] },
  53. { "type" : "function", "name" : "test", "constant" : false, "inputs" : [ { "name" : "number", "type" : "uint32" } ] },
  54. { "type" : "function", "name" : "string", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "string" } ] },
  55. { "type" : "function", "name" : "bool", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "bool" } ] },
  56. { "type" : "function", "name" : "address", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address" } ] },
  57. { "type" : "function", "name" : "uint64[2]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
  58. { "type" : "function", "name" : "uint64[]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
  59. { "type" : "function", "name" : "foo", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
  60. { "type" : "function", "name" : "bar", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
  61. { "type" : "function", "name" : "slice", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
  62. { "type" : "function", "name" : "slice256", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] },
  63. { "type" : "function", "name" : "sliceAddress", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] },
  64. { "type" : "function", "name" : "sliceMultiAddress", "constant" : false, "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] }
  65. ]`
  66. func TestReader(t *testing.T) {
  67. Uint256, _ := NewType("uint256")
  68. exp := ABI{
  69. Methods: map[string]Method{
  70. "balance": {
  71. "balance", true, nil, nil,
  72. },
  73. "send": {
  74. "send", false, []Argument{
  75. {"amount", Uint256, false},
  76. }, nil,
  77. },
  78. },
  79. }
  80. abi, err := JSON(strings.NewReader(jsondata))
  81. if err != nil {
  82. t.Error(err)
  83. }
  84. // deep equal fails for some reason
  85. t.Skip()
  86. if !reflect.DeepEqual(abi, exp) {
  87. t.Errorf("\nabi: %v\ndoes not match exp: %v", abi, exp)
  88. }
  89. }
  90. func TestTestNumbers(t *testing.T) {
  91. abi, err := JSON(strings.NewReader(jsondata2))
  92. if err != nil {
  93. t.Error(err)
  94. t.FailNow()
  95. }
  96. if _, err := abi.Pack("balance"); err != nil {
  97. t.Error(err)
  98. }
  99. if _, err := abi.Pack("balance", 1); err == nil {
  100. t.Error("expected error for balance(1)")
  101. }
  102. if _, err := abi.Pack("doesntexist", nil); err == nil {
  103. t.Errorf("doesntexist shouldn't exist")
  104. }
  105. if _, err := abi.Pack("doesntexist", 1); err == nil {
  106. t.Errorf("doesntexist(1) shouldn't exist")
  107. }
  108. if _, err := abi.Pack("send", big.NewInt(1000)); err != nil {
  109. t.Error(err)
  110. }
  111. i := new(int)
  112. *i = 1000
  113. if _, err := abi.Pack("send", i); err == nil {
  114. t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int")
  115. }
  116. if _, err := abi.Pack("test", uint32(1000)); err != nil {
  117. t.Error(err)
  118. }
  119. }
  120. func TestTestString(t *testing.T) {
  121. abi, err := JSON(strings.NewReader(jsondata2))
  122. if err != nil {
  123. t.Error(err)
  124. t.FailNow()
  125. }
  126. if _, err := abi.Pack("string", "hello world"); err != nil {
  127. t.Error(err)
  128. }
  129. }
  130. func TestTestBool(t *testing.T) {
  131. abi, err := JSON(strings.NewReader(jsondata2))
  132. if err != nil {
  133. t.Error(err)
  134. t.FailNow()
  135. }
  136. if _, err := abi.Pack("bool", true); err != nil {
  137. t.Error(err)
  138. }
  139. }
  140. func TestTestSlice(t *testing.T) {
  141. abi, err := JSON(strings.NewReader(jsondata2))
  142. if err != nil {
  143. t.Error(err)
  144. t.FailNow()
  145. }
  146. slice := make([]uint64, 2)
  147. if _, err := abi.Pack("uint64[2]", slice); err != nil {
  148. t.Error(err)
  149. }
  150. if _, err := abi.Pack("uint64[]", slice); err != nil {
  151. t.Error(err)
  152. }
  153. }
  154. func TestMethodSignature(t *testing.T) {
  155. String, _ := NewType("string")
  156. m := Method{"foo", false, []Argument{{"bar", String, false}, {"baz", String, false}}, nil}
  157. exp := "foo(string,string)"
  158. if m.Sig() != exp {
  159. t.Error("signature mismatch", exp, "!=", m.Sig())
  160. }
  161. idexp := crypto.Keccak256([]byte(exp))[:4]
  162. if !bytes.Equal(m.Id(), idexp) {
  163. t.Errorf("expected ids to match %x != %x", m.Id(), idexp)
  164. }
  165. uintt, _ := NewType("uint")
  166. m = Method{"foo", false, []Argument{{"bar", uintt, false}}, nil}
  167. exp = "foo(uint256)"
  168. if m.Sig() != exp {
  169. t.Error("signature mismatch", exp, "!=", m.Sig())
  170. }
  171. }
  172. func TestMultiPack(t *testing.T) {
  173. abi, err := JSON(strings.NewReader(jsondata2))
  174. if err != nil {
  175. t.Error(err)
  176. t.FailNow()
  177. }
  178. sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
  179. sig = append(sig, make([]byte, 64)...)
  180. sig[35] = 10
  181. sig[67] = 11
  182. packed, err := abi.Pack("bar", uint32(10), uint16(11))
  183. if err != nil {
  184. t.Error(err)
  185. t.FailNow()
  186. }
  187. if !bytes.Equal(packed, sig) {
  188. t.Errorf("expected %x got %x", sig, packed)
  189. }
  190. }
  191. func ExampleJSON() {
  192. const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
  193. abi, err := JSON(strings.NewReader(definition))
  194. if err != nil {
  195. log.Fatalln(err)
  196. }
  197. out, err := abi.Pack("isBar", common.HexToAddress("01"))
  198. if err != nil {
  199. log.Fatalln(err)
  200. }
  201. fmt.Printf("%x\n", out)
  202. // Output:
  203. // 1f2c40920000000000000000000000000000000000000000000000000000000000000001
  204. }
  205. func TestInputVariableInputLength(t *testing.T) {
  206. const definition = `[
  207. { "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] },
  208. { "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] },
  209. { "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] }
  210. ]`
  211. abi, err := JSON(strings.NewReader(definition))
  212. if err != nil {
  213. t.Fatal(err)
  214. }
  215. // test one string
  216. strin := "hello world"
  217. strpack, err := abi.Pack("strOne", strin)
  218. if err != nil {
  219. t.Error(err)
  220. }
  221. offset := make([]byte, 32)
  222. offset[31] = 32
  223. length := make([]byte, 32)
  224. length[31] = byte(len(strin))
  225. value := common.RightPadBytes([]byte(strin), 32)
  226. exp := append(offset, append(length, value...)...)
  227. // ignore first 4 bytes of the output. This is the function identifier
  228. strpack = strpack[4:]
  229. if !bytes.Equal(strpack, exp) {
  230. t.Errorf("expected %x, got %x\n", exp, strpack)
  231. }
  232. // test one bytes
  233. btspack, err := abi.Pack("bytesOne", []byte(strin))
  234. if err != nil {
  235. t.Error(err)
  236. }
  237. // ignore first 4 bytes of the output. This is the function identifier
  238. btspack = btspack[4:]
  239. if !bytes.Equal(btspack, exp) {
  240. t.Errorf("expected %x, got %x\n", exp, btspack)
  241. }
  242. // test two strings
  243. str1 := "hello"
  244. str2 := "world"
  245. str2pack, err := abi.Pack("strTwo", str1, str2)
  246. if err != nil {
  247. t.Error(err)
  248. }
  249. offset1 := make([]byte, 32)
  250. offset1[31] = 64
  251. length1 := make([]byte, 32)
  252. length1[31] = byte(len(str1))
  253. value1 := common.RightPadBytes([]byte(str1), 32)
  254. offset2 := make([]byte, 32)
  255. offset2[31] = 128
  256. length2 := make([]byte, 32)
  257. length2[31] = byte(len(str2))
  258. value2 := common.RightPadBytes([]byte(str2), 32)
  259. exp2 := append(offset1, offset2...)
  260. exp2 = append(exp2, append(length1, value1...)...)
  261. exp2 = append(exp2, append(length2, value2...)...)
  262. // ignore first 4 bytes of the output. This is the function identifier
  263. str2pack = str2pack[4:]
  264. if !bytes.Equal(str2pack, exp2) {
  265. t.Errorf("expected %x, got %x\n", exp, str2pack)
  266. }
  267. // test two strings, first > 32, second < 32
  268. str1 = strings.Repeat("a", 33)
  269. str2pack, err = abi.Pack("strTwo", str1, str2)
  270. if err != nil {
  271. t.Error(err)
  272. }
  273. offset1 = make([]byte, 32)
  274. offset1[31] = 64
  275. length1 = make([]byte, 32)
  276. length1[31] = byte(len(str1))
  277. value1 = common.RightPadBytes([]byte(str1), 64)
  278. offset2[31] = 160
  279. exp2 = append(offset1, offset2...)
  280. exp2 = append(exp2, append(length1, value1...)...)
  281. exp2 = append(exp2, append(length2, value2...)...)
  282. // ignore first 4 bytes of the output. This is the function identifier
  283. str2pack = str2pack[4:]
  284. if !bytes.Equal(str2pack, exp2) {
  285. t.Errorf("expected %x, got %x\n", exp, str2pack)
  286. }
  287. // test two strings, first > 32, second >32
  288. str1 = strings.Repeat("a", 33)
  289. str2 = strings.Repeat("a", 33)
  290. str2pack, err = abi.Pack("strTwo", str1, str2)
  291. if err != nil {
  292. t.Error(err)
  293. }
  294. offset1 = make([]byte, 32)
  295. offset1[31] = 64
  296. length1 = make([]byte, 32)
  297. length1[31] = byte(len(str1))
  298. value1 = common.RightPadBytes([]byte(str1), 64)
  299. offset2 = make([]byte, 32)
  300. offset2[31] = 160
  301. length2 = make([]byte, 32)
  302. length2[31] = byte(len(str2))
  303. value2 = common.RightPadBytes([]byte(str2), 64)
  304. exp2 = append(offset1, offset2...)
  305. exp2 = append(exp2, append(length1, value1...)...)
  306. exp2 = append(exp2, append(length2, value2...)...)
  307. // ignore first 4 bytes of the output. This is the function identifier
  308. str2pack = str2pack[4:]
  309. if !bytes.Equal(str2pack, exp2) {
  310. t.Errorf("expected %x, got %x\n", exp, str2pack)
  311. }
  312. }
  313. func TestDefaultFunctionParsing(t *testing.T) {
  314. const definition = `[{ "name" : "balance" }]`
  315. abi, err := JSON(strings.NewReader(definition))
  316. if err != nil {
  317. t.Fatal(err)
  318. }
  319. if _, ok := abi.Methods["balance"]; !ok {
  320. t.Error("expected 'balance' to be present")
  321. }
  322. }
  323. func TestBareEvents(t *testing.T) {
  324. const definition = `[
  325. { "type" : "event", "name" : "balance" },
  326. { "type" : "event", "name" : "anon", "anonymous" : true},
  327. { "type" : "event", "name" : "args", "inputs" : [{ "indexed":false, "name":"arg0", "type":"uint256" }, { "indexed":true, "name":"arg1", "type":"address" }] }
  328. ]`
  329. arg0, _ := NewType("uint256")
  330. arg1, _ := NewType("address")
  331. expectedEvents := map[string]struct {
  332. Anonymous bool
  333. Args []Argument
  334. }{
  335. "balance": {false, nil},
  336. "anon": {true, nil},
  337. "args": {false, []Argument{
  338. {Name: "arg0", Type: arg0, Indexed: false},
  339. {Name: "arg1", Type: arg1, Indexed: true},
  340. }},
  341. }
  342. abi, err := JSON(strings.NewReader(definition))
  343. if err != nil {
  344. t.Fatal(err)
  345. }
  346. if len(abi.Events) != len(expectedEvents) {
  347. t.Fatalf("invalid number of events after parsing, want %d, got %d", len(expectedEvents), len(abi.Events))
  348. }
  349. for name, exp := range expectedEvents {
  350. got, ok := abi.Events[name]
  351. if !ok {
  352. t.Errorf("could not found event %s", name)
  353. continue
  354. }
  355. if got.Anonymous != exp.Anonymous {
  356. t.Errorf("invalid anonymous indication for event %s, want %v, got %v", name, exp.Anonymous, got.Anonymous)
  357. }
  358. if len(got.Inputs) != len(exp.Args) {
  359. t.Errorf("invalid number of args, want %d, got %d", len(exp.Args), len(got.Inputs))
  360. continue
  361. }
  362. for i, arg := range exp.Args {
  363. if arg.Name != got.Inputs[i].Name {
  364. t.Errorf("events[%s].Input[%d] has an invalid name, want %s, got %s", name, i, arg.Name, got.Inputs[i].Name)
  365. }
  366. if arg.Indexed != got.Inputs[i].Indexed {
  367. t.Errorf("events[%s].Input[%d] has an invalid indexed indication, want %v, got %v", name, i, arg.Indexed, got.Inputs[i].Indexed)
  368. }
  369. if arg.Type.T != got.Inputs[i].Type.T {
  370. t.Errorf("events[%s].Input[%d] has an invalid type, want %x, got %x", name, i, arg.Type.T, got.Inputs[i].Type.T)
  371. }
  372. }
  373. }
  374. }