Beispiel #1
0
class Miner:
    def __init__(self, host, port, miners, genesis):
        self.host = host
        self.port = port
        self.miners = miners
        self.queue = multiprocessing.Queue()
        self.genesis = genesis
        self.blockchain = None

    def broadcast(self, block):
        for miner in miners:
            [host, port] = miner.split(":")
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.sendto(block.encode(), (host, int(port)))

    def create_blocks(self):
        while True:
            time.sleep(1)
            if self.blockchain != None:
                block = Block("random", self.blockchain.chain[-1].hash())
                self.queue.put(block)
                self.broadcast(block)

    def add_blocks(self):
        while True:
            block = self.queue.get()
            print(block.hash())
            if self.blockchain == None:
                self.blockchain = BlockChain(block)
            else:
                self.blockchain.append(block)
            print(self.blockchain.chain[-1].hash())

    def run(self):
        # Create the genesis block if you are the genesis miner
        if self.genesis:
            self.blockchain = BlockChain(Block("GENESIS", bytes()))

        # Create a thead for block creating
        block_creator = multiprocessing.Process(target=self.create_blocks)
        block_creator.start()

        # Create a thead for block adding
        block_adder = multiprocessing.Process(target=self.add_blocks)
        block_adder.start()

        # Listen for blocks
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind((self.host, int(self.port)))
        while True:
            data, addr = sock.recvfrom(5120)
            block = Block.decode(data)
            self.queue.put(block)
def main():

    num_of_blocks = 8
    chain = BlockChain()

    genesis_block = Block('First block',['transactionXYZ'])
    chain.append(genesis_block)

    for i in range(1, num_of_blocks):
        block = Block(chain.get_block(i-1).block_hash, ['transaction' + str(i)])
        chain.append(block)

    chain.print_chain()
Beispiel #3
0
genesis_prev_hash = sha256((b'\x00' * 32))

genesis_data = 'Hello there!'.encode('utf-8')
data1 = '1!'.encode('utf-8')
data2 = '2!'.encode('utf-8')
data3 = '3!'.encode('utf-8')
data4 = '4!'.encode('utf-8')

genesis_block = Block(genesis_data, genesis_prev_hash.digest())
block1 = Block(data1, genesis_block.hash())
block2 = Block(data2, block1.hash())
block3 = Block(data3, block2.hash())
block4 = Block(data4, block1.hash())

blockchain = BlockChain(genesis_block)

one = blockchain.append(block1)
two = blockchain.append(block2)
three = blockchain.append(block3)
four = blockchain.append(block4)

test_dict = {
    "data": "MyE=",
    "previous":
    "3b9448477c4dc133872b1029ab8d3e5ca151ad872cf5de636c2e8595dbf67855"
}

test = Block.decode(dumps(test_dict))

print(test)
Beispiel #4
0
class Miner:
    def __init__(self, host, port, miners, genesis):
        self.address = (host, port)
        self.__blockchain = None
        self.miners = miners
        self.genesis = genesis
        self.__read_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.__write_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.__write_lock = threading.Lock()
        self.__block_queue = multiprocessing.Queue()
        self.__receive_process = threading.Thread(target=self.__receive_blocks)
        self.__update_process = threading.Thread(target=self.__update_chain)

    def broadcast(self, block):
        for miner in self.miners:
            self.__write_lock.acquire()
            self.__write_socket.sendto(block.encode(), miner)
            self.__write_lock.release()

    def __find_p_o_w(self):
        max_val = int.from_bytes(b'\xff' * 8, byteorder='big', signed=False)
        p_o_w = None
        for i in range(max_val + 1):
            i_bytes = i.to_bytes(8, 'big')
            if Block.is_valid_p_o_w(i_bytes):
                p_o_w = i_bytes
                break
        return p_o_w

    def __receive_blocks(self):
        while True:
            data, addr = self.__read_socket.recvfrom(1024)
            new_block = Block.decode(data)
            self.__block_queue.put(new_block)

    def __update_chain(self):
        while True:
            block = self.__block_queue.get()
            if not Block.is_valid_p_o_w(block.p_o_w):
                raise ValueError(
                    'Received a block, but it has invalid Proof of work!')
            if self.__blockchain is None:
                self.__blockchain = BlockChain(block)
                print('Block chain created')
            else:
                if self.__blockchain.append(block) is None:
                    print('Received block but didnt add')
                else:
                    print('Block added')

    def __create_block(self, block):
        self.__block_queue.put(block)
        self.broadcast(block)

    def run(self):
        self.__read_socket.bind(self.address)
        self.__receive_process.start()
        self.__update_process.start()
        if self.genesis:
            time.sleep(.1)
            genesis_block = Block(b'I\'m the one that come before all others',
                                  b'\x00', self.__find_p_o_w())
            self.__create_block(genesis_block)

        while True:
            time.sleep(1e-3)
            if self.__blockchain is not None:
                proof_of_work = self.__find_p_o_w()
                target = self.__blockchain.blocks[
                    -1] if self.__blockchain.blocks else self.__blockchain.root
                new_block = Block(b'Random block', target.hash(),
                                  proof_of_work)
                self.__create_block(new_block)
Beispiel #5
0
bc = BlockChain()

# Alice's wallet to send messages.
alice_wallet = new_wallet()

# Bob's wallet to send messages.
bob_wallet = new_wallet()

alice_msg = alice_wallet.generate_transaction(
    message='Hello, Bob!  What time shall we meet for our run?',
    sender='Alice',
    recipient='Bob')

print('appending {} to chain.'.format(alice_msg))

bc.append(alice_msg)

bob_msg = bob_wallet.generate_transaction(message='Hello, Alice!',
                                          sender='Bob',
                                          recipient='Alice')

print('appending {} to chain.'.format(bob_msg))

bc.append(bob_msg)

bob_msg2 = bob_wallet.generate_transaction(
    message='I am planning a run tomorrow at 9:00.  Are you free?',
    sender='Bob',
    recipient='Alice')

print('appending {} to chain.'.format(bob_msg2))