inproc.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. NoUSB: true,
  92. Logger: log.New("node.id", id.String()),
  93. })
  94. if err != nil {
  95. return nil, err
  96. }
  97. simNode := &SimNode{
  98. ID: id,
  99. config: config,
  100. node: n,
  101. adapter: s,
  102. running: make(map[string]node.Lifecycle),
  103. }
  104. s.nodes[id] = simNode
  105. return simNode, nil
  106. }
  107. // Dial implements the p2p.NodeDialer interface by connecting to the node using
  108. // an in-memory net.Pipe
  109. func (s *SimAdapter) Dial(ctx context.Context, dest *enode.Node) (conn net.Conn, err error) {
  110. node, ok := s.GetNode(dest.ID())
  111. if !ok {
  112. return nil, fmt.Errorf("unknown node: %s", dest.ID())
  113. }
  114. srv := node.Server()
  115. if srv == nil {
  116. return nil, fmt.Errorf("node not running: %s", dest.ID())
  117. }
  118. // SimAdapter.pipe is net.Pipe (NewSimAdapter)
  119. pipe1, pipe2, err := s.pipe()
  120. if err != nil {
  121. return nil, err
  122. }
  123. // this is simulated 'listening'
  124. // asynchronously call the dialed destination node's p2p server
  125. // to set up connection on the 'listening' side
  126. go srv.SetupConn(pipe1, 0, nil)
  127. return pipe2, nil
  128. }
  129. // DialRPC implements the RPCDialer interface by creating an in-memory RPC
  130. // client of the given node
  131. func (s *SimAdapter) DialRPC(id enode.ID) (*rpc.Client, error) {
  132. node, ok := s.GetNode(id)
  133. if !ok {
  134. return nil, fmt.Errorf("unknown node: %s", id)
  135. }
  136. return node.node.Attach()
  137. }
  138. // GetNode returns the node with the given ID if it exists
  139. func (s *SimAdapter) GetNode(id enode.ID) (*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 enode.ID
  151. config *NodeConfig
  152. adapter *SimAdapter
  153. node *node.Node
  154. running map[string]node.Lifecycle
  155. client *rpc.Client
  156. registerOnce sync.Once
  157. }
  158. // Close closes the underlaying node.Node to release
  159. // acquired resources.
  160. func (sn *SimNode) Close() error {
  161. return sn.node.Close()
  162. }
  163. // Addr returns the node's discovery address
  164. func (sn *SimNode) Addr() []byte {
  165. return []byte(sn.Node().String())
  166. }
  167. // Node returns a node descriptor representing the SimNode
  168. func (sn *SimNode) Node() *enode.Node {
  169. return sn.config.Node()
  170. }
  171. // Client returns an rpc.Client which can be used to communicate with the
  172. // underlying services (it is set once the node has started)
  173. func (sn *SimNode) Client() (*rpc.Client, error) {
  174. sn.lock.RLock()
  175. defer sn.lock.RUnlock()
  176. if sn.client == nil {
  177. return nil, errors.New("node not started")
  178. }
  179. return sn.client, nil
  180. }
  181. // ServeRPC serves RPC requests over the given connection by creating an
  182. // in-memory client to the node's RPC server.
  183. func (sn *SimNode) ServeRPC(conn *websocket.Conn) error {
  184. handler, err := sn.node.RPCHandler()
  185. if err != nil {
  186. return err
  187. }
  188. codec := rpc.NewFuncCodec(conn, conn.WriteJSON, conn.ReadJSON)
  189. handler.ServeCodec(codec, 0)
  190. return nil
  191. }
  192. // Snapshots creates snapshots of the services by calling the
  193. // simulation_snapshot RPC method
  194. func (sn *SimNode) Snapshots() (map[string][]byte, error) {
  195. sn.lock.RLock()
  196. services := make(map[string]node.Lifecycle, len(sn.running))
  197. for name, service := range sn.running {
  198. services[name] = service
  199. }
  200. sn.lock.RUnlock()
  201. if len(services) == 0 {
  202. return nil, errors.New("no running services")
  203. }
  204. snapshots := make(map[string][]byte)
  205. for name, service := range services {
  206. if s, ok := service.(interface {
  207. Snapshot() ([]byte, error)
  208. }); ok {
  209. snap, err := s.Snapshot()
  210. if err != nil {
  211. return nil, err
  212. }
  213. snapshots[name] = snap
  214. }
  215. }
  216. return snapshots, nil
  217. }
  218. // Start registers the services and starts the underlying devp2p node
  219. func (sn *SimNode) Start(snapshots map[string][]byte) error {
  220. // ensure we only register the services once in the case of the node
  221. // being stopped and then started again
  222. var regErr error
  223. sn.registerOnce.Do(func() {
  224. for _, name := range sn.config.Lifecycles {
  225. ctx := &ServiceContext{
  226. RPCDialer: sn.adapter,
  227. Config: sn.config,
  228. }
  229. if snapshots != nil {
  230. ctx.Snapshot = snapshots[name]
  231. }
  232. serviceFunc := sn.adapter.lifecycles[name]
  233. service, err := serviceFunc(ctx, sn.node)
  234. if err != nil {
  235. regErr = err
  236. break
  237. }
  238. // if the service has already been registered, don't register it again.
  239. if _, ok := sn.running[name]; ok {
  240. continue
  241. }
  242. sn.running[name] = service
  243. }
  244. })
  245. if regErr != nil {
  246. return regErr
  247. }
  248. if err := sn.node.Start(); err != nil {
  249. return err
  250. }
  251. // create an in-process RPC client
  252. client, err := sn.node.Attach()
  253. if err != nil {
  254. return err
  255. }
  256. sn.lock.Lock()
  257. sn.client = client
  258. sn.lock.Unlock()
  259. return nil
  260. }
  261. // Stop closes the RPC client and stops the underlying devp2p node
  262. func (sn *SimNode) Stop() error {
  263. sn.lock.Lock()
  264. if sn.client != nil {
  265. sn.client.Close()
  266. sn.client = nil
  267. }
  268. sn.lock.Unlock()
  269. return sn.node.Close()
  270. }
  271. // Service returns a running service by name
  272. func (sn *SimNode) Service(name string) node.Lifecycle {
  273. sn.lock.RLock()
  274. defer sn.lock.RUnlock()
  275. return sn.running[name]
  276. }
  277. // Services returns a copy of the underlying services
  278. func (sn *SimNode) Services() []node.Lifecycle {
  279. sn.lock.RLock()
  280. defer sn.lock.RUnlock()
  281. services := make([]node.Lifecycle, 0, len(sn.running))
  282. for _, service := range sn.running {
  283. services = append(services, service)
  284. }
  285. return services
  286. }
  287. // ServiceMap returns a map by names of the underlying services
  288. func (sn *SimNode) ServiceMap() map[string]node.Lifecycle {
  289. sn.lock.RLock()
  290. defer sn.lock.RUnlock()
  291. services := make(map[string]node.Lifecycle, len(sn.running))
  292. for name, service := range sn.running {
  293. services[name] = service
  294. }
  295. return services
  296. }
  297. // Server returns the underlying p2p.Server
  298. func (sn *SimNode) Server() *p2p.Server {
  299. return sn.node.Server()
  300. }
  301. // SubscribeEvents subscribes the given channel to peer events from the
  302. // underlying p2p.Server
  303. func (sn *SimNode) SubscribeEvents(ch chan *p2p.PeerEvent) event.Subscription {
  304. srv := sn.Server()
  305. if srv == nil {
  306. panic("node not running")
  307. }
  308. return srv.SubscribeEvents(ch)
  309. }
  310. // NodeInfo returns information about the node
  311. func (sn *SimNode) NodeInfo() *p2p.NodeInfo {
  312. server := sn.Server()
  313. if server == nil {
  314. return &p2p.NodeInfo{
  315. ID: sn.ID.String(),
  316. Enode: sn.Node().String(),
  317. }
  318. }
  319. return server.NodeInfo()
  320. }