js_test.go 15 KB

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