consolecmd.go 7.11 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
	"os"
22
	"path/filepath"
23
	"strings"
24 25 26

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

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

35
	consoleCommand = cli.Command{
36 37 38
		Action:   utils.MigrateFlags(localConsole),
		Name:     "console",
		Usage:    "Start an interactive JavaScript environment",
39
		Flags:    append(append(nodeFlags, rpcFlags...), consoleFlags...),
40
		Category: "CONSOLE COMMANDS",
41 42 43
		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.
44
See https://geth.ethereum.org/docs/interface/javascript-console.`,
45
	}
46

47
	attachCommand = cli.Command{
48
		Action:    utils.MigrateFlags(remoteConsole),
49 50
		Name:      "attach",
		Usage:     "Start an interactive JavaScript environment (connect to node)",
51 52
		ArgsUsage: "[endpoint]",
		Flags:     append(consoleFlags, utils.DataDirFlag),
53
		Category:  "CONSOLE COMMANDS",
54 55 56
		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.
57
See https://geth.ethereum.org/docs/interface/javascript-console.
58
This command allows to open a console on a running geth node.`,
59
	}
60

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

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

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

95 96 97 98 99 100 101 102 103
	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)
104
		return nil
105 106 107 108
	}
	// Otherwise print the welcome screen and enter interactive mode
	console.Welcome()
	console.Interactive()
109 110

	return nil
111 112 113 114
}

// remoteConsole will connect to a remote geth instance, attaching a JavaScript
// console to it.
115
func remoteConsole(ctx *cli.Context) error {
116
	// Attach to a remotely running geth instance and start the JavaScript console
117
	endpoint := ctx.Args().First()
118 119 120 121 122
	if endpoint == "" {
		path := node.DefaultDataDir()
		if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
			path = ctx.GlobalString(utils.DataDirFlag.Name)
		}
123
		if path != "" {
124
			if ctx.GlobalBool(utils.RopstenFlag.Name) {
125 126 127 128 129 130 131 132
				// 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")
				}
133 134
			} else if ctx.GlobalBool(utils.RinkebyFlag.Name) {
				path = filepath.Join(path, "rinkeby")
135 136
			} else if ctx.GlobalBool(utils.GoerliFlag.Name) {
				path = filepath.Join(path, "goerli")
137 138
			} else if ctx.GlobalBool(utils.YoloV3Flag.Name) {
				path = filepath.Join(path, "yolo-v3")
139
			}
140 141
		}
		endpoint = fmt.Sprintf("%s/geth.ipc", path)
142 143
	}
	client, err := dialRPC(endpoint)
144 145 146 147
	if err != nil {
		utils.Fatalf("Unable to attach to remote geth: %v", err)
	}
	config := console.Config{
148
		DataDir: utils.MakeDataDir(ctx),
149 150 151 152
		DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
		Client:  client,
		Preload: utils.MakeConsolePreloads(ctx),
	}
153

154 155 156 157 158 159 160 161
	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)
162
		return nil
163
	}
164

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

	return nil
170 171
}

172 173 174 175 176
// 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 == "" {
177
		endpoint = node.DefaultIPCEndpoint(clientIdentifier)
178 179 180 181 182 183 184 185
	} 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)
}

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

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

207 208 209 210 211 212 213 214 215 216 217 218 219 220
	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)
		}
	}

	go func() {
221 222
		stack.Wait()
		console.Stop(false)
223 224
	}()
	console.Stop(true)
225 226

	return nil
227
}