js_test.go 16 KB

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