Example #1
0
def mine_block():
    """Add block (dictionary) to blockchain (list)."""
    last_block = blockchain[-1]
    # hashed_block creates a new list using 'list comprehensions': For each
    # element (key) in last_block, a new element is generated (the dictionary
    # value last_block[key]) to fill a new list. The hash is generated using
    # "".join(str()) to create a new string from the list and join it together.
    hashed_block = hash_block(last_block)
    proof = proof_of_work()

    reward_transaction = Transaction("mining", owner, mining_reward)
    # reward_transaction = OrderedDict(
    #     [("sender", "mining"), ("recipient", owner), ("amount", mining_reward)]
    # )

    # The reward for mining is added before a block is successfully
    # incorporated into the blockchain

    # A separate copy of the *values* in a preexisting list are not copied in
    # variable assignment, e.g. copied_transactions = open_transactions, but
    # rather a mirror image of the *references* is created. This means that
    # changes to one affect the other. In order to create a separate copy of a
    # list's values, a range must be specified in the original, e.g.
    # copied_transactions = open_transactions[:].
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)

    # Block
    block = Block(len(blockchain), hashed_block, copied_transactions, proof)
    blockchain.append(block)
    return True
Example #2
0
def proof_of_work():
    last_block = blockchain[-1]
    last_hash = hash_block(last_block)
    proof = 0
    while not valid_proof(open_transactions ,last_hash, proof):
        proof += 1
    return proof
Example #3
0
    def mine_block(self):
        if self.public_key == None:
            return None
        last_block = self.__chain[-1]
        hashed_block = hash_block(last_block)
        proof = self.proof_of_work()
        reward_transaction = Transaction ('MINING', self.public_key,'', MINING_REWARD)
        copied_transactions = self.__open_transactions[:]
		
        for tx in copied_transactions:
            if not Wallet.verify_transaction(tx):
                return None
				
        copied_transactions.append(reward_transaction)
        block = Block(len(self.__chain), hashed_block, copied_transactions, proof)
        self.__chain.append(block)
        self.__open_transactions = []
        self.save_data()
		
        for node in self.__peer_nodes:
            url = 'http://{}/broadcast-block'.format(node)
            converted_block = block.__dict__.copy()
            converted_block['transactions'] = [tx.__dict__ for tx in converted_block['transactions']]
            try:
                    response = requests.post(url, json={'block': converted_block})
                    if response.status_code == 400 or response.status_code == 500:
                        print('Block declined, needs resolving')
                    if response.status_code == 409:
                        self.resolve_conflicts = True
            except requests.exceptions.ConnectionError:
                continue
        return block
Example #4
0
def mine_block():
    last_block = blockchain[-1]
    hashed_block = hash_block(last_block)
    proof = proof_of_work(
    )  # We want to exclude reward transaction thats why we are calculating PoW before adding reward
    '''
        We are putting reward points in open_transaction as for mining block takes open_transaction data
        we can have many open_transaction and then mine them all at a time.
    '''
    # reward_transaction = {
    #     'sender':'MINING',
    #     'recipient': owner,
    #     'amount': MINING_REWARD
    # }
    reward_transaction = OrderedDict([('sender', 'MINING'),
                                      ('recipient', owner),
                                      ('amount', MINING_REWARD)])
    '''
        We need copied_transaction incase there is some problem with mining the block then the transaction will remain in the 
        open_transaction which is global so we are copying it to local variable. Incase the mining is failed then the global open transaction will not have the invalid value.
    '''
    copied_transaction = open_transaction[:]  #Copying open_transaction list to copied_transaction
    copied_transaction.append(reward_transaction)
    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transaction': copied_transaction,
        'proof': proof
    }
    blockchain.append(block)
    return True
Example #5
0
    def add_block(self, block):
        transactions = [
            Transaction(tx['sender'], tx['recipient'], tx['signature'],
                        tx['amount']) for tx in block['transactions']
        ]
        proof_is_valid = Verification.valid_proof(transactions[:-1],
                                                  block['previous_hash'],
                                                  block['proof'])
        hashes_match = hash_block(self.chain[-1]) == block['previous_hash']
        if not proof_is_valid or not hashes_match:
            return False
        converted_block = Block(block['index'], block['previous_hash'],
                                transactions, block['proof'],
                                block['timestamp'])
        self.__chain.append(converted_block)
        self.save_data()
        stored_transactions = self.__open_transactions[:]
        for itx in block['transactions']:
            for opentx in stored_transactions:
                if opentx.sender == itx['sender'] and opentx.recipient == itx['recipient'] and\
                        opentx.amount == itx['amount'] and opentx.signature == itx['signature']:
                    try:
                        self.__open_transactions.remove(opentx)
                    except ValueError:
                        print('Item was already removed')

        return True
def mine_block():
    # we want  to take open transactions and  include in new block
    # we add new block variable and make a dictionalry
    last_block = blockchain[-1]
    # create list comprehension
    hashed_block = hash_block(last_block)
    proof = proof_of_work()
    # we want the participant who mined the block to get a reward
    #reward_transaction = {
    #	'sender': 'MINING',
    #	'recipient': owner,
    #	'amount': MINING_REWARD
    #}
    # add rewards before processing1

    reward_transaction = OrderedDict([('sender', 'MINING'),
                                      ('recipient', owner),
                                      ('amount', MINING_REWARD)])
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)

    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transactions': copied_transactions,
        'proof': proof
    }
    #append the block to the blockchain
    blockchain.append(block)
    save_data()
    # we want to then reste open transactions to an empty array
    return True
    print(block)
Example #7
0
    def mine_block(self,vote):
        if self.hosting_node==None:
            return Flase
        
        last_block = self.__chain[-1]
        
        hashed_block = hash_block(last_block)
        
        block = Block(len(self.__chain),hashed_block,self.hosting_node,vote)
        self.__chain.append(block)
        self.length=len(self.__chain)
        self.save_data()
    
        for node in self.__peers:
            url = 'http://{}/Broadcast'.format(node)
            converted_block = block.__dict__.copy()
            
           
            try:
                response = requests.post(url, json={'block': converted_block})
                if response.status_code == 400 or response.status_code == 500:
                    print('Block declined, needs resolving')
                if response.status_code == 409:
                    self.resolve_conflicts = True
                    self.resolve()

            except requests.exceptions.ConnectionError:
                continue
        return True
Example #8
0
def mine_block():
    """Create a new block and add open transactions to it."""
    # Fetch the currently last block of the blockchain
    last_block = blockchain[-1]
    # Hash the last block (=> to be able to compare it to the stored hash value)
    hashed_block = hash_block(last_block)
    proof = proof_of_work()
    # Miners should be rewarded, so let's create a reward transaction
    # reward_transaction = {
    #     'sender': 'MINING',
    #     'recipient': owner,
    #     'amount': MINING_REWARD
    # }
    reward_transaction = OrderedDict([('sender', 'MINING'),
                                      ('recipient', owner),
                                      ('amount', MINING_REWARD)])
    # Copy transaction instead of manipulating the original open_transactions list
    # This ensures that if for some reason the mining should fail, we don't have the reward transaction stored in the open transactions
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)
    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transactions': copied_transactions,
        'proof': proof
    }
    blockchain.append(block)
    return True
Example #9
0
def mine_block():
    """ All open transactions taken, added to a new block, then added to blockchain.
        Can invalidate following block if hash does not match previous.
    """  
    # Fetch the current last block of blockchain
    last_block = blockchain[-1]
    # Hash th elast block (=> to be able to compare it to stored hash value)
    hashed_block = hash_block(last_block)
    proof = proof_of_work()
    # Miners should be rewarded, so here is reward
    # reward_transaction = {
    #     'sender': 'MINING',
    #     'recipient': owner,
    #     'amount': MINING_REWARD
    # }
    reward_transaction = OrderedDict([('sender', 'MINING'), ('recipient', owner), ('amount', MINING_REWARD)])
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)

    block = {
      'previous_hash': hashed_block,
      'index': len(blockchain),
      'transactions': copied_transactions,
      'proof': proof
    }
    blockchain.append(block)
    return True
Example #10
0
def add_to_block():
    """
    function adds processed transactions to the blockChain
    """

    prev_block = blockChainList[-1]
    hashed_block = hash_block(prev_block)
    proof = proof_of_work()
    # reward_transaction = {
    #     'sender': 'MINING',
    #     'receiver':owner,
    #     'amount': mining_reward
    # }
    reward_transaction = OrderedDict([('sender', 'MINING'),
                                      ('receiver', owner),
                                      ('amount', mining_reward)])
    copied_transaction = incomplete_transactions[:]
    copied_transaction.append(reward_transaction)
    block = {
        'previous_hash': hashed_block,
        'index': len(blockChainList),
        'transactions': copied_transaction,
        'proof': proof
    }
    print(hashed_block)
    blockChainList.append(block)
Example #11
0
def mine_block():
    # Fetch the current last block of the blockchain
    last_block = blockchain[-1]
    # Hash the last block. So, we can compare it to the stored hash value
    hashed_block = hash_block(last_block)
    proof = proof_of_work()
    # For rewarding miners, Mining Reward was created
    # reward_transaction = {
    #     'sender': 'mining_system',
    #     'recipient': owner,
    #     'amount': mining_reward
    # }
    reward_transaction = OrderedDict(
        [('sender', 'mining_system'), ('recipient', owner), ('amount', mining_reward)])
    # Copy transaction instead of manipulating the original open_transactions list
    # This ensures that if for some reason the mining should fail, we don't have the reward transaction stored in the open transactions
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)
    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transactions': copied_transactions,
        'proof': proof
    }
    blockchain.append(block)
    return True
Example #12
0
def proof_of_work():
    last_block = blockChainList[-1]
    last_hash = hash_block(last_block)
    proof = 0
    while not (valid_proof(incomplete_transactions, last_hash, proof)):
        proof += 1
    return proof
Example #13
0
def mine_block():
    last_block = blockchain[-1]

    # implementing list comprehension to get key in each dictionary in the block
    hashed_block = hash_block(last_block)
    proof = proof_of_work()

    # determine reward for miners
    # reward_transaction ={
    #     'sender': 'MINING',
    #     'recipient': owner,
    #     'amount': MINING_REWARD,
    # }
    reward_transaction = OrderedDict([('sender', 'MINING'),
                                      ('recipient', owner),
                                      ('amount', MINING_REWARD)])
    # appending reward of mining transaction to transaction details
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)
    """
    joining hashed list of dictionaries
    
    """
    # print(hashed_block)
    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transactions': copied_transactions,
        'proof': proof,
    }
    blockchain.append(block)

    # resetting open transactions back to empty array
    return True
Example #14
0
def mine_block():
    """ Create a new block and open transactions to it. """
    last_block = blockchain[-1]
    hashed_block = '' # an empty block
    hashed_block = hash_block(last_block)
    #print(hashed_block)
    proof = proof_of_work() #  nb needs to be before we add reward
    # reward_transaction = {
    #     'sender': 'MINING',
    #     'recipient': owner,
    #     'amount': MINING_REWARD
    # }
    reward_transaction = OrderedDict([('sender', 'MINING'), ('recipient', owner), ('amount', MINING_REWARD)])
    # initially the list of transactions needs to be managed locally rather than globally so copy the open_transactions list by value using range selector to a new list called copied_transactions
    copied_transactions = open_transactions[:] # nb copied by *value*

    # then append the reward transaction to copied_transactions rather than open_transactions
    copied_transactions.append(reward_transaction)  # add reward before mining block

    # then add copied_transactions to the block rather than open_transactions
    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transactions': copied_transactions,  # nb local not global
        'proof': proof
    }
    blockchain.append(block)
    return True
Example #15
0
 def mine_block(self):
     if self.public_key is None:
         return None
     hashed_block = hash_block(self.__chain[-1])
     proof = self.proof_of_work()
     reward_transaction = Transaction('MINING', self.public_key, '',
                                      MINING_REWARD)
     copied_transactions = self.get_open_transactions()
     for tx in copied_transactions:
         if not Verification.verify_transaction(tx):
             return None
     copied_transactions.append(reward_transaction)
     block = Block(index=len(self.__chain),
                   previous_hash=hashed_block,
                   transactions=copied_transactions,
                   proof=proof)
     self.__chain.append(block)
     self.__open_transactions = []
     self.save_data()
     for node in self.__peer_nodes:
         converted_block = block.__dict__.copy()
         converted_block['transactions'] = [
             tx.__dict__ for tx in converted_block['transactions']
         ]
         url = 'http://{}/broadcast-block'.format(node)
         try:
             response = requests.post(url, json={'block': converted_block})
             if response.status_code == 500 or response.status_code == 400:
                 print('Block declined, need resolving')
         except requests.ConnectionError:
             continue
     return block
def mine_block():
    last_block = blockchain[-1]
    hashed_block = hash_block(last_block)
    proof = proof_of_work()
    ##Add the proof of work within our block
    #OLD: unordered dictionary
    # reward_transaction = {
    #     #the sender is hard-coded is basically the system which sends the reward
    #     'sender': "MINING",
    #     'recipient': owner,
    #     'amount': MINING_REWARD
    # }

    #NEW: ordered dictionary
    reward_transaction = OrderedDict(
        [('sender', "MINING"), ('recipient', owner), ('amount', MINING_REWARD)])
    #In order to manipulte the list only locally to be more safe you can copy the open_transactions to that copy
    #lists and other iterable data structures are copied by reference so that if I would simply set them both equal only the pointer would be
    #copied and not the values --> if I change the copied list it would also change the original list
    #so in case the mine block ever would deny adding that transaction we could safely do that without risking that the general open_transactions is affected
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)
    # when we always take the current len of the blockchain we get always an untaken index
    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transactions': copied_transactions,
        'proof': proof
    }
    blockchain.append(block)
    return True
Example #17
0
def mine_block():
    """Create a new block and add open transactions to it."""

    # Fetch the last block of the blockchain
    last_block = blockchain[-1]

    # Hash the last block (=> to be able to compare it to the stored has value)
    hashed_block = hash_block(last_block)
    proof = proof_of_work()

    # Providing a reward for miners
    # reward_transaction = {
    #     'sender': 'MINING',
    #     'recipient': owner,
    #     'amount': MINING_REWARD
    # }
    reward_transaction = Transaction('MINING', owner, MINING_REWARD)

    # Copy transaction instead of manipulating the original open_transactions
    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)
    block = Block(len(blockchain), hashed_block, copied_transactions, proof)

    blockchain.append(block)

    return True
 def mine_block(self):
     """Create a new block and add open transactions to it."""
     # Fetch the currently last block of the blockchain
     last_block = self.chain[-1]
     # Hash the last block (=> to be able to compare it to the stored hash value)
     hashed_block = hash_block(last_block)
     proof = self.proof_of_work()
     # Miners should be rewarded, so let's create a reward transaction
     # reward_transaction = {
     #     'sender': 'MINING',
     #     'recipient': owner,
     #     'amount': MINING_REWARD
     # }
     reward_transaction = Transaction('MINING', self.hosting_node,
                                      MINING_REWARD)
     # Copy transaction instead of manipulating the original open_transactions list
     # This ensures that if for some reason the mining should fail,
     # we don't have the reward transaction stored in the open transactions
     copied_transactions = self.open_transactions[:]
     copied_transactions.append(reward_transaction)
     block = Block(len(self.chain), hashed_block, copied_transactions,
                   proof)
     self.chain.append(block)
     self.open_transactions = []
     self.save_data()
     return True
def verify_chain():
    # block_index = 0
    # is_valid = True
    # print(blockchain)
    # for  block_index in range(len(blockchain)):

    #     if block_index == 0:
    #         block_index += 1
    #         continue
    #     elif blockchain[block_index][0] == blockchain[block_index-1]:
    #         is_valid = True
    #     else:
    #         is_valid = False
    #         break
    #     block_index += 1

    for (index, block) in enumerate(blockchain):
        if index == 0:
            continue
        if block['previous_hash'] != hash_block(blockchain[index - 1]):
            return False

        if not valid_proof(block['transactions'][:-1],
                           block['previous_hash'], block['proof']):
            print("Invalid proof")
            return False

    return True
def mine_block():
    last_block = blockchain[-1]
    hashed_block = hash_block(last_block)

    proof = proof_of_work()

    # reward_transaction = {
    #     'sender': 'MINING',
    #     'recipient': owner,
    #     'amount': MINING_REWARD
    # }

    reward_transaction = OrderedDict([
        ('sender', 'MINING'),
        ('recipient', owner),
        ('amount', MINING_REWARD)
    ])

    # for key in last_block:
    #     value = last_block[key]
    #     hashed_block = hashed_block + str(value)

    # print(hashed_block)

    copied_transactions = open_transactions[:]
    copied_transactions.append(reward_transaction)
    block = {
        'previous_hash': hashed_block,
        'index': len(blockchain),
        'transactions': copied_transactions,
        'proof': proof
    }
    blockchain.append(block)

    return True
Example #21
0
def proof_of_work():
    ''' generates potential proofs '''
    last_block = blockchain[-1]  # the last block
    last_hash = hash_block(last_block)  # hashes block to a string
    proof = 0
    while not valid_proof(open_transactions, last_hash, proof):
        proof += 1  # keep trying different proofs until a winner is found and valid_proof() returns true
    return proof  # the winning number
Example #22
0
 def proof_of_work(self):
     last_block = self.chain[-1]
     last_hash = hash_block(last_block)
     proof = 0
     while not Verification.valid_proof(self.open_transactions, last_hash,
                                        proof):
         proof += 1
     return proof
def proof_of_work():
    """Increment the proof number"""
    last_block = blockchain[-1]
    last_hash = hash_block(last_block)
    proof = 0
    while not valid_proof(open_transactions, last_hash, proof):
        proof += 1
    return proof
Example #24
0
def verify_chain():
    """ Verify the current blockchain and return True if it's valid, False otherwise."""
    for (index, block) in enumerate(blockchain):
        if index == 0:
            continue
        if block['previous_hash'] != hash_block(blockchain[index - 1]):
            return False
    return True
Example #25
0
 def proof_of_work(self):
     """Increment the proof number"""
     last_block = self.chain[-1]
     last_hash = hash_block(last_block)
     proof = 0
     verifier = Verification()
     while not verifier.valid_proof(self.open_transactions, last_hash, proof):
         proof += 1
     return proof
Example #26
0
def proof_of_work():
    """Generate a proof of work for the open transactions, the hash of the previous block and a random number (which is guessed until it fits)."""
    last_block = blockchain[-1]
    last_hash = hash_block(last_block)
    proof = 0
    # Try different PoW numbers and return the first valid one
    while not valid_proof(open_transactions, last_hash, proof):
        proof += 1
    return proof
Example #27
0
def proof_of_work():
    # This function uses a while loop to try numbers our until the hash algorithm (aka valid proof) results in a hash that begins with two 00's

    last_block = blockchain[-1]
    last_hash = hash_block(last_block)
    proof = 0
    while not valid_proof(open_txns, last_hash, proof):
        proof += 1
    return proof
Example #28
0
 def proof_of_work(self):
     """Generate a proof of work for the open transactions, the hash of the pr"""
     last_block = self.__chain[-1]
     last_hash = hash_block(last_block)
     proof = 0
     # Try different PoW numbers and return the first valid one
     while not Verification.valid_proof(self.__open_transactions, last_hash,
                                        proof):
         proof += 1
     return proof
Example #29
0
def proof_of_work():
    """ Generate a proof of work for open transactions."""
    last_block = blockchain[-1]
    last_hash = hash_block(last_block)
    # Try different PoW numbers and return the frst valid one.
    proof = 0
    while not valid_proof(open_transactions, last_hash, proof):
        proof += 1

    return proof
Example #30
0
 def verify_chain(self, blockchain):
     for (index, block) in enumerate(blockchain):
         if index == 0:
             continue
         if block.previous_hash != hash_block(blockchain[index - 1]):
             return False
         if not self.valid_proof(block.transactions[:-1], block.previous_hash, block.proof):
             print('Proof of work is invalid')
             return False
     return True