js_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "regexp"
  9. "runtime"
  10. "strconv"
  11. "testing"
  12. "github.com/ethereum/go-ethereum/accounts"
  13. "github.com/ethereum/go-ethereum/common"
  14. "github.com/ethereum/go-ethereum/common/compiler"
  15. "github.com/ethereum/go-ethereum/common/docserver"
  16. "github.com/ethereum/go-ethereum/common/natspec"
  17. "github.com/ethereum/go-ethereum/common/resolver"
  18. "github.com/ethereum/go-ethereum/core"
  19. "github.com/ethereum/go-ethereum/core/state"
  20. "github.com/ethereum/go-ethereum/crypto"
  21. "github.com/ethereum/go-ethereum/eth"
  22. )
  23. const (
  24. testSolcPath = ""
  25. solcVersion = "0.9.17"
  26. testKey = "e6fab74a43941f82d89cb7faa408e227cdad3153c4720e540e855c19b15e6674"
  27. testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
  28. testBalance = "10000000000000000000"
  29. // of empty string
  30. testHash = "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
  31. )
  32. var (
  33. testGenesis = `{"` + testAddress[2:] + `": {"balance": "` + testBalance + `"}}`
  34. )
  35. type testjethre struct {
  36. *jsre
  37. stateDb *state.StateDB
  38. lastConfirm string
  39. ds *docserver.DocServer
  40. }
  41. func (self *testjethre) UnlockAccount(acc []byte) bool {
  42. err := self.ethereum.AccountManager().Unlock(acc, "")
  43. if err != nil {
  44. panic("unable to unlock")
  45. }
  46. return true
  47. }
  48. func (self *testjethre) ConfirmTransaction(tx string) bool {
  49. if self.ethereum.NatSpec {
  50. self.lastConfirm = natspec.GetNotice(self.xeth, tx, self.ds)
  51. }
  52. return true
  53. }
  54. func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
  55. tmp, err := ioutil.TempDir("", "geth-test")
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. // set up mock genesis with balance on the testAddress
  60. core.GenesisData = []byte(testGenesis)
  61. ks := crypto.NewKeyStorePassphrase(filepath.Join(tmp, "keys"))
  62. am := accounts.NewManager(ks)
  63. ethereum, err := eth.New(&eth.Config{
  64. DataDir: tmp,
  65. AccountManager: am,
  66. MaxPeers: 0,
  67. Name: "test",
  68. })
  69. if err != nil {
  70. t.Fatal("%v", err)
  71. }
  72. keyb, err := crypto.HexToECDSA(testKey)
  73. if err != nil {
  74. t.Fatal(err)
  75. }
  76. key := crypto.NewKeyFromECDSA(keyb)
  77. err = ks.StoreKey(key, "")
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. err = am.Unlock(key.Address, "")
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. assetPath := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
  86. ds, err := docserver.New("/")
  87. if err != nil {
  88. t.Errorf("Error creating DocServer: %v", err)
  89. }
  90. tf := &testjethre{ds: ds, stateDb: ethereum.ChainManager().State().Copy()}
  91. repl := newJSRE(ethereum, assetPath, testSolcPath, "", false, tf)
  92. tf.jsre = repl
  93. return tmp, tf, ethereum
  94. }
  95. // this line below is needed for transaction to be applied to the state in testing
  96. // the heavy lifing is done in XEth.ApplyTestTxs
  97. // this is fragile, overwriting xeth will result in
  98. // process leaking since xeth loops cannot quit safely
  99. // should be replaced by proper mining with testDAG for easy full integration tests
  100. // txc, self.xeth = self.xeth.ApplyTestTxs(self.xeth.repl.stateDb, coinbase, txc)
  101. func TestNodeInfo(t *testing.T) {
  102. tmp, repl, ethereum := testJEthRE(t)
  103. if err := ethereum.Start(); err != nil {
  104. t.Fatalf("error starting ethereum: %v", err)
  105. }
  106. defer ethereum.Stop()
  107. defer os.RemoveAll(tmp)
  108. want := `{"DiscPort":0,"IP":"0.0.0.0","ListenAddr":"","Name":"test","NodeID":"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","NodeUrl":"enode://00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000@0.0.0.0:0","TCPPort":0,"Td":"0"}`
  109. checkEvalJSON(t, repl, `admin.nodeInfo()`, want)
  110. }
  111. func TestAccounts(t *testing.T) {
  112. tmp, repl, ethereum := testJEthRE(t)
  113. if err := ethereum.Start(); err != nil {
  114. t.Fatalf("error starting ethereum: %v", err)
  115. }
  116. defer ethereum.Stop()
  117. defer os.RemoveAll(tmp)
  118. checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`"]`)
  119. checkEvalJSON(t, repl, `eth.coinbase`, `"`+testAddress+`"`)
  120. val, err := repl.re.Run(`admin.newAccount("password")`)
  121. if err != nil {
  122. t.Errorf("expected no error, got %v", err)
  123. }
  124. addr := val.String()
  125. if !regexp.MustCompile(`0x[0-9a-f]{40}`).MatchString(addr) {
  126. t.Errorf("address not hex: %q", addr)
  127. }
  128. // skip until order fixed #824
  129. // checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`", "`+addr+`"]`)
  130. // checkEvalJSON(t, repl, `eth.coinbase`, `"`+testAddress+`"`)
  131. }
  132. func TestBlockChain(t *testing.T) {
  133. tmp, repl, ethereum := testJEthRE(t)
  134. if err := ethereum.Start(); err != nil {
  135. t.Fatalf("error starting ethereum: %v", err)
  136. }
  137. defer ethereum.Stop()
  138. defer os.RemoveAll(tmp)
  139. // get current block dump before export/import.
  140. val, err := repl.re.Run("JSON.stringify(admin.debug.dumpBlock())")
  141. if err != nil {
  142. t.Errorf("expected no error, got %v", err)
  143. }
  144. beforeExport := val.String()
  145. // do the export
  146. extmp, err := ioutil.TempDir("", "geth-test-export")
  147. if err != nil {
  148. t.Fatal(err)
  149. }
  150. defer os.RemoveAll(extmp)
  151. tmpfile := filepath.Join(extmp, "export.chain")
  152. tmpfileq := strconv.Quote(tmpfile)
  153. checkEvalJSON(t, repl, `admin.export(`+tmpfileq+`)`, `true`)
  154. if _, err := os.Stat(tmpfile); err != nil {
  155. t.Fatal(err)
  156. }
  157. // check import, verify that dumpBlock gives the same result.
  158. checkEvalJSON(t, repl, `admin.import(`+tmpfileq+`)`, `true`)
  159. checkEvalJSON(t, repl, `admin.debug.dumpBlock()`, beforeExport)
  160. }
  161. func TestMining(t *testing.T) {
  162. tmp, repl, ethereum := testJEthRE(t)
  163. if err := ethereum.Start(); err != nil {
  164. t.Fatalf("error starting ethereum: %v", err)
  165. }
  166. defer ethereum.Stop()
  167. defer os.RemoveAll(tmp)
  168. checkEvalJSON(t, repl, `eth.mining`, `false`)
  169. }
  170. func TestRPC(t *testing.T) {
  171. tmp, repl, ethereum := testJEthRE(t)
  172. if err := ethereum.Start(); err != nil {
  173. t.Errorf("error starting ethereum: %v", err)
  174. return
  175. }
  176. defer ethereum.Stop()
  177. defer os.RemoveAll(tmp)
  178. checkEvalJSON(t, repl, `admin.startRPC("127.0.0.1", 5004)`, `true`)
  179. }
  180. func TestCheckTestAccountBalance(t *testing.T) {
  181. tmp, repl, ethereum := testJEthRE(t)
  182. if err := ethereum.Start(); err != nil {
  183. t.Errorf("error starting ethereum: %v", err)
  184. return
  185. }
  186. defer ethereum.Stop()
  187. defer os.RemoveAll(tmp)
  188. repl.re.Run(`primary = "` + testAddress + `"`)
  189. checkEvalJSON(t, repl, `eth.getBalance(primary)`, `"`+testBalance+`"`)
  190. }
  191. func TestSignature(t *testing.T) {
  192. tmp, repl, ethereum := testJEthRE(t)
  193. if err := ethereum.Start(); err != nil {
  194. t.Errorf("error starting ethereum: %v", err)
  195. return
  196. }
  197. defer ethereum.Stop()
  198. defer os.RemoveAll(tmp)
  199. val, err := repl.re.Run(`eth.sign({from: "` + testAddress + `", data: "` + testHash + `"})`)
  200. // This is a very preliminary test, lacking actual signature verification
  201. if err != nil {
  202. t.Errorf("Error runnig js: %v", err)
  203. return
  204. }
  205. output := val.String()
  206. t.Logf("Output: %v", output)
  207. regex := regexp.MustCompile(`^0x[0-9a-f]{130}$`)
  208. if !regex.MatchString(output) {
  209. t.Errorf("Signature is not 65 bytes represented in hexadecimal.")
  210. return
  211. }
  212. }
  213. func TestContract(t *testing.T) {
  214. tmp, repl, ethereum := testJEthRE(t)
  215. if err := ethereum.Start(); err != nil {
  216. t.Errorf("error starting ethereum: %v", err)
  217. return
  218. }
  219. defer ethereum.Stop()
  220. defer os.RemoveAll(tmp)
  221. var txc uint64
  222. coinbase := common.HexToAddress(testAddress)
  223. resolver.New(repl.xeth).CreateContracts(coinbase)
  224. source := `contract test {\n` +
  225. " /// @notice Will multiply `a` by 7." + `\n` +
  226. ` function multiply(uint a) returns(uint d) {\n` +
  227. ` return a * 7;\n` +
  228. ` }\n` +
  229. `}\n`
  230. checkEvalJSON(t, repl, `admin.contractInfo.stop()`, `true`)
  231. contractInfo, err := ioutil.ReadFile("info_test.json")
  232. if err != nil {
  233. t.Fatalf("%v", err)
  234. }
  235. checkEvalJSON(t, repl, `primary = eth.accounts[0]`, `"`+testAddress+`"`)
  236. checkEvalJSON(t, repl, `source = "`+source+`"`, `"`+source+`"`)
  237. // if solc is found with right version, test it, otherwise read from file
  238. sol, err := compiler.New("")
  239. if err != nil {
  240. t.Logf("solc not found: skipping compiler test")
  241. } else if sol.Version() != solcVersion {
  242. err = fmt.Errorf("solc wrong version found (%v, expect %v): skipping compiler test", sol.Version(), solcVersion)
  243. t.Log(err)
  244. }
  245. if err != nil {
  246. info, err := ioutil.ReadFile("info_test.json")
  247. if err != nil {
  248. t.Fatalf("%v", err)
  249. }
  250. _, err = repl.re.Run(`contract = JSON.parse(` + strconv.Quote(string(info)) + `)`)
  251. if err != nil {
  252. t.Errorf("%v", err)
  253. }
  254. } else {
  255. checkEvalJSON(t, repl, `contract = eth.compile.solidity(source)`, string(contractInfo))
  256. }
  257. checkEvalJSON(t, repl, `contract.code`, `"605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056"`)
  258. checkEvalJSON(
  259. t, repl,
  260. `contractaddress = eth.sendTransaction({from: primary, data: contract.code })`,
  261. `"0x5dcaace5982778b409c524873b319667eba5d074"`,
  262. )
  263. callSetup := `abiDef = JSON.parse('[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]');
  264. Multiply7 = eth.contract(abiDef);
  265. multiply7 = new Multiply7(contractaddress);
  266. `
  267. _, err = repl.re.Run(callSetup)
  268. if err != nil {
  269. t.Errorf("unexpected error registering, got %v", err)
  270. }
  271. // updatespec
  272. // why is this sometimes failing?
  273. // checkEvalJSON(t, repl, `multiply7.multiply.call(6)`, `42`)
  274. expNotice := ""
  275. if repl.lastConfirm != expNotice {
  276. t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
  277. }
  278. // why 0?
  279. checkEvalJSON(t, repl, `eth.getBlock("pending", true).transactions.length`, `0`)
  280. txc, repl.xeth = repl.xeth.ApplyTestTxs(repl.stateDb, coinbase, txc)
  281. checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`)
  282. checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary, gas: "1000000", gasPrice: "100000" })`, `undefined`)
  283. expNotice = `About to submit transaction (no NatSpec info found for contract: content hash not found for '0x4a6c99e127191d2ee302e42182c338344b39a37a47cdbb17ab0f26b6802eb4d1'): {"params":[{"to":"0x5dcaace5982778b409c524873b319667eba5d074","data": "0xc6888fa10000000000000000000000000000000000000000000000000000000000000006"}]}`
  284. if repl.lastConfirm != expNotice {
  285. t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
  286. }
  287. checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`)
  288. checkEvalJSON(t, repl, `contenthash = admin.contractInfo.register(primary, contractaddress, contract, filename)`, `"0x0d067e2dd99a4d8f0c0279738b17130dd415a89f24a23f0e7cf68c546ae3089d"`)
  289. checkEvalJSON(t, repl, `admin.contractInfo.registerUrl(primary, contenthash, "file://"+filename)`, `true`)
  290. if err != nil {
  291. t.Errorf("unexpected error registering, got %v", err)
  292. }
  293. checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`)
  294. // update state
  295. txc, repl.xeth = repl.xeth.ApplyTestTxs(repl.stateDb, coinbase, txc)
  296. checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary, gas: "1000000", gasPrice: "100000" })`, `undefined`)
  297. expNotice = "Will multiply 6 by 7."
  298. if repl.lastConfirm != expNotice {
  299. t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
  300. }
  301. }
  302. func checkEvalJSON(t *testing.T, re *testjethre, expr, want string) error {
  303. val, err := re.re.Run("JSON.stringify(" + expr + ")")
  304. if err == nil && val.String() != want {
  305. err = fmt.Errorf("Output mismatch for `%s`:\ngot: %s\nwant: %s", expr, val.String(), want)
  306. }
  307. if err != nil {
  308. _, file, line, _ := runtime.Caller(1)
  309. file = path.Base(file)
  310. fmt.Printf("\t%s:%d: %v\n", file, line, err)
  311. t.Fail()
  312. }
  313. return err
  314. }