consolecmd.go 7.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright 2016 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

package main

import (
20
	"fmt"
21 22
	"os"
	"os/signal"
23
	"path/filepath"
24
	"strings"
25
	"syscall"
26 27 28

	"github.com/ethereum/go-ethereum/cmd/utils"
	"github.com/ethereum/go-ethereum/console"
29 30
	"github.com/ethereum/go-ethereum/node"
	"github.com/ethereum/go-ethereum/rpc"
31
	"gopkg.in/urfave/cli.v1"
32 33
)

34 35 36
var (
	consoleFlags = []cli.Flag{utils.JSpathFlag, utils.ExecFlag, utils.PreloadJSFlag}

37
	consoleCommand = cli.Command{
38 39 40
		Action:   utils.MigrateFlags(localConsole),
		Name:     "console",
		Usage:    "Start an interactive JavaScript environment",
41
		Flags:    append(append(append(nodeFlags, rpcFlags...), consoleFlags...), whisperFlags...),
42
		Category: "CONSOLE COMMANDS",
43 44 45
		Description: `
The Geth console is an interactive shell for the JavaScript runtime environment
which exposes a node admin interface as well as the Ðapp JavaScript API.
46
See https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console.`,
47
	}
48

49
	attachCommand = cli.Command{
50
		Action:    utils.MigrateFlags(remoteConsole),
51 52
		Name:      "attach",
		Usage:     "Start an interactive JavaScript environment (connect to node)",
53 54
		ArgsUsage: "[endpoint]",
		Flags:     append(consoleFlags, utils.DataDirFlag),
55
		Category:  "CONSOLE COMMANDS",
56 57 58
		Description: `
The Geth console is an interactive shell for the JavaScript runtime environment
which exposes a node admin interface as well as the Ðapp JavaScript API.
59
See https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console.
60
This command allows to open a console on a running geth node.`,
61
	}
62

63
	javascriptCommand = cli.Command{
64
		Action:    utils.MigrateFlags(ephemeralConsole),
65 66
		Name:      "js",
		Usage:     "Execute the specified JavaScript files",
67 68
		ArgsUsage: "<jsfile> [jsfile...]",
		Flags:     append(nodeFlags, consoleFlags...),
69
		Category:  "CONSOLE COMMANDS",
70 71
		Description: `
The JavaScript VM exposes a node admin interface as well as the Ðapp
72
JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console`,
73 74 75 76 77
	}
)

// localConsole starts a new geth node, attaching a JavaScript console to it at the
// same time.
78
func localConsole(ctx *cli.Context) error {
79
	// Create and start the node based on the CLI flags
80
	prepare(ctx)
81
	node := makeFullNode(ctx)
82
	startNode(ctx, node)
83
	defer node.Close()
84 85 86 87 88 89 90

	// Attach to the newly started node and start the JavaScript console
	client, err := node.Attach()
	if err != nil {
		utils.Fatalf("Failed to attach to the inproc geth: %v", err)
	}
	config := console.Config{
91
		DataDir: utils.MakeDataDir(ctx),
92 93 94 95
		DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
		Client:  client,
		Preload: utils.MakeConsolePreloads(ctx),
	}
96

97 98 99 100 101 102 103 104 105
	console, err := console.New(config)
	if err != nil {
		utils.Fatalf("Failed to start the JavaScript console: %v", err)
	}
	defer console.Stop(false)

	// If only a short execution was requested, evaluate and return
	if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
		console.Evaluate(script)
106
		return nil
107 108 109 110
	}
	// Otherwise print the welcome screen and enter interactive mode
	console.Welcome()
	console.Interactive()
111 112

	return nil
113 114 115 116
}

// remoteConsole will connect to a remote geth instance, attaching a JavaScript
// console to it.
117
func remoteConsole(ctx *cli.Context) error {
118
	// Attach to a remotely running geth instance and start the JavaScript console
119
	endpoint := ctx.Args().First()
120 121 122 123 124
	if endpoint == "" {
		path := node.DefaultDataDir()
		if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
			path = ctx.GlobalString(utils.DataDirFlag.Name)
		}
125
		if path != "" {
126 127 128 129 130 131 132 133 134
			if ctx.GlobalBool(utils.LegacyTestnetFlag.Name) || ctx.GlobalBool(utils.RopstenFlag.Name) {
				// Maintain compatibility with older Geth configurations storing the
				// Ropsten database in `testnet` instead of `ropsten`.
				legacyPath := filepath.Join(path, "testnet")
				if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
					path = legacyPath
				} else {
					path = filepath.Join(path, "ropsten")
				}
135 136
			} else if ctx.GlobalBool(utils.RinkebyFlag.Name) {
				path = filepath.Join(path, "rinkeby")
137 138
			} else if ctx.GlobalBool(utils.GoerliFlag.Name) {
				path = filepath.Join(path, "goerli")
139 140
			} else if ctx.GlobalBool(utils.YoloV1Flag.Name) {
				path = filepath.Join(path, "yolo-v1")
141
			}
142 143
		}
		endpoint = fmt.Sprintf("%s/geth.ipc", path)
144 145
	}
	client, err := dialRPC(endpoint)
146 147 148 149
	if err != nil {
		utils.Fatalf("Unable to attach to remote geth: %v", err)
	}
	config := console.Config{
150
		DataDir: utils.MakeDataDir(ctx),
151 152 153 154
		DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
		Client:  client,
		Preload: utils.MakeConsolePreloads(ctx),
	}
155

156 157 158 159 160 161 162 163
	console, err := console.New(config)
	if err != nil {
		utils.Fatalf("Failed to start the JavaScript console: %v", err)
	}
	defer console.Stop(false)

	if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
		console.Evaluate(script)
164
		return nil
165
	}
166

167 168 169
	// Otherwise print the welcome screen and enter interactive mode
	console.Welcome()
	console.Interactive()
170 171

	return nil
172 173
}

174 175 176 177 178
// dialRPC returns a RPC client which connects to the given endpoint.
// The check for empty endpoint implements the defaulting logic
// for "geth attach" and "geth monitor" with no argument.
func dialRPC(endpoint string) (*rpc.Client, error) {
	if endpoint == "" {
179
		endpoint = node.DefaultIPCEndpoint(clientIdentifier)
180 181 182 183 184 185 186 187
	} else if strings.HasPrefix(endpoint, "rpc:") || strings.HasPrefix(endpoint, "ipc:") {
		// Backwards compatibility with geth < 1.5 which required
		// these prefixes.
		endpoint = endpoint[4:]
	}
	return rpc.Dial(endpoint)
}

188
// ephemeralConsole starts a new geth node, attaches an ephemeral JavaScript
189
// console to it, executes each of the files specified as arguments and tears
190
// everything down.
191
func ephemeralConsole(ctx *cli.Context) error {
192
	// Create and start the node based on the CLI flags
193
	node := makeFullNode(ctx)
194
	startNode(ctx, node)
195
	defer node.Close()
196 197 198 199 200 201 202

	// Attach to the newly started node and start the JavaScript console
	client, err := node.Attach()
	if err != nil {
		utils.Fatalf("Failed to attach to the inproc geth: %v", err)
	}
	config := console.Config{
203
		DataDir: utils.MakeDataDir(ctx),
204 205 206 207
		DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
		Client:  client,
		Preload: utils.MakeConsolePreloads(ctx),
	}
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222
	console, err := console.New(config)
	if err != nil {
		utils.Fatalf("Failed to start the JavaScript console: %v", err)
	}
	defer console.Stop(false)

	// Evaluate each of the specified JavaScript files
	for _, file := range ctx.Args() {
		if err = console.Execute(file); err != nil {
			utils.Fatalf("Failed to execute %s: %v", file, err)
		}
	}
	// Wait for pending callbacks, but stop for Ctrl-C.
	abort := make(chan os.Signal, 1)
223
	signal.Notify(abort, syscall.SIGINT, syscall.SIGTERM)
224 225 226 227 228 229

	go func() {
		<-abort
		os.Exit(0)
	}()
	console.Stop(true)
230 231

	return nil
232
}