inproc.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // Copyright 2017 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. package adapters
  17. import (
  18. "errors"
  19. "fmt"
  20. "math"
  21. "net"
  22. "sync"
  23. "github.com/ethereum/go-ethereum/event"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/node"
  26. "github.com/ethereum/go-ethereum/p2p"
  27. "github.com/ethereum/go-ethereum/p2p/discover"
  28. "github.com/ethereum/go-ethereum/p2p/simulations/pipes"
  29. "github.com/ethereum/go-ethereum/rpc"
  30. )
  31. // SimAdapter is a NodeAdapter which creates in-memory simulation nodes and
  32. // connects them using net.Pipe
  33. type SimAdapter struct {
  34. pipe func() (net.Conn, net.Conn, error)
  35. mtx sync.RWMutex
  36. nodes map[discover.NodeID]*SimNode
  37. services map[string]ServiceFunc
  38. }
  39. // NewSimAdapter creates a SimAdapter which is capable of running in-memory
  40. // simulation nodes running any of the given services (the services to run on a
  41. // particular node are passed to the NewNode function in the NodeConfig)
  42. // the adapter uses a net.Pipe for in-memory simulated network connections
  43. func NewSimAdapter(services map[string]ServiceFunc) *SimAdapter {
  44. return &SimAdapter{
  45. pipe: pipes.NetPipe,
  46. nodes: make(map[discover.NodeID]*SimNode),
  47. services: services,
  48. }
  49. }
  50. func NewTCPAdapter(services map[string]ServiceFunc) *SimAdapter {
  51. return &SimAdapter{
  52. pipe: pipes.TCPPipe,
  53. nodes: make(map[discover.NodeID]*SimNode),
  54. services: services,
  55. }
  56. }
  57. // Name returns the name of the adapter for logging purposes
  58. func (s *SimAdapter) Name() string {
  59. return "sim-adapter"
  60. }
  61. // NewNode returns a new SimNode using the given config
  62. func (s *SimAdapter) NewNode(config *NodeConfig) (Node, error) {
  63. s.mtx.Lock()
  64. defer s.mtx.Unlock()
  65. // check a node with the ID doesn't already exist
  66. id := config.ID
  67. if _, exists := s.nodes[id]; exists {
  68. return nil, fmt.Errorf("node already exists: %s", id)
  69. }
  70. // check the services are valid
  71. if len(config.Services) == 0 {
  72. return nil, errors.New("node must have at least one service")
  73. }
  74. for _, service := range config.Services {
  75. if _, exists := s.services[service]; !exists {
  76. return nil, fmt.Errorf("unknown node service %q", service)
  77. }
  78. }
  79. n, err := node.New(&node.Config{
  80. P2P: p2p.Config{
  81. PrivateKey: config.PrivateKey,
  82. MaxPeers: math.MaxInt32,
  83. NoDiscovery: true,
  84. Dialer: s,
  85. EnableMsgEvents: config.EnableMsgEvents,
  86. },
  87. NoUSB: true,
  88. Logger: log.New("node.id", id.String()),
  89. })
  90. if err != nil {
  91. return nil, err
  92. }
  93. simNode := &SimNode{
  94. ID: id,
  95. config: config,
  96. node: n,
  97. adapter: s,
  98. running: make(map[string]node.Service),
  99. }
  100. s.nodes[id] = simNode
  101. return simNode, nil
  102. }
  103. // Dial implements the p2p.NodeDialer interface by connecting to the node using
  104. // an in-memory net.Pipe
  105. func (s *SimAdapter) Dial(dest *discover.Node) (conn net.Conn, err error) {
  106. node, ok := s.GetNode(dest.ID)
  107. if !ok {
  108. return nil, fmt.Errorf("unknown node: %s", dest.ID)
  109. }
  110. srv := node.Server()
  111. if srv == nil {
  112. return nil, fmt.Errorf("node not running: %s", dest.ID)
  113. }
  114. // SimAdapter.pipe is net.Pipe (NewSimAdapter)
  115. pipe1, pipe2, err := s.pipe()
  116. if err != nil {
  117. return nil, err
  118. }
  119. // this is simulated 'listening'
  120. // asynchronously call the dialed destintion node's p2p server
  121. // to set up connection on the 'listening' side
  122. go srv.SetupConn(pipe1, 0, nil)
  123. return pipe2, nil
  124. }
  125. // DialRPC implements the RPCDialer interface by creating an in-memory RPC
  126. // client of the given node
  127. func (s *SimAdapter) DialRPC(id discover.NodeID) (*rpc.Client, error) {
  128. node, ok := s.GetNode(id)
  129. if !ok {
  130. return nil, fmt.Errorf("unknown node: %s", id)
  131. }
  132. handler, err := node.node.RPCHandler()
  133. if err != nil {
  134. return nil, err
  135. }
  136. return rpc.DialInProc(handler), nil
  137. }
  138. // GetNode returns the node with the given ID if it exists
  139. func (s *SimAdapter) GetNode(id discover.NodeID) (*SimNode, bool) {
  140. s.mtx.RLock()
  141. defer s.mtx.RUnlock()
  142. node, ok := s.nodes[id]
  143. return node, ok
  144. }
  145. // SimNode is an in-memory simulation node which connects to other nodes using
  146. // net.Pipe (see SimAdapter.Dial), running devp2p protocols directly over that
  147. // pipe
  148. type SimNode struct {
  149. lock sync.RWMutex
  150. ID discover.NodeID
  151. config *NodeConfig
  152. adapter *SimAdapter
  153. node *node.Node
  154. running map[string]node.Service
  155. client *rpc.Client
  156. registerOnce sync.Once
  157. }
  158. // Addr returns the node's discovery address
  159. func (sn *SimNode) Addr() []byte {
  160. return []byte(sn.Node().String())
  161. }
  162. // Node returns a discover.Node representing the SimNode
  163. func (sn *SimNode) Node() *discover.Node {
  164. return discover.NewNode(sn.ID, net.IP{127, 0, 0, 1}, 30303, 30303)
  165. }
  166. // Client returns an rpc.Client which can be used to communicate with the
  167. // underlying services (it is set once the node has started)
  168. func (sn *SimNode) Client() (*rpc.Client, error) {
  169. sn.lock.RLock()
  170. defer sn.lock.RUnlock()
  171. if sn.client == nil {
  172. return nil, errors.New("node not started")
  173. }
  174. return sn.client, nil
  175. }
  176. // ServeRPC serves RPC requests over the given connection by creating an
  177. // in-memory client to the node's RPC server
  178. func (sn *SimNode) ServeRPC(conn net.Conn) error {
  179. handler, err := sn.node.RPCHandler()
  180. if err != nil {
  181. return err
  182. }
  183. handler.ServeCodec(rpc.NewJSONCodec(conn), rpc.OptionMethodInvocation|rpc.OptionSubscriptions)
  184. return nil
  185. }
  186. // Snapshots creates snapshots of the services by calling the
  187. // simulation_snapshot RPC method
  188. func (sn *SimNode) Snapshots() (map[string][]byte, error) {
  189. sn.lock.RLock()
  190. services := make(map[string]node.Service, len(sn.running))
  191. for name, service := range sn.running {
  192. services[name] = service
  193. }
  194. sn.lock.RUnlock()
  195. if len(services) == 0 {
  196. return nil, errors.New("no running services")
  197. }
  198. snapshots := make(map[string][]byte)
  199. for name, service := range services {
  200. if s, ok := service.(interface {
  201. Snapshot() ([]byte, error)
  202. }); ok {
  203. snap, err := s.Snapshot()
  204. if err != nil {
  205. return nil, err
  206. }
  207. snapshots[name] = snap
  208. }
  209. }
  210. return snapshots, nil
  211. }
  212. // Start registers the services and starts the underlying devp2p node
  213. func (sn *SimNode) Start(snapshots map[string][]byte) error {
  214. newService := func(name string) func(ctx *node.ServiceContext) (node.Service, error) {
  215. return func(nodeCtx *node.ServiceContext) (node.Service, error) {
  216. ctx := &ServiceContext{
  217. RPCDialer: sn.adapter,
  218. NodeContext: nodeCtx,
  219. Config: sn.config,
  220. }
  221. if snapshots != nil {
  222. ctx.Snapshot = snapshots[name]
  223. }
  224. serviceFunc := sn.adapter.services[name]
  225. service, err := serviceFunc(ctx)
  226. if err != nil {
  227. return nil, err
  228. }
  229. sn.running[name] = service
  230. return service, nil
  231. }
  232. }
  233. // ensure we only register the services once in the case of the node
  234. // being stopped and then started again
  235. var regErr error
  236. sn.registerOnce.Do(func() {
  237. for _, name := range sn.config.Services {
  238. if err := sn.node.Register(newService(name)); err != nil {
  239. regErr = err
  240. break
  241. }
  242. }
  243. })
  244. if regErr != nil {
  245. return regErr
  246. }
  247. if err := sn.node.Start(); err != nil {
  248. return err
  249. }
  250. // create an in-process RPC client
  251. handler, err := sn.node.RPCHandler()
  252. if err != nil {
  253. return err
  254. }
  255. sn.lock.Lock()
  256. sn.client = rpc.DialInProc(handler)
  257. sn.lock.Unlock()
  258. return nil
  259. }
  260. // Stop closes the RPC client and stops the underlying devp2p node
  261. func (sn *SimNode) Stop() error {
  262. sn.lock.Lock()
  263. if sn.client != nil {
  264. sn.client.Close()
  265. sn.client = nil
  266. }
  267. sn.lock.Unlock()
  268. return sn.node.Stop()
  269. }
  270. // Services returns a copy of the underlying services
  271. func (sn *SimNode) Services() []node.Service {
  272. sn.lock.RLock()
  273. defer sn.lock.RUnlock()
  274. services := make([]node.Service, 0, len(sn.running))
  275. for _, service := range sn.running {
  276. services = append(services, service)
  277. }
  278. return services
  279. }
  280. // Server returns the underlying p2p.Server
  281. func (sn *SimNode) Server() *p2p.Server {
  282. return sn.node.Server()
  283. }
  284. // SubscribeEvents subscribes the given channel to peer events from the
  285. // underlying p2p.Server
  286. func (sn *SimNode) SubscribeEvents(ch chan *p2p.PeerEvent) event.Subscription {
  287. srv := sn.Server()
  288. if srv == nil {
  289. panic("node not running")
  290. }
  291. return srv.SubscribeEvents(ch)
  292. }
  293. // NodeInfo returns information about the node
  294. func (sn *SimNode) NodeInfo() *p2p.NodeInfo {
  295. server := sn.Server()
  296. if server == nil {
  297. return &p2p.NodeInfo{
  298. ID: sn.ID.String(),
  299. Enode: sn.Node().String(),
  300. }
  301. }
  302. return server.NodeInfo()
  303. }
  304. func setSocketBuffer(conn net.Conn, socketReadBuffer int, socketWriteBuffer int) error {
  305. switch v := conn.(type) {
  306. case *net.UnixConn:
  307. err := v.SetReadBuffer(socketReadBuffer)
  308. if err != nil {
  309. return err
  310. }
  311. err = v.SetWriteBuffer(socketWriteBuffer)
  312. if err != nil {
  313. return err
  314. }
  315. }
  316. return nil
  317. }