Ejemplo n.º 1
0
    def _try_to_mine(self):
        fee = float(BankSettings.objects.all()[0].fee)
        valid_transactions = []
        for tid, not_mined_transaction in self.shell.blockchain.not_mined_transactions.items():
            if (len(valid_transactions) < self.shell.block_size - 1 and
                    not_mined_transaction.is_valid(self.shell.blockchain.all_utxos,
                                                   self.shell.blockchain.minimum_transaction, fee)):
                valid_transactions.append(not_mined_transaction)
        if len(valid_transactions) < self.shell.block_size - 1:
            return
        block = Block(self.shell.blockchain.last_block_hash())

        value = float(BankSettings.objects.all()[0].reward) + fee * (self.shell.block_size - 1)
        coinbase = Transaction('', self.bank.wallet.get_keys()[0], value=value, inputs=[])
        block.add_transaction(transaction=coinbase,
                              all_utxos=self.shell.blockchain.all_utxos,
                              minimum_transaction=self.shell.blockchain.minimum_transaction,
                              fee=fee, should_check=True, is_coinbase=True)
        self.shell.blockchain.append_transaction(coinbase)
        for valid_transaction in valid_transactions:
            block.add_transaction(valid_transaction, self.shell.blockchain.all_utxos,
                                  self.shell.blockchain.minimum_transaction,
                                  fee=fee, should_check=True)
        block.mine(BankSettings.objects.all()[0].difficulty)
        print('block mined: {}.'.format(block.calculate_hash()))
        self.shell.blockchain.append_block(block)
Ejemplo n.º 2
0
def block_serializer(data):
    block = Block(index=data['index'])
    for transaction in data['transactions']:
        block.add_transaction(sender=transaction['sender'],
                              receiver=transaction['receiver'],
                              amount=transaction['amount'],
                              timestamp=transaction['timestamp'],
                              thash=transaction['hash'])
    block.hash = data['hash']
    return block
Ejemplo n.º 3
0
def main():
    bc = Blockchain()

    walletA = Wallet('A')
    walletB = Wallet('B')
    coinbase = Wallet('C')
    
    genesis_trx = Transaction(coinbase.public_key, walletA.public_key, 1000000, None)
    genesis_trx.generate_signature(coinbase.private_key, coinbase.password)
    genesis_trx.transaction_id = '0'
    genesis_trx.outputs.append(TransactionOutput(genesis_trx.recipient, genesis_trx.value, genesis_trx.transaction_id))
    bc.genesis_trx = genesis_trx
    bc.UTXOs[bc.genesis_trx.outputs[0].id] = bc.genesis_trx.outputs[0]

    print('Creating and mining genesis block...')
    genesis = Block('0')
    genesis.add_transaction(genesis_trx)
    bc.add(genesis)

    f=open("time.csv", "w+")

    for i in range(1000000):
        print("%d: " % i, end='')
        start = time.time()
        block = Block(bc.get_last_hash())
        # print("Wallet A's balance is:", walletA.get_balance())
        # print("Wallet A is attempting to send funds(1) to Wallet B...")
        block.add_transaction(walletA.send_funds(walletB.public_key, 1))
        bc.add(block)
        end = time.time()
        f.write(("%d,%f\n" % (i, end-start)))
        # print("Wallet A's balance is:", walletA.get_balance())
        # print("Wallet B's balance is:", walletB.get_balance())

    print("Wallet B's balance is:", walletB.get_balance())
    print("Wallet B is attempting to send funds(1000000) to Wallet A...")
    
    start = time.time()
    block = Block(bc.get_last_hash())
    block.add_transaction(walletB.send_funds(walletA.public_key, 1000000))
    bc.add(block)
    end = time.time()

    print("Wallet A's balance is:", walletA.get_balance())
    print("Wallet B's balance is:", walletB.get_balance())

    print("Time elapsed: %fs" % (end-start))

    bc.is_valid()

    f.close()
Ejemplo n.º 4
0
    difficulty = 2

    blockchain = BlockChain(difficulty)

    wallet_one = Wallet(utxos)
    wallet_two = Wallet(utxos)

    wallet_coinbase = Wallet(utxos)

    # create genesis transaction, which sends 100 coins to wallet_one
    genesis_transaction = get_genesis_transaction(wallet_coinbase, wallet_one,
                                                  100, utxos)

    print("Creating and mining genesis block")
    genesis = Block("0")
    genesis.add_transaction(genesis_transaction, utxos, minimum_transaction)

    blockchain.append_block(genesis)

    # testing
    print("Wallet one balance: %d" % wallet_one.get_balance())

    print()
    print("Attemping to send funds (40) to Wallet two")
    block1 = Block(genesis.hash)
    block1.add_transaction(
        wallet_one.send_funds(wallet_two.public_key_as_str(), 40), utxos,
        minimum_transaction)
    blockchain.append_block(block1)
    print("Wallet one balance: %d" % wallet_one.get_balance())
    print("Wallet two balance: %d" % wallet_two.get_balance())
Ejemplo n.º 5
0
import random
import time

from blockchain import Block, Blockchain, Transaction

USERS = ['Alice', 'James', 'Smith', 'David', 'Adams', 'Isaac', 'Lewis']

SLEEP_TIME = 0

if __name__ == '__main__':

    chain = Blockchain()

    for _ in range(random.randint(1, 5)):
        block = Block()

        for _ in range(random.randint(1, 3)):
            sender, receiver = random.sample(USERS, k=2)
            transaction = Transaction(sender=sender,
                                      receiver=receiver,
                                      value=random.randint(10, 100))
            block.add_transaction(transaction)
            time.sleep(SLEEP_TIME)
        chain.add_block(block)
        print(chain)
        time.sleep(SLEEP_TIME)
Ejemplo n.º 6
0
class BlockchainHandler:

    BLOCKCHAIN_PATH = 'resources/blockchain.json'

    def __init__(self):
        self.blockchain = None
        self.central_bank = None
        self.current_block = None
        self.all_utxos = {}

    def import_json(self, path):
        if os.path.exists(self.BLOCKCHAIN_PATH):
            raise Exception("blockchain file imported previously, if you want to reload it first reset blockchain")

        copyfile(path, self.BLOCKCHAIN_PATH)

        self.load_blockchain()

    def reset_blockchain(self):
        os.remove(self.BLOCKCHAIN_PATH)

        self.load_blockchain()

    def load_blockchain(self):
        from models import CentralBank

        try:
            with open(self.BLOCKCHAIN_PATH) as f:
                blocks_data = json.loads(f.read())

                if not (isinstance(blocks_data, dict) or isinstance(blocks_data, list)):
                    raise Exception("blockchain.json file is not valid")

                if isinstance(blocks_data, dict):
                    blocks_data = [blocks_data]

            self.blockchain = 'pending'
            self.central_bank = CentralBank.get_central_bank()
            if not self.central_bank.has_valid_configuration():
                raise Exception('central bank configuration is not properly set')

            self.blockchain = BlockChain(self.central_bank.difficulty)

            self.all_utxos = {}

            for block_data in blocks_data:
                block = Block.deserialize(block_data)
                self.blockchain.append_block(block, mine_block=False)

                for transaction in block.transactions:

                    for inp in transaction.inputs:
                        del self.all_utxos[inp.transaction_output_id]

                    for output in transaction.outputs:
                        self.all_utxos[output.id] = output

        except Exception as exp:
            print("Error occurred while loading blockchain")
            print(exp)

            self.blockchain = None
            return

        self.blockchain.print()

    def is_blockchain_imported(self):
        return bool(self.blockchain)

    def new_transaction(self, sender_wallet: Wallet, receiver_wallet: Wallet, amount):

        if not self.current_block:
            self.current_block = Block(self.blockchain.last_block_hash())

        transaction = sender_wallet.send_funds(self.all_utxos, receiver_wallet.public_key_str, amount)
        self.current_block.add_transaction(transaction, self.all_utxos, 0.001)

        if len(self.current_block.transactions) == self.central_bank.number_of_transactions_in_block:
            self.blockchain.append_block(self.current_block, True)
            self.current_block = None