js_test.go 12 KB

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