/ tracker / tracker-rest-api.js
tracker-rest-api.js
 1  /*!
 2   * tracker/tracker-rest-api.js
 3   * Copyright (c) 2016-2019, Samourai Wallet (CC BY-NC-ND 4.0 License).
 4   */
 5  
 6  
 7  import validator from 'validator'
 8  
 9  import errors from '../lib/errors.js'
10  import authMgr from '../lib/auth/authorizations-manager.js'
11  import HttpServer from '../lib/http-server/http-server.js'
12  import network from '../lib/bitcoin/network.js'
13  import keysFile from '../keys/index.js'
14  
15  const keys = keysFile[network.key]
16  
17  /**
18   * Tracker API endpoints
19   */
20  class TrackerRestApi {
21  
22      /**
23     * Constructor
24     * @param {HttpServer} httpServer - HTTP server
25     * @param {Tracker} tracker - tracker
26     */
27      constructor(httpServer, tracker) {
28          this.httpServer = httpServer
29          this.tracker = tracker
30  
31          // Establish routes. Proxy server strips /pushtx
32          this.httpServer.app.get(
33              `/${keys.prefixes.support}/rescan`,
34              authMgr.checkHasAdminProfile.bind(authMgr),
35              this.getBlocksRescan.bind(this),
36          )
37      }
38  
39      /**
40     * Rescan a range of blocks
41     */
42      async getBlocksRescan(req, res) {
43      // Check req.arguments
44          if (!req.query)
45              return HttpServer.sendError(res, errors.body.INVDATA)
46  
47          if (!req.query.fromHeight || !validator.isInt(req.query.fromHeight))
48              return HttpServer.sendError(res, errors.body.INVDATA)
49  
50          if (req.query.toHeight && !validator.isInt(req.query.toHeight))
51              return HttpServer.sendError(res, errors.body.INVDATA)
52  
53          // Retrieve the req.arguments
54          const fromHeight = Number.parseInt(req.query.fromHeight, 10)
55          const toHeight = req.query.toHeight ? Number.parseInt(req.query.toHeight, 10) : fromHeight
56  
57          if (req.query.toHeight && (toHeight < fromHeight))
58              return HttpServer.sendError(res, errors.body.INVDATA)
59  
60          try {
61              await this.tracker.blockchainProcessor.rescanBlocks(fromHeight, toHeight)
62              const returnValue = {
63                  status: 'Rescan complete',
64                  fromHeight: fromHeight,
65                  toHeight: toHeight
66              }
67              HttpServer.sendRawData(res, JSON.stringify(returnValue, null, 2))
68          } catch(error) {
69              return HttpServer.sendError(res, error)
70          }
71      }
72  
73  }
74  
75  export default TrackerRestApi