js_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. "runtime"
  9. "strconv"
  10. "testing"
  11. "github.com/ethereum/go-ethereum/accounts"
  12. "github.com/ethereum/go-ethereum/common"
  13. "github.com/ethereum/go-ethereum/common/compiler"
  14. "github.com/ethereum/go-ethereum/common/docserver"
  15. "github.com/ethereum/go-ethereum/common/natspec"
  16. "github.com/ethereum/go-ethereum/common/resolver"
  17. "github.com/ethereum/go-ethereum/core"
  18. "github.com/ethereum/go-ethereum/core/state"
  19. "github.com/ethereum/go-ethereum/crypto"
  20. "github.com/ethereum/go-ethereum/eth"
  21. "github.com/ethereum/go-ethereum/rpc/comms"
  22. "github.com/ethereum/go-ethereum/rpc/codec"
  23. )
  24. const (
  25. testSolcPath = ""
  26. solcVersion = "0.9.23"
  27. testKey = "e6fab74a43941f82d89cb7faa408e227cdad3153c4720e540e855c19b15e6674"
  28. testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
  29. testBalance = "10000000000000000000"
  30. // of empty string
  31. testHash = "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
  32. )
  33. var (
  34. versionRE = regexp.MustCompile(strconv.Quote(`"compilerVersion":"` + solcVersion + `"`))
  35. testNodeKey = crypto.ToECDSA(common.Hex2Bytes("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f"))
  36. testGenesis = `{"` + testAddress[2:] + `": {"balance": "` + testBalance + `"}}`
  37. )
  38. type testjethre struct {
  39. *jsre
  40. stateDb *state.StateDB
  41. lastConfirm string
  42. ds *docserver.DocServer
  43. }
  44. func (self *testjethre) UnlockAccount(acc []byte) bool {
  45. err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(acc), "")
  46. if err != nil {
  47. panic("unable to unlock")
  48. }
  49. return true
  50. }
  51. func (self *testjethre) ConfirmTransaction(tx string) bool {
  52. if self.ethereum.NatSpec {
  53. self.lastConfirm = natspec.GetNotice(self.xeth, tx, self.ds)
  54. }
  55. return true
  56. }
  57. func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
  58. tmp, err := ioutil.TempDir("", "geth-test")
  59. if err != nil {
  60. t.Fatal(err)
  61. }
  62. // set up mock genesis with balance on the testAddress
  63. core.GenesisAccounts = []byte(testGenesis)
  64. ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore"))
  65. am := accounts.NewManager(ks)
  66. ethereum, err := eth.New(&eth.Config{
  67. NodeKey: testNodeKey,
  68. DataDir: tmp,
  69. AccountManager: am,
  70. MaxPeers: 0,
  71. Name: "test",
  72. SolcPath: testSolcPath,
  73. })
  74. if err != nil {
  75. t.Fatal("%v", err)
  76. }
  77. keyb, err := crypto.HexToECDSA(testKey)
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. key := crypto.NewKeyFromECDSA(keyb)
  82. err = ks.StoreKey(key, "")
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. err = am.Unlock(key.Address, "")
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. assetPath := filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
  91. ds, err := docserver.New("/")
  92. if err != nil {
  93. t.Errorf("Error creating DocServer: %v", err)
  94. }
  95. tf := &testjethre{ds: ds, stateDb: ethereum.ChainManager().State().Copy()}
  96. client := comms.NewInProcClient(codec.JSON)
  97. repl := newJSRE(ethereum, assetPath, "", client, false, tf)
  98. tf.jsre = repl
  99. return tmp, tf, ethereum
  100. }
  101. // this line below is needed for transaction to be applied to the state in testing
  102. // the heavy lifing is done in XEth.ApplyTestTxs
  103. // this is fragile, overwriting xeth will result in
  104. // process leaking since xeth loops cannot quit safely
  105. // should be replaced by proper mining with testDAG for easy full integration tests
  106. // txc, self.xeth = self.xeth.ApplyTestTxs(self.xeth.repl.stateDb, coinbase, txc)
  107. func TestNodeInfo(t *testing.T) {
  108. tmp, repl, ethereum := testJEthRE(t)
  109. if err := ethereum.Start(); err != nil {
  110. t.Fatalf("error starting ethereum: %v", err)
  111. }
  112. defer ethereum.Stop()
  113. defer os.RemoveAll(tmp)
  114. 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"}`
  115. checkEvalJSON(t, repl, `admin.nodeInfo`, want)
  116. }
  117. func TestAccounts(t *testing.T) {
  118. tmp, repl, ethereum := testJEthRE(t)
  119. if err := ethereum.Start(); err != nil {
  120. t.Fatalf("error starting ethereum: %v", err)
  121. }
  122. defer ethereum.Stop()
  123. defer os.RemoveAll(tmp)
  124. checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`"]`)
  125. checkEvalJSON(t, repl, `eth.coinbase`, `"`+common.Address{}.Hex()+`"`)
  126. val, err := repl.re.Run(`personal.newAccount("password")`)
  127. if err != nil {
  128. t.Errorf("expected no error, got %v", err)
  129. }
  130. addr := val.String()
  131. if !regexp.MustCompile(`0x[0-9a-f]{40}`).MatchString(addr) {
  132. t.Errorf("address not hex: %q", addr)
  133. }
  134. // skip until order fixed #824
  135. // checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`", "`+addr+`"]`)
  136. // checkEvalJSON(t, repl, `eth.coinbase`, `"`+testAddress+`"`)
  137. }
  138. func TestBlockChain(t *testing.T) {
  139. tmp, repl, ethereum := testJEthRE(t)
  140. if err := ethereum.Start(); err != nil {
  141. t.Fatalf("error starting ethereum: %v", err)
  142. }
  143. defer ethereum.Stop()
  144. defer os.RemoveAll(tmp)
  145. // get current block dump before export/import.
  146. val, err := repl.re.Run("JSON.stringify(debug.dumpBlock(eth.blockNumber))")
  147. if err != nil {
  148. t.Errorf("expected no error, got %v", err)
  149. }
  150. beforeExport := val.String()
  151. // do the export
  152. extmp, err := ioutil.TempDir("", "geth-test-export")
  153. if err != nil {
  154. t.Fatal(err)
  155. }
  156. defer os.RemoveAll(extmp)
  157. tmpfile := filepath.Join(extmp, "export.chain")
  158. tmpfileq := strconv.Quote(tmpfile)
  159. ethereum.ChainManager().Reset()
  160. checkEvalJSON(t, repl, `admin.exportChain(`+tmpfileq+`)`, `true`)
  161. if _, err := os.Stat(tmpfile); err != nil {
  162. t.Fatal(err)
  163. }
  164. // check import, verify that dumpBlock gives the same result.
  165. checkEvalJSON(t, repl, `admin.importChain(`+tmpfileq+`)`, `true`)
  166. checkEvalJSON(t, repl, `debug.dumpBlock(eth.blockNumber)`, beforeExport)
  167. }
  168. func TestMining(t *testing.T) {
  169. tmp, repl, ethereum := testJEthRE(t)
  170. if err := ethereum.Start(); err != nil {
  171. t.Fatalf("error starting ethereum: %v", err)
  172. }
  173. defer ethereum.Stop()
  174. defer os.RemoveAll(tmp)
  175. checkEvalJSON(t, repl, `eth.mining`, `false`)
  176. }
  177. func TestRPC(t *testing.T) {
  178. tmp, repl, ethereum := testJEthRE(t)
  179. if err := ethereum.Start(); err != nil {
  180. t.Errorf("error starting ethereum: %v", err)
  181. return
  182. }
  183. defer ethereum.Stop()
  184. defer os.RemoveAll(tmp)
  185. checkEvalJSON(t, repl, `admin.startRPC("127.0.0.1", 5004, "*", "web3,eth,net")`, `true`)
  186. }
  187. func TestCheckTestAccountBalance(t *testing.T) {
  188. t.Skip() // i don't think it tests the correct behaviour here. it's actually testing
  189. // internals which shouldn't be tested. This now fails because of a change in the core
  190. // and i have no means to fix this, sorry - @obscuren
  191. tmp, repl, ethereum := testJEthRE(t)
  192. if err := ethereum.Start(); err != nil {
  193. t.Errorf("error starting ethereum: %v", err)
  194. return
  195. }
  196. defer ethereum.Stop()
  197. defer os.RemoveAll(tmp)
  198. repl.re.Run(`primary = "` + testAddress + `"`)
  199. checkEvalJSON(t, repl, `eth.getBalance(primary)`, `"`+testBalance+`"`)
  200. }
  201. func TestSignature(t *testing.T) {
  202. tmp, repl, ethereum := testJEthRE(t)
  203. if err := ethereum.Start(); err != nil {
  204. t.Errorf("error starting ethereum: %v", err)
  205. return
  206. }
  207. defer ethereum.Stop()
  208. defer os.RemoveAll(tmp)
  209. val, err := repl.re.Run(`eth.sign("` + testAddress + `", "` + testHash + `")`)
  210. // This is a very preliminary test, lacking actual signature verification
  211. if err != nil {
  212. t.Errorf("Error running js: %v", err)
  213. return
  214. }
  215. output := val.String()
  216. t.Logf("Output: %v", output)
  217. regex := regexp.MustCompile(`^0x[0-9a-f]{130}$`)
  218. if !regex.MatchString(output) {
  219. t.Errorf("Signature is not 65 bytes represented in hexadecimal.")
  220. return
  221. }
  222. }
  223. func TestContract(t *testing.T) {
  224. t.Skip()
  225. tmp, repl, ethereum := testJEthRE(t)
  226. if err := ethereum.Start(); err != nil {
  227. t.Errorf("error starting ethereum: %v", err)
  228. return
  229. }
  230. defer ethereum.Stop()
  231. defer os.RemoveAll(tmp)
  232. var txc uint64
  233. coinbase := common.HexToAddress(testAddress)
  234. resolver.New(repl.xeth).CreateContracts(coinbase)
  235. // time.Sleep(1000 * time.Millisecond)
  236. // checkEvalJSON(t, repl, `eth.getBlock("pending", true).transactions.length`, `2`)
  237. source := `contract test {\n` +
  238. " /// @notice Will multiply `a` by 7." + `\n` +
  239. ` function multiply(uint a) returns(uint d) {\n` +
  240. ` return a * 7;\n` +
  241. ` }\n` +
  242. `}\n`
  243. checkEvalJSON(t, repl, `admin.contractInfo.stop()`, `true`)
  244. contractInfo, err := ioutil.ReadFile("info_test.json")
  245. if err != nil {
  246. t.Fatalf("%v", err)
  247. }
  248. checkEvalJSON(t, repl, `primary = eth.accounts[0]`, `"`+testAddress+`"`)
  249. checkEvalJSON(t, repl, `source = "`+source+`"`, `"`+source+`"`)
  250. // if solc is found with right version, test it, otherwise read from file
  251. sol, err := compiler.New("")
  252. if err != nil {
  253. t.Logf("solc not found: mocking contract compilation step")
  254. } else if sol.Version() != solcVersion {
  255. t.Logf("WARNING: solc different version found (%v, test written for %v, may need to update)", sol.Version(), solcVersion)
  256. }
  257. if err != nil {
  258. info, err := ioutil.ReadFile("info_test.json")
  259. if err != nil {
  260. t.Fatalf("%v", err)
  261. }
  262. _, err = repl.re.Run(`contract = JSON.parse(` + strconv.Quote(string(info)) + `)`)
  263. if err != nil {
  264. t.Errorf("%v", err)
  265. }
  266. } else {
  267. checkEvalJSON(t, repl, `contract = eth.compile.solidity(source).test`, string(contractInfo))
  268. }
  269. checkEvalJSON(t, repl, `contract.code`, `"0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056"`)
  270. checkEvalJSON(
  271. t, repl,
  272. `contractaddress = eth.sendTransaction({from: primary, data: contract.code })`,
  273. `"0x5dcaace5982778b409c524873b319667eba5d074"`,
  274. )
  275. callSetup := `abiDef = JSON.parse('[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]');
  276. Multiply7 = eth.contract(abiDef);
  277. multiply7 = Multiply7.at(contractaddress);
  278. `
  279. // time.Sleep(1500 * time.Millisecond)
  280. _, err = repl.re.Run(callSetup)
  281. if err != nil {
  282. t.Errorf("unexpected error setting up contract, got %v", err)
  283. }
  284. // checkEvalJSON(t, repl, `eth.getBlock("pending", true).transactions.length`, `3`)
  285. // why is this sometimes failing?
  286. // checkEvalJSON(t, repl, `multiply7.multiply.call(6)`, `42`)
  287. expNotice := ""
  288. if repl.lastConfirm != expNotice {
  289. t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
  290. }
  291. txc, repl.xeth = repl.xeth.ApplyTestTxs(repl.stateDb, coinbase, txc)
  292. checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`)
  293. checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary, gas: "1000000", gasPrice: "100000" })`, `undefined`)
  294. expNotice = `About to submit transaction (no NatSpec info found for contract: content hash not found for '0x87e2802265838c7f14bb69eecd2112911af6767907a702eeaa445239fb20711b'): {"params":[{"to":"0x5dcaace5982778b409c524873b319667eba5d074","data": "0xc6888fa10000000000000000000000000000000000000000000000000000000000000006"}]}`
  295. if repl.lastConfirm != expNotice {
  296. t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
  297. }
  298. var contenthash = `"0x86d2b7cf1e72e9a7a3f8d96601f0151742a2f780f1526414304fbe413dc7f9bd"`
  299. if sol != nil {
  300. modContractInfo := versionRE.ReplaceAll(contractInfo, []byte(`"compilerVersion":"`+sol.Version()+`"`))
  301. _ = modContractInfo
  302. // contenthash = crypto.Sha3(modContractInfo)
  303. }
  304. checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`)
  305. checkEvalJSON(t, repl, `contenthash = admin.contractInfo.register(primary, contractaddress, contract, filename)`, contenthash)
  306. checkEvalJSON(t, repl, `admin.contractInfo.registerUrl(primary, contenthash, "file://"+filename)`, `true`)
  307. if err != nil {
  308. t.Errorf("unexpected error registering, got %v", err)
  309. }
  310. checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`)
  311. // update state
  312. txc, repl.xeth = repl.xeth.ApplyTestTxs(repl.stateDb, coinbase, txc)
  313. checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary, gas: "1000000", gasPrice: "100000" })`, `undefined`)
  314. expNotice = "Will multiply 6 by 7."
  315. if repl.lastConfirm != expNotice {
  316. t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
  317. }
  318. }
  319. func checkEvalJSON(t *testing.T, re *testjethre, expr, want string) error {
  320. val, err := re.re.Run("JSON.stringify(" + expr + ")")
  321. if err == nil && val.String() != want {
  322. err = fmt.Errorf("Output mismatch for `%s`:\ngot: %s\nwant: %s", expr, val.String(), want)
  323. }
  324. if err != nil {
  325. _, file, line, _ := runtime.Caller(1)
  326. file = filepath.Base(file)
  327. fmt.Printf("\t%s:%d: %v\n", file, line, err)
  328. t.Fail()
  329. }
  330. return err
  331. }