js.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "fmt"
  19. "math/big"
  20. "os"
  21. "os/signal"
  22. "path/filepath"
  23. "regexp"
  24. "sort"
  25. "strings"
  26. "github.com/codegangsta/cli"
  27. "github.com/ethereum/go-ethereum/accounts"
  28. "github.com/ethereum/go-ethereum/cmd/utils"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/registrar"
  31. "github.com/ethereum/go-ethereum/eth"
  32. "github.com/ethereum/go-ethereum/internal/web3ext"
  33. re "github.com/ethereum/go-ethereum/jsre"
  34. "github.com/ethereum/go-ethereum/node"
  35. "github.com/ethereum/go-ethereum/rpc"
  36. "github.com/peterh/liner"
  37. "github.com/robertkrimen/otto"
  38. )
  39. var (
  40. passwordRegexp = regexp.MustCompile("personal.[nu]")
  41. leadingSpace = regexp.MustCompile("^ ")
  42. onlyws = regexp.MustCompile("^\\s*$")
  43. exit = regexp.MustCompile("^\\s*exit\\s*;*\\s*$")
  44. )
  45. type jsre struct {
  46. re *re.JSRE
  47. stack *node.Node
  48. wait chan *big.Int
  49. ps1 string
  50. atexit func()
  51. corsDomain string
  52. client rpc.Client
  53. }
  54. func makeCompleter(re *jsre) liner.WordCompleter {
  55. return func(line string, pos int) (head string, completions []string, tail string) {
  56. if len(line) == 0 || pos == 0 {
  57. return "", nil, ""
  58. }
  59. // chuck data to relevant part for autocompletion, e.g. in case of nested lines eth.getBalance(eth.coinb<tab><tab>
  60. i := 0
  61. for i = pos - 1; i > 0; i-- {
  62. if line[i] == '.' || (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') {
  63. continue
  64. }
  65. if i >= 3 && line[i] == '3' && line[i-3] == 'w' && line[i-2] == 'e' && line[i-1] == 'b' {
  66. continue
  67. }
  68. i += 1
  69. break
  70. }
  71. return line[:i], re.re.CompleteKeywords(line[i:pos]), line[pos:]
  72. }
  73. }
  74. func newLightweightJSRE(docRoot string, client rpc.Client, datadir string, interactive bool) *jsre {
  75. js := &jsre{ps1: "> "}
  76. js.wait = make(chan *big.Int)
  77. js.client = client
  78. js.re = re.New(docRoot)
  79. if err := js.apiBindings(); err != nil {
  80. utils.Fatalf("Unable to initialize console - %v", err)
  81. }
  82. js.setupInput(datadir)
  83. return js
  84. }
  85. func newJSRE(stack *node.Node, docRoot, corsDomain string, client rpc.Client, interactive bool) *jsre {
  86. js := &jsre{stack: stack, ps1: "> "}
  87. // set default cors domain used by startRpc from CLI flag
  88. js.corsDomain = corsDomain
  89. js.wait = make(chan *big.Int)
  90. js.client = client
  91. js.re = re.New(docRoot)
  92. if err := js.apiBindings(); err != nil {
  93. utils.Fatalf("Unable to connect - %v", err)
  94. }
  95. js.setupInput(stack.DataDir())
  96. return js
  97. }
  98. func (self *jsre) setupInput(datadir string) {
  99. self.withHistory(datadir, func(hist *os.File) { utils.Stdin.ReadHistory(hist) })
  100. utils.Stdin.SetCtrlCAborts(true)
  101. utils.Stdin.SetWordCompleter(makeCompleter(self))
  102. utils.Stdin.SetTabCompletionStyle(liner.TabPrints)
  103. self.atexit = func() {
  104. self.withHistory(datadir, func(hist *os.File) {
  105. hist.Truncate(0)
  106. utils.Stdin.WriteHistory(hist)
  107. })
  108. utils.Stdin.Close()
  109. close(self.wait)
  110. }
  111. }
  112. func (self *jsre) batch(statement string) {
  113. err := self.re.EvalAndPrettyPrint(statement)
  114. if err != nil {
  115. fmt.Printf("error: %v", err)
  116. }
  117. if self.atexit != nil {
  118. self.atexit()
  119. }
  120. self.re.Stop(false)
  121. }
  122. // show summary of current geth instance
  123. func (self *jsre) welcome() {
  124. self.re.Run(`
  125. (function () {
  126. console.log('instance: ' + web3.version.node);
  127. console.log("coinbase: " + eth.coinbase);
  128. var ts = 1000 * eth.getBlock(eth.blockNumber).timestamp;
  129. console.log("at block: " + eth.blockNumber + " (" + new Date(ts) + ")");
  130. console.log(' datadir: ' + admin.datadir);
  131. })();
  132. `)
  133. if modules, err := self.supportedApis(); err == nil {
  134. loadedModules := make([]string, 0)
  135. for api, version := range modules {
  136. loadedModules = append(loadedModules, fmt.Sprintf("%s:%s", api, version))
  137. }
  138. sort.Strings(loadedModules)
  139. }
  140. }
  141. func (self *jsre) supportedApis() (map[string]string, error) {
  142. return self.client.SupportedModules()
  143. }
  144. func (js *jsre) apiBindings() error {
  145. apis, err := js.supportedApis()
  146. if err != nil {
  147. return err
  148. }
  149. apiNames := make([]string, 0, len(apis))
  150. for a, _ := range apis {
  151. apiNames = append(apiNames, a)
  152. }
  153. jeth := utils.NewJeth(js.re, js.client)
  154. js.re.Set("jeth", struct{}{})
  155. t, _ := js.re.Get("jeth")
  156. jethObj := t.Object()
  157. jethObj.Set("send", jeth.Send)
  158. jethObj.Set("sendAsync", jeth.Send)
  159. err = js.re.Compile("bignumber.js", re.BigNumber_JS)
  160. if err != nil {
  161. utils.Fatalf("Error loading bignumber.js: %v", err)
  162. }
  163. err = js.re.Compile("web3.js", re.Web3_JS)
  164. if err != nil {
  165. utils.Fatalf("Error loading web3.js: %v", err)
  166. }
  167. _, err = js.re.Run("var Web3 = require('web3');")
  168. if err != nil {
  169. utils.Fatalf("Error requiring web3: %v", err)
  170. }
  171. _, err = js.re.Run("var web3 = new Web3(jeth);")
  172. if err != nil {
  173. utils.Fatalf("Error setting web3 provider: %v", err)
  174. }
  175. // load only supported API's in javascript runtime
  176. shortcuts := "var eth = web3.eth; var personal = web3.personal; "
  177. for _, apiName := range apiNames {
  178. if apiName == "web3" || apiName == "rpc" {
  179. continue // manually mapped or ignore
  180. }
  181. if jsFile, ok := web3ext.Modules[apiName]; ok {
  182. if err = js.re.Compile(fmt.Sprintf("%s.js", apiName), jsFile); err == nil {
  183. shortcuts += fmt.Sprintf("var %s = web3.%s; ", apiName, apiName)
  184. } else {
  185. utils.Fatalf("Error loading %s.js: %v", apiName, err)
  186. }
  187. }
  188. }
  189. _, err = js.re.Run(shortcuts)
  190. if err != nil {
  191. utils.Fatalf("Error setting namespaces: %v", err)
  192. }
  193. js.re.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `); registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`)
  194. // overrule some of the methods that require password as input and ask for it interactively
  195. p, err := js.re.Get("personal")
  196. if err != nil {
  197. fmt.Println("Unable to overrule sensitive methods in personal module")
  198. return nil
  199. }
  200. // Override the unlockAccount and newAccount methods on the personal object since these require user interaction.
  201. // Assign the jeth.unlockAccount and jeth.newAccount in the jsre the original web3 callbacks. These will be called
  202. // by the jeth.* methods after they got the password from the user and send the original web3 request to the backend.
  203. if persObj := p.Object(); persObj != nil { // make sure the personal api is enabled over the interface
  204. js.re.Run(`jeth.unlockAccount = personal.unlockAccount;`)
  205. persObj.Set("unlockAccount", jeth.UnlockAccount)
  206. js.re.Run(`jeth.newAccount = personal.newAccount;`)
  207. persObj.Set("newAccount", jeth.NewAccount)
  208. }
  209. // The admin.sleep and admin.sleepBlocks are offered by the console and not by the RPC layer.
  210. // Bind these if the admin module is available.
  211. if a, err := js.re.Get("admin"); err == nil {
  212. if adminObj := a.Object(); adminObj != nil {
  213. adminObj.Set("sleepBlocks", jeth.SleepBlocks)
  214. adminObj.Set("sleep", jeth.Sleep)
  215. }
  216. }
  217. return nil
  218. }
  219. func (self *jsre) AskPassword() (string, bool) {
  220. pass, err := utils.Stdin.PasswordPrompt("Passphrase: ")
  221. if err != nil {
  222. return "", false
  223. }
  224. return pass, true
  225. }
  226. func (self *jsre) ConfirmTransaction(tx string) bool {
  227. // Retrieve the Ethereum instance from the node
  228. var ethereum *eth.Ethereum
  229. if err := self.stack.Service(&ethereum); err != nil {
  230. return false
  231. }
  232. // If natspec is enabled, ask for permission
  233. if ethereum.NatSpec && false /* disabled for now */ {
  234. // notice := natspec.GetNotice(self.xeth, tx, ethereum.HTTPClient())
  235. // fmt.Println(notice)
  236. // answer, _ := self.Prompt("Confirm Transaction [y/n]")
  237. // return strings.HasPrefix(strings.Trim(answer, " "), "y")
  238. }
  239. return true
  240. }
  241. func (self *jsre) UnlockAccount(addr []byte) bool {
  242. fmt.Printf("Please unlock account %x.\n", addr)
  243. pass, err := utils.Stdin.PasswordPrompt("Passphrase: ")
  244. if err != nil {
  245. return false
  246. }
  247. // TODO: allow retry
  248. var ethereum *eth.Ethereum
  249. if err := self.stack.Service(&ethereum); err != nil {
  250. return false
  251. }
  252. a := accounts.Account{Address: common.BytesToAddress(addr)}
  253. if err := ethereum.AccountManager().Unlock(a, pass); err != nil {
  254. return false
  255. } else {
  256. fmt.Println("Account is now unlocked for this session.")
  257. return true
  258. }
  259. }
  260. // preloadJSFiles loads JS files that the user has specified with ctx.PreLoadJSFlag into
  261. // the JSRE. If not all files could be loaded it will return an error describing the error.
  262. func (self *jsre) preloadJSFiles(ctx *cli.Context) error {
  263. if ctx.GlobalString(utils.PreLoadJSFlag.Name) != "" {
  264. assetPath := ctx.GlobalString(utils.JSpathFlag.Name)
  265. jsFiles := strings.Split(ctx.GlobalString(utils.PreLoadJSFlag.Name), ",")
  266. for _, file := range jsFiles {
  267. filename := common.AbsolutePath(assetPath, strings.TrimSpace(file))
  268. if err := self.re.Exec(filename); err != nil {
  269. return fmt.Errorf("%s: %v", file, err)
  270. }
  271. }
  272. }
  273. return nil
  274. }
  275. // exec executes the JS file with the given filename and stops the JSRE
  276. func (self *jsre) exec(filename string) error {
  277. if err := self.re.Exec(filename); err != nil {
  278. self.re.Stop(false)
  279. return fmt.Errorf("Javascript Error: %v", err)
  280. }
  281. self.re.Stop(true)
  282. return nil
  283. }
  284. func (self *jsre) interactive() {
  285. // Read input lines.
  286. prompt := make(chan string)
  287. inputln := make(chan string)
  288. go func() {
  289. defer close(inputln)
  290. for {
  291. line, err := utils.Stdin.Prompt(<-prompt)
  292. if err != nil {
  293. if err == liner.ErrPromptAborted { // ctrl-C
  294. self.resetPrompt()
  295. inputln <- ""
  296. continue
  297. }
  298. return
  299. }
  300. inputln <- line
  301. }
  302. }()
  303. // Wait for Ctrl-C, too.
  304. sig := make(chan os.Signal, 1)
  305. signal.Notify(sig, os.Interrupt)
  306. defer func() {
  307. if self.atexit != nil {
  308. self.atexit()
  309. }
  310. self.re.Stop(false)
  311. }()
  312. for {
  313. prompt <- self.ps1
  314. select {
  315. case <-sig:
  316. fmt.Println("caught interrupt, exiting")
  317. return
  318. case input, ok := <-inputln:
  319. if !ok || indentCount <= 0 && exit.MatchString(input) {
  320. return
  321. }
  322. if onlyws.MatchString(input) {
  323. continue
  324. }
  325. str += input + "\n"
  326. self.setIndent()
  327. if indentCount <= 0 {
  328. if mustLogInHistory(str) {
  329. utils.Stdin.AppendHistory(str[:len(str)-1])
  330. }
  331. self.parseInput(str)
  332. str = ""
  333. }
  334. }
  335. }
  336. }
  337. func mustLogInHistory(input string) bool {
  338. return len(input) == 0 ||
  339. passwordRegexp.MatchString(input) ||
  340. !leadingSpace.MatchString(input)
  341. }
  342. func (self *jsre) withHistory(datadir string, op func(*os.File)) {
  343. hist, err := os.OpenFile(filepath.Join(datadir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  344. if err != nil {
  345. fmt.Printf("unable to open history file: %v\n", err)
  346. return
  347. }
  348. op(hist)
  349. hist.Close()
  350. }
  351. func (self *jsre) parseInput(code string) {
  352. defer func() {
  353. if r := recover(); r != nil {
  354. fmt.Println("[native] error", r)
  355. }
  356. }()
  357. if err := self.re.EvalAndPrettyPrint(code); err != nil {
  358. if ottoErr, ok := err.(*otto.Error); ok {
  359. fmt.Println(ottoErr.String())
  360. } else {
  361. fmt.Println(err)
  362. }
  363. return
  364. }
  365. }
  366. var indentCount = 0
  367. var str = ""
  368. func (self *jsre) resetPrompt() {
  369. indentCount = 0
  370. str = ""
  371. self.ps1 = "> "
  372. }
  373. func (self *jsre) setIndent() {
  374. open := strings.Count(str, "{")
  375. open += strings.Count(str, "(")
  376. closed := strings.Count(str, "}")
  377. closed += strings.Count(str, ")")
  378. indentCount = open - closed
  379. if indentCount <= 0 {
  380. self.ps1 = "> "
  381. } else {
  382. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  383. self.ps1 += " "
  384. }
  385. }