js_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "math/big"
  6. "os"
  7. "path/filepath"
  8. "regexp"
  9. "runtime"
  10. "strconv"
  11. "testing"
  12. "time"
  13. "github.com/ethereum/go-ethereum/accounts"
  14. "github.com/ethereum/go-ethereum/common"
  15. "github.com/ethereum/go-ethereum/common/compiler"
  16. "github.com/ethereum/go-ethereum/common/docserver"
  17. "github.com/ethereum/go-ethereum/common/natspec"
  18. "github.com/ethereum/go-ethereum/common/registrar"
  19. "github.com/ethereum/go-ethereum/core"
  20. "github.com/ethereum/go-ethereum/crypto"
  21. "github.com/ethereum/go-ethereum/eth"
  22. "github.com/ethereum/go-ethereum/rpc/codec"
  23. "github.com/ethereum/go-ethereum/rpc/comms"
  24. )
  25. const (
  26. testSolcPath = ""
  27. solcVersion = "0.9.23"
  28. testKey = "e6fab74a43941f82d89cb7faa408e227cdad3153c4720e540e855c19b15e6674"
  29. testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
  30. testBalance = "10000000000000000000"
  31. // of empty string
  32. testHash = "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
  33. )
  34. var (
  35. versionRE = regexp.MustCompile(strconv.Quote(`"compilerVersion":"` + solcVersion + `"`))
  36. testNodeKey = crypto.ToECDSA(common.Hex2Bytes("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f"))
  37. testGenesis = `{"` + testAddress[2:] + `": {"balance": "` + testBalance + `"}}`
  38. )
  39. type testjethre struct {
  40. *jsre
  41. lastConfirm string
  42. ds *docserver.DocServer
  43. }
  44. func (self *testjethre) UnlockAccount(acc []byte) bool {
  45. err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(acc), "")
  46. if err != nil {
  47. panic("unable to unlock")
  48. }
  49. return true
  50. }
  51. func (self *testjethre) ConfirmTransaction(tx string) bool {
  52. if self.ethereum.NatSpec {
  53. self.lastConfirm = natspec.GetNotice(self.xeth, tx, self.ds)
  54. }
  55. return true
  56. }
  57. func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
  58. return testREPL(t, nil)
  59. }
  60. func testREPL(t *testing.T, config func(*eth.Config)) (string, *testjethre, *eth.Ethereum) {
  61. tmp, err := ioutil.TempDir("", "geth-test")
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. // set up mock genesis with balance on the testAddress
  66. core.GenesisAccounts = []byte(testGenesis)
  67. ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore"))
  68. am := accounts.NewManager(ks)
  69. conf := &eth.Config{
  70. NodeKey: testNodeKey,
  71. DataDir: tmp,
  72. AccountManager: am,
  73. MaxPeers: 0,
  74. Name: "test",
  75. SolcPath: testSolcPath,
  76. PowTest: true,
  77. }
  78. if config != nil {
  79. config(conf)
  80. }
  81. ethereum, err := eth.New(conf)
  82. if err != nil {
  83. t.Fatal("%v", err)
  84. }
  85. keyb, err := crypto.HexToECDSA(testKey)
  86. if err != nil {
  87. t.Fatal(err)
  88. }
  89. key := crypto.NewKeyFromECDSA(keyb)
  90. err = ks.StoreKey(key, "")
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. err = am.Unlock(key.Address, "")
  95. if err != nil {
  96. t.Fatal(err)
  97. }
  98. assetPath := filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
  99. client := comms.NewInProcClient(codec.JSON)
  100. ds := docserver.New("/")
  101. tf := &testjethre{ds: ds}
  102. repl := newJSRE(ethereum, assetPath, "", client, false, tf)
  103. tf.jsre = repl
  104. return tmp, tf, ethereum
  105. }
  106. func TestNodeInfo(t *testing.T) {
  107. t.Skip("broken after p2p update")
  108. tmp, repl, ethereum := testJEthRE(t)
  109. if err := ethereum.Start(); err != nil {
  110. t.Fatalf("error starting ethereum: %v", err)
  111. }
  112. defer ethereum.Stop()
  113. defer os.RemoveAll(tmp)
  114. want := `{"DiscPort":0,"IP":"0.0.0.0","ListenAddr":"","Name":"test","NodeID":"4cb2fc32924e94277bf94b5e4c983beedb2eabd5a0bc941db32202735c6625d020ca14a5963d1738af43b6ac0a711d61b1a06de931a499fe2aa0b1a132a902b5","NodeUrl":"enode://4cb2fc32924e94277bf94b5e4c983beedb2eabd5a0bc941db32202735c6625d020ca14a5963d1738af43b6ac0a711d61b1a06de931a499fe2aa0b1a132a902b5@0.0.0.0:0","TCPPort":0,"Td":"131072"}`
  115. checkEvalJSON(t, repl, `admin.nodeInfo`, want)
  116. }
  117. func TestAccounts(t *testing.T) {
  118. tmp, repl, ethereum := testJEthRE(t)
  119. if err := ethereum.Start(); err != nil {
  120. t.Fatalf("error starting ethereum: %v", err)
  121. }
  122. defer ethereum.Stop()
  123. defer os.RemoveAll(tmp)
  124. checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`"]`)
  125. checkEvalJSON(t, repl, `eth.coinbase`, `null`)
  126. val, err := repl.re.Run(`personal.newAccount("password")`)
  127. if err != nil {
  128. t.Errorf("expected no error, got %v", err)
  129. }
  130. addr := val.String()
  131. if !regexp.MustCompile(`0x[0-9a-f]{40}`).MatchString(addr) {
  132. t.Errorf("address not hex: %q", addr)
  133. }
  134. checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`","`+addr+`"]`)
  135. }
  136. func TestBlockChain(t *testing.T) {
  137. tmp, repl, ethereum := testJEthRE(t)
  138. if err := ethereum.Start(); err != nil {
  139. t.Fatalf("error starting ethereum: %v", err)
  140. }
  141. defer ethereum.Stop()
  142. defer os.RemoveAll(tmp)
  143. // get current block dump before export/import.
  144. val, err := repl.re.Run("JSON.stringify(debug.dumpBlock(eth.blockNumber))")
  145. if err != nil {
  146. t.Errorf("expected no error, got %v", err)
  147. }
  148. beforeExport := val.String()
  149. // do the export
  150. extmp, err := ioutil.TempDir("", "geth-test-export")
  151. if err != nil {
  152. t.Fatal(err)
  153. }
  154. defer os.RemoveAll(extmp)
  155. tmpfile := filepath.Join(extmp, "export.chain")
  156. tmpfileq := strconv.Quote(tmpfile)
  157. ethereum.ChainManager().Reset()
  158. checkEvalJSON(t, repl, `admin.exportChain(`+tmpfileq+`)`, `true`)
  159. if _, err := os.Stat(tmpfile); err != nil {
  160. t.Fatal(err)
  161. }
  162. // check import, verify that dumpBlock gives the same result.
  163. checkEvalJSON(t, repl, `admin.importChain(`+tmpfileq+`)`, `true`)
  164. checkEvalJSON(t, repl, `debug.dumpBlock(eth.blockNumber)`, beforeExport)
  165. }
  166. func TestMining(t *testing.T) {
  167. tmp, repl, ethereum := testJEthRE(t)
  168. if err := ethereum.Start(); err != nil {
  169. t.Fatalf("error starting ethereum: %v", err)
  170. }
  171. defer ethereum.Stop()
  172. defer os.RemoveAll(tmp)
  173. checkEvalJSON(t, repl, `eth.mining`, `false`)
  174. }
  175. func TestRPC(t *testing.T) {
  176. tmp, repl, ethereum := testJEthRE(t)
  177. if err := ethereum.Start(); err != nil {
  178. t.Errorf("error starting ethereum: %v", err)
  179. return
  180. }
  181. defer ethereum.Stop()
  182. defer os.RemoveAll(tmp)
  183. checkEvalJSON(t, repl, `admin.startRPC("127.0.0.1", 5004, "*", "web3,eth,net")`, `true`)
  184. }
  185. func TestCheckTestAccountBalance(t *testing.T) {
  186. t.Skip() // i don't think it tests the correct behaviour here. it's actually testing
  187. // internals which shouldn't be tested. This now fails because of a change in the core
  188. // and i have no means to fix this, sorry - @obscuren
  189. tmp, repl, ethereum := testJEthRE(t)
  190. if err := ethereum.Start(); err != nil {
  191. t.Errorf("error starting ethereum: %v", err)
  192. return
  193. }
  194. defer ethereum.Stop()
  195. defer os.RemoveAll(tmp)
  196. repl.re.Run(`primary = "` + testAddress + `"`)
  197. checkEvalJSON(t, repl, `eth.getBalance(primary)`, `"`+testBalance+`"`)
  198. }
  199. func TestSignature(t *testing.T) {
  200. tmp, repl, ethereum := testJEthRE(t)
  201. if err := ethereum.Start(); err != nil {
  202. t.Errorf("error starting ethereum: %v", err)
  203. return
  204. }
  205. defer ethereum.Stop()
  206. defer os.RemoveAll(tmp)
  207. val, err := repl.re.Run(`eth.sign("` + testAddress + `", "` + testHash + `")`)
  208. // This is a very preliminary test, lacking actual signature verification
  209. if err != nil {
  210. t.Errorf("Error running js: %v", err)
  211. return
  212. }
  213. output := val.String()
  214. t.Logf("Output: %v", output)
  215. regex := regexp.MustCompile(`^0x[0-9a-f]{130}$`)
  216. if !regex.MatchString(output) {
  217. t.Errorf("Signature is not 65 bytes represented in hexadecimal.")
  218. return
  219. }
  220. }
  221. func TestContract(t *testing.T) {
  222. t.Skip("contract testing is implemented with mining in ethash test mode. This takes about 7seconds to run. Unskip and run on demand")
  223. tmp, repl, ethereum := testJEthRE(t)
  224. if err := ethereum.Start(); err != nil {
  225. t.Errorf("error starting ethereum: %v", err)
  226. return
  227. }
  228. defer ethereum.Stop()
  229. defer os.RemoveAll(tmp)
  230. coinbase := common.HexToAddress(testAddress)
  231. reg := registrar.New(repl.xeth)
  232. err := reg.SetGlobalRegistrar("", coinbase)
  233. if err != nil {
  234. t.Errorf("error setting HashReg: %v", err)
  235. }
  236. err = reg.SetHashReg("", coinbase)
  237. if err != nil {
  238. t.Errorf("error setting HashReg: %v", err)
  239. }
  240. err = reg.SetUrlHint("", coinbase)
  241. if err != nil {
  242. t.Errorf("error setting HashReg: %v", err)
  243. }
  244. source := `contract test {\n` +
  245. " /// @notice Will multiply `a` by 7." + `\n` +
  246. ` function multiply(uint a) returns(uint d) {\n` +
  247. ` return a * 7;\n` +
  248. ` }\n` +
  249. `}\n`
  250. if checkEvalJSON(t, repl, `admin.contractInfo.stop()`, `true`) != nil {
  251. return
  252. }
  253. contractInfo, err := ioutil.ReadFile("info_test.json")
  254. if err != nil {
  255. t.Fatalf("%v", err)
  256. }
  257. if checkEvalJSON(t, repl, `primary = eth.accounts[0]`, `"`+testAddress+`"`) != nil {
  258. return
  259. }
  260. if checkEvalJSON(t, repl, `source = "`+source+`"`, `"`+source+`"`) != nil {
  261. return
  262. }
  263. // if solc is found with right version, test it, otherwise read from file
  264. sol, err := compiler.New("")
  265. if err != nil {
  266. t.Logf("solc not found: mocking contract compilation step")
  267. } else if sol.Version() != solcVersion {
  268. t.Logf("WARNING: solc different version found (%v, test written for %v, may need to update)", sol.Version(), solcVersion)
  269. }
  270. if err != nil {
  271. info, err := ioutil.ReadFile("info_test.json")
  272. if err != nil {
  273. t.Fatalf("%v", err)
  274. }
  275. _, err = repl.re.Run(`contract = JSON.parse(` + strconv.Quote(string(info)) + `)`)
  276. if err != nil {
  277. t.Errorf("%v", err)
  278. }
  279. } else {
  280. if checkEvalJSON(t, repl, `contract = eth.compile.solidity(source).test`, string(contractInfo)) != nil {
  281. return
  282. }
  283. }
  284. if checkEvalJSON(t, repl, `contract.code`, `"0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056"`) != nil {
  285. return
  286. }
  287. if checkEvalJSON(
  288. t, repl,
  289. `contractaddress = eth.sendTransaction({from: primary, data: contract.code})`,
  290. `"0x291293d57e0a0ab47effe97c02577f90d9211567"`,
  291. ) != nil {
  292. return
  293. }
  294. if !processTxs(repl, t, 7) {
  295. return
  296. }
  297. callSetup := `abiDef = JSON.parse('[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]');
  298. Multiply7 = eth.contract(abiDef);
  299. multiply7 = Multiply7.at(contractaddress);
  300. `
  301. _, err = repl.re.Run(callSetup)
  302. if err != nil {
  303. t.Errorf("unexpected error setting up contract, got %v", err)
  304. return
  305. }
  306. expNotice := ""
  307. if repl.lastConfirm != expNotice {
  308. t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
  309. return
  310. }
  311. if checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`) != nil {
  312. return
  313. }
  314. if checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary })`, `"0xcb08355dff8f8cadb5dc3d72e652ef5c33792cb0d871229dd1aef5db1c4ba1f2"`) != nil {
  315. return
  316. }
  317. if !processTxs(repl, t, 1) {
  318. return
  319. }
  320. expNotice = `About to submit transaction (no NatSpec info found for contract: content hash not found for '0x87e2802265838c7f14bb69eecd2112911af6767907a702eeaa445239fb20711b'): {"params":[{"to":"0x291293d57e0a0ab47effe97c02577f90d9211567","data": "0xc6888fa10000000000000000000000000000000000000000000000000000000000000006"}]}`
  321. if repl.lastConfirm != expNotice {
  322. t.Errorf("incorrect confirmation message: expected\n%v, got\n%v", expNotice, repl.lastConfirm)
  323. return
  324. }
  325. var contentHash = `"0x86d2b7cf1e72e9a7a3f8d96601f0151742a2f780f1526414304fbe413dc7f9bd"`
  326. if sol != nil && solcVersion != sol.Version() {
  327. modContractInfo := versionRE.ReplaceAll(contractInfo, []byte(`"compilerVersion":"`+sol.Version()+`"`))
  328. fmt.Printf("modified contractinfo:\n%s\n", modContractInfo)
  329. contentHash = `"` + common.ToHex(crypto.Sha3([]byte(modContractInfo))) + `"`
  330. }
  331. if checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`) != nil {
  332. return
  333. }
  334. if checkEvalJSON(t, repl, `contentHash = admin.contractInfo.saveInfo(contract.info, filename)`, contentHash) != nil {
  335. return
  336. }
  337. if checkEvalJSON(t, repl, `admin.contractInfo.register(primary, contractaddress, contentHash)`, `true`) != nil {
  338. return
  339. }
  340. if checkEvalJSON(t, repl, `admin.contractInfo.registerUrl(primary, contentHash, "file://"+filename)`, `true`) != nil {
  341. return
  342. }
  343. if checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`) != nil {
  344. return
  345. }
  346. if !processTxs(repl, t, 3) {
  347. return
  348. }
  349. if checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary })`, `"0xe773bf05b027e4485c8b28967c35c939a71c5f6c177db78b51db52e76760d903"`) != nil {
  350. return
  351. }
  352. if !processTxs(repl, t, 1) {
  353. return
  354. }
  355. expNotice = "Will multiply 6 by 7."
  356. if repl.lastConfirm != expNotice {
  357. t.Errorf("incorrect confirmation message: expected\n%v, got\n%v", expNotice, repl.lastConfirm)
  358. return
  359. }
  360. }
  361. func pendingTransactions(repl *testjethre, t *testing.T) (txc int64, err error) {
  362. txs := repl.ethereum.TxPool().GetTransactions()
  363. return int64(len(txs)), nil
  364. }
  365. func processTxs(repl *testjethre, t *testing.T, expTxc int) bool {
  366. var txc int64
  367. var err error
  368. for i := 0; i < 50; i++ {
  369. txc, err = pendingTransactions(repl, t)
  370. if err != nil {
  371. t.Errorf("unexpected error checking pending transactions: %v", err)
  372. return false
  373. }
  374. if expTxc < int(txc) {
  375. t.Errorf("too many pending transactions: expected %v, got %v", expTxc, txc)
  376. return false
  377. } else if expTxc == int(txc) {
  378. break
  379. }
  380. time.Sleep(100 * time.Millisecond)
  381. }
  382. if int(txc) != expTxc {
  383. t.Errorf("incorrect number of pending transactions, expected %v, got %v", expTxc, txc)
  384. return false
  385. }
  386. err = repl.ethereum.StartMining(runtime.NumCPU())
  387. if err != nil {
  388. t.Errorf("unexpected error mining: %v", err)
  389. return false
  390. }
  391. defer repl.ethereum.StopMining()
  392. timer := time.NewTimer(100 * time.Second)
  393. height := new(big.Int).Add(repl.xeth.CurrentBlock().Number(), big.NewInt(1))
  394. repl.wait <- height
  395. select {
  396. case <-timer.C:
  397. // if times out make sure the xeth loop does not block
  398. go func() {
  399. select {
  400. case repl.wait <- nil:
  401. case <-repl.wait:
  402. }
  403. }()
  404. case <-repl.wait:
  405. }
  406. txc, err = pendingTransactions(repl, t)
  407. if err != nil {
  408. t.Errorf("unexpected error checking pending transactions: %v", err)
  409. return false
  410. }
  411. if txc != 0 {
  412. t.Errorf("%d trasactions were not mined", txc)
  413. return false
  414. }
  415. return true
  416. }
  417. func checkEvalJSON(t *testing.T, re *testjethre, expr, want string) error {
  418. val, err := re.re.Run("JSON.stringify(" + expr + ")")
  419. if err == nil && val.String() != want {
  420. err = fmt.Errorf("Output mismatch for `%s`:\ngot: %s\nwant: %s", expr, val.String(), want)
  421. }
  422. if err != nil {
  423. _, file, line, _ := runtime.Caller(1)
  424. file = filepath.Base(file)
  425. fmt.Printf("\t%s:%d: %v\n", file, line, err)
  426. t.Fail()
  427. }
  428. return err
  429. }