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