js_test.go 15 KB

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