inproc.go 8.4 KB

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