js_test.go 12 KB

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