def mine(): transactions = get_transactions() transactions = [Transaction.from_dict(x) for x in transactions] last_block = get_last_block() block = Block(last_block['id'] + 1, transactions, 0) while not block.get_hash(last_block['hash']).startswith('0000'): block.nonce += 1 block.set_hash(block.get_hash(last_block['hash'])) r = requests.post(b_url + '/add_block', json=block.to_dict()) return r.text
def create_gift_coin(self, blockchain): """ This method creates a new coin for the new client """ # Get address of the client hash_public_key = self.hash_pubkey() coin_gift_tx_input = TransactionInput(prev_tx="1" * 64, pk_spender="1" * 64, signature=bytes( "\x11" * 64, encoding="utf-8")) coin_gift_tx_output = TransactionOutput( value=100, hash_pubkey_recipient=hash_public_key) coin_gift_tx = Transaction(tx_input=coin_gift_tx_input, tx_output=coin_gift_tx_output) transactions = [coin_gift_tx] nonce = 0 new_block = None while True: if len(blockchain.blocks) != 0: hash_prev_block = blockchain.blocks[len(blockchain.blocks) - 1].get_hash() new_block = Block(transactions, nonce, hash_prev_block) else: new_block = Block(transactions=transactions, nonce=nonce, prev_block_hash="0" * 64) if new_block.get_hash().startswith("0" * blockchain.difficulty): print("Nonce found:", nonce) break nonce += 1 print(coin_gift_tx.serialize()) message = "\x12" + new_block.serialize() self.socket.sendall(message.encode('utf-8'))
def handler(self, connection_handler, ip_port_tuple): try: while True: #data = connection_handler.recv(self.byte_size) data = recv_timeout(connection_handler) # Check if the peer wants to disconnect for connection in self.connections: if data and data == 'cmd_show_peers': connection.sendall( ('---' + str(self.peers)).encode('utf-8')) elif data and data[0:1] == "\x12": print("==> New mined block.") new_block_info = data[1:] new_block = Block(serialization=new_block_info) in_blockchain = False for block in self.blockchain.blocks: if new_block.equal_blocks(block): print( "==> This block is already mined and is in your blockchain. It will not be added to server blockchain" ) in_blockchain = True break if not in_blockchain: print("\t", new_block.__dict__) print("\tNew Block Hash:", new_block.get_hash()) self.blockchain.add_block(new_block) update_blockchain_file(self.blockchain.serialize()) connection.sendall(data.encode("utf-8")) elif data: connection.sendall(data.encode("utf-8")) except ConnectionResetError: print("==> " + str(ip_port_tuple) + " disconnected") self.connections.remove(connection_handler) connection_handler.close() self.peers.remove(ip_port_tuple) self.send_peers()
def __init__(self, address): """ Initialization method for Client class Convention: 0x10 - New Transaction 0x11 - New peers 0x12 - New mined block 0x13 - Blockchain """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Make the connection self.socket.connect((address, 5000)) self.byte_size = 1024 self.peers = [] print('==> Connected to server.') self.generate_key_pair() client_listener_thread = threading.Thread(target=self.send_message) client_listener_thread.start() while True: try: data = self.receive_message() if data[0:1] == '\x11': print('==> Got peers.') update_peers(data[1:]) elif data[0:1] == '\x10': print('==> New transaction.') transaction_info = data[1:] transaction = Transaction(serialization=transaction_info) # Mining block result = mine_block(transaction=transaction, blockchain=self.blockchain, miner_address=self.hash_pubkey()) if result["status"]: message = "\x12" + result["new_block"].serialize() print("==> Sending new mined block") self.socket.sendall(message.encode("utf-8")) else: print( "==> Invalid transaction. The block have not been mined" ) elif data[0:1] == '\x13': print('==> Blockchain downloaded.') blockchain_info = data[1:] self.blockchain = Blockchain(serialization=blockchain_info) update_blockchain_file(self.blockchain.serialize()) elif data[0:1] == '\x12': print('==> New mined block.') block_info = data[1:] new_block = Block(serialization=block_info) in_blockchain = False for block in self.blockchain.blocks: if new_block.equal_blocks(block): print( "==> This block is already mined and is in your blockchain. It will not be added" ) in_blockchain = True break if not in_blockchain: print("\t", new_block.__dict__) print("\tNew Block Hash:", new_block.get_hash()) self.blockchain.add_block(new_block) update_blockchain_file(self.blockchain.serialize()) elif data != "": print("[#] " + data) except ConnectionError as error: print("==> Server disconnected. ") print('\t--' + str(error)) break