js_test.go 12 KB

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