js_test.go 15 KB

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