Skip to content

Commit ffaf58f

Browse files
committed
cmd, console: split off the console into a reusable package
1 parent ab664c7 commit ffaf58f

26 files changed

Lines changed: 1548 additions & 1519 deletions

‎cmd/geth/accountcmd.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"github.com/codegangsta/cli"
2424
"github.com/ethereum/go-ethereum/accounts"
2525
"github.com/ethereum/go-ethereum/cmd/utils"
26+
"github.com/ethereum/go-ethereum/console"
2627
"github.com/ethereum/go-ethereum/crypto"
2728
"github.com/ethereum/go-ethereum/logger"
2829
"github.com/ethereum/go-ethereum/logger/glog"
@@ -215,12 +216,12 @@ func getPassPhrase(prompt string, confirmation bool, i int, passwords []string)
215216
if prompt != "" {
216217
fmt.Println(prompt)
217218
}
218-
password, err := utils.Stdin.PasswordPrompt("Passphrase: ")
219+
password, err := console.TerminalPrompter.PromptPassword("Passphrase: ")
219220
if err != nil {
220221
utils.Fatalf("Failed to read passphrase: %v", err)
221222
}
222223
if confirmation {
223-
confirm, err := utils.Stdin.PasswordPrompt("Repeat passphrase: ")
224+
confirm, err := console.TerminalPrompter.PromptPassword("Repeat passphrase: ")
224225
if err != nil {
225226
utils.Fatalf("Failed to read passphrase confirmation: %v", err)
226227
}

‎cmd/geth/chaincmd.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"github.com/codegangsta/cli"
2727
"github.com/ethereum/go-ethereum/cmd/utils"
2828
"github.com/ethereum/go-ethereum/common"
29+
"github.com/ethereum/go-ethereum/console"
2930
"github.com/ethereum/go-ethereum/core"
3031
"github.com/ethereum/go-ethereum/core/state"
3132
"github.com/ethereum/go-ethereum/core/types"
@@ -116,7 +117,7 @@ func exportChain(ctx *cli.Context) {
116117
}
117118

118119
func removeDB(ctx *cli.Context) {
119-
confirm, err := utils.Stdin.ConfirmPrompt("Remove local database?")
120+
confirm, err := console.TerminalPrompter.PromptConfirm("Remove local database?")
120121
if err != nil {
121122
utils.Fatalf("%v", err)
122123
}

‎cmd/geth/consolecmd.go‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// Copyright 2016 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+
17+
package main
18+
19+
import (
20+
"os"
21+
"os/signal"
22+
23+
"github.com/codegangsta/cli"
24+
"github.com/ethereum/go-ethereum/cmd/utils"
25+
"github.com/ethereum/go-ethereum/console"
26+
)
27+
28+
var (
29+
consoleCommand = cli.Command{
30+
Action: localConsole,
31+
Name: "console",
32+
Usage: `Geth Console: interactive JavaScript environment`,
33+
Description: `
34+
The Geth console is an interactive shell for the JavaScript runtime environment
35+
which exposes a node admin interface as well as the Ðapp JavaScript API.
36+
See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
37+
`,
38+
}
39+
attachCommand = cli.Command{
40+
Action: remoteConsole,
41+
Name: "attach",
42+
Usage: `Geth Console: interactive JavaScript environment (connect to node)`,
43+
Description: `
44+
The Geth console is an interactive shell for the JavaScript runtime environment
45+
which exposes a node admin interface as well as the Ðapp JavaScript API.
46+
See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console.
47+
This command allows to open a console on a running geth node.
48+
`,
49+
}
50+
javascriptCommand = cli.Command{
51+
Action: ephemeralConsole,
52+
Name: "js",
53+
Usage: `executes the given JavaScript files in the Geth JavaScript VM`,
54+
Description: `
55+
The JavaScript VM exposes a node admin interface as well as the Ðapp
56+
JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
57+
`,
58+
}
59+
)
60+
61+
// localConsole starts a new geth node, attaching a JavaScript console to it at the
62+
// same time.
63+
func localConsole(ctx *cli.Context) {
64+
// Create and start the node based on the CLI flags
65+
node := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx)
66+
startNode(ctx, node)
67+
defer node.Stop()
68+
69+
// Attach to the newly started node and start the JavaScript console
70+
client, err := node.Attach()
71+
if err != nil {
72+
utils.Fatalf("Failed to attach to the inproc geth: %v", err)
73+
}
74+
config := console.Config{
75+
DataDir: node.DataDir(),
76+
DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
77+
Client: client,
78+
Preload: utils.MakeConsolePreloads(ctx),
79+
}
80+
console, err := console.New(config)
81+
if err != nil {
82+
utils.Fatalf("Failed to start the JavaScript console: %v", err)
83+
}
84+
defer console.Stop(false)
85+
86+
// If only a short execution was requested, evaluate and return
87+
if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
88+
console.Evaluate(script)
89+
return
90+
}
91+
// Otherwise print the welcome screen and enter interactive mode
92+
console.Welcome()
93+
console.Interactive()
94+
}
95+
96+
// remoteConsole will connect to a remote geth instance, attaching a JavaScript
97+
// console to it.
98+
func remoteConsole(ctx *cli.Context) {
99+
// Attach to a remotely running geth instance and start the JavaScript console
100+
client, err := utils.NewRemoteRPCClient(ctx)
101+
if err != nil {
102+
utils.Fatalf("Unable to attach to remote geth: %v", err)
103+
}
104+
config := console.Config{
105+
DataDir: utils.MustMakeDataDir(ctx),
106+
DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
107+
Client: client,
108+
Preload: utils.MakeConsolePreloads(ctx),
109+
}
110+
console, err := console.New(config)
111+
if err != nil {
112+
utils.Fatalf("Failed to start the JavaScript console: %v", err)
113+
}
114+
defer console.Stop(false)
115+
116+
// If only a short execution was requested, evaluate and return
117+
if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
118+
console.Evaluate(script)
119+
return
120+
}
121+
// Otherwise print the welcome screen and enter interactive mode
122+
console.Welcome()
123+
console.Interactive()
124+
}
125+
126+
// ephemeralConsole starts a new geth node, attaches an ephemeral JavaScript
127+
// console to it, and each of the files specified as arguments and tears the
128+
// everything down.
129+
func ephemeralConsole(ctx *cli.Context) {
130+
// Create and start the node based on the CLI flags
131+
node := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx)
132+
startNode(ctx, node)
133+
defer node.Stop()
134+
135+
// Attach to the newly started node and start the JavaScript console
136+
client, err := node.Attach()
137+
if err != nil {
138+
utils.Fatalf("Failed to attach to the inproc geth: %v", err)
139+
}
140+
config := console.Config{
141+
DataDir: node.DataDir(),
142+
DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
143+
Client: client,
144+
Preload: utils.MakeConsolePreloads(ctx),
145+
}
146+
console, err := console.New(config)
147+
if err != nil {
148+
utils.Fatalf("Failed to start the JavaScript console: %v", err)
149+
}
150+
defer console.Stop(false)
151+
152+
// Evaluate each of the specified JavaScript files
153+
for _, file := range ctx.Args() {
154+
if err = console.Execute(file); err != nil {
155+
utils.Fatalf("Failed to execute %s: %v", file, err)
156+
}
157+
}
158+
// Wait for pending callbacks, but stop for Ctrl-C.
159+
abort := make(chan os.Signal, 1)
160+
signal.Notify(abort, os.Interrupt)
161+
162+
go func() {
163+
<-abort
164+
os.Exit(0)
165+
}()
166+
console.Stop(true)
167+
}

‎cmd/geth/consolecmd_test.go‎

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Copyright 2016 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+
17+
package main
18+
19+
import (
20+
"math/rand"
21+
"os"
22+
"path/filepath"
23+
"runtime"
24+
"sort"
25+
"strconv"
26+
"strings"
27+
"testing"
28+
"time"
29+
30+
"github.com/ethereum/go-ethereum/console"
31+
"github.com/ethereum/go-ethereum/rpc"
32+
)
33+
34+
// Tests that a node embedded within a console can be started up properly and
35+
// then terminated by closing the input stream.
36+
func TestConsoleWelcome(t *testing.T) {
37+
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
38+
39+
// Start a geth console, make sure it's cleaned up and terminate the console
40+
geth := runGeth(t, "--nat", "none", "--nodiscover", "--etherbase", coinbase, "-shh", "console")
41+
defer geth.expectExit()
42+
geth.stdin.Close()
43+
44+
// Gather all the infos the welcome message needs to contain
45+
geth.setTemplateFunc("goos", func() string { return runtime.GOOS })
46+
geth.setTemplateFunc("gover", runtime.Version)
47+
geth.setTemplateFunc("gethver", func() string { return verString })
48+
geth.setTemplateFunc("niltime", func() string { return time.Unix(0, 0).Format(time.RFC1123) })
49+
geth.setTemplateFunc("apis", func() []string {
50+
apis := append(strings.Split(rpc.DefaultIPCApis, ","), rpc.MetadataApi)
51+
sort.Strings(apis)
52+
return apis
53+
})
54+
geth.setTemplateFunc("prompt", func() string { return console.DefaultPrompt })
55+
56+
// Verify the actual welcome message to the required template
57+
geth.expect(`
58+
Welcome to the Geth JavaScript console!
59+
60+
instance: Geth/v{{gethver}}/{{goos}}/{{gover}}
61+
coinbase: {{.Etherbase}}
62+
at block: 0 ({{niltime}})
63+
datadir: {{.Datadir}}
64+
modules:{{range apis}} {{.}}:1.0{{end}}
65+
66+
{{prompt}}
67+
`)
68+
}
69+
70+
// Tests that a console can be attached to a running node via various means.
71+
func TestIPCAttachWelcome(t *testing.T) {
72+
// Configure the instance for IPC attachement
73+
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
74+
75+
var ipc string
76+
if runtime.GOOS == "windows" {
77+
ipc = `\\.\pipe\geth` + strconv.Itoa(rand.Int())
78+
} else {
79+
ws := tmpdir(t)
80+
defer os.RemoveAll(ws)
81+
82+
ipc = filepath.Join(ws, "geth.ipc")
83+
}
84+
// Run the parent geth and attach with a child console
85+
geth := runGeth(t, "--nat", "none", "--nodiscover", "--etherbase", coinbase, "-shh", "--ipcpath", ipc)
86+
defer geth.interrupt()
87+
88+
time.Sleep(2 * time.Second) // Simple way to wait for the RPC endpoint to open
89+
testAttachWelcome(t, geth, "ipc:"+ipc)
90+
}
91+
92+
func TestHTTPAttachWelcome(t *testing.T) {
93+
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
94+
port := strconv.Itoa(rand.Intn(65535-1024) + 1024) // Yeah, sometimes this will fail, sorry :P
95+
96+
geth := runGeth(t, "--nat", "none", "--nodiscover", "--etherbase", coinbase, "--rpc", "--rpcport", port)
97+
defer geth.interrupt()
98+
99+
time.Sleep(2 * time.Second) // Simple way to wait for the RPC endpoint to open
100+
testAttachWelcome(t, geth, "http://localhost:"+port)
101+
}
102+
103+
func TestWSAttachWelcome(t *testing.T) {
104+
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
105+
port := strconv.Itoa(rand.Intn(65535-1024) + 1024) // Yeah, sometimes this will fail, sorry :P
106+
107+
geth := runGeth(t, "--nat", "none", "--nodiscover", "--etherbase", coinbase, "--ws", "--wsport", port)
108+
defer geth.interrupt()
109+
110+
time.Sleep(2 * time.Second) // Simple way to wait for the RPC endpoint to open
111+
testAttachWelcome(t, geth, "ws://localhost:"+port)
112+
}
113+
114+
func testAttachWelcome(t *testing.T, geth *testgeth, endpoint string) {
115+
// Attach to a running geth note and terminate immediately
116+
attach := runGeth(t, "attach", endpoint)
117+
defer attach.expectExit()
118+
attach.stdin.Close()
119+
120+
// Gather all the infos the welcome message needs to contain
121+
attach.setTemplateFunc("goos", func() string { return runtime.GOOS })
122+
attach.setTemplateFunc("gover", runtime.Version)
123+
attach.setTemplateFunc("gethver", func() string { return verString })
124+
attach.setTemplateFunc("etherbase", func() string { return geth.Etherbase })
125+
attach.setTemplateFunc("niltime", func() string { return time.Unix(0, 0).Format(time.RFC1123) })
126+
attach.setTemplateFunc("ipc", func() bool { return strings.HasPrefix(endpoint, "ipc") })
127+
attach.setTemplateFunc("datadir", func() string { return geth.Datadir })
128+
attach.setTemplateFunc("apis", func() []string {
129+
var apis []string
130+
if strings.HasPrefix(endpoint, "ipc") {
131+
apis = append(strings.Split(rpc.DefaultIPCApis, ","), rpc.MetadataApi)
132+
} else {
133+
apis = append(strings.Split(rpc.DefaultHTTPApis, ","), rpc.MetadataApi)
134+
}
135+
sort.Strings(apis)
136+
return apis
137+
})
138+
attach.setTemplateFunc("prompt", func() string { return console.DefaultPrompt })
139+
140+
// Verify the actual welcome message to the required template
141+
attach.expect(`
142+
Welcome to the Geth JavaScript console!
143+
144+
instance: Geth/v{{gethver}}/{{goos}}/{{gover}}
145+
coinbase: {{etherbase}}
146+
at block: 0 ({{niltime}}){{if ipc}}
147+
datadir: {{datadir}}{{end}}
148+
modules:{{range apis}} {{.}}:1.0{{end}}
149+
150+
{{prompt}}
151+
`)
152+
}

0 commit comments

Comments
 (0)