github.com/jeffallen/go-ethereum@v1.1.4-0.20150910155051-571d3236c49c/rpc/comms/ipc.go (about) 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 comms 18 19 import ( 20 "fmt" 21 "math/rand" 22 "net" 23 24 "encoding/json" 25 26 "github.com/ethereum/go-ethereum/rpc/codec" 27 "github.com/ethereum/go-ethereum/rpc/shared" 28 ) 29 30 type IpcConfig struct { 31 Endpoint string 32 } 33 34 type ipcClient struct { 35 endpoint string 36 c net.Conn 37 codec codec.Codec 38 coder codec.ApiCoder 39 } 40 41 func (self *ipcClient) Close() { 42 self.coder.Close() 43 } 44 45 func (self *ipcClient) Send(msg interface{}) error { 46 var err error 47 if err = self.coder.WriteResponse(msg); err != nil { 48 if err = self.reconnect(); err == nil { 49 err = self.coder.WriteResponse(msg) 50 } 51 } 52 return err 53 } 54 55 func (self *ipcClient) Recv() (interface{}, error) { 56 return self.coder.ReadResponse() 57 } 58 59 func (self *ipcClient) SupportedModules() (map[string]string, error) { 60 req := shared.Request{ 61 Id: 1, 62 Jsonrpc: "2.0", 63 Method: "modules", 64 } 65 66 if err := self.coder.WriteResponse(req); err != nil { 67 return nil, err 68 } 69 70 res, err := self.coder.ReadResponse() 71 if err != nil { 72 return nil, err 73 } 74 75 if sucRes, ok := res.(*shared.SuccessResponse); ok { 76 data, _ := json.Marshal(sucRes.Result) 77 modules := make(map[string]string) 78 err = json.Unmarshal(data, &modules) 79 if err == nil { 80 return modules, nil 81 } 82 } 83 84 return nil, fmt.Errorf("Invalid response") 85 } 86 87 // Create a new IPC client, UNIX domain socket on posix, named pipe on Windows 88 func NewIpcClient(cfg IpcConfig, codec codec.Codec) (*ipcClient, error) { 89 return newIpcClient(cfg, codec) 90 } 91 92 // Start IPC server 93 func StartIpc(cfg IpcConfig, codec codec.Codec, initializer func(conn net.Conn) (shared.EthereumApi, error)) error { 94 return startIpc(cfg, codec, initializer) 95 } 96 97 func newIpcConnId() int { 98 return rand.Int() % 1000000 99 }