js.go 12 KB

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