Esempio n. 1
0
    def add_transaction(self, recipient, sender, signature, amount=1.0, is_receiving=False):
        """Append a new value as well as the last blockchain value
        to the blockchain.

        Arguments:
            :sender: The sender of the coins
            :recipient: The recipient of the coins
            :amount: The amount of coins sent with the transaction (default = 1.0)
        """
        if self.__public_key is None:
            return False

        transaction = Transaction(sender, recipient, signature, amount)
        if verifier.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            if not is_receiving:
                for node in self.__peer_nodes:
                    url = 'http://{}/broadcast-transaction'.format(node)
                    try:
                        response = requests.post(url, json={
                            'sender': sender,
                            'recipient': recipient,
                            'amount': amount,
                            'signature': signature
                        })
                        if response.status_code == 400 or response.status_code == 500:
                            print('Transaction declined, needs resolving')
                            return False
                    except requests.exceptions.ConnectionError:
                        continue
            return True
        return False
Esempio n. 2
0
 def add_block(self, block):
     """Add a block received as dictionary to the blockchain."""
     transactions = [
         Transaction(tx['sender'],
                     tx['recipient'],
                     tx['signature'],
                     tx['amount'])
         for tx in block['transactions']
     ]
     proof_is_valid = verifier.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)
     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")
     self.save_data()
     return True
Esempio n. 3
0
 def proof_of_work(self):
     """Generate a proof of work to commit a new block to the blockchain."""
     last_block = self.__chain[-1]
     last_hash = hash_block(last_block)
     proof = 0
     while not verifier.valid_proof(self.__open_transactions, last_hash, proof):
         proof += 1
     return proof
Esempio n. 4
0
 def proof_of_work(self):
     """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 = 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
 def proof_of_work(self):
     last_block = self.__chain[-1]
     last_hash = hash_block(last_block)
     proof = 0
     #try diffrent POw numbers and return the first valid number
     while not Verification.valid_proof(self.__open_transcations, last_hash,
                                        proof):
         proof += 1
     return proof
 def proof_of_work(self):
     """Generating proof of work"""  # Proof of work
     last_block = self.get_last_blockchain_value()
     last_hash = hash_block(last_block)
     proof = 0
     while not Verification.valid_proof(self.__open_transactions, last_hash,
                                        proof):
         proof += 1
     return proof
Esempio n. 7
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
Esempio n. 8
0
    def listening_for_input(self):
        waiting_for_input = True
        while waiting_for_input:
            choice = self.get_user_choice()
            if choice == '1':
                if self.wallet.public_key==None:
                    print('Transaction failed!')
                    continue
                new_recipient, new_amount = self.get_transaction_value()
                signature=self.wallet.sign_transaction(self.wallet.public_key,new_recipient,new_amount)
                if self.blockchain.add_transaction(new_recipient, self.wallet.public_key, signature, new_amount)!=None:
                    print('Added transaction!')
                else:
                    print('Transaction failed!')
            elif choice == '2':
                if not self.blockchain.mine_block():
                    print('Mining failed. Got no wallet?')
            elif choice == '3':
                self.print_blockchain_elements()
            elif choice == '4':
                if Verification.verify_transactions(self.blockchain.get_balance,self.blockchain.get_open_transactions()):
                    print('All transactions are valid')
                else:
                    print('There are invalid transactions')
                print(self.blockchain.get_open_transactions())
            elif choice == '5':
                self.wallet.create_keys()
                self.blockchain=Blockchain(self.wallet.public_key)
            elif choice == '6':
                self.wallet.load_keys()
                self.blockchain=Blockchain(self.wallet.public_key)
            elif choice == 'q':
                waiting_for_input = False
            else:
                print('Input was invalid, please pick a value from the list!')
            if not Verification.verify_blockchain(self.blockchain.chain):
                print('Invalid blockchain!')
                break
            print(f"Balance of {self.wallet.public_key}: {self.blockchain.get_balance():6.2f}")
        else:
            print('User left!')

        print("Done!")
Esempio n. 9
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_transaction, last_hash,
                                        proof):
         proof += 1
         # Printing the number of hashes done to check the proof.
         # print(proof)
     return proof
Esempio n. 10
0
 def add_transaction(self, recipient, sender, signature, amount):
     if self.hosting_node == None:
         return False
     transaction = Transaction(sender,recipient, amount, signature)
     if Verification.verify_transaction(transaction, self.get_balances):
         self.__open_transactions.append(transaction)
         #add into file
         self.save_data()
         return True
     return False
Esempio n. 11
0
 def proof_of_work(self):
     """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 = self.__chain[-1]
     last_hash = hash_block(last_block)
     proof = 0
     # Try different PoW numbers and return the first valid one
     # verifier = Verification()
     while not Verification.valid_proof(self.__open_transactions, last_hash, proof):
         proof += 1
     return proof
Esempio n. 12
0
    def listen_for_input(self):
        waiting_for_input = True
        while waiting_for_input:
            print('Please choose:')
            print('1: Add new transaction value')
            print('2: Mine a new block')
            print('3: Output the blockchain blocks')
            print('4: Check transactions validity')
            print('q: Quit')

            user_choice = self.get_user_choice()
            if user_choice == '1':
                recipient, amount = self.get_user_input()
                if self.blockchain.add_transaction(recipient,
                                                   self.id,
                                                   amount=amount):
                    print('Added transaction!')
                else:
                    print('Transaction failed!')
                print(self.blockchain.get_open_transactions())
            elif user_choice == '2':
                self.blockchain.mine_block()
            elif user_choice == '3':
                self.print_blockchain_elements()
            elif user_choice == '4':
                if Verification.verify_transactions(
                        self.blockchain.get_open_transactions(),
                        self.blockchain.get_balances):
                    print('All transactions are valid!')
                else:
                    print('There are invalid transactions!')
            elif user_choice == 'q':
                waiting_for_input = False
            else:
                print('Input was invalid, please pick a value from the list!')
            if not Verification.verify_chain(self.blockchain.chain):
                self.print_blockchain_elements()
                print('Invalid blockchain!')
                break
            print('Balance of {}: {:6.2f}'.format(
                self.id, self.blockchain.get_balances()))
        print('Done!')
Esempio n. 13
0
    def add_transaction(self, recipent, sender, amount=1.0):
        '''append new value to your blockchain'''
        if self.hosting_node == None:
            return False

        transaction = Transaction(sender, recipent, amount)
        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transaction.append(transaction)
            self.save_data()
            return True
        return False
Esempio n. 14
0
 def proof_of_work(self):
     """ Generate a proof of work for the open transactions and the hash of
     the last block """
     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
Esempio n. 15
0
    def add_transaction(self, transaction):
        """ Add a new transaction to the open_transactions. """

        if transaction.sender == SUN.PUBLIC_KEY:
            if Verification.verify_transaction(transaction, self.get_balance,
                                               False):
                self.__transactions.append(transaction)

                self.save_data()

                return True
            else:
                return False
        else:
            if Verification.verify_transaction(transaction, self.get_balance):
                self.__transactions.append(transaction)
                self.save_data()
                return True
            else:
                return False
Esempio n. 16
0
 def add_block(self, block):
     """Add a block which was received via broadcasting to the localb
     lockchain."""
     # Create a list of transaction objects
     transactions = []
     for tx in block['transactions']:
             transactions = [Transaction(
                 tx['sender'],
                 tx['recipient'],
                 tx['signature'],
                 tx['amount'],
                 tx['tx_sender'],
                 tx['tx_recipient'])]
     # Validate the proof of work of the block and store the result (True
     # or False) in a variable
     proof_is_valid = Verification.valid_proof(
         transactions[:-1], block['previous_hash'], block['nonce'])
     # Check if previous_hash stored in the block is equal to the local
     # blockchain's last block's hash and store the result in a block
     hashes_match = hash_block(self.chain[-1]) == block['previous_hash']
     current_hash= self.chain[:]
     if not proof_is_valid or not hashes_match:
         return False
     # Create a Block object
     converted_block = Block(
         block['index'],
         block['previous_hash'],
         block['current_hash'],
         transactions,
         block['nonce'],
         block['timestamp'])
     self.__chain.append(converted_block)
     stored_transactions = self.__open_transactions[:]
     # Check which open transactions were included in the received block
     # and remove them
     # This could be improved by giving each transaction an ID that would
     # uniquely identify it
     for itx in block['transactions']:
         for opentx in stored_transactions:
             # if (opentx.id == itx['id']):
             #     try:
             #         self.__open_transactions.remove(opentx)
             #     except ValueError:
             #         print('Item was already removed')
             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')
     self.save_data()
     return True
Esempio n. 17
0
    def add_transaction(self, recipient, sender, signature, amount=1.0):
        """ Append a new value as well as the last blockchain value to the blockchain"""
        if self.hosting_node == None:
            return False

        transaction = Transaction(sender, recipient, signature, amount)
        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            return True
        return False
Esempio n. 18
0
 def proofOfWork(self):
     """proof of work:  
     the unconfirmed transactions, the hash of the previous block and a proof guessed number """
     last_block = self.__chain[-1]
     lastHash = hashBlock(last_block)
     proof = 0
     # Try different PoW numbers and return the first valid one
     while not Verification.validProof(self.unconfirmedTransaction,
                                       lastHash, proof):
         proof += 1
     return proof
Esempio n. 19
0
    def add_transaction(self,recipient,sender, signature, amount = 1.0):
        if self.hosting_node == None:
            return False

        transaction = Transaction(sender,recipient,signature,amount)

        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()                           #Adding it to list of participants
            return True
        return False
Esempio n. 20
0
    def proof_of_work(self):
        """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 = self.__chain[-1]
        last_hash = hash_block(last_block)
        proof_nonce = 0

        while not Verification.valid_proof(self.__open_transactions, last_hash,
                                           proof_nonce):
            proof_nonce += 1

        return proof_nonce
 def proof_of_work(self):
     """Increments the proof of work number until a valid proof is found"""
     # Grabs the last block in the blockchain
     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
Esempio n. 22
0
 def add_transaction(self, recipient, sender, signature, amount=1.0):
     # transaction = {'sender': sender,
     #                'recipient': recipient,
     #                'amount': amount}
     if self.hosting_node is None:
         return False
     transaction = Transaction(sender, recipient, signature, amount)
     if Verification.verify_transaction(transaction, self.get_balance):
         self.__open_transactions.append(transaction)
         self.save_data()
         return True
     return False
Esempio n. 23
0
 def proof_of_work(self):
     """ This makes the previous hash, proof (integer), and dictionary of
         open transactions into a new hash string and checks if it starts with 00.
         For iterations where this is NOT true, the current proof (integer) increases by one.
         When finally the generated hash string starts with 00, it will return the proof (integer).
     """
     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
Esempio n. 24
0
    def add_transaction(self, recipient, sender, amount=1.0):
        """ Append a new value as well as the last blockchain value to the blockchain """

        transaction = Transaction(sender, recipient, amount)

        # Passes the get_balance function to verifier
        if Verification.verify_transaction(transaction, self.get_balance):
            # No longer appending directly to the blockchain, but instead appending to the open_transaction list
            self.__open_transactions.append(transaction)
            self.save_data()
            return True
        return False
Esempio n. 25
0
    def proof_of_work(self):
        '''Struggle with DIFFICULTY seeking correct proof'''
        last_block = self.__chain[-1]
        last_block_hash = hash_block(last_block)

        nonce = 0

        # IMPORTANT: Proof of Work should NOT INCLUDE REWARD TRANSACTION
        while not Verification.valid_proof(self.__open_transactions,
                                           last_block_hash, nonce, DIFFICULTY):
            nonce += 1
        return nonce
Esempio n. 26
0
 def proof_of_work(self):
     """
     Tries sequential numbers until it finds one that solves the Proof of Work challenge
     :return: An integer which is the number that solves the Proof of Work challenge.
     """
     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
Esempio n. 27
0
    def add_transaction(self,
                        recipient,
                        sender,
                        signature,
                        amount=1.0,
                        is_receiving=False):
        """Adds transactions to the open_transactions dictionary
        Arguments:
            :sender: the sender of the transaction
            :recipient: the receiver of the transaction
            :signature: the signature of the transaction 
            :amount: the value of the transaction (default 1.0)
        """

        # As the order of Dictionaries can change we need to work with
        # imported Ordereddics package
        # The order is important to us for the SHA256 hash algorithm
        # It's defined as a list of tuples
        # transaction = OrderedDict(
        #     [('sender', sender), ('recipient', recipient), ('amount', amount)])

        # prevent adding transaction when no wallet loaded
        # if self.public_key == None:
        #     return None

        transaction = Transaction(sender, recipient, amount, signature)
        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            # Broadcast transaction to all peer nodes as long it is NOT a
            # received broadcast
            if not is_receiving:
                for node in self.__peer_nodes:
                    url = 'http://{}/broadcast-transaction'.format(node)
                    try:
                        response = requests.post(url,
                                                 json={
                                                     'sender': sender,
                                                     'recipient': recipient,
                                                     'amount': amount,
                                                     'signature': signature
                                                 })
                        if response.status_code == 400 or response.status_code == 500:
                            print('Transaction declined. Need resolving')
                            return False
                    # continue with next peer node if connection error (node not online)
                    except requests.exceptions.ConnectionError:
                        continue

            return transaction
        else:
            return None
Esempio n. 28
0
 def proof_by_vote(self):
     """Generate a proof by vote for the open submissions, the hash of the
     previous bloc and a random number (which is guessed until it fits)."""
     last_bloc = self.__chain[-1]
     last_hash = hash_bloc(last_bloc)
     proof = 0
     # Try different Pbv numbers and return the first valid one
     while not Verification.valid_proof(
         self.__open_submissions,
         last_hash, proof
     ):
         proof += 1
     return proof
 def proofOfWork(self):
     """
     工作量证明
     为返回一个Nouse使当区块hash之后前三位为0
     """
     lastBlock = self.__chain[-1]
     lastHash = hashBlock(lastBlock)
     proof = 0
     while not Verification.validProof(self.__openTransactions, lastHash,
                                       proof):
         proof += 1
     print('proof = ' + str(proof))
     return proof
    def listen_for_input(self):
        waiting_for_input = True
        while waiting_for_input:
            user_choice = self.print_menu()

            if user_choice == '1':
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data  # tuple unpacking
                if self.blockchain.add_transaction(recipient,
                                                   self.id,
                                                   amount=amount):
                    print('Added transaction!')
                else:
                    print('Transaction failed')
                print(self.blockchain.get_open_transactions())
            elif user_choice == '2':
                self.blockchain.mine_block()
            elif user_choice == '3':
                self.print_blockchain_elements()
            elif user_choice == '4':
                print('=== Transactions are all valid: ' + str(
                    Verification.verify_transactions(
                        self.blockchain.get_open_transactions(),
                        self.blockchain.get_balance)))
            elif user_choice == 'q':
                waiting_for_input = False
            else:
                print('Input was invalid, please pick from the list')

            if not Verification.verify_chain(self.blockchain.get_chain()):
                print('Invalid blockchain')
                waiting_for_input = False

            print(f'Balance for {self.id}: {self.blockchain.get_balance()}')
        else:
            print('User left!')

        print('Done!')
Esempio n. 31
0
 def add_vote(self, vote_to, sender, signature):
     if self.hosting_node == None:
         return False
     self.vote_to = vote_to
     self.sender = sender
     vote = Vote(sender, vote_to, signature)
     if Verification.verify_vote(vote, self.get_balance):
         self.__open_transactions.append(vote)
         self.save_data()
         self.save_database()
         if len(self.__open_transactions) == 3:
             self.mine_block()
         return True
     return False
Esempio n. 32
0
 def mine_block(self):
     """ Create a new block and adds open transactions to it. """
     if self.public_key == None:
         return None
     last_block = self.__chain[-1]
     hashed_block = hash_block_256(last_block)
     node_id, proof = self.proof_of_stake()
     copied_transaction = self.__transactions[:]
     if not Verification.verify_transactions(copied_transaction,
                                             self.get_balance):
         return None
     block = Block(len(self.__chain), node_id, proof, copied_transaction,
                   hashed_block)
     return block
    def addTransaction(self,
                       copyrightOwner,
                       picUrl,
                       signature,
                       picPhash,
                       isReceiving=False):
        """
        向事务队列添加新事务
        :param isReceiving: 标志是否为被广播的事务
        :param copyrightOwner: 版权所有人
        :param picUrl:图片ID
        :param signature:数字签名
        :param picPhash:图片PHash
        """
        # if self.publicKey is None:
        #     return False
        transaction = Transaction(copyrightOwner, picUrl, signature, picPhash)

        # transaction =  OrderedDict(
        #     [
        #         ("copyrightOwner",copyrightOwner),
        #         ("picUrl",picUrl),
        #         ("picPhash",picPhash)
        #     ])

        if Verification.verifyTransaction(self.__chain,
                                          self.__openTransactions,
                                          transaction):
            self.__openTransactions.append(transaction)
            self.saveData()
            # 主动广播
            if not isReceiving:
                for node in self.__peerNodes:
                    url = 'http://{}/broadcastTransaction'.format(node)
                    try:
                        response = requests.post(url,
                                                 json={
                                                     'copyrightOwner':
                                                     copyrightOwner,
                                                     'picUrl': picUrl,
                                                     'picPhash': picPhash,
                                                     'signature': signature
                                                 })
                        if response.status_code == 400 or response.status_code == 500:
                            print('请求不合法或事务添加失败')
                            return False
                    except requests.exceptions.ConnectionError:
                        continue
            return True
        return False
Esempio n. 34
0
    def __init__(self, hosting_node):

        proof = 0
        while True:
            if Verification.valid_proof([], '', proof):
                break
            proof += 1

        genesis_block = Block(0, '', [], proof, '14:03:03.849673')
        self.__chain = [genesis_block]
        self.__open_votes = []
        self.hosting_node = hosting_node
        self.nodes_url = set()
        self.candidates_set = set()
Esempio n. 35
0
 def resolve(self):
     winner_chain = self.get_chain()
     replace = False
     for node in self.__peer_nodes:
         url = "http://{}/chain".format(node)
         try:
             response = requests.get(url)
             node_chain = response.json()
             node_chain = [Block(block['index'], block['previous_hash'], [Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount'])
                                                                          for tx in block['transactions']], block['proof'], block['timestamp']) for block in node_chain]
             node_chain_length = len(node_chain)
             local_chain_length = len(self.get_chain())
             if node_chain_length > local_chain_length and Verification.verify_chain(node_chain):
                 winner_chain = node_chain
                 replace = True
         except requests.exceptions.ConnectionError:
             continue
     self.resolve_conflicts = False
     self.__chain = winner_chain
     if replace:
         self.__open_transactions = []
     self.save_data()
     return replace
Esempio n. 36
0
    def listen_for_input(self):
        """Starts the node and waits for user input."""
        waiting_for_input = True
        # A while loop for the user input interface
        # It's a loop that exits once waiting_for_input becomes False or when break is called
        while waiting_for_input:
            print("Please enter your choice")
            print("1: Add a new transaction value")
            print("2: Mine Block")
            print("3: Output the blockchain blocks")
            print("4: Check transaction validity")
            print("5: Create Wallet")
            print("6: Load Wallet")
            print("7: Save keys")
            print("q: Quit")
            user_choice = self.get_user_choice()
            if user_choice == "1":
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data
                signature = self.wallet.sign_transaction(self.wallet.public_key, recipient, amount)
                # Add the transaction amount to the blockchain
                if self.blockchain.add_transaction(recipient, self.wallet.public_key, signature, amount=amount):
                    print('Added transaction!')
                else:
                    print('Transaction failed!')
                print(self.blockchain.get_open_transactions())
            elif user_choice == "2":
                if not self.blockchain.mine_block():
                    print("Mining Failed. Got no Wallet?")
            elif user_choice == "3":
                self.print_blockchain_blocks()
            elif user_choice == "4":
                # verifier = Verification()
                if Verification.verify_transactions(self.blockchain.get_open_transactions(), self.blockchain.get_balances):
                    print("All transactions are valid!")
                else:
                    print("There are some transactions failed!")
            elif user_choice == "5":
                self.wallet.create_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == "6":
                self.wallet.load_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == "7":
                self.wallet.save_keys()
            elif user_choice == "q":
                # This will lead to the loop to exist because it's running condition becomes False
                waiting_for_input = False
            else:
                print("Input is invalid, please pick a value from a list.")

            # verifier = Verification()
            if not Verification.verify_chain(self.blockchain.get_chain()):
                self.print_blockchain_blocks()
                print("Invalid Blockchain!")
                # Break out of the loop
                break

            print("Balance of {}: {:6.2f}".format(self.wallet.public_key, self.blockchain.get_balances()))
        else:
            print("User Left!")
        print ("Done!")