Example #1
0
def create_client(wallet_file, node_ip, node_port):
    crypto_helper = CryptoHelper.instance()
    network_interface = ClientNetworkInterface(JsonRpcClient(),
                                               {node_ip: {
                                                   node_port: {}
                                               }})
    return BlockchainClient(Wallet(wallet_file), network_interface,
                            crypto_helper)
Example #2
0
 def test_key_pairs_match(self):
     helper = CryptoHelper.instance()
     private_key, public_key = helper.generate_key_pair()
     private_key = b64decode(private_key).decode()
     public_key = b64decode(public_key).decode()
     key = ECC.import_key(private_key)
     public_key_true = key.public_key().export_key(format='PEM')
     self.assertEqual(public_key_true, public_key)
Example #3
0
    def test_show_validate_true(self):
        helper = CryptoHelper.instance()
        private_key, public_key = helper.generate_key_pair()

        data = {'message': 'Hello World'}
        message = json.dumps(data)
        signature_true = helper.sign(private_key, message)

        self.assertTrue(helper.validate(public_key, message, signature_true))
Example #4
0
    def test_show_hash_true(self):
        #  Values Dumped
        data = {'message': 'Hello World'}
        message = json.dumps(data)
        hash_true = 'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'

        helper = CryptoHelper.instance()
        returned_hash = helper.hash(message)
        self.assertEqual(hash_true, returned_hash)
Example #5
0
    def __init__(self,
                 block_id=None,
                 transactions=[],
                 predecessor_hash=None,
                 block_creator_id=None,
                 merkle_tree_root=None,
                 nonce=0,
                 timestamp=time.time(),
                 consensus_obj=None,
                 difficulty=-1):
        """Constructor for LogicalBlock, derives properties from the
        placeholder class Block.

        Parameters
        ----------
        block_id : Int
            ID of the block
        transactions : List
            Transactions to be included in the block
        predecessor_hash : Hash
            Hash of the predecessor block to this block
        block_creator_id : String
            ID of the node who created this block
        merkle_tree_root : Hash
            Merkle Tree Root of all transactions combined
        nonce : Int
            Value for which block hash satisfies criteria of HashCash
        timestamp : Timestamp of the block creation
        consensus_obj : Instance of consensus module
        difficulty: Int
            Difficulty value used for the block mining

        Attributes
        ----------
        _length_in_chain : Int
            Position at which it resides in the node's chain
        _crypto_helper : Instance of the Crypto Helper Module
        _merkle_tree_root : Hash
            Merkle Tree Root of all transactions combined
        _consensus : Instance of consensus module

        """
        super(LogicalBlock, self).__init__(block_id=block_id,
                                           merkle_tree_root=merkle_tree_root,
                                           predecessor_hash=predecessor_hash,
                                           block_creator_id=block_creator_id,
                                           transactions=transactions,
                                           nonce=nonce,
                                           timestamp=timestamp,
                                           difficulty=difficulty)
        self._length_in_chain = None
        self._crypto_helper = CryptoHelper.instance()
        self._consensus = consensus_obj
        if not self._merkle_tree_root:
            self._merkle_tree_root = self.compute_merkle_root()
Example #6
0
    def test_show_hash_false(self):
        #  Values Dumped
        data = {'message': 'Bye World'}
        message = json.dumps(data)

        hash_false = '98be8b9818c2538fd0c476f3ddd0d6b7e3a58ad77be5cef38a74ecdcd9c01ef1'

        helper = CryptoHelper.instance()
        returned_hash = helper.hash(message)

        self.assertNotEqual(hash_false, returned_hash)
Example #7
0
    def __init__(self):

        self.crypto_helper = CryptoHelper.instance()
        self.max_diff = 5  # Threshold to be defined
        self.min_diff = 1
        self.kill_mine = 0
        self.last_mine_time_sec = time.time()
        self.expected_mine_freq = 30
        self.granular = True
        self.granular_factor = 1
        self.diflag = False
        if not self.granular:
            self.diflag = True
        if self.diflag:
            self.granular = False
        if self.granular:
            self.granular_factor = 4
        self.min_mining_time = time.time()
        self.max_mining_time = 0
        self.avg_mining_time = 0
        self.avg_helper = 0
        self.num_of_mined_blocks = 0
        self.num_of_transactions = 0
        self.avg_diff = 4
Example #8
0
    def init_components(self):
        node_config = './labchain/resources/node_configuration.ini'
        config_reader = ConfigReader(node_config)

        tolerance = config_reader.get_config(section='BLOCK_CHAIN',
                                             option='TOLERANCE_LEVEL')
        pruning = config_reader.get_config(section='BLOCK_CHAIN',
                                           option='TIME_TO_PRUNE')
        min_blocks = config_reader.get_config(
            section='MINING', option='NUM_OF_BLOCKS_FOR_DIFFICULTY')

        self.consensus = Consensus()
        self.crypto_helper_obj = crypto.instance()
        self.txpool = TxPool(self.crypto_helper_obj)
        self.block_list = []
        self.blockchain = BlockChain(node_id="nodeId1",
                                     tolerance_value=tolerance,
                                     pruning_interval=pruning,
                                     consensus_obj=self.consensus,
                                     txpool_obj=self.txpool,
                                     crypto_helper_obj=self.crypto_helper_obj,
                                     min_blocks_for_difficulty=min_blocks,
                                     db=self.database,
                                     q=None)
Example #9
0
    def test_show_validate_false(self):
        helper = CryptoHelper.instance()
        private_key, public_key = helper.generate_key_pair()

        data = {'message': 'Hello World'}
        message = json.dumps(data)
        signature_true = helper.sign(private_key, message)

        #  generate a new public key
        private_key_false, public_key_false = helper.generate_key_pair()

        #  tamper with signature

        signature_true_bytes = b64decode(signature_true.encode('utf-8'))

        signature_byte_array = bytearray(signature_true_bytes)
        signature_byte_array[0] = (signature_byte_array[0] + 1) % 256
        signature_false_bytes = bytes(signature_byte_array)

        signature_false = b64encode(signature_false_bytes).decode('utf-8')

        self.assertFalse(helper.validate(public_key, message, signature_false))
        self.assertFalse(
            helper.validate(public_key_false, message, signature_true))
Example #10
0
    def initialize_components(self):
        """ Initialize every componenent of the node"""
        self.logger.debug("Initialized every component for the node")
        self.consensus_obj = Consensus()
        self.crypto_helper_obj = CryptoHelper.instance()
        self.txpool_obj = TxPool(crypto_helper_obj=self.crypto_helper_obj)
        self.db = Db(block_chain_db_file=os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         'resources/labchaindb.sqlite')))
        """init blockchain"""
        # Generate the node ID using host ID
        node_uuid = str(uuid.uuid1())
        node_id = node_uuid[node_uuid.rfind('-') + 1:]
        self.logger.info("Creator id " + str(node_id))

        # Read all configurations to be used
        try:
            tolerance_value = self.config_reader.get_config(
                section='BLOCK_CHAIN', option='TOLERANCE_LEVEL')
            pruning_interval = self.config_reader.get_config(
                section='BLOCK_CHAIN', option='TIME_TO_PRUNE')
            fetch_prev_interval = self.config_reader.get_config(
                section='BLOCK_CHAIN', option='FETCH_PREV_INTERVAL')
            if not self.network_port:
                self.network_port = self.config_reader.get_config(
                    section='NETWORK', option='PORT')
            initial_peers_from_config = self.config_reader.get_config(
                section='NETWORK', option='PEER_LIST')
            pool_interval = self.config_reader.get_config(
                section='NETWORK', option='POOLING_INTERVAL_SEC')
            mine_freq = self.config_reader.get_config(
                section='MINING', option='MINE_SCHEDULING_FREQUENCY_SEC')
            num_of_transactions = self.config_reader.get_config(
                section='MINING', option='BLOCK_TRANSACTION_SIZE')
            min_blocks = self.config_reader.get_config(
                section='MINING', option='NUM_OF_BLOCKS_FOR_DIFFICULTY')
        except ConfigReaderException as e:
            self.logger.error(str(e))
            self.logger.error("Exiting Node startup ..!! \n")
            sys.exit(0)

        # Create tables if not already
        self.db.create_tables()

        self.q = Queue()

        self.blockchain_obj = BlockChain(
            node_id=node_id,
            tolerance_value=tolerance_value,
            pruning_interval=pruning_interval,
            consensus_obj=self.consensus_obj,
            txpool_obj=self.txpool_obj,
            crypto_helper_obj=self.crypto_helper_obj,
            min_blocks_for_difficulty=min_blocks,
            db=self.db,
            q=self.q)

        self.logger.debug("Initialized web server")
        """init network interface"""
        intial_peer_list = self.initial_peers
        if not intial_peer_list:
            intial_peer_list = json.loads(initial_peers_from_config)
            self.initial_peers = initial_peers_from_config
        self.network_interface = self.create_network_interface(
            self.network_port, initial_peers=intial_peer_list)

        # start the web servers for receiving JSON-RPC calls
        self.logger.debug('Starting web server thread...')
        self.webserver_thread = threading.Thread(
            name='Web Server', target=self.network_interface.start_listening)
        self.webserver_thread.start()

        # start the polling threads
        self.logger.debug('Starting polling threads...')
        self.polling_thread = threading.Thread(
            name='Polling',
            target=self.network_interface.poll_update_peer_lists,
            args=(pool_interval, ))
        self.polling_thread.start()

        self.logger.info("Fetching Blocks from Database if present...")
        blocks_from_db = self.reinitialize_blockchain_from_db()
        if blocks_from_db is not None:
            for block in blocks_from_db:
                self.blockchain_obj.add_block(
                    LogicalBlock.from_block(block, self.consensus_obj), False)
                self.logger.info('Fetched block nr ' + str(block.block_id) +
                                 ' from DB')

        self.logger.info("Starting bootstrap...")
        """Bootstrap the blockchain node"""
        bootstrapper = Bootstrapper(self.network_interface)
        bootstrapper.do_bootstrap(self.blockchain_obj)

        self.logger.debug("Starting request block thread...")
        """init rb"""
        # start the scheduler for rb
        self.rb_thread = threading.Thread(target=self.fetch_prev_blocks,
                                          kwargs=dict(
                                              q=self.q,
                                              interval=fetch_prev_interval))
        self.rb_thread.start()

        self.logger.debug("Starting mining thread...")
        """init mining"""
        # start the scheduler for mining
        self.mine_thread = threading.Thread(
            target=self.block_mine_timer,
            kwargs=dict(mine_freq=mine_freq,
                        block_transactions_size=num_of_transactions))
        self.mine_thread.start()

        self.logger.debug("Starting orphan pruning thread...")
        self.orphan_killer = threading.Thread(
            target=self.schedule_orphans_killing,
            kwargs=dict(interval=pruning_interval))

        self.orphan_killer.start()
Example #11
0
 def test_hash_input_false(self):
     message = "Hello World"
     helper = CryptoHelper.instance()
     with self.assertRaises(ValueError):
         helper.hash(message)