text: #!/usr/bin/env python2
  # Copyright (c) 2014 The Bitcoin Core developers
  # Distributed under the MIT software license, see the accompanying
  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  from test_framework.test_framework import BitcoinTestFramework
  from test_framework.util import assert_equal, initialize_chain_clean, \
      connect_nodes_bi, assert_true, assert_false, \
      start_node
  
  import time
  import requests
  import math
  from decimal import Decimal
  
  '''
  This test wants to verify the transactions endpoints of the explorer based on the RPC commands, both from correctness
  and completeness point of view.
  '''
  
  
  class UtilsTest(BitcoinTestFramework):
      BASE_URL = 'http://localhost:3001/insight-api-zen/'
      FEE = 0.0001
  
      def setup_chain(self):
          print("Initializing test directory " + self.options.tmpdir)
          initialize_chain_clean(self.options.tmpdir, 3)
  
      def setup_network(self, split=False):
          self.nodes = []
          self.nodes += [start_node(0, self.options.tmpdir,
                                    extra_args=['-txindex=1', '-spentindex=1', '-addressindex=1', '-timestampindex=1',
                                                '-zmqpubrawtx=tcp://127.0.0.1:13000',
                                                '-zmqpubhashblock=tcp://127.0.0.1:13000'])]
          self.nodes += [start_node(1, self.options.tmpdir)]
          self.nodes += [start_node(2, self.options.tmpdir)]
  
          connect_nodes_bi(self.nodes, 0, 1)
          connect_nodes_bi(self.nodes, 1, 2)
  
          self.is_network_split = False
          self.sync_all()
  
      def truncate(self, number, decimals=0):
          """
          Returns a value truncated to a specific number of decimal places.
          """
          if not isinstance(decimals, int):
              raise TypeError("decimal places must be an integer.")
          elif decimals < 0:
              raise ValueError("decimal places has to be 0 or more.")
          elif decimals == 0:
              return math.trunc(number)
  
      def run_test(self):
          # Give time to explorer to start
          self.nodes[0].generate(150)
          self.sync_all()
          time.sleep(30)
          info = self.nodes[0].getinfo()
  
          # ############################################################################################################################
  
          # #### /status ####
          print("#### /status ####")
  
          # Test the endpoint without parameter (= getInfo)
          r = requests.get(url=self.BASE_URL + "status", params={})
          data = r.json()['info']
          assert_equal(data['version'], info['version'])
          assert_equal(data['protocolversion'], info['protocolversion'])
          assert_equal(data['blocks'], info['blocks'])
          assert_equal(data['timeoffset'], info['timeoffset'])
          assert_equal(data['connections'], info['connections'])
          assert_equal(data['proxy'], info['proxy'])
          assert_equal(self.truncate(float(data['difficulty']), 8), self.truncate(float(info['difficulty']), 8))
          assert_equal(data['testnet'], info['testnet'])
          # assert_equal(float(data['relayfee']),float(info['relayfee']))
          assert_equal(data['errors'], info['errors'])
          assert_equal(data['network'], 'regtest')
  
          # Test the endpoint with parameter getDifficulty
          r = requests.get(url=self.BASE_URL + "status?q=getDifficulty", params={})
          data = r.json()
          assert_equal(self.truncate(float(data['difficulty']), 8), self.truncate(float(info['difficulty']), 8))
  
          # Test the endpoint with parameter getTotalSupply
          r = requests.get(url=self.BASE_URL + "status?q=getTotalSupply", params={})
          data = r.json()
          assert_equal(self.truncate(float(data['supply']), 8), self.truncate(float(info['blocks'] * 12.5), 8))
  
          # Test the endpoint with parameter getLastBlockHash
          r = requests.get(url=self.BASE_URL + "status?q=getLastBlockHash", params={})
          data = r.json()
          lastBlockHash = self.nodes[0].getblock("150")
          assert_equal({}, data,
                       'data is empty because the method is trying to return '
                       'this.node.services.bitcoind.tiphash that is undefined')
          # assert_equal(data['syncTipHash'], lastBlockHash['hash'])
  
          # Test the endpoint with parameter getBestBlockHash
          r = requests.get(url=self.BASE_URL + "status?q=getBestBlockHash", params={})
          data = r.json()
          blockchainInfo = self.nodes[0].getblockchaininfo()
          assert_equal(data['bestblockhash'], blockchainInfo['bestblockhash'])
  
          #############################################################################################################################
  
          #### /sync ####
          print("#### /sync ####")
  
          # Test the endpoint
          r = requests.get(url=self.BASE_URL + "sync", params={})
          data = r.json()
          assert_equal(data['status'], 'finished')
          assert_equal(data['blockChainHeight'], blockchainInfo['blocks'])
          assert_equal(data['syncPercentage'], 100)
          assert_equal(data['error'], None)
          assert_equal(data['type'], 'bitcore node')
          assert_equal(data['height'], blockchainInfo['blocks'])
  
          #############################################################################################################################
  
          #### /peer ####
          print("#### /peer ####")
  
          # Test the endpoint
          r = requests.get(url=self.BASE_URL + "peer", params={})
          data = r.json()
          assert_true(data['connected'])
          assert_equal(data['host'], '127.0.0.1')
          assert_equal(data['port'], None)
  
          #############################################################################################################################
  
          #### /version ####
          print("#### /version ####")
  
          # Test the endpoint
          r = requests.get(url=self.BASE_URL + "version", params={})
          data = r.json()
          assert_equal('1.0.1', data['version'])
  
          #############################################################################################################################
  
          #### /estimatefee ####
          print("#### /estimatefee ####")
  
          estimateFee = self.nodes[0].estimatefee(10)
  
          # Test the endpoint
          r = requests.get(url=self.BASE_URL + "utils/estimatefee?nbBlocks=10", params={})
          data = r.json()
  
          # Estimate fee method is broken in zendoo #
          assert_equal({}, data, 'Estimate fee method is broken in zendoo')
          assert_equal(-1, estimateFee, 'Estimate fee method is broken in zendoo')
  
          #############################################################################################################################
  
          #### /currency ####
          print("#### /currency ####")
  
          r = requests.get(url="https://blockchain.info/ticker", params={})
          bitstampRate = r.json()
  
          r = requests.get(url="https://bittrex.com/api/v1.1/public/getticker?market=btc-zen", params={})
          bittrexRate = r.json()['result']['Last']
  
          bitstamp = bitstampRate['USD']['last'] * bittrexRate
  
          # Test the endpoint
          r = requests.get(url=self.BASE_URL + "currency", params={})
          data = r.json()
          assert_equal(self.truncate(float(data['data']['bitstamp']), 8), self.truncate(float(bitstamp), 8))
  
          #############################################################################################################################
  
          #### /message/verify ####
          print("#### /message/verify ####")
  
          address = self.nodes[0].getnewaddress()
          message = "Hello World!"
          invalidMessage = "Bye World!"
          signature = self.nodes[0].signmessage(address, message)
          signatureReplaced = signature.replace("+", "%2b")
  
          # Test the endpoint in GET
          r = requests.get(
              url=self.BASE_URL + "messages/verify?address=" + address + "&signature=" + signatureReplaced + "&message=" + message,
              params={})
          data = r.json()
          assert_true(data['result'])
  
          # Test the endpoint in GET with invalid message
          r = requests.get(
              url=self.BASE_URL + "messages/verify?address=" + address + "&signature=" + signatureReplaced + "&message=" + invalidMessage,
              params={})
          data = r.json()
          assert_false(data['result'])
  
          # Test the endpoint in POST
          r = requests.post(url=self.BASE_URL + "messages/verify",
                            json={"address": address, "signature": signature, "message": message})
          data = r.json()
          print(data)
          assert_true(data['result'])
  
          # Test the endpoint in POST with invalid message
          r = requests.post(url=self.BASE_URL + "messages/verify",
                            json={"address": address, "signature": signature, "message": invalidMessage})
          data = r.json()
          assert_false(data['result'])
  
          #############################################################################################################################
  
          #### /charts ####
          print("#### /charts ####")
  
          # Test the endpoint
          r = requests.get(url=self.BASE_URL + "charts", params={})
          data = r.json()['charts']
          assert_equal(len(data), 4)
          assert_equal(data['block-size']['name'], 'Block Size')
          assert_equal(data['block-interval']['name'], 'Block Interval')
          assert_equal(data['difficulty']['name'], 'Difficulty')
          assert_equal(data['mining-revenue']['name'], 'Mining revenue')
  
          #############################################################################################################################
  
          #### /chart/:chartType ####
          print("#### /chart/:chartType ####")
  
          # Test the endpoint with mining-revenue parameter
          txs = []
          for i in range(1, 11):
              txs += [self.nodes[0].sendtoaddress(address, Decimal(str(i)))]
          self.sync_all()
          self.nodes[0].generate(1)
          self.sync_all()
          time.sleep(10)
  
          miningRevenue = Decimal(12.5)
          for tx in txs:
              transaction = self.nodes[0].gettransaction(tx)
              miningRevenue += abs(transaction['fee'])
  
          r = requests.get(url=self.BASE_URL + "chart/mining-revenue", params={})
          data = r.json()['data']
          assert_equal(len(data['json']['revenue']), 151)
          assert_equal(len(data['json']['height']), 151)
          for i in range(0, 151):
              assert_equal(i + 1, data['json']['height'][i])
              if (i == 150):
                  assert_equal("{:.8f}".format(float(abs(miningRevenue))),
                               "{:.8f}".format(float(data['json']['revenue'][i])))
              else:
                  assert_equal("{:.8f}".format(float(data['json']['revenue'][i])), "{:.8f}".format(float(Decimal(12.5))))
  
          # Test the endpoint with block-size and difficulty parameter
          r = requests.get(url=self.BASE_URL + "chart/block-size", params={})
          data = r.json()['data']
          assert_equal(len(data['json']['size']), 151)
          assert_equal(len(data['json']['height']), 151)
  
          r = requests.get(url=self.BASE_URL + "chart/difficulty", params={})
          data2 = r.json()['data']
          assert_equal(len(data2['json']['difficulty']), 151)
          assert_equal(len(data2['json']['height']), 151)
          for i in range(0, 151):
              block = self.nodes[0].getblock(str(i + 1))
              assert_equal(data['json']['height'][i], i + 1)
              assert_equal(data['json']['size'][i], block['size'])
              assert_equal(self.truncate(float(data2['json']['difficulty'][i]), 8),
                           self.truncate(float(block['difficulty']), 8))
  
          # Test the endpoint with block-interval parameter
          block0 = self.nodes[0].generate(1)
          self.sync_all()
          time.sleep(2)
          t0 = self.nodes[0].getblock(block0[0])['time']
          block1 = self.nodes[0].generate(1)
          self.sync_all()
          time.sleep(2)
          t1 = self.nodes[0].getblock(block1[0])['time']
  
          r = requests.get(url=self.BASE_URL + "chart/block-interval", params={})
          data = r.json()['data']
  
          assert_equal(len(data['json']['blockinterval']), 152)
          assert_equal(data['json']['blockinterval'][151], (t1 - t0))
  
  
  if __name__ == '__main__':
      UtilsTest().main()
  