Skip to content

Commit eae8146

Browse files
author
Bas van Kervel
committed
rpc: new RPC implementation with pub/sub support
1 parent 8db9d44 commit eae8146

38 files changed

Lines changed: 4651 additions & 14 deletions

‎accounts/account_manager.go‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ type Account struct {
4444
Address common.Address
4545
}
4646

47+
func (acc *Account) MarshalJSON() ([]byte, error) {
48+
return []byte(`"` + acc.Address.Hex() + `"`), nil
49+
}
50+
4751
type Manager struct {
4852
keyStore crypto.KeyStore
4953
unlocked map[common.Address]*unlocked
@@ -92,6 +96,17 @@ func (am *Manager) Unlock(addr common.Address, keyAuth string) error {
9296
return am.TimedUnlock(addr, keyAuth, 0)
9397
}
9498

99+
func (am *Manager) Lock(addr common.Address) error {
100+
am.mutex.Lock()
101+
if unl, found := am.unlocked[addr]; found {
102+
am.mutex.Unlock()
103+
am.expire(addr, unl, time.Duration(0) * time.Nanosecond)
104+
} else {
105+
am.mutex.Unlock()
106+
}
107+
return nil
108+
}
109+
95110
// TimedUnlock unlocks the account with the given address. The account
96111
// stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
97112
// until the program exits.

‎cmd/geth/js.go‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,10 +246,10 @@ func (self *jsre) welcome() {
246246
self.re.Run(`
247247
(function () {
248248
console.log('instance: ' + web3.version.node);
249-
console.log(' datadir: ' + admin.datadir);
250249
console.log("coinbase: " + eth.coinbase);
251250
var ts = 1000 * eth.getBlock(eth.blockNumber).timestamp;
252251
console.log("at block: " + eth.blockNumber + " (" + new Date(ts) + ")");
252+
console.log(' datadir: ' + admin.datadir);
253253
})();
254254
`)
255255
if modules, err := self.supportedApis(); err == nil {
@@ -258,7 +258,7 @@ func (self *jsre) welcome() {
258258
loadedModules = append(loadedModules, fmt.Sprintf("%s:%s", api, version))
259259
}
260260
sort.Strings(loadedModules)
261-
fmt.Println("modules:", strings.Join(loadedModules, " "))
261+
262262
}
263263
}
264264

@@ -325,12 +325,28 @@ func (js *jsre) apiBindings(f xeth.Frontend) error {
325325
}
326326

327327
_, err = js.re.Run(shortcuts)
328-
329328
if err != nil {
330329
utils.Fatalf("Error setting namespaces: %v", err)
331330
}
332331

333332
js.re.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `); registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`)
333+
334+
// overrule some of the methods that require password as input and ask for it interactively
335+
p, err := js.re.Get("personal")
336+
if err != nil {
337+
fmt.Println("Unable to overrule sensitive methods in personal module")
338+
return nil
339+
}
340+
341+
// Override the unlockAccount and newAccount methods on the personal object since these require user interaction.
342+
// Assign the jeth.unlockAccount and jeth.newAccount in the jsre the original web3 callbacks. These will be called
343+
// by the jeth.* methods after they got the password from the user and send the original web3 request to the backend.
344+
persObj := p.Object()
345+
js.re.Run(`jeth.unlockAccount = personal.unlockAccount;`)
346+
persObj.Set("unlockAccount", jeth.UnlockAccount)
347+
js.re.Run(`jeth.newAccount = personal.newAccount;`)
348+
persObj.Set("newAccount", jeth.NewAccount)
349+
334350
return nil
335351
}
336352

‎cmd/geth/js_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ func TestAccounts(t *testing.T) {
168168

169169
checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`"]`)
170170
checkEvalJSON(t, repl, `eth.coinbase`, `"`+testAddress+`"`)
171-
val, err := repl.re.Run(`personal.newAccount("password")`)
171+
val, err := repl.re.Run(`jeth.newAccount("password")`)
172172
if err != nil {
173173
t.Errorf("expected no error, got %v", err)
174174
}

‎cmd/geth/main.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
313313
utils.IPCDisabledFlag,
314314
utils.IPCApiFlag,
315315
utils.IPCPathFlag,
316+
utils.IPCExperimental,
316317
utils.ExecFlag,
317318
utils.WhisperEnabledFlag,
318319
utils.DevModeFlag,

‎cmd/geth/usage.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ var AppHelpFlagGroups = []flagGroup{
158158
Flags: []cli.Flag{
159159
utils.WhisperEnabledFlag,
160160
utils.NatspecEnabledFlag,
161+
utils.IPCExperimental,
161162
},
162163
},
163164
{

‎cmd/gethrpctest/main.go‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,22 @@ import (
2323
"log"
2424
"os"
2525
"os/signal"
26+
"path/filepath"
27+
"runtime"
2628

2729
"github.com/ethereum/go-ethereum/accounts"
30+
"github.com/ethereum/go-ethereum/cmd/utils"
31+
"github.com/ethereum/go-ethereum/common"
2832
"github.com/ethereum/go-ethereum/crypto"
2933
"github.com/ethereum/go-ethereum/eth"
3034
"github.com/ethereum/go-ethereum/ethdb"
35+
"github.com/ethereum/go-ethereum/logger"
36+
"github.com/ethereum/go-ethereum/logger/glog"
3137
"github.com/ethereum/go-ethereum/node"
3238
"github.com/ethereum/go-ethereum/rpc/api"
3339
"github.com/ethereum/go-ethereum/rpc/codec"
3440
"github.com/ethereum/go-ethereum/rpc/comms"
41+
rpc "github.com/ethereum/go-ethereum/rpc/v2"
3542
"github.com/ethereum/go-ethereum/tests"
3643
"github.com/ethereum/go-ethereum/whisper"
3744
"github.com/ethereum/go-ethereum/xeth"
@@ -81,9 +88,14 @@ func main() {
8188
}
8289
log.Println("Initial test suite passed...")
8390

91+
if err := StartIPC(stack); err != nil {
92+
log.Fatalf("Failed to start IPC interface: %v\n", err)
93+
}
94+
log.Println("IPC Interface started, accepting requests...")
95+
8496
// Start the RPC interface and wait until terminated
8597
if err := StartRPC(stack); err != nil {
86-
log.Fatalf("Failed to start RPC instarface: %v", err)
98+
log.Fatalf("Failed to start RPC interface: %v", err)
8799
}
88100
log.Println("RPC Interface started, accepting requests...")
89101

@@ -177,3 +189,54 @@ func StartRPC(stack *node.Node) error {
177189
}
178190
return comms.StartHttp(config, codec, api.Merge(apis...))
179191
}
192+
193+
// StartRPC initializes an IPC interface to the given protocol stack.
194+
func StartIPC(stack *node.Node) error {
195+
var ethereum *eth.Ethereum
196+
if err := stack.Service(&ethereum); err != nil {
197+
return err
198+
}
199+
200+
endpoint := `\\.\pipe\geth.ipc`
201+
if runtime.GOOS != "windows" {
202+
endpoint = filepath.Join(common.DefaultDataDir(), "geth.ipc")
203+
}
204+
205+
config := comms.IpcConfig{
206+
Endpoint: endpoint,
207+
}
208+
209+
listener, err := comms.CreateListener(config)
210+
if err != nil {
211+
return err
212+
}
213+
214+
server := rpc.NewServer()
215+
216+
// register package API's this node provides
217+
offered := stack.RPCAPIs()
218+
for _, api := range offered {
219+
server.RegisterName(api.Namespace, api.Service)
220+
glog.V(logger.Debug).Infof("Register %T@%s for IPC service\n", api.Service, api.Namespace)
221+
}
222+
223+
web3 := utils.NewPublicWeb3API(stack)
224+
server.RegisterName("web3", web3)
225+
net := utils.NewPublicNetAPI(stack.Server(), ethereum.NetVersion())
226+
server.RegisterName("net", net)
227+
228+
go func() {
229+
glog.V(logger.Info).Infof("Start IPC server on %s\n", config.Endpoint)
230+
for {
231+
conn, err := listener.Accept()
232+
if err != nil {
233+
glog.V(logger.Error).Infof("Unable to accept connection - %v\n", err)
234+
}
235+
236+
codec := rpc.NewJSONCodec(conn)
237+
go server.ServeCodec(codec)
238+
}
239+
}()
240+
241+
return nil
242+
}

‎cmd/utils/api.go‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Copyright 2015 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 utils
18+
19+
import (
20+
"fmt"
21+
22+
"github.com/ethereum/go-ethereum/common"
23+
"github.com/ethereum/go-ethereum/crypto"
24+
"github.com/ethereum/go-ethereum/node"
25+
"github.com/ethereum/go-ethereum/p2p"
26+
rpc "github.com/ethereum/go-ethereum/rpc/v2"
27+
)
28+
29+
// PublicWeb3API offers helper utils
30+
type PublicWeb3API struct {
31+
stack *node.Node
32+
}
33+
34+
// NewPublicWeb3API creates a new Web3Service instance
35+
func NewPublicWeb3API(stack *node.Node) *PublicWeb3API {
36+
return &PublicWeb3API{stack}
37+
}
38+
39+
// ClientVersion returns the node name
40+
func (s *PublicWeb3API) ClientVersion() string {
41+
return s.stack.Server().Name
42+
}
43+
44+
// Sha3 applies the ethereum sha3 implementation on the input.
45+
// It assumes the input is hex encoded.
46+
func (s *PublicWeb3API) Sha3(input string) string {
47+
return common.ToHex(crypto.Sha3(common.FromHex(input)))
48+
}
49+
50+
// PublicNetAPI offers network related RPC methods
51+
type PublicNetAPI struct {
52+
net *p2p.Server
53+
networkVersion int
54+
}
55+
56+
// NewPublicNetAPI creates a new net api instance.
57+
func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
58+
return &PublicNetAPI{net, networkVersion}
59+
}
60+
61+
// Listening returns an indication if the node is listening for network connections.
62+
func (s *PublicNetAPI) Listening() bool {
63+
return true // always listening
64+
}
65+
66+
// Peercount returns the number of connected peers
67+
func (s *PublicNetAPI) PeerCount() *rpc.HexNumber {
68+
return rpc.NewHexNumber(s.net.PeerCount())
69+
}
70+
71+
// ProtocolVersion returns the current ethereum protocol version.
72+
func (s *PublicNetAPI) Version() string {
73+
return fmt.Sprintf("%d", s.networkVersion)
74+
}

‎cmd/utils/flags.go‎

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import (
5454
"github.com/ethereum/go-ethereum/rpc/comms"
5555
"github.com/ethereum/go-ethereum/rpc/shared"
5656
"github.com/ethereum/go-ethereum/rpc/useragent"
57+
rpc "github.com/ethereum/go-ethereum/rpc/v2"
5758
"github.com/ethereum/go-ethereum/whisper"
5859
"github.com/ethereum/go-ethereum/xeth"
5960
)
@@ -300,6 +301,10 @@ var (
300301
Usage: "Filename for IPC socket/pipe",
301302
Value: DirectoryString{common.DefaultIpcPath()},
302303
}
304+
IPCExperimental = cli.BoolFlag{
305+
Name: "ipcexp",
306+
Usage: "Enable the new RPC implementation",
307+
}
303308
ExecFlag = cli.StringFlag{
304309
Name: "exec",
305310
Usage: "Execute JavaScript statement (only in combination with console/attach)",
@@ -690,6 +695,7 @@ func MakeSystemNode(name, version string, extra []byte, ctx *cli.Context) *node.
690695
Fatalf("Failed to register the Whisper service: %v", err)
691696
}
692697
}
698+
693699
return stack
694700
}
695701

@@ -773,17 +779,53 @@ func IpcSocketPath(ctx *cli.Context) (ipcpath string) {
773779
return
774780
}
775781

776-
// StartIPC starts a IPC JSON-RPC API server.
777782
func StartIPC(stack *node.Node, ctx *cli.Context) error {
778783
config := comms.IpcConfig{
779784
Endpoint: IpcSocketPath(ctx),
780785
}
781786

782-
initializer := func(conn net.Conn) (comms.Stopper, shared.EthereumApi, error) {
783-
var ethereum *eth.Ethereum
784-
if err := stack.Service(&ethereum); err != nil {
785-
return nil, nil, err
787+
var ethereum *eth.Ethereum
788+
if err := stack.Service(&ethereum); err != nil {
789+
return err
790+
}
791+
792+
if ctx.GlobalIsSet(IPCExperimental.Name) {
793+
listener, err := comms.CreateListener(config)
794+
if err != nil {
795+
return err
796+
}
797+
798+
server := rpc.NewServer()
799+
800+
// register package API's this node provides
801+
offered := stack.RPCAPIs()
802+
for _, api := range offered {
803+
server.RegisterName(api.Namespace, api.Service)
804+
glog.V(logger.Debug).Infof("Register %T under namespace '%s' for IPC service\n", api.Service, api.Namespace)
786805
}
806+
807+
web3 := NewPublicWeb3API(stack)
808+
server.RegisterName("web3", web3)
809+
net := NewPublicNetAPI(stack.Server(), ethereum.NetVersion())
810+
server.RegisterName("net", net)
811+
812+
go func() {
813+
glog.V(logger.Info).Infof("Start IPC server on %s\n", config.Endpoint)
814+
for {
815+
conn, err := listener.Accept()
816+
if err != nil {
817+
glog.V(logger.Error).Infof("Unable to accept connection - %v\n", err)
818+
}
819+
820+
codec := rpc.NewJSONCodec(conn)
821+
go server.ServeCodec(codec)
822+
}
823+
}()
824+
825+
return nil
826+
}
827+
828+
initializer := func(conn net.Conn) (comms.Stopper, shared.EthereumApi, error) {
787829
fe := useragent.NewRemoteFrontend(conn, ethereum.AccountManager())
788830
xeth := xeth.New(stack, fe)
789831
apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec.JSON, xeth, stack)

0 commit comments

Comments
 (0)