http.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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 simulations
  17. import (
  18. "bufio"
  19. "bytes"
  20. "context"
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "net/http"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "github.com/ethereum/go-ethereum/event"
  30. "github.com/ethereum/go-ethereum/p2p"
  31. "github.com/ethereum/go-ethereum/p2p/enode"
  32. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  33. "github.com/ethereum/go-ethereum/rpc"
  34. "github.com/gorilla/websocket"
  35. "github.com/julienschmidt/httprouter"
  36. )
  37. // DefaultClient is the default simulation API client which expects the API
  38. // to be running at http://localhost:8888
  39. var DefaultClient = NewClient("http://localhost:8888")
  40. // Client is a client for the simulation HTTP API which supports creating
  41. // and managing simulation networks
  42. type Client struct {
  43. URL string
  44. client *http.Client
  45. }
  46. // NewClient returns a new simulation API client
  47. func NewClient(url string) *Client {
  48. return &Client{
  49. URL: url,
  50. client: http.DefaultClient,
  51. }
  52. }
  53. // GetNetwork returns details of the network
  54. func (c *Client) GetNetwork() (*Network, error) {
  55. network := &Network{}
  56. return network, c.Get("/", network)
  57. }
  58. // StartNetwork starts all existing nodes in the simulation network
  59. func (c *Client) StartNetwork() error {
  60. return c.Post("/start", nil, nil)
  61. }
  62. // StopNetwork stops all existing nodes in a simulation network
  63. func (c *Client) StopNetwork() error {
  64. return c.Post("/stop", nil, nil)
  65. }
  66. // CreateSnapshot creates a network snapshot
  67. func (c *Client) CreateSnapshot() (*Snapshot, error) {
  68. snap := &Snapshot{}
  69. return snap, c.Get("/snapshot", snap)
  70. }
  71. // LoadSnapshot loads a snapshot into the network
  72. func (c *Client) LoadSnapshot(snap *Snapshot) error {
  73. return c.Post("/snapshot", snap, nil)
  74. }
  75. // SubscribeOpts is a collection of options to use when subscribing to network
  76. // events
  77. type SubscribeOpts struct {
  78. // Current instructs the server to send events for existing nodes and
  79. // connections first
  80. Current bool
  81. // Filter instructs the server to only send a subset of message events
  82. Filter string
  83. }
  84. // SubscribeNetwork subscribes to network events which are sent from the server
  85. // as a server-sent-events stream, optionally receiving events for existing
  86. // nodes and connections and filtering message events
  87. func (c *Client) SubscribeNetwork(events chan *Event, opts SubscribeOpts) (event.Subscription, error) {
  88. url := fmt.Sprintf("%s/events?current=%t&filter=%s", c.URL, opts.Current, opts.Filter)
  89. req, err := http.NewRequest("GET", url, nil)
  90. if err != nil {
  91. return nil, err
  92. }
  93. req.Header.Set("Accept", "text/event-stream")
  94. res, err := c.client.Do(req)
  95. if err != nil {
  96. return nil, err
  97. }
  98. if res.StatusCode != http.StatusOK {
  99. response, _ := ioutil.ReadAll(res.Body)
  100. res.Body.Close()
  101. return nil, fmt.Errorf("unexpected HTTP status: %s: %s", res.Status, response)
  102. }
  103. // define a producer function to pass to event.Subscription
  104. // which reads server-sent events from res.Body and sends
  105. // them to the events channel
  106. producer := func(stop <-chan struct{}) error {
  107. defer res.Body.Close()
  108. // read lines from res.Body in a goroutine so that we are
  109. // always reading from the stop channel
  110. lines := make(chan string)
  111. errC := make(chan error, 1)
  112. go func() {
  113. s := bufio.NewScanner(res.Body)
  114. for s.Scan() {
  115. select {
  116. case lines <- s.Text():
  117. case <-stop:
  118. return
  119. }
  120. }
  121. errC <- s.Err()
  122. }()
  123. // detect any lines which start with "data:", decode the data
  124. // into an event and send it to the events channel
  125. for {
  126. select {
  127. case line := <-lines:
  128. if !strings.HasPrefix(line, "data:") {
  129. continue
  130. }
  131. data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
  132. event := &Event{}
  133. if err := json.Unmarshal([]byte(data), event); err != nil {
  134. return fmt.Errorf("error decoding SSE event: %s", err)
  135. }
  136. select {
  137. case events <- event:
  138. case <-stop:
  139. return nil
  140. }
  141. case err := <-errC:
  142. return err
  143. case <-stop:
  144. return nil
  145. }
  146. }
  147. }
  148. return event.NewSubscription(producer), nil
  149. }
  150. // GetNodes returns all nodes which exist in the network
  151. func (c *Client) GetNodes() ([]*p2p.NodeInfo, error) {
  152. var nodes []*p2p.NodeInfo
  153. return nodes, c.Get("/nodes", &nodes)
  154. }
  155. // CreateNode creates a node in the network using the given configuration
  156. func (c *Client) CreateNode(config *adapters.NodeConfig) (*p2p.NodeInfo, error) {
  157. node := &p2p.NodeInfo{}
  158. return node, c.Post("/nodes", config, node)
  159. }
  160. // GetNode returns details of a node
  161. func (c *Client) GetNode(nodeID string) (*p2p.NodeInfo, error) {
  162. node := &p2p.NodeInfo{}
  163. return node, c.Get(fmt.Sprintf("/nodes/%s", nodeID), node)
  164. }
  165. // StartNode starts a node
  166. func (c *Client) StartNode(nodeID string) error {
  167. return c.Post(fmt.Sprintf("/nodes/%s/start", nodeID), nil, nil)
  168. }
  169. // StopNode stops a node
  170. func (c *Client) StopNode(nodeID string) error {
  171. return c.Post(fmt.Sprintf("/nodes/%s/stop", nodeID), nil, nil)
  172. }
  173. // ConnectNode connects a node to a peer node
  174. func (c *Client) ConnectNode(nodeID, peerID string) error {
  175. return c.Post(fmt.Sprintf("/nodes/%s/conn/%s", nodeID, peerID), nil, nil)
  176. }
  177. // DisconnectNode disconnects a node from a peer node
  178. func (c *Client) DisconnectNode(nodeID, peerID string) error {
  179. return c.Delete(fmt.Sprintf("/nodes/%s/conn/%s", nodeID, peerID))
  180. }
  181. // RPCClient returns an RPC client connected to a node
  182. func (c *Client) RPCClient(ctx context.Context, nodeID string) (*rpc.Client, error) {
  183. baseURL := strings.Replace(c.URL, "http", "ws", 1)
  184. return rpc.DialWebsocket(ctx, fmt.Sprintf("%s/nodes/%s/rpc", baseURL, nodeID), "")
  185. }
  186. // Get performs a HTTP GET request decoding the resulting JSON response
  187. // into "out"
  188. func (c *Client) Get(path string, out interface{}) error {
  189. return c.Send("GET", path, nil, out)
  190. }
  191. // Post performs a HTTP POST request sending "in" as the JSON body and
  192. // decoding the resulting JSON response into "out"
  193. func (c *Client) Post(path string, in, out interface{}) error {
  194. return c.Send("POST", path, in, out)
  195. }
  196. // Delete performs a HTTP DELETE request
  197. func (c *Client) Delete(path string) error {
  198. return c.Send("DELETE", path, nil, nil)
  199. }
  200. // Send performs a HTTP request, sending "in" as the JSON request body and
  201. // decoding the JSON response into "out"
  202. func (c *Client) Send(method, path string, in, out interface{}) error {
  203. var body []byte
  204. if in != nil {
  205. var err error
  206. body, err = json.Marshal(in)
  207. if err != nil {
  208. return err
  209. }
  210. }
  211. req, err := http.NewRequest(method, c.URL+path, bytes.NewReader(body))
  212. if err != nil {
  213. return err
  214. }
  215. req.Header.Set("Content-Type", "application/json")
  216. req.Header.Set("Accept", "application/json")
  217. res, err := c.client.Do(req)
  218. if err != nil {
  219. return err
  220. }
  221. defer res.Body.Close()
  222. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
  223. response, _ := ioutil.ReadAll(res.Body)
  224. return fmt.Errorf("unexpected HTTP status: %s: %s", res.Status, response)
  225. }
  226. if out != nil {
  227. if err := json.NewDecoder(res.Body).Decode(out); err != nil {
  228. return err
  229. }
  230. }
  231. return nil
  232. }
  233. // Server is an HTTP server providing an API to manage a simulation network
  234. type Server struct {
  235. router *httprouter.Router
  236. network *Network
  237. mockerStop chan struct{} // when set, stops the current mocker
  238. mockerMtx sync.Mutex // synchronises access to the mockerStop field
  239. }
  240. // NewServer returns a new simulation API server
  241. func NewServer(network *Network) *Server {
  242. s := &Server{
  243. router: httprouter.New(),
  244. network: network,
  245. }
  246. s.OPTIONS("/", s.Options)
  247. s.GET("/", s.GetNetwork)
  248. s.POST("/start", s.StartNetwork)
  249. s.POST("/stop", s.StopNetwork)
  250. s.POST("/mocker/start", s.StartMocker)
  251. s.POST("/mocker/stop", s.StopMocker)
  252. s.GET("/mocker", s.GetMockers)
  253. s.POST("/reset", s.ResetNetwork)
  254. s.GET("/events", s.StreamNetworkEvents)
  255. s.GET("/snapshot", s.CreateSnapshot)
  256. s.POST("/snapshot", s.LoadSnapshot)
  257. s.POST("/nodes", s.CreateNode)
  258. s.GET("/nodes", s.GetNodes)
  259. s.GET("/nodes/:nodeid", s.GetNode)
  260. s.POST("/nodes/:nodeid/start", s.StartNode)
  261. s.POST("/nodes/:nodeid/stop", s.StopNode)
  262. s.POST("/nodes/:nodeid/conn/:peerid", s.ConnectNode)
  263. s.DELETE("/nodes/:nodeid/conn/:peerid", s.DisconnectNode)
  264. s.GET("/nodes/:nodeid/rpc", s.NodeRPC)
  265. return s
  266. }
  267. // GetNetwork returns details of the network
  268. func (s *Server) GetNetwork(w http.ResponseWriter, req *http.Request) {
  269. s.JSON(w, http.StatusOK, s.network)
  270. }
  271. // StartNetwork starts all nodes in the network
  272. func (s *Server) StartNetwork(w http.ResponseWriter, req *http.Request) {
  273. if err := s.network.StartAll(); err != nil {
  274. http.Error(w, err.Error(), http.StatusInternalServerError)
  275. return
  276. }
  277. w.WriteHeader(http.StatusOK)
  278. }
  279. // StopNetwork stops all nodes in the network
  280. func (s *Server) StopNetwork(w http.ResponseWriter, req *http.Request) {
  281. if err := s.network.StopAll(); err != nil {
  282. http.Error(w, err.Error(), http.StatusInternalServerError)
  283. return
  284. }
  285. w.WriteHeader(http.StatusOK)
  286. }
  287. // StartMocker starts the mocker node simulation
  288. func (s *Server) StartMocker(w http.ResponseWriter, req *http.Request) {
  289. s.mockerMtx.Lock()
  290. defer s.mockerMtx.Unlock()
  291. if s.mockerStop != nil {
  292. http.Error(w, "mocker already running", http.StatusInternalServerError)
  293. return
  294. }
  295. mockerType := req.FormValue("mocker-type")
  296. mockerFn := LookupMocker(mockerType)
  297. if mockerFn == nil {
  298. http.Error(w, fmt.Sprintf("unknown mocker type %q", mockerType), http.StatusBadRequest)
  299. return
  300. }
  301. nodeCount, err := strconv.Atoi(req.FormValue("node-count"))
  302. if err != nil {
  303. http.Error(w, "invalid node-count provided", http.StatusBadRequest)
  304. return
  305. }
  306. s.mockerStop = make(chan struct{})
  307. go mockerFn(s.network, s.mockerStop, nodeCount)
  308. w.WriteHeader(http.StatusOK)
  309. }
  310. // StopMocker stops the mocker node simulation
  311. func (s *Server) StopMocker(w http.ResponseWriter, req *http.Request) {
  312. s.mockerMtx.Lock()
  313. defer s.mockerMtx.Unlock()
  314. if s.mockerStop == nil {
  315. http.Error(w, "stop channel not initialized", http.StatusInternalServerError)
  316. return
  317. }
  318. close(s.mockerStop)
  319. s.mockerStop = nil
  320. w.WriteHeader(http.StatusOK)
  321. }
  322. // GetMockerList returns a list of available mockers
  323. func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request) {
  324. list := GetMockerList()
  325. s.JSON(w, http.StatusOK, list)
  326. }
  327. // ResetNetwork resets all properties of a network to its initial (empty) state
  328. func (s *Server) ResetNetwork(w http.ResponseWriter, req *http.Request) {
  329. s.network.Reset()
  330. w.WriteHeader(http.StatusOK)
  331. }
  332. // StreamNetworkEvents streams network events as a server-sent-events stream
  333. func (s *Server) StreamNetworkEvents(w http.ResponseWriter, req *http.Request) {
  334. events := make(chan *Event)
  335. sub := s.network.events.Subscribe(events)
  336. defer sub.Unsubscribe()
  337. // write writes the given event and data to the stream like:
  338. //
  339. // event: <event>
  340. // data: <data>
  341. //
  342. write := func(event, data string) {
  343. fmt.Fprintf(w, "event: %s\n", event)
  344. fmt.Fprintf(w, "data: %s\n\n", data)
  345. if fw, ok := w.(http.Flusher); ok {
  346. fw.Flush()
  347. }
  348. }
  349. writeEvent := func(event *Event) error {
  350. data, err := json.Marshal(event)
  351. if err != nil {
  352. return err
  353. }
  354. write("network", string(data))
  355. return nil
  356. }
  357. writeErr := func(err error) {
  358. write("error", err.Error())
  359. }
  360. // check if filtering has been requested
  361. var filters MsgFilters
  362. if filterParam := req.URL.Query().Get("filter"); filterParam != "" {
  363. var err error
  364. filters, err = NewMsgFilters(filterParam)
  365. if err != nil {
  366. http.Error(w, err.Error(), http.StatusBadRequest)
  367. return
  368. }
  369. }
  370. w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
  371. w.WriteHeader(http.StatusOK)
  372. fmt.Fprintf(w, "\n\n")
  373. if fw, ok := w.(http.Flusher); ok {
  374. fw.Flush()
  375. }
  376. // optionally send the existing nodes and connections
  377. if req.URL.Query().Get("current") == "true" {
  378. snap, err := s.network.Snapshot()
  379. if err != nil {
  380. writeErr(err)
  381. return
  382. }
  383. for _, node := range snap.Nodes {
  384. event := NewEvent(&node.Node)
  385. if err := writeEvent(event); err != nil {
  386. writeErr(err)
  387. return
  388. }
  389. }
  390. for _, conn := range snap.Conns {
  391. event := NewEvent(&conn)
  392. if err := writeEvent(event); err != nil {
  393. writeErr(err)
  394. return
  395. }
  396. }
  397. }
  398. clientGone := req.Context().Done()
  399. for {
  400. select {
  401. case event := <-events:
  402. // only send message events which match the filters
  403. if event.Msg != nil && !filters.Match(event.Msg) {
  404. continue
  405. }
  406. if err := writeEvent(event); err != nil {
  407. writeErr(err)
  408. return
  409. }
  410. case <-clientGone:
  411. return
  412. }
  413. }
  414. }
  415. // NewMsgFilters constructs a collection of message filters from a URL query
  416. // parameter.
  417. //
  418. // The parameter is expected to be a dash-separated list of individual filters,
  419. // each having the format '<proto>:<codes>', where <proto> is the name of a
  420. // protocol and <codes> is a comma-separated list of message codes.
  421. //
  422. // A message code of '*' or '-1' is considered a wildcard and matches any code.
  423. func NewMsgFilters(filterParam string) (MsgFilters, error) {
  424. filters := make(MsgFilters)
  425. for _, filter := range strings.Split(filterParam, "-") {
  426. protoCodes := strings.SplitN(filter, ":", 2)
  427. if len(protoCodes) != 2 || protoCodes[0] == "" || protoCodes[1] == "" {
  428. return nil, fmt.Errorf("invalid message filter: %s", filter)
  429. }
  430. proto := protoCodes[0]
  431. for _, code := range strings.Split(protoCodes[1], ",") {
  432. if code == "*" || code == "-1" {
  433. filters[MsgFilter{Proto: proto, Code: -1}] = struct{}{}
  434. continue
  435. }
  436. n, err := strconv.ParseUint(code, 10, 64)
  437. if err != nil {
  438. return nil, fmt.Errorf("invalid message code: %s", code)
  439. }
  440. filters[MsgFilter{Proto: proto, Code: int64(n)}] = struct{}{}
  441. }
  442. }
  443. return filters, nil
  444. }
  445. // MsgFilters is a collection of filters which are used to filter message
  446. // events
  447. type MsgFilters map[MsgFilter]struct{}
  448. // Match checks if the given message matches any of the filters
  449. func (m MsgFilters) Match(msg *Msg) bool {
  450. // check if there is a wildcard filter for the message's protocol
  451. if _, ok := m[MsgFilter{Proto: msg.Protocol, Code: -1}]; ok {
  452. return true
  453. }
  454. // check if there is a filter for the message's protocol and code
  455. if _, ok := m[MsgFilter{Proto: msg.Protocol, Code: int64(msg.Code)}]; ok {
  456. return true
  457. }
  458. return false
  459. }
  460. // MsgFilter is used to filter message events based on protocol and message
  461. // code
  462. type MsgFilter struct {
  463. // Proto is matched against a message's protocol
  464. Proto string
  465. // Code is matched against a message's code, with -1 matching all codes
  466. Code int64
  467. }
  468. // CreateSnapshot creates a network snapshot
  469. func (s *Server) CreateSnapshot(w http.ResponseWriter, req *http.Request) {
  470. snap, err := s.network.Snapshot()
  471. if err != nil {
  472. http.Error(w, err.Error(), http.StatusInternalServerError)
  473. return
  474. }
  475. s.JSON(w, http.StatusOK, snap)
  476. }
  477. // LoadSnapshot loads a snapshot into the network
  478. func (s *Server) LoadSnapshot(w http.ResponseWriter, req *http.Request) {
  479. snap := &Snapshot{}
  480. if err := json.NewDecoder(req.Body).Decode(snap); err != nil {
  481. http.Error(w, err.Error(), http.StatusBadRequest)
  482. return
  483. }
  484. if err := s.network.Load(snap); err != nil {
  485. http.Error(w, err.Error(), http.StatusInternalServerError)
  486. return
  487. }
  488. s.JSON(w, http.StatusOK, s.network)
  489. }
  490. // CreateNode creates a node in the network using the given configuration
  491. func (s *Server) CreateNode(w http.ResponseWriter, req *http.Request) {
  492. config := &adapters.NodeConfig{}
  493. err := json.NewDecoder(req.Body).Decode(config)
  494. if err != nil && err != io.EOF {
  495. http.Error(w, err.Error(), http.StatusBadRequest)
  496. return
  497. }
  498. node, err := s.network.NewNodeWithConfig(config)
  499. if err != nil {
  500. http.Error(w, err.Error(), http.StatusInternalServerError)
  501. return
  502. }
  503. s.JSON(w, http.StatusCreated, node.NodeInfo())
  504. }
  505. // GetNodes returns all nodes which exist in the network
  506. func (s *Server) GetNodes(w http.ResponseWriter, req *http.Request) {
  507. nodes := s.network.GetNodes()
  508. infos := make([]*p2p.NodeInfo, len(nodes))
  509. for i, node := range nodes {
  510. infos[i] = node.NodeInfo()
  511. }
  512. s.JSON(w, http.StatusOK, infos)
  513. }
  514. // GetNode returns details of a node
  515. func (s *Server) GetNode(w http.ResponseWriter, req *http.Request) {
  516. node := req.Context().Value("node").(*Node)
  517. s.JSON(w, http.StatusOK, node.NodeInfo())
  518. }
  519. // StartNode starts a node
  520. func (s *Server) StartNode(w http.ResponseWriter, req *http.Request) {
  521. node := req.Context().Value("node").(*Node)
  522. if err := s.network.Start(node.ID()); err != nil {
  523. http.Error(w, err.Error(), http.StatusInternalServerError)
  524. return
  525. }
  526. s.JSON(w, http.StatusOK, node.NodeInfo())
  527. }
  528. // StopNode stops a node
  529. func (s *Server) StopNode(w http.ResponseWriter, req *http.Request) {
  530. node := req.Context().Value("node").(*Node)
  531. if err := s.network.Stop(node.ID()); err != nil {
  532. http.Error(w, err.Error(), http.StatusInternalServerError)
  533. return
  534. }
  535. s.JSON(w, http.StatusOK, node.NodeInfo())
  536. }
  537. // ConnectNode connects a node to a peer node
  538. func (s *Server) ConnectNode(w http.ResponseWriter, req *http.Request) {
  539. node := req.Context().Value("node").(*Node)
  540. peer := req.Context().Value("peer").(*Node)
  541. if err := s.network.Connect(node.ID(), peer.ID()); err != nil {
  542. http.Error(w, err.Error(), http.StatusInternalServerError)
  543. return
  544. }
  545. s.JSON(w, http.StatusOK, node.NodeInfo())
  546. }
  547. // DisconnectNode disconnects a node from a peer node
  548. func (s *Server) DisconnectNode(w http.ResponseWriter, req *http.Request) {
  549. node := req.Context().Value("node").(*Node)
  550. peer := req.Context().Value("peer").(*Node)
  551. if err := s.network.Disconnect(node.ID(), peer.ID()); err != nil {
  552. http.Error(w, err.Error(), http.StatusInternalServerError)
  553. return
  554. }
  555. s.JSON(w, http.StatusOK, node.NodeInfo())
  556. }
  557. // Options responds to the OPTIONS HTTP method by returning a 200 OK response
  558. // with the "Access-Control-Allow-Headers" header set to "Content-Type"
  559. func (s *Server) Options(w http.ResponseWriter, req *http.Request) {
  560. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  561. w.WriteHeader(http.StatusOK)
  562. }
  563. var wsUpgrade = websocket.Upgrader{
  564. CheckOrigin: func(*http.Request) bool { return true },
  565. }
  566. // NodeRPC forwards RPC requests to a node in the network via a WebSocket
  567. // connection
  568. func (s *Server) NodeRPC(w http.ResponseWriter, req *http.Request) {
  569. conn, err := wsUpgrade.Upgrade(w, req, nil)
  570. if err != nil {
  571. return
  572. }
  573. defer conn.Close()
  574. node := req.Context().Value("node").(*Node)
  575. node.ServeRPC(conn)
  576. }
  577. // ServeHTTP implements the http.Handler interface by delegating to the
  578. // underlying httprouter.Router
  579. func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  580. s.router.ServeHTTP(w, req)
  581. }
  582. // GET registers a handler for GET requests to a particular path
  583. func (s *Server) GET(path string, handle http.HandlerFunc) {
  584. s.router.GET(path, s.wrapHandler(handle))
  585. }
  586. // POST registers a handler for POST requests to a particular path
  587. func (s *Server) POST(path string, handle http.HandlerFunc) {
  588. s.router.POST(path, s.wrapHandler(handle))
  589. }
  590. // DELETE registers a handler for DELETE requests to a particular path
  591. func (s *Server) DELETE(path string, handle http.HandlerFunc) {
  592. s.router.DELETE(path, s.wrapHandler(handle))
  593. }
  594. // OPTIONS registers a handler for OPTIONS requests to a particular path
  595. func (s *Server) OPTIONS(path string, handle http.HandlerFunc) {
  596. s.router.OPTIONS("/*path", s.wrapHandler(handle))
  597. }
  598. // JSON sends "data" as a JSON HTTP response
  599. func (s *Server) JSON(w http.ResponseWriter, status int, data interface{}) {
  600. w.Header().Set("Content-Type", "application/json")
  601. w.WriteHeader(status)
  602. json.NewEncoder(w).Encode(data)
  603. }
  604. // wrapHandler returns an httprouter.Handle which wraps an http.HandlerFunc by
  605. // populating request.Context with any objects from the URL params
  606. func (s *Server) wrapHandler(handler http.HandlerFunc) httprouter.Handle {
  607. return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  608. w.Header().Set("Access-Control-Allow-Origin", "*")
  609. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  610. ctx := req.Context()
  611. if id := params.ByName("nodeid"); id != "" {
  612. var nodeID enode.ID
  613. var node *Node
  614. if nodeID.UnmarshalText([]byte(id)) == nil {
  615. node = s.network.GetNode(nodeID)
  616. } else {
  617. node = s.network.GetNodeByName(id)
  618. }
  619. if node == nil {
  620. http.NotFound(w, req)
  621. return
  622. }
  623. ctx = context.WithValue(ctx, "node", node)
  624. }
  625. if id := params.ByName("peerid"); id != "" {
  626. var peerID enode.ID
  627. var peer *Node
  628. if peerID.UnmarshalText([]byte(id)) == nil {
  629. peer = s.network.GetNode(peerID)
  630. } else {
  631. peer = s.network.GetNodeByName(id)
  632. }
  633. if peer == nil {
  634. http.NotFound(w, req)
  635. return
  636. }
  637. ctx = context.WithValue(ctx, "peer", peer)
  638. }
  639. handler(w, req.WithContext(ctx))
  640. }
  641. }