예제 #1
0
class TestBlockChain(TestCase):
    def setUp(self):
        self.block_chain = BlockChain()

    def test_get_size(self):
        self.assertEquals(len(self.block_chain.chain),
                          self.block_chain.get_size(),
                          "# Chain Size does not match!!")

    def test_get_last_block(self):
        last_block = self.block_chain.get_last_block()
        self.assertIsNotNone(last_block.Hash)
        self.assertIsNotNone(last_block.Index)
        self.assertIsNotNone(last_block.PreviousHash)
        self.assertIsNotNone(last_block.Transactions)
        self.assertIsNotNone(last_block.Timestamp)

    def test_create_transaction(self):
        transaction = self.block_chain.create_transaction("A", "B", 100)
        self.assertEqual(
            transaction.From, "A",
            "Sender and From in Transaction created not matching ")
        self.assertEqual(
            transaction.To, "B",
            "Recipient and To in Transaction created not matching ")
        self.assertEqual(transaction.Amount, 100,
                         "Amount and Amount in Transaction not matching")

    def test_create_block(self):
        block = self.block_chain.create_block(is_genesis=False)
        self.assertEqual(block.Index, len(self.block_chain.chain))
        self.assertIsNotNone(block.Hash)
        self.assertIsNotNone(block.PreviousHash)
        self.assertIsNotNone(block.Transactions)
        self.assertIsNotNone(block.Timestamp)
        self.assertEqual(block, self.block_chain.get_last_block())
        self.assertEqual(self.block_chain.current, [])

    def test_get_chain(self):
        chain = self.block_chain.get_chain()
        self.assertEqual(chain, self.block_chain.chain)

    def test_validate_proof(self):
        block1 = self.block_chain.create_block(is_genesis=False)
        block2 = self.block_chain.create_block(is_genesis=False)
        self.assertTrue(
            BlockChain.validate_proof(last_proof=block1.Hash,
                                      proof=block2.Hash,
                                      last_hash=BlockChain.hash_block(block1)),
            "Proof of Work Hash in the last block does not align with Second Last block. Chain Corrupt!!!"
        )
예제 #2
0
class Node:

    def __init__(self):
        self.wallet = Wallet()
        self.wallet.create_keys()
        self.blockchain = BlockChain(self.wallet.public_key)

    def get_transaction_value(self):
        """ Returns the input of the user ( a new transaction amount) as float. """

        tx_recipient = input("Enter the recipient of the transaction: ")
        tx_amount = float(input("Your transaction amount please: "))
        return tx_recipient, tx_amount

    def print_blockchain_element(self):
        """Out the blockchain list in the terminal"""
        for block in self.blockchain.get_chain():
            print("Displaying Block")
            print(block)

    def get_user_choice(self):
        user_input = input('Enter your choice: ')
        return user_input

    def listen_for_input(self):
        waiting_for_input = True
        while waiting_for_input:
            print("Please Choose")
            print("1: Add a new trasaction value")
            print("2: Mine a new block ")
            print("3: Output the blockchain blocks")
            print("4: Check transaction validity")
            print("5: Create wallet")
            print("6: Load wallet")
            print("7: save wallet 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_transactions(self.wallet.public_key, recipient, amount)
                if self.blockchain.add_transaction(recipient, self.wallet.public_key, amount, signature):
                    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_element()

            elif user_choice == "4":
                if Verification.verify_transactions(self.blockchain.get_open_transactions(), self.blockchain.get_balance):
                    print("All transactions are valid")
                else:
                    print("There are invalid transactions")
            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":
                if self.wallet.public_key != None and self.wallet.private_key != None:
                    self.wallet.save_keys()
            elif user_choice == "q":
                waiting_for_input = False

            else:
                print("Invalid input. Please select a value from the list")
            if not Verification.verify_chain(self.blockchain.get_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')
예제 #3
0
class Node:
    def __init__(self):
        self.wallet = Wallet()
        # By default the node generate a new wallet while the user
        # can still generate a new WALLET
        self.wallet.create_keys()
        self.blockchain = BlockChain(self.wallet.public_key)
        #self.blockchain = None

    def get_transaction_value(self):
        #tx_sender = input("Enter the sender of the transaction:")
        tx_sender = self.wallet.public_key
        tx_recipient = input("Enter the recipient of the transaction:")
        tx_amount = float(input("Enter the amount of the transaction:"))
        return tx_sender, tx_recipient, tx_amount

    def print_blockchain_elements(self):
        for block in self.blockchain.get_chain():
            print(block)
        else:
            print("-" * 30)

    def get_user_choice(self):
        return int(input("Your choice:"))

    def display_balance_all(self):
        for person in self.blockchain.participants:
            print("Balance of {} : {:6.2f}".format(
                person, self.blockchain.get_balance(person)))

    def listen_for_input(self):
        waiting_for_input = True
        while waiting_for_input:
            print("Please select your choice: ")
            print("1) Add a a new transaction. ")
            print("2) Mine a new block")
            print("3) Print the blockchain. ")
            print("4) Show participants. ")
            print("5) Manipulate. ")
            print("6) Verify. ")
            print("7) Quit. ")
            print("8) Load Data.")
            print("9) Create Wallet")
            print("10) Load Wallet")
            print("11) Save Keys")
            user_choice = self.get_user_choice()
            if user_choice == 1:
                tx_sender, tx_recipient, tx_amount = self.get_transaction_value(
                )
                signature = self.wallet.sign_transaction(
                    tx_sender, tx_recipient, tx_amount)
                if self.blockchain.add_transaction(tx_sender, tx_recipient,
                                                   self.wallet.public_key,
                                                   signature, tx_amount):
                    print("Transaction successfully added.")
                else:
                    print("Transaction failed.")
                print([
                    tx.__dict__
                    for tx in self.blockchain.get_open_transactions()
                ])
            elif user_choice == 2:
                if self.blockchain.mine_block():
                    print(" New Block Mined!")
            elif user_choice == 3:
                self.print_blockchain_elements()
            elif user_choice == 4:
                print(self.blockchain.participants)
            elif user_choice == 5:
                print("NONE")
            elif user_choice == 6:
                print(Verification.verify_chain(self.blockchain.get_chain()))

            elif user_choice == 7:
                waiting_for_input = False

            elif user_choice == 8:
                self.blockchain.load_data()

            elif user_choice == 9:  # Create Wallet
                self.wallet.create_keys()
                self.blockchain = BlockChain(self.wallet.public_key)
                print(self.wallet.public_key)

            elif user_choice == 10:  # Load Wallet
                self.wallet.load_keys()
                self.blockchain = BlockChain(self.wallet.public_key)
                print(self.wallet.public_key)

            elif user_choice == 11:  # Save the keys
                if self.wallet.save_keys():
                    print("Keys SAVED.")
                else:
                    print("Keys NOT saved.")

            else:
                print("Not a valid input.")

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

            self.display_balance_all()

        else:
            print("User left.")