js_test.go 15 KB

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