inproc.go 9.4 KB

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