Skip to content

Commit a13bc9d

Browse files
committed
cmd, common, node, rpc: move HTTP RPC into node, drop singletone aspect
1 parent ba7c125 commit a13bc9d

10 files changed

Lines changed: 274 additions & 215 deletions

File tree

‎cmd/geth/main.go‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -503,11 +503,6 @@ func startNode(ctx *cli.Context, stack *node.Node) {
503503
}
504504
}
505505
// Start auxiliary services if enabled
506-
if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
507-
if err := utils.StartRPC(stack, ctx); err != nil {
508-
utils.Fatalf("Failed to start RPC: %v", err)
509-
}
510-
}
511506
if ctx.GlobalBool(utils.WSEnabledFlag.Name) {
512507
if err := utils.StartWS(stack, ctx); err != nil {
513508
utils.Fatalf("Failed to start WS: %v", err)

‎cmd/gethrpctest/main.go‎

Lines changed: 8 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,17 @@
1818
package main
1919

2020
import (
21-
"errors"
2221
"flag"
2322
"io/ioutil"
2423
"log"
2524
"os"
2625
"os/signal"
2726

2827
"github.com/ethereum/go-ethereum/accounts"
28+
"github.com/ethereum/go-ethereum/common"
2929
"github.com/ethereum/go-ethereum/crypto"
3030
"github.com/ethereum/go-ethereum/eth"
3131
"github.com/ethereum/go-ethereum/ethdb"
32-
"github.com/ethereum/go-ethereum/logger"
3332
"github.com/ethereum/go-ethereum/logger/glog"
3433
"github.com/ethereum/go-ethereum/node"
3534
"github.com/ethereum/go-ethereum/tests"
@@ -84,12 +83,6 @@ func main() {
8483
}
8584
log.Println("Initial test suite passed...")
8685

87-
// Start the RPC interface and wait until terminated
88-
if err := StartRPC(stack); err != nil {
89-
log.Fatalf("Failed to start RPC interface: %v", err)
90-
}
91-
log.Println("RPC Interface started, accepting requests...")
92-
9386
quit := make(chan os.Signal, 1)
9487
signal.Notify(quit, os.Interrupt)
9588
<-quit
@@ -99,7 +92,13 @@ func main() {
9992
// keystore path and initial pre-state.
10093
func MakeSystemNode(keydir string, privkey string, test *tests.BlockTest) (*node.Node, error) {
10194
// Create a networkless protocol stack
102-
stack, err := node.New(&node.Config{IpcPath: node.DefaultIpcEndpoint(), NoDiscovery: true})
95+
stack, err := node.New(&node.Config{
96+
IpcPath: node.DefaultIpcEndpoint(),
97+
HttpHost: common.DefaultHttpHost,
98+
HttpPort: common.DefaultHttpPort,
99+
HttpModules: []string{"admin", "db", "eth", "debug", "miner", "net", "shh", "txpool", "personal", "web3"},
100+
NoDiscovery: true,
101+
})
103102
if err != nil {
104103
return nil, err
105104
}
@@ -164,23 +163,3 @@ func RunTest(stack *node.Node, test *tests.BlockTest) error {
164163
}
165164
return nil
166165
}
167-
168-
// StartRPC initializes an RPC interface to the given protocol stack.
169-
func StartRPC(stack *node.Node) error {
170-
/*
171-
web3 := NewPublicWeb3API(stack)
172-
server.RegisterName("web3", web3)
173-
net := NewPublicNetAPI(stack.Server(), ethereum.NetVersion())
174-
server.RegisterName("net", net)
175-
*/
176-
177-
for _, api := range stack.APIs() {
178-
if adminApi, ok := api.Service.(*node.PrivateAdminAPI); ok {
179-
_, err := adminApi.StartRPC("127.0.0.1", 8545, "", "admin,db,eth,debug,miner,net,shh,txpool,personal,web3")
180-
return err
181-
}
182-
}
183-
184-
glog.V(logger.Error).Infof("Unable to start RPC-HTTP interface, could not find admin API")
185-
return errors.New("Unable to start RPC-HTTP interface")
186-
}

‎cmd/utils/flags.go‎

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -233,12 +233,12 @@ var (
233233
RPCListenAddrFlag = cli.StringFlag{
234234
Name: "rpcaddr",
235235
Usage: "HTTP-RPC server listening interface",
236-
Value: "127.0.0.1",
236+
Value: common.DefaultHttpHost,
237237
}
238238
RPCPortFlag = cli.IntFlag{
239239
Name: "rpcport",
240240
Usage: "HTTP-RPC server listening port",
241-
Value: 8545,
241+
Value: common.DefaultHttpPort,
242242
}
243243
RPCCORSDomainFlag = cli.StringFlag{
244244
Name: "rpccorsdomain",
@@ -262,7 +262,7 @@ var (
262262
IPCPathFlag = DirectoryFlag{
263263
Name: "ipcpath",
264264
Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)",
265-
Value: DirectoryString{common.DefaultIpcSocket()},
265+
Value: DirectoryString{common.DefaultIpcSocket},
266266
}
267267
WSEnabledFlag = cli.BoolFlag{
268268
Name: "ws",
@@ -271,20 +271,20 @@ var (
271271
WSListenAddrFlag = cli.StringFlag{
272272
Name: "wsaddr",
273273
Usage: "WS-RPC server listening interface",
274-
Value: "127.0.0.1",
274+
Value: common.DefaultWsHost,
275275
}
276276
WSPortFlag = cli.IntFlag{
277277
Name: "wsport",
278278
Usage: "WS-RPC server listening port",
279-
Value: 8546,
279+
Value: common.DefaultWsPort,
280280
}
281281
WSApiFlag = cli.StringFlag{
282282
Name: "wsapi",
283283
Usage: "API's offered over the WS-RPC interface",
284284
Value: rpc.DefaultHttpRpcApis,
285285
}
286286
WSAllowedDomainsFlag = cli.StringFlag{
287-
Name: "wsdomains",
287+
Name: "wscors",
288288
Usage: "Domains from which to accept websockets requests",
289289
Value: "",
290290
}
@@ -482,6 +482,15 @@ func MakeNAT(ctx *cli.Context) nat.Interface {
482482
return natif
483483
}
484484

485+
// MakeHttpRpcHost creates the HTTP RPC listener interface string from the set
486+
// command line flags, returning empty if the HTTP endpoint is disabled.
487+
func MakeHttpRpcHost(ctx *cli.Context) string {
488+
if !ctx.GlobalBool(RPCEnabledFlag.Name) {
489+
return ""
490+
}
491+
return ctx.GlobalString(RPCListenAddrFlag.Name)
492+
}
493+
485494
// MakeGenesisBlock loads up a genesis block from an input file specified in the
486495
// command line, or returns the empty string if none set.
487496
func MakeGenesisBlock(ctx *cli.Context) string {
@@ -591,7 +600,6 @@ func MakeSystemNode(name, version string, extra []byte, ctx *cli.Context) *node.
591600
// Configure the node's service container
592601
stackConf := &node.Config{
593602
DataDir: MustMakeDataDir(ctx),
594-
IpcPath: MakeIpcPath(ctx),
595603
PrivateKey: MakeNodeKey(ctx),
596604
Name: MakeNodeName(name, version, ctx),
597605
NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name),
@@ -600,6 +608,11 @@ func MakeSystemNode(name, version string, extra []byte, ctx *cli.Context) *node.
600608
NAT: MakeNAT(ctx),
601609
MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
602610
MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
611+
IpcPath: MakeIpcPath(ctx),
612+
HttpHost: MakeHttpRpcHost(ctx),
613+
HttpPort: ctx.GlobalInt(RPCPortFlag.Name),
614+
HttpCors: ctx.GlobalString(RPCCORSDomainFlag.Name),
615+
HttpModules: strings.Split(ctx.GlobalString(RPCApiFlag.Name), ","),
603616
}
604617
// Configure the Ethereum service
605618
accman := MakeAccountManager(ctx)
@@ -744,27 +757,6 @@ func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database
744757
return chain, chainDb
745758
}
746759

747-
// StartRPC starts a HTTP JSON-RPC API server.
748-
func StartRPC(stack *node.Node, ctx *cli.Context) error {
749-
for _, api := range stack.APIs() {
750-
if adminApi, ok := api.Service.(*node.PrivateAdminAPI); ok {
751-
address := ctx.GlobalString(RPCListenAddrFlag.Name)
752-
port := ctx.GlobalInt(RPCPortFlag.Name)
753-
cors := ctx.GlobalString(RPCCORSDomainFlag.Name)
754-
apiStr := ""
755-
if ctx.GlobalIsSet(RPCApiFlag.Name) {
756-
apiStr = ctx.GlobalString(RPCApiFlag.Name)
757-
}
758-
759-
_, err := adminApi.StartRPC(address, port, cors, apiStr)
760-
return err
761-
}
762-
}
763-
764-
glog.V(logger.Error).Infof("Unable to start RPC-HTTP interface, could not find admin API")
765-
return errors.New("Unable to start RPC-HTTP interface")
766-
}
767-
768760
// StartWS starts a websocket JSON-RPC API server.
769761
func StartWS(stack *node.Node, ctx *cli.Context) error {
770762
for _, api := range stack.APIs() {

‎common/defaults.go‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Copyright 2016 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser 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+
// The go-ethereum library 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 Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package common
18+
19+
import (
20+
"path/filepath"
21+
"runtime"
22+
)
23+
24+
const (
25+
DefaultIpcSocket = "geth.ipc" // Default (relative) name of the IPC RPC socket
26+
DefaultHttpHost = "localhost" // Default host interface for the HTTP RPC server
27+
DefaultHttpPort = 8545 // Default TCP port for the HTTP RPC server
28+
DefaultWsHost = "localhost" // Default host interface for the websocket RPC server
29+
DefaultWsPort = 8546 // Default TCP port for the websocket RPC server
30+
)
31+
32+
// DefaultDataDir is the default data directory to use for the databases and other
33+
// persistence requirements.
34+
func DefaultDataDir() string {
35+
// Try to place the data folder in the user's home dir
36+
home := HomeDir()
37+
if home != "" {
38+
if runtime.GOOS == "darwin" {
39+
return filepath.Join(home, "Library", "Ethereum")
40+
} else if runtime.GOOS == "windows" {
41+
return filepath.Join(home, "AppData", "Roaming", "Ethereum")
42+
} else {
43+
return filepath.Join(home, ".ethereum")
44+
}
45+
}
46+
// As we cannot guess a stable location, return empty and handle later
47+
return ""
48+
}

‎common/path.go‎

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -72,25 +72,3 @@ func HomeDir() string {
7272
}
7373
return ""
7474
}
75-
76-
func DefaultDataDir() string {
77-
// Try to place the data folder in the user's home dir
78-
home := HomeDir()
79-
if home != "" {
80-
if runtime.GOOS == "darwin" {
81-
return filepath.Join(home, "Library", "Ethereum")
82-
} else if runtime.GOOS == "windows" {
83-
return filepath.Join(home, "AppData", "Roaming", "Ethereum")
84-
} else {
85-
return filepath.Join(home, ".ethereum")
86-
}
87-
}
88-
// As we cannot guess a stable location, return empty and handle later
89-
return ""
90-
}
91-
92-
// DefaultIpcSocket returns the relative name of the default IPC socket. The path
93-
// resolution is done by a node with other contextual infos.
94-
func DefaultIpcSocket() string {
95-
return "geth.ipc"
96-
}

‎node/api.go‎

Lines changed: 16 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ import (
2727
"github.com/ethereum/go-ethereum/p2p/discover"
2828
"github.com/ethereum/go-ethereum/rpc"
2929
"github.com/rcrowley/go-metrics"
30-
3130
"gopkg.in/fatih/set.v0"
3231
)
3332

@@ -61,42 +60,29 @@ func (api *PrivateAdminAPI) AddPeer(url string) (bool, error) {
6160
}
6261

6362
// StartRPC starts the HTTP RPC API server.
64-
func (api *PrivateAdminAPI) StartRPC(address string, port int, cors string, apis string) (bool, error) {
65-
var offeredAPIs []rpc.API
66-
if len(apis) > 0 {
67-
namespaces := set.New()
68-
for _, a := range strings.Split(apis, ",") {
69-
namespaces.Add(strings.TrimSpace(a))
70-
}
71-
for _, api := range api.node.APIs() {
72-
if namespaces.Has(api.Namespace) {
73-
offeredAPIs = append(offeredAPIs, api)
74-
}
75-
}
76-
} else { // use by default all public API's
77-
for _, api := range api.node.APIs() {
78-
if api.Public {
79-
offeredAPIs = append(offeredAPIs, api)
80-
}
81-
}
82-
}
63+
func (api *PrivateAdminAPI) StartRPC(host string, port int, cors string, apis string) (bool, error) {
64+
api.node.lock.Lock()
65+
defer api.node.lock.Unlock()
8366

84-
if address == "" {
85-
address = "127.0.0.1"
67+
if api.node.httpHandler != nil {
68+
return false, fmt.Errorf("HTTP RPC already running on %s", api.node.httpEndpoint)
8669
}
87-
if port == 0 {
88-
port = 8545
70+
if err := api.node.startHTTP(fmt.Sprintf("%s:%d", host, port), api.node.rpcAPIs, strings.Split(apis, ","), cors); err != nil {
71+
return false, err
8972
}
90-
91-
corsDomains := strings.Split(cors, " ")
92-
err := rpc.StartHTTP(address, port, corsDomains, offeredAPIs)
93-
return err == nil, err
73+
return true, nil
9474
}
9575

9676
// StopRPC terminates an already running HTTP RPC API endpoint.
9777
func (api *PrivateAdminAPI) StopRPC() (bool, error) {
98-
err := rpc.StopHTTP()
99-
return err == nil, err
78+
api.node.lock.Lock()
79+
defer api.node.lock.Unlock()
80+
81+
if api.node.httpHandler == nil {
82+
return false, fmt.Errorf("HTTP RPC not running")
83+
}
84+
api.node.stopHTTP()
85+
return true, nil
10086
}
10187

10288
// StartWS starts the websocket RPC API server.

‎node/config.go‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package node
1919
import (
2020
"crypto/ecdsa"
2121
"encoding/json"
22+
"fmt"
2223
"io/ioutil"
2324
"net"
2425
"os"
@@ -97,6 +98,25 @@ type Config struct {
9798
// handshake phase, counted separately for inbound and outbound connections.
9899
// Zero defaults to preset values.
99100
MaxPendingPeers int
101+
102+
// HttpHost is the host interface on which to start the HTTP RPC server. If this
103+
// field is empty, no HTTP API endpoint will be started.
104+
HttpHost string
105+
106+
// HttpPort is the TCP port number on which to start the HTTP RPC server. The
107+
// default zero value is/ valid and will pick a port number randomly (useful
108+
// for ephemeral nodes).
109+
HttpPort int
110+
111+
// HttpCors is the Cross-Origin Resource Sharing header to send to requesting
112+
// clients. Please be aware that CORS is a browser enforced security, it's fully
113+
// useless for custom HTTP clients.
114+
HttpCors string
115+
116+
// HttpModules is a list of API modules to expose via the HTTP RPC interface.
117+
// If the module list is empty, all RPC API endpoints designated public will be
118+
// exposed.
119+
HttpModules []string
100120
}
101121

102122
// IpcEndpoint resolves an IPC endpoint based on a configured value, taking into
@@ -126,10 +146,25 @@ func (c *Config) IpcEndpoint() string {
126146

127147
// DefaultIpcEndpoint returns the IPC path used by default.
128148
func DefaultIpcEndpoint() string {
129-
config := &Config{DataDir: common.DefaultDataDir(), IpcPath: common.DefaultIpcSocket()}
149+
config := &Config{DataDir: common.DefaultDataDir(), IpcPath: common.DefaultIpcSocket}
130150
return config.IpcEndpoint()
131151
}
132152

153+
// HttpEndpoint resolves an HTTP endpoint based on the configured host interface
154+
// and port parameters.
155+
func (c *Config) HttpEndpoint() string {
156+
if c.HttpHost == "" {
157+
return ""
158+
}
159+
return fmt.Sprintf("%s:%d", c.HttpHost, c.HttpPort)
160+
}
161+
162+
// DefaultHttpEndpoint returns the HTTP endpoint used by default.
163+
func DefaultHttpEndpoint() string {
164+
config := &Config{HttpHost: common.DefaultHttpHost, HttpPort: common.DefaultHttpPort}
165+
return config.HttpEndpoint()
166+
}
167+
133168
// NodeKey retrieves the currently configured private key of the node, checking
134169
// first any manually set key, falling back to the one found in the configured
135170
// data folder. If no key can be found, a new one is generated.

0 commit comments

Comments
 (0)