http.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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/discover"
  32. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  33. "github.com/ethereum/go-ethereum/rpc"
  34. "github.com/julienschmidt/httprouter"
  35. "golang.org/x/net/websocket"
  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. // stop the stream if the client goes away
  338. var clientGone <-chan bool
  339. if cn, ok := w.(http.CloseNotifier); ok {
  340. clientGone = cn.CloseNotify()
  341. }
  342. // write writes the given event and data to the stream like:
  343. //
  344. // event: <event>
  345. // data: <data>
  346. //
  347. write := func(event, data string) {
  348. fmt.Fprintf(w, "event: %s\n", event)
  349. fmt.Fprintf(w, "data: %s\n\n", data)
  350. if fw, ok := w.(http.Flusher); ok {
  351. fw.Flush()
  352. }
  353. }
  354. writeEvent := func(event *Event) error {
  355. data, err := json.Marshal(event)
  356. if err != nil {
  357. return err
  358. }
  359. write("network", string(data))
  360. return nil
  361. }
  362. writeErr := func(err error) {
  363. write("error", err.Error())
  364. }
  365. // check if filtering has been requested
  366. var filters MsgFilters
  367. if filterParam := req.URL.Query().Get("filter"); filterParam != "" {
  368. var err error
  369. filters, err = NewMsgFilters(filterParam)
  370. if err != nil {
  371. http.Error(w, err.Error(), http.StatusBadRequest)
  372. return
  373. }
  374. }
  375. w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
  376. w.WriteHeader(http.StatusOK)
  377. fmt.Fprintf(w, "\n\n")
  378. if fw, ok := w.(http.Flusher); ok {
  379. fw.Flush()
  380. }
  381. // optionally send the existing nodes and connections
  382. if req.URL.Query().Get("current") == "true" {
  383. snap, err := s.network.Snapshot()
  384. if err != nil {
  385. writeErr(err)
  386. return
  387. }
  388. for _, node := range snap.Nodes {
  389. event := NewEvent(&node.Node)
  390. if err := writeEvent(event); err != nil {
  391. writeErr(err)
  392. return
  393. }
  394. }
  395. for _, conn := range snap.Conns {
  396. event := NewEvent(&conn)
  397. if err := writeEvent(event); err != nil {
  398. writeErr(err)
  399. return
  400. }
  401. }
  402. }
  403. for {
  404. select {
  405. case event := <-events:
  406. // only send message events which match the filters
  407. if event.Msg != nil && !filters.Match(event.Msg) {
  408. continue
  409. }
  410. if err := writeEvent(event); err != nil {
  411. writeErr(err)
  412. return
  413. }
  414. case <-clientGone:
  415. return
  416. }
  417. }
  418. }
  419. // NewMsgFilters constructs a collection of message filters from a URL query
  420. // parameter.
  421. //
  422. // The parameter is expected to be a dash-separated list of individual filters,
  423. // each having the format '<proto>:<codes>', where <proto> is the name of a
  424. // protocol and <codes> is a comma-separated list of message codes.
  425. //
  426. // A message code of '*' or '-1' is considered a wildcard and matches any code.
  427. func NewMsgFilters(filterParam string) (MsgFilters, error) {
  428. filters := make(MsgFilters)
  429. for _, filter := range strings.Split(filterParam, "-") {
  430. protoCodes := strings.SplitN(filter, ":", 2)
  431. if len(protoCodes) != 2 || protoCodes[0] == "" || protoCodes[1] == "" {
  432. return nil, fmt.Errorf("invalid message filter: %s", filter)
  433. }
  434. proto := protoCodes[0]
  435. for _, code := range strings.Split(protoCodes[1], ",") {
  436. if code == "*" || code == "-1" {
  437. filters[MsgFilter{Proto: proto, Code: -1}] = struct{}{}
  438. continue
  439. }
  440. n, err := strconv.ParseUint(code, 10, 64)
  441. if err != nil {
  442. return nil, fmt.Errorf("invalid message code: %s", code)
  443. }
  444. filters[MsgFilter{Proto: proto, Code: int64(n)}] = struct{}{}
  445. }
  446. }
  447. return filters, nil
  448. }
  449. // MsgFilters is a collection of filters which are used to filter message
  450. // events
  451. type MsgFilters map[MsgFilter]struct{}
  452. // Match checks if the given message matches any of the filters
  453. func (m MsgFilters) Match(msg *Msg) bool {
  454. // check if there is a wildcard filter for the message's protocol
  455. if _, ok := m[MsgFilter{Proto: msg.Protocol, Code: -1}]; ok {
  456. return true
  457. }
  458. // check if there is a filter for the message's protocol and code
  459. if _, ok := m[MsgFilter{Proto: msg.Protocol, Code: int64(msg.Code)}]; ok {
  460. return true
  461. }
  462. return false
  463. }
  464. // MsgFilter is used to filter message events based on protocol and message
  465. // code
  466. type MsgFilter struct {
  467. // Proto is matched against a message's protocol
  468. Proto string
  469. // Code is matched against a message's code, with -1 matching all codes
  470. Code int64
  471. }
  472. // CreateSnapshot creates a network snapshot
  473. func (s *Server) CreateSnapshot(w http.ResponseWriter, req *http.Request) {
  474. snap, err := s.network.Snapshot()
  475. if err != nil {
  476. http.Error(w, err.Error(), http.StatusInternalServerError)
  477. return
  478. }
  479. s.JSON(w, http.StatusOK, snap)
  480. }
  481. // LoadSnapshot loads a snapshot into the network
  482. func (s *Server) LoadSnapshot(w http.ResponseWriter, req *http.Request) {
  483. snap := &Snapshot{}
  484. if err := json.NewDecoder(req.Body).Decode(snap); err != nil {
  485. http.Error(w, err.Error(), http.StatusBadRequest)
  486. return
  487. }
  488. if err := s.network.Load(snap); err != nil {
  489. http.Error(w, err.Error(), http.StatusInternalServerError)
  490. return
  491. }
  492. s.JSON(w, http.StatusOK, s.network)
  493. }
  494. // CreateNode creates a node in the network using the given configuration
  495. func (s *Server) CreateNode(w http.ResponseWriter, req *http.Request) {
  496. config := &adapters.NodeConfig{}
  497. err := json.NewDecoder(req.Body).Decode(config)
  498. if err != nil && err != io.EOF {
  499. http.Error(w, err.Error(), http.StatusBadRequest)
  500. return
  501. }
  502. node, err := s.network.NewNodeWithConfig(config)
  503. if err != nil {
  504. http.Error(w, err.Error(), http.StatusInternalServerError)
  505. return
  506. }
  507. s.JSON(w, http.StatusCreated, node.NodeInfo())
  508. }
  509. // GetNodes returns all nodes which exist in the network
  510. func (s *Server) GetNodes(w http.ResponseWriter, req *http.Request) {
  511. nodes := s.network.GetNodes()
  512. infos := make([]*p2p.NodeInfo, len(nodes))
  513. for i, node := range nodes {
  514. infos[i] = node.NodeInfo()
  515. }
  516. s.JSON(w, http.StatusOK, infos)
  517. }
  518. // GetNode returns details of a node
  519. func (s *Server) GetNode(w http.ResponseWriter, req *http.Request) {
  520. node := req.Context().Value("node").(*Node)
  521. s.JSON(w, http.StatusOK, node.NodeInfo())
  522. }
  523. // StartNode starts a node
  524. func (s *Server) StartNode(w http.ResponseWriter, req *http.Request) {
  525. node := req.Context().Value("node").(*Node)
  526. if err := s.network.Start(node.ID()); err != nil {
  527. http.Error(w, err.Error(), http.StatusInternalServerError)
  528. return
  529. }
  530. s.JSON(w, http.StatusOK, node.NodeInfo())
  531. }
  532. // StopNode stops a node
  533. func (s *Server) StopNode(w http.ResponseWriter, req *http.Request) {
  534. node := req.Context().Value("node").(*Node)
  535. if err := s.network.Stop(node.ID()); err != nil {
  536. http.Error(w, err.Error(), http.StatusInternalServerError)
  537. return
  538. }
  539. s.JSON(w, http.StatusOK, node.NodeInfo())
  540. }
  541. // ConnectNode connects a node to a peer node
  542. func (s *Server) ConnectNode(w http.ResponseWriter, req *http.Request) {
  543. node := req.Context().Value("node").(*Node)
  544. peer := req.Context().Value("peer").(*Node)
  545. if err := s.network.Connect(node.ID(), peer.ID()); err != nil {
  546. http.Error(w, err.Error(), http.StatusInternalServerError)
  547. return
  548. }
  549. s.JSON(w, http.StatusOK, node.NodeInfo())
  550. }
  551. // DisconnectNode disconnects a node from a peer node
  552. func (s *Server) DisconnectNode(w http.ResponseWriter, req *http.Request) {
  553. node := req.Context().Value("node").(*Node)
  554. peer := req.Context().Value("peer").(*Node)
  555. if err := s.network.Disconnect(node.ID(), peer.ID()); err != nil {
  556. http.Error(w, err.Error(), http.StatusInternalServerError)
  557. return
  558. }
  559. s.JSON(w, http.StatusOK, node.NodeInfo())
  560. }
  561. // Options responds to the OPTIONS HTTP method by returning a 200 OK response
  562. // with the "Access-Control-Allow-Headers" header set to "Content-Type"
  563. func (s *Server) Options(w http.ResponseWriter, req *http.Request) {
  564. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  565. w.WriteHeader(http.StatusOK)
  566. }
  567. // NodeRPC forwards RPC requests to a node in the network via a WebSocket
  568. // connection
  569. func (s *Server) NodeRPC(w http.ResponseWriter, req *http.Request) {
  570. node := req.Context().Value("node").(*Node)
  571. handler := func(conn *websocket.Conn) {
  572. node.ServeRPC(conn)
  573. }
  574. websocket.Server{Handler: handler}.ServeHTTP(w, req)
  575. }
  576. // ServeHTTP implements the http.Handler interface by delegating to the
  577. // underlying httprouter.Router
  578. func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  579. s.router.ServeHTTP(w, req)
  580. }
  581. // GET registers a handler for GET requests to a particular path
  582. func (s *Server) GET(path string, handle http.HandlerFunc) {
  583. s.router.GET(path, s.wrapHandler(handle))
  584. }
  585. // POST registers a handler for POST requests to a particular path
  586. func (s *Server) POST(path string, handle http.HandlerFunc) {
  587. s.router.POST(path, s.wrapHandler(handle))
  588. }
  589. // DELETE registers a handler for DELETE requests to a particular path
  590. func (s *Server) DELETE(path string, handle http.HandlerFunc) {
  591. s.router.DELETE(path, s.wrapHandler(handle))
  592. }
  593. // OPTIONS registers a handler for OPTIONS requests to a particular path
  594. func (s *Server) OPTIONS(path string, handle http.HandlerFunc) {
  595. s.router.OPTIONS("/*path", s.wrapHandler(handle))
  596. }
  597. // JSON sends "data" as a JSON HTTP response
  598. func (s *Server) JSON(w http.ResponseWriter, status int, data interface{}) {
  599. w.Header().Set("Content-Type", "application/json")
  600. w.WriteHeader(status)
  601. json.NewEncoder(w).Encode(data)
  602. }
  603. // wrapHandler returns a httprouter.Handle which wraps a http.HandlerFunc by
  604. // populating request.Context with any objects from the URL params
  605. func (s *Server) wrapHandler(handler http.HandlerFunc) httprouter.Handle {
  606. return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  607. w.Header().Set("Access-Control-Allow-Origin", "*")
  608. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  609. ctx := context.Background()
  610. if id := params.ByName("nodeid"); id != "" {
  611. var node *Node
  612. if nodeID, err := discover.HexID(id); err == nil {
  613. node = s.network.GetNode(nodeID)
  614. } else {
  615. node = s.network.GetNodeByName(id)
  616. }
  617. if node == nil {
  618. http.NotFound(w, req)
  619. return
  620. }
  621. ctx = context.WithValue(ctx, "node", node)
  622. }
  623. if id := params.ByName("peerid"); id != "" {
  624. var peer *Node
  625. if peerID, err := discover.HexID(id); err == nil {
  626. peer = s.network.GetNode(peerID)
  627. } else {
  628. peer = s.network.GetNodeByName(id)
  629. }
  630. if peer == nil {
  631. http.NotFound(w, req)
  632. return
  633. }
  634. ctx = context.WithValue(ctx, "peer", peer)
  635. }
  636. handler(w, req.WithContext(ctx))
  637. }
  638. }