def test_init(): actual_transaction = 'transaction' actual_previous_block = 'previous_block' block = Block(actual_transaction, actual_previous_block) assert block.timestamp is not None assert block.transaction is actual_transaction assert block.previous_block is actual_previous_block
def test_to_dict(): actual_transaction = 'transaction' actual_previous_block = 'previous_block' block = Block(actual_transaction, actual_previous_block) assert isinstance(block.to_dict(), dict) == True assert block.to_dict()['transaction'] == json.dumps(actual_transaction) assert block.to_dict()['previous_block'] == actual_previous_block
def add_data(self, data: str) -> bool: """ Adds a new Block to the Blockchain. Returns a bool indicating success or failure. Parameters: data -- the data (represented as a string) to be stored. """ timestamp = time.time() # The previous hash is important since this is what helps us ensure # that our Blockchain has not lost its integrity. Each block will # keep track of the block before it, using its hash, thus we # will know that no block has been tamperered with. previous_hash = self.blocks[-1].generate_hash() block = Block() block.data = data block.timestamp = timestamp block.previous_hash = previous_hash self.blocks.append(block) # We validate the entire Blockchain to ensure that # the block we just inserted did not break our # Blockchain integrity. if not self.validate(): self.blocks.remove(block) return False return True
def next_block_branch2(chain): block_information = chain.genesis_block.get_block_information() next_block_branch2 = Block(block_information, PUBLIC_KEY) next_block_branch2.timestamp = chain.genesis_block.timestamp + CONFIG.block_time + 1 next_block_branch2.sign(PRIVATE_KEY) next_block_branch2.update_hash() yield next_block_branch2
def create_genesis_block(self): genesis_block = Block(index=0, transactions=[], timestamp=time.time(), previous_hash='0') genesis_block.hash = genesis_block.compute_hash() self.chain.append(genesis_block)
def test_genesisBlock(): # testing genesis block block = Block(**GENESIS_DATA) assert isinstance(block,Block) assert block.timestamp==GENESIS_DATA['timestamp'] assert block.data==GENESIS_DATA['data'] assert block.hash==GENESIS_DATA['hash'] assert block.previousHash==GENESIS_DATA['previousHash']
def dangling_block(chain): dangling_block = Block({"index": 4, "hash": "ab1234"}, PUBLIC_KEY) dangling_block.timestamp = chain.genesis_block.timestamp + 2 * CONFIG.block_time + 1 dangling_block.sign(PRIVATE_KEY) dangling_block.update_hash() chain.add_dangling_block(dangling_block) yield dangling_block
def __init__(self): self.chain = list() self.chain.append( Block( 0, '0000000000000000000000000000000000000000000000000000000000000000', 'first Block'))
def mine(self, reward_address): """ Mines a new block into the chain :param reward_address: <str> address where the reward coin will be transferred to :return: result of the mining attempt and the new block """ last_block = self.last_block index = last_block.index + 1 previous_hash = last_block.hash # Let's start with the heavy duty, generating the proof of work nonce = self.generate_proof_of_work(last_block) # In the next step we will create a new transaction to reward the miner # In this particular case, the miner will receive coins that are just "created", so there is no sender self.create_transaction( sender="0", recipient=reward_address, amount=1, ) # Add the block to the new chain block = Block(index, self.__current_transactions, nonce, previous_hash) if self.add_block(block): return block return None
def new_block(genesis): new_block = Block(genesis.get_block_information(), PUBLIC_KEY) new_block.add_transaction("tx1") new_block.add_transaction("tx2") new_block.sign(PRIVATE_KEY) new_block.update_hash() yield new_block
def test_block_setup(self): previous_hash = '0000000000000000000000000000000000000000000000000000000000000000' block = Block(0, previous_hash, 'TestBlock') assert block.index == 0 assert block.previous_hash == previous_hash assert block.data == 'TestBlock' assert len(block.hash) == 64
def test_set_new_block(): genesis = GenesisBlock() bm = BlockchainManager(genesis.to_dict()) block = Block('transaction', 'prev_block_hash') bm.set_new_block(block) assert len(bm.chain) == 2 assert bm.chain[0] == genesis.to_dict() assert bm.chain[1] == block
def test_get_hash(): bm = BlockchainManager(None) block = Block('transaction', 'prev_block_hash') block_json = json.dumps(block.to_dict(), sort_keys=True) hash_b = hashlib.sha256( hashlib.sha256(block_json.encode('utf-8')).digest()).digest() actual_hash = binascii.hexlify(hash_b).decode('ascii') assert bm.get_hash(block.to_dict()) == actual_hash
def test_received_new_block(full_client): block_information = full_client.chain.genesis_block.get_block_information() next_block = Block(block_information, PUBLIC_KEY) next_block.sign(PRIVATE_KEY) next_block.update_hash() full_client.received_new_block(repr(next_block)) assert os.path.exists(os.path.join(CONFIG.persistance_folder, "_".join([str(next_block.index), next_block.previous_block, next_block.hash])))
def create_genesis(self): """ Creates the Genesis block and passes it to the chain :return: None """ genesis_block = Block(0, self.__current_transactions, 0, '00') self.__chain.append(genesis_block)
def test_block_hash(self): """ Test hashing blocks """ block = Block(1, [], 0, '0') # If we recalculate the hash on the block we should get the same result as we have stored self.assertEqual(block.hash, block.hash_block())
def replace_chain(self, chain): if len(chain) > len(self._chain_list): chain_list = [] for block in chain: chain_list.append( Block(int(block['index']), int(block['nonce']), block['previous_hash'], block['data'], block['hash'], float(block['timestamp']))) self._chain_list = chain_list
def mine(self, data): previous = self._latest_block nonce = 0 while True: nonce += 1 new = Block(previous.index + 1, nonce, previous.hash, data) if self._is_hash_valid(new.hash): self._chain_list.append(new) break
def append_blockchain(): data = request.get_json() print(data) # difficulty = data['difficulty'] # difficulty_num = data['difficulty_num'] block = Block(data['latest_block'], data['time'], data['latest_block'], data['data'], data['nonce'], data['difficulty']) BLOCKCHAIN.append(block) return 'k'
def addNewBlock(transactionType, success, mineInt, catchInt, encounter, numGraphicCards, numDogecoin, numEthereum, numBitcoin): blockData = BlockData(transactionType, success, mineInt, catchInt, encounter, numGraphicCards, numDogecoin, numEthereum, numBitcoin) previousBlockHash = None if len(blockchain) > 0: previousBlockHash = blockchain[len(blockchain)-1].getHash() newBlock = Block(blockData, previousBlockHash) blockchain.append(newBlock) return newBlock
def _add_block(self, previous_hash): new_block = Block( block_number=len(self.chain) + 1, transactions=self.transactions, nonce=len(self.chain), previous_hash=previous_hash, ) self.transactions = [] self.chain.append(new_block) return new_block
def add_new_block(self, data): new_index = len(self.chain.blocks) previous_hash = self.get_latest_block().hash Block(new_index, previous_hash, data).add_to_proto(self.chain.blocks.add()) try: f = open(PROTOBUF_FILE, "wb") f.write(self.chain.SerializeToString()) f.close() except IOError: print("Writing to file failed. Last Block was not stored")
def test_hash_generate(self): block = Block( index=1, nonce=80578, previous_hash=( '8724f78170aee146b794ca6ad451d23c254717727e18e2b9643b81d5666aa' '908'), data='hello', timestamp=1520923121.335219) self.assertEqual( block.hash, '0000f307ce360b39986cc164b7770f3029acd8f568be13765b22b482981675ca')
def _read_block_from_dict(self, dict): # print(dict) previous_hash = dict['prev_block'] block = Block(previous_hash=previous_hash) block.hash = dict['hash'] block.nonce = dict['nonce'] block.timestamp = dict['time_stamp'] is_coinbase = True for transaction_dict in dict['transactions']: sender = '' if 'sender_public_key' in transaction_dict: sender = transaction_dict['sender_public_key'] signature = None if 'signature' in transaction_dict: signature = transaction_dict['signature'] reciever = transaction_dict['receiver_public_key'] value = transaction_dict['value'] transaction_inputs = [] if 'input' in transaction_dict: for transaction_input_dict in transaction_dict['input']: transaction_output_id = transaction_input_dict[ 'transactionOutputId'] transaction_input = TransactionInput( transaction_output_id=transaction_output_id) transaction_inputs.append(transaction_input) transaction = Transaction(sender, reciever, value, transaction_inputs) transaction.transaction_id = transaction_dict['id'] transaction.signature = signature block.add_transaction(transaction, all_utxos=self.blockchain.all_utxos, minimum_transaction=self.minimum_transaction, fee=self.blockchain.fee, should_check=False, is_coinbase=is_coinbase) is_coinbase = False if 'output' in transaction_dict: for transaction_output_dict in transaction_dict['output']: value = transaction_output_dict['value'] parent_transaction_id = '' if 'parent_transaction_id' in transaction_output_dict: parent_transaction_id = transaction_output_dict[ 'parent_transaction_id'] recipient_public_key = transaction_output_dict[ 'recipient_public_key'] transaction_output = TransactionOutput( recipient_public_key_str=recipient_public_key, value=value, parent_transaction_id=parent_transaction_id) transaction_output.id = transaction_output_dict['id'] transaction.outputs.append(transaction_output) self.blockchain.append_transaction(transaction) self.blockchain.append_block(block)
def add_block(self, verbose: bool) -> None: index = len(self.chain) previous_block_hash = self.chain[-1].hash() proof, tries = self.find_proof() block = Block(index=index, previous_hash=previous_block_hash, proof=proof) self.chain.append(block) self.validate() if verbose: print(f'Block has been closed with work amount of: {str(tries)}') print(self.chain[-2])
def mine(self): # add pending transactions to the blockchain if not self.unconfirmed_transactions: return "Add transactions" last_block = self.last_block new_block = Block(index=last_block.index + 1, transactions=self.unconfirmed_transactions, timestamp=time.time(), previous_hash=last_block.hash) proof = self.proof_of_work(new_block) self.add_block(new_block, proof) self.unconfirmed_transactions = [] return new_block.__dict__
def load_local(self): res = os.listdir() if '.chaindata' in res: with open('.chaindata/.data.txt', 'r') as doc: chain_data = json.load(doc) doc.close() for obj in chain_data: del obj['hash'] self.chain = [Block(x) for x in chain_data] return self.validate_chain() else: self.__genesis() self.save_local()
def __genesis(self): self.chain = [ Block( self.__proof_of_work({ 'data': 'Genesis', 'index': 0, 'nonce': 0, 'prev_hash': 0, 'destination': 0, 'origin': 0, 'timestamp': time.time() })) ]
def __init__(self): self.chain = blockchain_pb2.BlockChain() try: f = open(PROTOBUF_FILE, "rb") self.chain.ParseFromString(f.read()) f.close() except IOError: print("No existing protobuf file found. Creating new one") first_block = self.chain.blocks.add() Block( 0, '0000000000000000000000000000000000000000000000000000000000000000', 'first Block').add_to_proto(first_block)
def add_chain_data(self, chain_data: list): """ Takes a list of blocks, usually ingested from a JSON file, and adds them to the chain. Parameters: chain_data -- a list of dicts with "data", "previous_hash", "timestamp". """ for chain_item in chain_data: block = Block() block.data = chain_item["data"] block.previous_hash = chain_item["previous_hash"] block.timestamp = chain_item["timestamp"] self.blocks.append(block)