files: #!/usr/bin/env python3
  # Copyright (c) 2014-2015 The Bitcoin Core developers
  # Copyright (c) 2015-2017 The Bitcoin Unlimited developers
  # Distributed under the MIT software license, see the accompanying
  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  """
  Run Regression Test Suite
  
  This module calls down into individual test cases via subprocess. It will
  forward all unrecognized arguments onto the individual test scripts, other
  than:
  
      - `-h` or '--help': print help about all options
      - `-extended`: run the "extended" test suite in addition to the basic one.
      - `-extended-only`: run ONLY the "extended" test suite
      - `-list`: only list the test scripts, do not run. Works in combination
        with '-extended' and '-extended-only' too, to print subsets.
      - `-win`: signal that this is running in a Windows environment, and we
        should run the tests.
      - `--coverage`: this generates a basic coverage report for the RPC
        interface.
  
  For more detailed help on options, run with '--help'.
  
  For a description of arguments recognized by test scripts, see
  `qa/pull-tester/test_framework/test_framework.py:BitcoinTestFramework.main`.
  
  """
  import pdb
  import os
  import time
  import shutil
  import sys
  import subprocess
  import tempfile
  import re
  
  sys.path.append("qa/pull-tester/")
  from tests_config import *
  from test_classes import RpcTest, Disabled, Skip
  
  BOLD = ("","")
  if os.name == 'posix':
      # primitive formatting on supported
      # terminal via ANSI escape sequences:
      BOLD = ('\033[0m', '\033[1m')
  
  RPC_TESTS_DIR = SRCDIR + '/qa/rpc-tests/'
  
  #If imported values are not defined then set to zero (or disabled)
  if 'ENABLE_WALLET' not in vars():
      ENABLE_WALLET=0
  if 'ENABLE_BITCOIND' not in vars():
      ENABLE_BITCOIND=0
  if 'ENABLE_UTILS' not in vars():
      ENABLE_UTILS=0
  if 'ENABLE_ZMQ' not in vars():
      ENABLE_ZMQ=0
  
  ENABLE_COVERAGE=0
  
  #Create a set to store arguments and create the passOn string
  opts = set()
  double_opts = set()  # BU: added for checking validity of -- opts
  passOn = ""
  showHelp = False  # if we need to print help
  p = re.compile("^--")
  # some of the single-dash options applicable only to this runner script
  # are also allowed in double-dash format (but are not passed on to the
  # test scripts themselves)
  private_single_opts = ('-h',
                         '-f',    # equivalent to -force-enable
                         '-help',
                         '-list',
                         '-extended',
                         '-extended-only',
                         '-only-extended',
                         '-force-enable',
                         '-win')
  private_double_opts = ('--list',
                         '--extended',
                         '--extended-only',
                         '--only-extended',
                         '--force-enable',
                         '--win')
  framework_opts = ('--tracerpc',
                    '--help',
                    '--noshutdown',
                    '--nocleanup',
                    '--srcdir',
                    '--tmpdir',
                    '--coveragedir',
                    '--randomseed',
                    '--testbinary',
                    '--refbinary')
  test_script_opts = ('--mineblock',
                      '--extensive')
  
  def option_passed(option_without_dashes):
      """check if option was specified in single-dash or double-dash format"""
      return ('-' + option_without_dashes in opts
              or '--' + option_without_dashes in double_opts)
  
  bold = ("","")
  if (os.name == 'posix'):
      bold = ('\033[0m', '\033[1m')
  
  for arg in sys.argv[1:]:
      if arg == '--coverage':
          ENABLE_COVERAGE = 1
      elif (p.match(arg) or arg in ('-h', '-help')):
          if arg not in private_double_opts:
              if arg == '--help' or arg == '-help' or arg == '-h':
                  passOn = '--help'
                  showHelp = True
              else:
                  if passOn is not '--help':
                      passOn += " " + arg
          # add it to double_opts only for validation
          double_opts.add(arg)
      else:
          # this is for single-dash options only
          # they are interpreted only by this script
          opts.add(arg)
  
  # check for unrecognized options
  bad_opts_found = []
  bad_opt_str="Unrecognized option: %s"
  for o in opts | double_opts:
      if o.startswith('--'):
          if o not in framework_opts + test_script_opts + private_double_opts:
              print(bad_opt_str % o)
              bad_opts_found.append(o)
      elif o.startswith('-'):
          if o not in private_single_opts:
              print(bad_opt_str % o)
              bad_opts_found.append(o)
              print("Run with -h to get help on usage.")
              sys.exit(1)
  
  #Set env vars
  if "BITCOIND" not in os.environ:
      os.environ["BITCOIND"] = BUILDDIR + '/src/bitcoind' + EXEEXT
  if "BITCOINCLI" not in os.environ:
      os.environ["BITCOINCLI"] = BUILDDIR + '/src/bitcoin-cli' + EXEEXT
  
  #Disable Windows tests by default
  if EXEEXT == ".exe" and not option_passed('win'):
      print("Win tests currently disabled.  Use -win option to enable")
      sys.exit(0)
  
  if not (ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1):
      print("No rpc tests to run. Wallet, utils, and bitcoind must all be enabled")
      sys.exit(0)
  
  # python3-zmq may not be installed. Handle this gracefully and with some helpful info
  if ENABLE_ZMQ:
      try:
          import zmq
      except ImportError as e:
          print("ERROR: \"import zmq\" failed. Set ENABLE_ZMQ=0 or " \
              "to run zmq tests, see dependency info in /qa/README.md.")
          raise e
  
  #Tests
  testScripts = [ RpcTest(t) for t in [
      'bip68-112-113-p2p',
      'validateblocktemplate',
      'parallel',
      'wallet',
      'excessive',
      'listtransactions',
      'receivedby',
      'mempool_resurrect_test',
      'txn_doublespend --mineblock',
      'txn_clone',
      'getchaintips',
      'rawtransactions',
      'rest',
      'mempool_spendcoinbase
  
  [... the rest is omitted ...]
files: qa/pull-tester/rpc-tests.py
files: #!/usr/bin/env python3
  # Copyright (c) 2014-2015 The Bitcoin Core developers
  # Copyright (c) 2015-2017 The Bitcoin Unlimited developers
  # Distributed under the MIT software license, see the accompanying
  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  """
  Run Regression Test Suite
  
  This module calls down into individual test cases via subprocess. It will
  forward all unrecognized arguments onto the individual test scripts, other
  than:
  
      - `-h` or '--help': print help about all options
      - `-extended`: run the "extended" test suite in addition to the basic one.
      - `-extended-only`: run ONLY the "extended" test suite
      - `-list`: only list the test scripts, do not run. Works in combination
        with '-extended' and '-extended-only' too, to print subsets.
      - `-win`: signal that this is running in a Windows environment, and we
        should run the tests.
      - `--coverage`: this generates a basic coverage report for the RPC
        interface.
  
  For more detailed help on options, run with '--help'.
  
  For a description of arguments recognized by test scripts, see
  `qa/pull-tester/test_framework/test_framework.py:BitcoinTestFramework.main`.
  
  """
  import pdb
  import os
  import time
  import shutil
  import sys
  import subprocess
  import tempfile
  import re
  
  sys.path.append("qa/pull-tester/")
  from tests_config import *
  from test_classes import RpcTest, Disabled, Skip
  
  BOLD = ("","")
  if os.name == 'posix':
      # primitive formatting on supported
      # terminal via ANSI escape sequences:
      BOLD = ('\033[0m', '\033[1m')
  
  RPC_TESTS_DIR = SRCDIR + '/qa/rpc-tests/'
  
  #If imported values are not defined then set to zero (or disabled)
  if 'ENABLE_WALLET' not in vars():
      ENABLE_WALLET=0
  if 'ENABLE_BITCOIND' not in vars():
      ENABLE_BITCOIND=0
  if 'ENABLE_UTILS' not in vars():
      ENABLE_UTILS=0
  if 'ENABLE_ZMQ' not in vars():
      ENABLE_ZMQ=0
  
  ENABLE_COVERAGE=0
  
  #Create a set to store arguments and create the passOn string
  opts = set()
  double_opts = set()  # BU: added for checking validity of -- opts
  passOn = ""
  showHelp = False  # if we need to print help
  p = re.compile("^--")
  # some of the single-dash options applicable only to this runner script
  # are also allowed in double-dash format (but are not passed on to the
  # test scripts themselves)
  private_single_opts = ('-h',
                         '-f',    # equivalent to -force-enable
                         '-help',
                         '-list',
                         '-extended',
                         '-extended-only',
                         '-only-extended',
                         '-force-enable',
                         '-win')
  private_double_opts = ('--list',
                         '--extended',
                         '--extended-only',
                         '--only-extended',
                         '--force-enable',
                         '--win')
  framework_opts = ('--tracerpc',
                    '--help',
                    '--noshutdown',
                    '--nocleanup',
                    '--srcdir',
                    '--tmpdir',
                    '--coveragedir',
                    '--randomseed',
                    '--testbinary',
                    '--refbinary')
  test_script_opts = ('--mineblock',
                      '--extensive')
  
  def option_passed(option_without_dashes):
      """check if option was specified in single-dash or double-dash format"""
      return ('-' + option_without_dashes in opts
              or '--' + option_without_dashes in double_opts)
  
  bold = ("","")
  if (os.name == 'posix'):
      bold = ('\033[0m', '\033[1m')
  
  for arg in sys.argv[1:]:
      if arg == '--coverage':
          ENABLE_COVERAGE = 1
      elif (p.match(arg) or arg in ('-h', '-help')):
          if arg not in private_double_opts:
              if arg == '--help' or arg == '-help' or arg == '-h':
                  passOn = '--help'
                  showHelp = True
              else:
                  if passOn is not '--help':
                      passOn += " " + arg
          # add it to double_opts only for validation
          double_opts.add(arg)
      else:
          # this is for single-dash options only
          # they are interpreted only by this script
          opts.add(arg)
  
  # check for unrecognized options
  bad_opts_found = []
  bad_opt_str="Unrecognized option: %s"
  for o in opts | double_opts:
      if o.startswith('--'):
          if o not in framework_opts + test_script_opts + private_double_opts:
              print(bad_opt_str % o)
              bad_opts_found.append(o)
      elif o.startswith('-'):
          if o not in private_single_opts:
              print(bad_opt_str % o)
              bad_opts_found.append(o)
              print("Run with -h to get help on usage.")
              sys.exit(1)
  
  #Set env vars
  if "BITCOIND" not in os.environ:
      os.environ["BITCOIND"] = BUILDDIR + '/src/bitcoind' + EXEEXT
  if "BITCOINCLI" not in os.environ:
      os.environ["BITCOINCLI"] = BUILDDIR + '/src/bitcoin-cli' + EXEEXT
  
  #Disable Windows tests by default
  if EXEEXT == ".exe" and not option_passed('win'):
      print("Win tests currently disabled.  Use -win option to enable")
      sys.exit(0)
  
  if not (ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1):
      print("No rpc tests to run. Wallet, utils, and bitcoind must all be enabled")
      sys.exit(0)
  
  # python3-zmq may not be installed. Handle this gracefully and with some helpful info
  if ENABLE_ZMQ:
      try:
          import zmq
      except ImportError as e:
          print("ERROR: \"import zmq\" failed. Set ENABLE_ZMQ=0 or " \
              "to run zmq tests, see dependency info in /qa/README.md.")
          raise e
  
  #Tests
  testScripts = [ RpcTest(t) for t in [
      'bip68-112-113-p2p',
      'validateblocktemplate',
      'parallel',
      'wallet',
      'excessive',
      'listtransactions',
      'receivedby',
      'mempool_resurrect_test',
      'txn_doublespend --mineblock',
      'txn_clone',
      'getchaintips',
      'rawtransactions',
      'rest',
      'mempool_spendcoinbase
  
  [... the rest is omitted ...]
files: qa/pull-tester/rpc-tests.py
files: #!/usr/bin/env python3
  # Copyright (c) 2014-2015 The Bitcoin Core developers
  # Copyright (c) 2015-2016 The Bitcoin Unlimited 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 *
  
  class ParallelTest (BitcoinTestFramework):
      def __init__(self):
        self.rep = False
        #self.extensive = False
        BitcoinTestFramework.__init__(self)
  
      def setup_chain(self):
          print ("Initializing test directory "+self.options.tmpdir)
          initialize_chain_clean(self.options.tmpdir, 6)
  
      def setup_network(self, split=False):
          self.nodes = []
          self.nodes.append(start_node(0, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          self.nodes.append(start_node(1, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          self.nodes.append(start_node(2, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          self.nodes.append(start_node(3, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          interconnect_nodes(self.nodes)
          self.is_network_split=False
          self.sync_all()
  
      def repetitiveTest(self):
          # get some coins
          self.nodeLookup = {}
          i = 0
          for n in self.nodes:
            print("Node %d is %s" % (i,n.url))
            print ("generating coins for node")  
            n.generate(200)
            self.sync_all()
            i += 1
            
          for i in range(0,200):
            # Create many utxo's
            print ("round %d: Generating txns..." % i)
            for n in self.nodes:  
              send_to = {}
              n.keypoolrefill(100)
              n.keypoolrefill(100)
              for i in range(200):
                send_to[n.getnewaddress()] = Decimal("0.01")
              n.sendmany("", send_to)
  
              self.sync_all()
            print ("  generating blocks...")
            i = 0
            for n in self.nodes:
              try:
                  n.generate(1)
              except JSONRPCException as e:
                  print (e)
                  print ("Node ", i, " ", n.url)
                  pdb.set_trace()
              i += 1
            print ("  syncing...")
            self.sync_all()
                      
      def run_test (self):
          if self.rep:
              self.repetitiveTest()
              return
  
          print ("Mining blocks with PV off...")
  
          # Mine some blocks on node2 which we will need at the end to generate a few transactions from that node
          # in order to create the small block with just a few transactions in it.
          self.nodes[2].generate(1)
          self.sync_all()
  
          # Mine the rest on node0 where we will generate the bigger block.
          self.nodes[0].generate(100)
          self.sync_all()
  
          self.nodes[0].generate(100)
          self.sync_all()
  
          # Create many utxo's
          print ("Generating txns...")
          send_to = {}
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
  
          # Mine a block so that the utxos are now spendable
          print ("mine a block")
          self.nodes[0].generate(1)
  
          connect_nodes(self.nodes[0],1)
          connect_nodes(self.nodes[0],2)
          connect_nodes(self.nodes[0],3)
          self.is_network_split=False
          self.sync_all()
  
          # Send more transactions
          print ("Generating
  
  [... the rest is omitted ...]
files: qa/rpc-tests/parallel.py
files: #!/usr/bin/env python3
  # Copyright (c) 2014-2015 The Bitcoin Core developers
  # Copyright (c) 2015-2016 The Bitcoin Unlimited 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 *
  
  class ParallelTest (BitcoinTestFramework):
      def __init__(self):
        self.rep = False
        BitcoinTestFramework.__init__(self)
  
      def setup_chain(self):
          print ("Initializing test directory "+self.options.tmpdir)
          initialize_chain_clean(self.options.tmpdir, 6)
  
      def setup_network(self, split=False):
          self.nodes = []
          self.nodes.append(start_node(0, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          self.nodes.append(start_node(1, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          self.nodes.append(start_node(2, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          self.nodes.append(start_node(3, self.options.tmpdir, ["-parallel=0", "-rpcservertimeout=0", "-debug", "-use-thinblocks=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"]))
          interconnect_nodes(self.nodes)
          self.is_network_split=False
          self.sync_all()
  
      def repetitiveTest(self):
          # get some coins
          self.nodeLookup = {}
          i = 0
          for n in self.nodes:
            print("Node %d is %s" % (i,n.url))
            print ("generating coins for node")  
            n.generate(200)
            self.sync_all()
            i += 1
            
          for i in range(0,200):
            # Create many utxo's
            print ("round %d: Generating txns..." % i)
            for n in self.nodes:  
              send_to = {}
              n.keypoolrefill(100)
              n.keypoolrefill(100)
              for i in range(200):
                send_to[n.getnewaddress()] = Decimal("0.01")
              n.sendmany("", send_to)
  
              self.sync_all()
            print ("  generating blocks...")
            i = 0
            for n in self.nodes:
              try:
                  n.generate(1)
              except JSONRPCException as e:
                  print (e)
                  print ("Node ", i, " ", n.url)
                  pdb.set_trace()
              i += 1
            print ("  syncing...")
            self.sync_all()
                      
      def run_test (self):
          if self.rep:
              self.repetitiveTest()
              return
          
          print ("Mining blocks with PV off...")
  
          # Mine some blocks on node2 which we will need at the end to generate a few transactions from that node
          # in order to create the small block with just a few transactions in it.
          self.nodes[2].generate(1)
          self.sync_all()
  
          # Mine the rest on node0 where we will generate the bigger block.
          self.nodes[0].generate(100)
          self.sync_all()
  
          self.nodes[0].generate(100)
          self.sync_all()
  
          # Create many utxo's
          print ("Generating txns...")
          send_to = {}
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
          self.nodes[0].keypoolrefill(100)
          self.nodes[0].keypoolrefill(100)
          for i in range(200):
              send_to[self.nodes[0].getnewaddress()] = Decimal("0.01")
          self.nodes[0].sendmany("", send_to)
  
          # Mine a block so that the utxos are now spendable
          print ("mine a block")
          self.nodes[0].generate(1)
  
          connect_nodes(self.nodes[0],1)
          connect_nodes(self.nodes[0],2)
          connect_nodes(self.nodes[0],3)
          self.is_network_split=False
          self.sync_all()
  
          # Send more transactions
          print ("Generating more txns...")
          output_total
  
  [... the rest is omitted ...]
files: qa/rpc-tests/parallel.py
files: // Copyright (c) 2017 Stephen McCarthy
  // Copyright (c) 2017 The Bitcoin Unlimited developers
  // Distributed under the MIT software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #include <set>
  
  #include "allowed_args.h"
  #include "chainparams.h"
  #include "dosman.h"
  #include "httpserver.h"
  #include "init.h"
  #include "main.h"
  #include "miner.h"
  #include "netbase.h"
  #include "policy/policy.h"
  #include "qt/guiconstants.h"
  #include "requestManager.h"
  #include "script/sigcache.h"
  #include "tinyformat.h"
  #include "torcontrol.h"
  #include "tweak.h"
  #include "txdb.h"
  #include "util.h"
  #include "utilmoneystr.h"
  #include "utilstrencodings.h"
  
  #ifdef ENABLE_WALLET
  #include "wallet/wallet.h"
  #endif
  
  // These globals are needed here so bitcoin-cli can link
  const std::string CURRENCY_UNIT = "BTC";
  const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
  const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
  
  // Variables for traffic shaping.  Needed here so bitcoin-cli can link
  /** Default value for the maximum amount of data that can be received in a burst */
  const int64_t DEFAULT_MAX_RECV_BURST = std::numeric_limits<int64_t>::max();
  /** Default value for the maximum amount of data that can be sent in a burst */
  const int64_t DEFAULT_MAX_SEND_BURST = std::numeric_limits<int64_t>::max();
  /** Default value for the average amount of data received per second */
  const int64_t DEFAULT_AVE_RECV = std::numeric_limits<int64_t>::max();
  /** Default value for the average amount of data sent per second */
  const int64_t DEFAULT_AVE_SEND = std::numeric_limits<int64_t>::max();
  
  namespace AllowedArgs
  {
  enum HelpMessageMode
  {
      HMM_BITCOIND,
      HMM_BITCOIN_QT
  };
  
  static const int screenWidth = 79;
  static const int optIndent = 2;
  static const int msgIndent = 7;
  
  std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); }
  std::string HelpMessageOpt(const std::string &option, const std::string &message)
  {
      return std::string(optIndent, ' ') + std::string(option) + std::string("\n") + std::string(msgIndent, ' ') +
             FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n");
  }
  
  AllowedArgs::AllowedArgs(bool permit_unrecognized) : m_permit_unrecognized(permit_unrecognized) {}
  AllowedArgs &AllowedArgs::addHeader(const std::string &strHeader, bool debug)
  {
      m_helpList.push_back(HelpComponent{strHeader + "\n\n", debug});
      return *this;
  }
  
  AllowedArgs &AllowedArgs::addDebugArg(const std::string &strArgsDefinition,
      CheckValueFunc checkValueFunc,
      const std::string &strHelp)
  {
      return addArg(strArgsDefinition, checkValueFunc, strHelp, true);
  }
  
  AllowedArgs &AllowedArgs::addArg(const std::string &strArgsDefinition,
      CheckValueFunc checkValueFunc,
      const std::string &strHelp,
      bool debug)
  {
      std::string strArgs = strArgsDefinition;
      std::string strExampleValue;
      size_t is_index = strArgsDefinition.find('=');
      if (is_index != std::string::npos)
      {
          strExampleValue = strArgsDefinition.substr(is_index + 1);
          strArgs = strArgsDefinition.substr(0, is_index);
      }
  
      if (strArgs == "")
          strArgs = ",";
  
      std::stringstream streamArgs(strArgs);
      std::string strArg;
      bool firstArg = true;
      while (std::getline(streamArgs, strArg, ','))
      {
          m_args[strArg] = checkValueFunc;
  
          std::string optionText = std::string(optIndent, ' ') + "-" + strArg;
          if (!strExampleValue.empty())
              optionText += "=" + strExampleValue;
          optionText += "\n";
          m_helpList.push_back(HelpComponent{optionText, debug || !firstArg});
  
          firstArg = false;
      }
  
      std::string helpText =
          std::string(msgIndent, ' ') + FormatParagraph(strHelp, screenWidth - msgIndent, msgIndent) + "\n\n";
      m_helpList.push_back(HelpComponent{helpText, debug});
  
      return *this;
  }
  
  void AllowedArgs::checkArg(const std::string &strArg, const std::string &strValue) const
  {
      if (!m_args.count(strArg))
      {
          if (m_permit_unrecognized)
              return;
          throw std::runtime_error(strprintf(_("unrecognized option '%s'"), strArg));
      }
  
      if (!m_args.at(strArg)(strValue))
          throw std::runtime_error(strprintf(_("invalid value '%s' for option '%s'"), strValue, strArg));
  }
  
  std::string AllowedArgs::helpMessage() const
  {
      const bool showDebug = GetBoolArg("-help-debug", false);
      std::string helpMessage;
  
      for (HelpComponent helpComponent : m_helpList)
          if (showDebug || !helpComponent.debug)
              helpMessage += helpComponent.text;
  
      return helpMessage;
  }
  
  //////////////////////////////////////////////////////////////////////////////
  //
  // CheckValueFunc functions
  //
  
  static const std::set<std::string> boolStrings{"", "1", "0", "t", "f", "y", "n", "true", "false", "yes", "no"};
  static const std::set<char> intChars{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  static const std::set<char> amountChars{'.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  
  static bool validateString(const std::string &str, const std::set<char> &validChars)
  {
      for (const char &c : str)
          if (!validChars.count(c))
              return false;
      return true;
  }
  
  static bool optionalBool(const std::string &str) { return (boolStrings.count(str) != 0); }
  static bool requiredStr(const std::string &str) { return !str.empty(); }
  static bool optionalStr(const std::string &str) { return true; }
  static bool requiredInt(const std::string &str)
  {
      if (str.empty() || str == "-")
          return false;
  
      // Allow the first character to be '-', to allow negative numbers.
      return validateString(str[0] == '-' ? str.substr(1) : str, intChars);
  }
  
  static bool optionalInt(const std::string &str)
  {
      if (str.empty())
          return true;
      return requiredInt(str);
  }
  
  static bool requiredAmount(const std::string &str)
  {
      if (str.empty())
  
  
  [... the rest is omitted ...]
files: src/allowed_args.cpp
files: // Copyright (c) 2017 Stephen McCarthy
  // Copyright (c) 2017 The Bitcoin Unlimited developers
  // Distributed under the MIT software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #include <set>
  
  #include "allowed_args.h"
  #include "chainparams.h"
  #include "dosman.h"
  #include "httpserver.h"
  #include "init.h"
  #include "main.h"
  #include "miner.h"
  #include "netbase.h"
  #include "policy/policy.h"
  #include "qt/guiconstants.h"
  #include "requestManager.h"
  #include "script/sigcache.h"
  #include "tinyformat.h"
  #include "torcontrol.h"
  #include "tweak.h"
  #include "txdb.h"
  #include "util.h"
  #include "utilmoneystr.h"
  #include "utilstrencodings.h"
  
  #ifdef ENABLE_WALLET
  #include "wallet/wallet.h"
  #endif
  
  // These globals are needed here so bitcoin-cli can link
  const std::string CURRENCY_UNIT = "BTC";
  const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
  const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
  
  // Variables for traffic shaping.  Needed here so bitcoin-cli can link
  /** Default value for the maximum amount of data that can be received in a burst */
  const int64_t DEFAULT_MAX_RECV_BURST = std::numeric_limits<int64_t>::max();
  /** Default value for the maximum amount of data that can be sent in a burst */
  const int64_t DEFAULT_MAX_SEND_BURST = std::numeric_limits<int64_t>::max();
  /** Default value for the average amount of data received per second */
  const int64_t DEFAULT_AVE_RECV = std::numeric_limits<int64_t>::max();
  /** Default value for the average amount of data sent per second */
  const int64_t DEFAULT_AVE_SEND = std::numeric_limits<int64_t>::max();
  
  namespace AllowedArgs
  {
  enum HelpMessageMode
  {
      HMM_BITCOIND,
      HMM_BITCOIN_QT
  };
  
  static const int screenWidth = 79;
  static const int optIndent = 2;
  static const int msgIndent = 7;
  
  std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); }
  std::string HelpMessageOpt(const std::string &option, const std::string &message)
  {
      return std::string(optIndent, ' ') + std::string(option) + std::string("\n") + std::string(msgIndent, ' ') +
             FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n");
  }
  
  AllowedArgs::AllowedArgs(bool permit_unrecognized) : m_permit_unrecognized(permit_unrecognized) {}
  AllowedArgs &AllowedArgs::addHeader(const std::string &strHeader, bool debug)
  {
      m_helpList.push_back(HelpComponent{strHeader + "\n\n", debug});
      return *this;
  }
  
  AllowedArgs &AllowedArgs::addDebugArg(const std::string &strArgsDefinition,
      CheckValueFunc checkValueFunc,
      const std::string &strHelp)
  {
      return addArg(strArgsDefinition, checkValueFunc, strHelp, true);
  }
  
  AllowedArgs &AllowedArgs::addArg(const std::string &strArgsDefinition,
      CheckValueFunc checkValueFunc,
      const std::string &strHelp,
      bool debug)
  {
      std::string strArgs = strArgsDefinition;
      std::string strExampleValue;
      size_t is_index = strArgsDefinition.find('=');
      if (is_index != std::string::npos)
      {
          strExampleValue = strArgsDefinition.substr(is_index + 1);
          strArgs = strArgsDefinition.substr(0, is_index);
      }
  
      if (strArgs == "")
          strArgs = ",";
  
      std::stringstream streamArgs(strArgs);
      std::string strArg;
      bool firstArg = true;
      while (std::getline(streamArgs, strArg, ','))
      {
          m_args[strArg] = checkValueFunc;
  
          std::string optionText = std::string(optIndent, ' ') + "-" + strArg;
          if (!strExampleValue.empty())
              optionText += "=" + strExampleValue;
          optionText += "\n";
          m_helpList.push_back(HelpComponent{optionText, debug || !firstArg});
  
          firstArg = false;
      }
  
      std::string helpText =
          std::string(msgIndent, ' ') + FormatParagraph(strHelp, screenWidth - msgIndent, msgIndent) + "\n\n";
      m_helpList.push_back(HelpComponent{helpText, debug});
  
      return *this;
  }
  
  void AllowedArgs::checkArg(const std::string &strArg, const std::string &strValue) const
  {
      if (!m_args.count(strArg))
      {
          if (m_permit_unrecognized)
              return;
          throw std::runtime_error(strprintf(_("unrecognized option '%s'"), strArg));
      }
  
      if (!m_args.at(strArg)(strValue))
          throw std::runtime_error(strprintf(_("invalid value '%s' for option '%s'"), strValue, strArg));
  }
  
  std::string AllowedArgs::helpMessage() const
  {
      const bool showDebug = GetBoolArg("-help-debug", false);
      std::string helpMessage;
  
      for (HelpComponent helpComponent : m_helpList)
          if (showDebug || !helpComponent.debug)
              helpMessage += helpComponent.text;
  
      return helpMessage;
  }
  
  //////////////////////////////////////////////////////////////////////////////
  //
  // CheckValueFunc functions
  //
  
  static const std::set<std::string> boolStrings{"", "1", "0", "t", "f", "y", "n", "true", "false", "yes", "no"};
  static const std::set<char> intChars{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  static const std::set<char> amountChars{'.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  
  static bool validateString(const std::string &str, const std::set<char> &validChars)
  {
      for (const char &c : str)
          if (!validChars.count(c))
              return false;
      return true;
  }
  
  static bool optionalBool(const std::string &str) { return (boolStrings.count(str) != 0); }
  static bool requiredStr(const std::string &str) { return !str.empty(); }
  static bool optionalStr(const std::string &str) { return true; }
  static bool requiredInt(const std::string &str)
  {
      if (str.empty() || str == "-")
          return false;
  
      // Allow the first character to be '-', to allow negative numbers.
      return validateString(str[0] == '-' ? str.substr(1) : str, intChars);
  }
  
  static bool optionalInt(const std::string &str)
  {
      if (str.empty())
          return true;
      return requiredInt(str);
  }
  
  static bool requiredAmount(const std::string &str)
  {
      if (str.empty())
  
  
  [... the rest is omitted ...]
files: src/allowed_args.cpp
files: // Copyright (c) 2009-2010 Satoshi Nakamoto
  // Copyright (c) 2009-2015 The Bitcoin Core developers
  // Copyright (c) 2015-2017 The Bitcoin Unlimited developers
  // Distributed under the MIT software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #ifndef BITCOIN_INIT_H
  #define BITCOIN_INIT_H
  
  #include <string>
  
  class CScheduler;
  class CWallet;
  
  namespace boost
  {
  class thread_group;
  } // namespace boost
  
  void StartShutdown();
  bool ShutdownRequested();
  /** Interrupt threads */
  void Interrupt(boost::thread_group& threadGroup);
  void Shutdown();
  //!Initialize the logging infrastructure
  void InitLogging();
  //!Parameter interaction: change current parameters depending on various rules
  void InitParameterInteraction();
  bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler);
  
  void MainCleanup();
  void NetCleanup();
  
  static const bool DEFAULT_PROXYRANDOMIZE = true;
  static const bool DEFAULT_REST_ENABLE = false;
  static const bool DEFAULT_DISABLE_SAFEMODE = false;
  static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
  static const bool DEFAULT_PV_TESTMODE = false;
  
  /** Returns licensing information (for -version) */
  std::string LicenseInfo();
  
  #endif // BITCOIN_INIT_H
  
  
  [... the rest is omitted ...]
files: src/init.h
files: // Copyright (c) 2009-2010 Satoshi Nakamoto
  // Copyright (c) 2009-2015 The Bitcoin Core developers
  // Copyright (c) 2015-2017 The Bitcoin Unlimited developers
  // Distributed under the MIT software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #ifndef BITCOIN_INIT_H
  #define BITCOIN_INIT_H
  
  #include <string>
  
  class CScheduler;
  class CWallet;
  
  namespace boost
  {
  class thread_group;
  } // namespace boost
  
  void StartShutdown();
  bool ShutdownRequested();
  /** Interrupt threads */
  void Interrupt(boost::thread_group& threadGroup);
  void Shutdown();
  //!Initialize the logging infrastructure
  void InitLogging();
  //!Parameter interaction: change current parameters depending on various rules
  void InitParameterInteraction();
  bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler);
  
  void MainCleanup();
  void NetCleanup();
  
  static const bool DEFAULT_PROXYRANDOMIZE = true;
  static const bool DEFAULT_REST_ENABLE = false;
  static const bool DEFAULT_DISABLE_SAFEMODE = false;
  static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
  
  /** Returns licensing information (for -version) */
  std::string LicenseInfo();
  
  #endif // BITCOIN_INIT_H
  
  
  [... the rest is omitted ...]
files: src/init.h
files: // Copyright (c) 2009-2010 Satoshi Nakamoto
  // Copyright (c) 2009-2015 The Bitcoin Core developers
  // Copyright (c) 2015-2017 The Bitcoin Unlimited developers
  // Copyright (c) 2016 Bitcoin Unlimited developers
  // Distributed under the MIT software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #include "main.h"
  
  #include "addrman.h"
  #include "arith_uint256.h"
  #include "chainparams.h"
  #include "checkpoints.h"
  #include "checkqueue.h"
  #include "connmgr.h"
  #include "consensus/consensus.h"
  #include "consensus/merkle.h"
  #include "consensus/validation.h"
  #include "dosman.h"
  #include "expedited.h"
  #include "hash.h"
  #include "init.h"
  #include "merkleblock.h"
  #include "net.h"
  #include "nodestate.h"
  #include "parallel.h"
  #include "policy/policy.h"
  #include "pow.h"
  #include "primitives/block.h"
  #include "primitives/transaction.h"
  #include "requestManager.h"
  #include "script/script.h"
  #include "script/sigcache.h"
  #include "script/standard.h"
  #include "thinblock.h"
  #include "tinyformat.h"
  #include "txdb.h"
  #include "txmempool.h"
  #include "ui_interface.h"
  #include "undo.h"
  #include "util.h"
  #include "utilmoneystr.h"
  #include "utilstrencodings.h"
  #include "validationinterface.h"
  #include "versionbits.h"
  
  #include <algorithm>
  #include <boost/algorithm/hex.hpp>
  #include <boost/algorithm/string/replace.hpp>
  #include <boost/filesystem.hpp>
  #include <boost/filesystem/fstream.hpp>
  #include <boost/math/distributions/poisson.hpp>
  #include <boost/scope_exit.hpp>
  #include <boost/thread.hpp>
  #include <sstream>
  
  #if defined(NDEBUG)
  #error "Bitcoin cannot be compiled without assertions."
  #endif
  
  /**
   * Global state
   */
  
  // BU variables moved to globals.cpp
  // BU moved CCriticalSection cs_main;
  
  // BU moved BlockMap mapBlockIndex;
  // BU movedCChain chainActive;
  CBlockIndex *pindexBestHeader = NULL;
  int64_t nTimeBestReceived = 0;
  // BU moved CWaitableCriticalSection csBestBlock;
  // BU moved CConditionVariable cvBlockChange;
  bool fImporting = false;
  bool fReindex = false;
  bool fTxIndex = false;
  bool fHavePruned = false;
  bool fPruneMode = false;
  bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
  bool fRequireStandard = true;
  unsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP;
  bool fCheckBlockIndex = false;
  bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
  size_t nCoinCacheUsage = 5000 * 300;
  uint64_t nPruneTarget = 0;
  
  CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
  
  // BU: Move global objects to a single file
  extern CTxMemPool mempool;
  
  // BU: change locking of orphan map from using cs_main to cs_orphancache.
  // There is too much dependance on cs_main locks which are generally too
  // broad in scope.
  // Move globals to a single file
  extern CCriticalSection cs_orphancache;
  extern std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_orphancache);
  extern std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_orphancache);
  
  int64_t nLastOrphanCheck = GetTime(); // Used in EraseOrphansByTime()
  static uint64_t nBytesOrphanPool = 0; // Current in memory size of the orphan pool.
  
  // BU: start block download at low numbers in case our peers are slow when we start
  /** Number of blocks that can be requested at any given time from a single peer. */
  static unsigned int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 1;
  /** Size of the "block download window": how far ahead of our current height do we fetch?
   *  Larger windows tolerate larger download speed differences between peer, but increase the potential
   *  degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
   *  harder). We'll probably want to make this a per-peer adaptive value at some point. */
  static unsigned int BLOCK_DOWNLOAD_WINDOW = 256;
  
  extern CTweak<unsigned int> maxBlocksInTransitPerPeer; // override the above
  extern CTweak<unsigned int> blockDownloadWindow;
  extern CTweak<uint64_t> reindexTypicalBlockSize;
  
  extern std::map<CNetAddr, ConnectionHistory> mapInboundConnectionTracker;
  extern CCriticalSection cs_mapInboundConnectionTracker;
  
  /** A cache to store headers that have arrived but can not yet be connected **/
  std::map<uint256, std::pair<CBlockHeader, int64_t> > mapUnConnectedHeaders;
  
  /**
   * Returns true if there are nRequired or more blocks of minVersion or above
   * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
   */
  static bool IsSuperMajority(int minVersion,
      const CBlockIndex *pstart,
      unsigned nRequired,
      const Consensus::Params &consensusParams);
  static void CheckBlockIndex(const Consensus::Params &consensusParams);
  
  /** Constant stuff for coinbase transactions we create: */
  CScript COINBASE_FLAGS;
  
  const std::string strMessageMagic = "Bitcoin Signed Message:\n";
  
  extern CStatHistory<uint64_t> nTxValidationTime;
  extern CStatHistory<uint64_t> nBlockValidationTime;
  extern CCriticalSection cs_blockvalidationtime;
  
  extern CCriticalSection cs_LastBlockFile;
  extern CCriticalSection cs_nBlockSequenceId;
  
  
  // Internal stuff
  namespace
  {
  struct CBlockIndexWorkComparator
  {
      bool operator()(CBlockIndex *pa, CBlockIndex *pb) const
      {
          // First sort by most total work, ...
          if (pa->nChainWork > pb->nChainWork)
              return false;
          if (pa->nChainWork < pb->nChainWork)
              return true;
  
          // ... then by earliest time received, ...
          if (pa->nSequenceId < pb->nSequenceId)
              return false;
          if (pa->nSequenceId > pb->nSequenceId)
              return true;
  
          // Use pointer address as tie breaker (should only happen with blocks
          // loaded from disk, as those all have id 0).
          if (pa < pb)
              return false;
          if (pa > pb)
              return true;
  
          // Identical blocks.
          return false;
      }
  };
  
  CBlockIndex *pindexBestInvalid;
  
  /**
   * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
   * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
   * missing the data for the block.
   */
  std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
  /** Number of nodes with fSyncStarted. */
  int nSync
  
  [... the rest is omitted ...]
files: src/main.cpp
files: // Copyright (c) 2009-2010 Satoshi Nakamoto
  // Copyright (c) 2009-2015 The Bitcoin Core developers
  // Copyright (c) 2015-2017 The Bitcoin Unlimited developers
  // Copyright (c) 2016 Bitcoin Unlimited developers
  // Distributed under the MIT software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #include "main.h"
  
  #include "addrman.h"
  #include "arith_uint256.h"
  #include "chainparams.h"
  #include "checkpoints.h"
  #include "checkqueue.h"
  #include "connmgr.h"
  #include "consensus/consensus.h"
  #include "consensus/merkle.h"
  #include "consensus/validation.h"
  #include "dosman.h"
  #include "expedited.h"
  #include "hash.h"
  #include "init.h"
  #include "merkleblock.h"
  #include "net.h"
  #include "nodestate.h"
  #include "parallel.h"
  #include "policy/policy.h"
  #include "pow.h"
  #include "primitives/block.h"
  #include "primitives/transaction.h"
  #include "requestManager.h"
  #include "script/script.h"
  #include "script/sigcache.h"
  #include "script/standard.h"
  #include "thinblock.h"
  #include "tinyformat.h"
  #include "txdb.h"
  #include "txmempool.h"
  #include "ui_interface.h"
  #include "undo.h"
  #include "util.h"
  #include "utilmoneystr.h"
  #include "utilstrencodings.h"
  #include "validationinterface.h"
  #include "versionbits.h"
  
  #include <algorithm>
  #include <boost/algorithm/hex.hpp>
  #include <boost/algorithm/string/replace.hpp>
  #include <boost/filesystem.hpp>
  #include <boost/filesystem/fstream.hpp>
  #include <boost/math/distributions/poisson.hpp>
  #include <boost/scope_exit.hpp>
  #include <boost/thread.hpp>
  #include <sstream>
  
  #if defined(NDEBUG)
  #error "Bitcoin cannot be compiled without assertions."
  #endif
  
  /**
   * Global state
   */
  
  // BU variables moved to globals.cpp
  // BU moved CCriticalSection cs_main;
  
  // BU moved BlockMap mapBlockIndex;
  // BU movedCChain chainActive;
  CBlockIndex *pindexBestHeader = NULL;
  int64_t nTimeBestReceived = 0;
  // BU moved CWaitableCriticalSection csBestBlock;
  // BU moved CConditionVariable cvBlockChange;
  bool fImporting = false;
  bool fReindex = false;
  bool fTxIndex = false;
  bool fHavePruned = false;
  bool fPruneMode = false;
  bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
  bool fRequireStandard = true;
  unsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP;
  bool fCheckBlockIndex = false;
  bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
  size_t nCoinCacheUsage = 5000 * 300;
  uint64_t nPruneTarget = 0;
  
  CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
  
  // BU: Move global objects to a single file
  extern CTxMemPool mempool;
  
  // BU: change locking of orphan map from using cs_main to cs_orphancache.
  // There is too much dependance on cs_main locks which are generally too
  // broad in scope.
  // Move globals to a single file
  extern CCriticalSection cs_orphancache;
  extern std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_orphancache);
  extern std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_orphancache);
  
  int64_t nLastOrphanCheck = GetTime(); // Used in EraseOrphansByTime()
  static uint64_t nBytesOrphanPool = 0; // Current in memory size of the orphan pool.
  
  // BU: start block download at low numbers in case our peers are slow when we start
  /** Number of blocks that can be requested at any given time from a single peer. */
  static unsigned int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 1;
  /** Size of the "block download window": how far ahead of our current height do we fetch?
   *  Larger windows tolerate larger download speed differences between peer, but increase the potential
   *  degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
   *  harder). We'll probably want to make this a per-peer adaptive value at some point. */
  static unsigned int BLOCK_DOWNLOAD_WINDOW = 256;
  
  extern CTweak<unsigned int> maxBlocksInTransitPerPeer; // override the above
  extern CTweak<unsigned int> blockDownloadWindow;
  extern CTweak<uint64_t> reindexTypicalBlockSize;
  
  extern std::map<CNetAddr, ConnectionHistory> mapInboundConnectionTracker;
  extern CCriticalSection cs_mapInboundConnectionTracker;
  
  /** A cache to store headers that have arrived but can not yet be connected **/
  std::map<uint256, std::pair<CBlockHeader, int64_t> > mapUnConnectedHeaders;
  
  /**
   * Returns true if there are nRequired or more blocks of minVersion or above
   * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
   */
  static bool IsSuperMajority(int minVersion,
      const CBlockIndex *pstart,
      unsigned nRequired,
      const Consensus::Params &consensusParams);
  static void CheckBlockIndex(const Consensus::Params &consensusParams);
  
  /** Constant stuff for coinbase transactions we create: */
  CScript COINBASE_FLAGS;
  
  const std::string strMessageMagic = "Bitcoin Signed Message:\n";
  
  extern CStatHistory<uint64_t> nTxValidationTime;
  extern CStatHistory<uint64_t> nBlockValidationTime;
  extern CCriticalSection cs_blockvalidationtime;
  
  extern CCriticalSection cs_LastBlockFile;
  extern CCriticalSection cs_nBlockSequenceId;
  
  
  // Internal stuff
  namespace
  {
  struct CBlockIndexWorkComparator
  {
      bool operator()(CBlockIndex *pa, CBlockIndex *pb) const
      {
          // First sort by most total work, ...
          if (pa->nChainWork > pb->nChainWork)
              return false;
          if (pa->nChainWork < pb->nChainWork)
              return true;
  
          // ... then by earliest time received, ...
          if (pa->nSequenceId < pb->nSequenceId)
              return false;
          if (pa->nSequenceId > pb->nSequenceId)
              return true;
  
          // Use pointer address as tie breaker (should only happen with blocks
          // loaded from disk, as those all have id 0).
          if (pa < pb)
              return false;
          if (pa > pb)
              return true;
  
          // Identical blocks.
          return false;
      }
  };
  
  CBlockIndex *pindexBestInvalid;
  
  /**
   * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
   * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
   * missing the data for the block.
   */
  std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
  /** Number of nodes with fSyncStarted. */
  int nSync
  
  [... the rest is omitted ...]
files: src/main.cpp