consolecmd.go 7.34 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
	stack, backend := makeFullNode(ctx)
80
	startNode(ctx, stack, backend, true)
81
	defer stack.Close()
82

83
	// Attach to the newly started node and create the JavaScript console.
84
	client, err := stack.Attach()
85
	if err != nil {
86
		return fmt.Errorf("Failed to attach to the inproc geth: %v", err)
87 88
	}
	config := console.Config{
89
		DataDir: utils.MakeDataDir(ctx),
90 91 92 93 94 95
		DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
		Client:  client,
		Preload: utils.MakeConsolePreloads(ctx),
	}
	console, err := console.New(config)
	if err != nil {
96
		return fmt.Errorf("Failed to start the JavaScript console: %v", err)
97 98 99
	}
	defer console.Stop(false)

100
	// If only a short execution was requested, evaluate and return.
101 102
	if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
		console.Evaluate(script)
103
		return nil
104
	}
105 106 107 108 109 110 111 112 113

	// Track node shutdown and stop the console when it goes down.
	// This happens when SIGTERM is sent to the process.
	go func() {
		stack.Wait()
		console.StopInteractive()
	}()

	// Print the welcome screen and enter interactive mode.
114 115
	console.Welcome()
	console.Interactive()
116
	return nil
117 118 119 120
}

// remoteConsole will connect to a remote geth instance, attaching a JavaScript
// console to it.
121
func remoteConsole(ctx *cli.Context) error {
122
	endpoint := ctx.Args().First()
123 124 125 126 127
	if endpoint == "" {
		path := node.DefaultDataDir()
		if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
			path = ctx.GlobalString(utils.DataDirFlag.Name)
		}
128
		if path != "" {
129
			if ctx.GlobalBool(utils.RopstenFlag.Name) {
130 131 132 133 134 135 136 137
				// 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")
				}
138 139
			} else if ctx.GlobalBool(utils.RinkebyFlag.Name) {
				path = filepath.Join(path, "rinkeby")
140 141
			} else if ctx.GlobalBool(utils.GoerliFlag.Name) {
				path = filepath.Join(path, "goerli")
142 143
			} else if ctx.GlobalBool(utils.SepoliaFlag.Name) {
				path = filepath.Join(path, "sepolia")
144
			}
145 146
		}
		endpoint = fmt.Sprintf("%s/geth.ipc", path)
147 148
	}
	client, err := dialRPC(endpoint)
149 150 151 152
	if err != nil {
		utils.Fatalf("Unable to attach to remote geth: %v", err)
	}
	config := console.Config{
153
		DataDir: utils.MakeDataDir(ctx),
154 155 156 157 158 159 160 161 162 163 164 165
		DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
		Client:  client,
		Preload: utils.MakeConsolePreloads(ctx),
	}
	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)
166
		return nil
167
	}
168

169 170 171
	// Otherwise print the welcome screen and enter interactive mode
	console.Welcome()
	console.Interactive()
172
	return nil
173 174
}

175 176
// dialRPC returns a RPC client which connects to the given endpoint.
// The check for empty endpoint implements the defaulting logic
177
// for "geth attach" with no argument.
178 179
func dialRPC(endpoint string) (*rpc.Client, error) {
	if endpoint == "" {
180
		endpoint = node.DefaultIPCEndpoint(clientIdentifier)
181 182 183 184 185 186 187 188
	} 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)
}

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

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

210 211
	console, err := console.New(config)
	if err != nil {
212
		return fmt.Errorf("Failed to start the JavaScript console: %v", err)
213 214 215
	}
	defer console.Stop(false)

216 217 218 219 220 221 222
	// Interrupt the JS interpreter when node is stopped.
	go func() {
		stack.Wait()
		console.Stop(false)
	}()

	// Evaluate each of the specified JavaScript files.
223 224
	for _, file := range ctx.Args() {
		if err = console.Execute(file); err != nil {
225
			return fmt.Errorf("Failed to execute %s: %v", file, err)
226 227 228
		}
	}

229
	// The main script is now done, but keep running timers/callbacks.
230
	console.Stop(true)
231
	return nil
232
}