inproc.go 9.7 KB

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