js_test.go 11 KB

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