def mining(): print("Into the mining process") # Initializing Election Class elec = Election() # Do not make a block if mempool is empty # if elec.redis_client.llen("mempool") == 0: # print("No block made! Mempool is empty!") # return # Transaction verification # Initializing Block Class blk = Block() # Create Coinbase Transaction blk.create_coinbase_transaction() # Connect to Previous Block blk.add_previous_block() # Scan Mempool vd = True for i in range(0, elec.redis_client.llen("mempool")): # Get Transaction tx = elec.redis_client.lindex('mempool', i).decode('utf-8') if tx == None: # Exit if tx is None break # Get tx verification verdict # verify_verdict = elec.verification.verify_tx(tx) # if verify_verdict == "verified": # # Sending data to block # blk.add_transaction(tx) # else: # vd = False # print("Some Transaction Verification Failed! Aborting Mining ...") # break # If Tx Verification Fails if vd == False: print("Mining Aborted!") return # create block blk.compute_hash() blk.calculate_merkle_root() block = blk # add block blkChain = BlockChain() blkChain.add_block(block) print("Block added to this Node's blockchain!") # check # full Blockchain verify # full_verify_message = elec.verification.full_chain_verify() # if msg != "verified": # return sync.chainsync() # if full_verify_message == "verified": # braodcast the block you made print("Broadcasting block made by this node ...") udphandler = UDPHandler() udphandler.sendblock(block.to_json())
def addtransaction(self, data): tx = Transaction.from_json({"block": "Mempool", **data}) mempool = Mempool() print("adding to mempool") mempool.add_transaction(tx) UDPHandler.broadcastmessage( json.dumps({ "command": "sendtransaction", "body": tx.to_json() })) return json.dumps({"status": "ok"})
def sync_server(self, ip=None): ip = self.fetch_nodes() if ip is not None: udp = UDPHandler() udp.synctime({"ip_addr": ip}) redis_client = redis.Redis(host='localhost', port=6379, db=0) while redis_client.exists('delay_time'): time.sleep(2) print("syncing time") if redis_client.exists('delay_time'): break print('time synced') print("server synced")
def file_split(filename): file_list = [] filesize = os.path.getsize(filename) part_filename = hashlib.sha256(filename.encode('utf-8')).hexdigest() # broadcast msg to give size to all nodes udp = UDPHandler() udp.get_disk_space(json.dumps({})) # get all node's free space ips = [] context = zmq.Context() zsocket = context.socket(zmq.REP) zsocket.bind("tcp://127.0.0.1:%s" % settings.STORAGE_ZMQ_PORT) zpoll = zmq.Poller() zpoll.register(zsocket) start_timestamp = time.time() while time.time() - start_timestamp < 8: events = dict(zpoll.poll(1)) for key in events: strecv = json.loads(key.recv_string()) key.send_string("recieved your free space") if strecv["data"] > filesize: # add ip to array ips.append(strecv["ip_addr"]) zsocket.send_string("got someone to store") zpoll.unregister(zsocket) zsocket.close() context.destroy() # size of ips n = len(ips) SPLIT_SIZE = math.ceil(filesize / n) with open(filename, "rb") as f: i = 0 while True: bytes_read = f.read(SPLIT_SIZE) if not bytes_read: break # hash = hashlib.sha256(json.dumps(bytes_read).encode("utf-8")).hexdigest() file_list.append(bytes_read) i = i + 1 for i in range(0, n): file_n = settings.TEMP_STORAGE_PATH + part_filename + str(i) with open(file_n, "wb") as f: f.write(file_list[i]) os.remove(filename) return ([n, ips])
def chainsync(self): redis_client = redis.Redis(host='localhost', port=6379, db=0) ip_list = [] nodes_map = utils.decode_redis(redis_client.hgetall("nodes_map")) for ip_addr, raw_data in nodes_map.items(): if ip_addr in settings.EXPLORER_IP: continue ip_list.append(ip_addr) # IP chosing method is under development! ip = random.choice(ip_list) udp = UDPHandler() context = zmq.Context() socket = context.socket(zmq.REP) udp.getchainlength({"ip_addr": ip}) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) res = json.loads(socket.recv_string()) length = res["body"] socket.send_string("Recieved Chain Length") socket.close() mylen = redis_client.llen("chain") if mylen == 0: for i in range(0, length): udp.getblockbyheight({"height": i, "ip_addr": ip}) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) res = json.loads(socket.recv_string()) socket.send_string("Recieved a block of the chain!!!") socket.close() blchain = Blockchain() blchain.add_block(res["body"]) # chain verification verf = Verification() msg = verf.full_chain_verify() if msg != "verified": return self.chainsync() elif mylen > length: return self.chainsync() elif mylen == length: return elif mylen < length: for i in range(mylen, length): udp.getblockbyheight({"height": i, "ip_addr": ip}) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) res = json.loads(socket.recv_string()) socket.send_string("Recieved a block of the chain!!!") socket.close() blchain = BlockChain() blchain.add_block(res["body"]) # chain verification verf = Verification() msg = verf.full_chain_verify() if msg != "verified": return self.chainsync()
def memsync(self): ip_address = utils.get_own_ip() print("Mempool sync started ...") redis_client = redis.Redis(host='localhost', port=6379, db=0) ip_list = [] ip_list.append(ip_address) nodes_map = utils.decode_redis(redis_client.hgetall("nodes_map")) for ip_addr, raw_data in nodes_map.items(): if ip_addr == ip_address: continue if ip_addr in settings.EXPLORER_IP: continue else: ip_list.append(ip_addr) print("Nodes list : " + str(ip_list)) ip_list.sort() length = len(ip_list) send = "" if length == 0: print("NO NODES ACTIVE TO SYNC WITH!!!") return for i in range(0, length): if ip_list[i] == ip_address: if i == 0: send = ip_list[-1] else: send = ip_list[i - 1] print("Starting mempool transaction sync ...") # UDP command to send txs to prev addr i = 0 while True: tx = redis_client.lindex("mempool", i) if tx == None: break udp = UDPHandler() print("Sending transaction for sync " + str(i) + "....") udp.synctx({"body": tx.decode(), "ip_addr": send}) i = i + 1 time.sleep(1) print("Mempool sync finished!!!")
def file_send(n, filehash, fileaddr, file_name, ips): stx = StorageTx() mem = Mempool() udp = UDPHandler() print(fileaddr) stx.add_input(filehash, fileaddr) part_filename = hashlib.sha256(file_name.encode('utf-8')).hexdigest() recv_hosts = ips for i in range(0, n): host = recv_hosts[i] port = 5001 filename = settings.TEMP_STORAGE_PATH + part_filename + str(i) filesize = math.ceil(os.path.getsize(filename)) filetype = "non-temp" send = socket.socket() print(f"[+] Connecting to {host}:{port}") send.connect((host, port)) print("[+] Connected.") info = { "filename": filename, "filesize": filesize, "filetype": filetype, "filehash": filehash, "fileaddr": fileaddr, } # send.send(f"{filename}{SEPARATOR}{filesize}{SEPARATOR}{filetype}{SEPARATOR}{filehash}{SEPARATOR}{fileaddr}".encode()) send.sendall(pickle.dumps(info)) filehash = "" with open(filename, "rb") as f: filehash = get_hash(filename, 15) print(filehash) while True: bytes_read = f.read(BUFFER_SIZE) if not bytes_read: break send.sendall(bytes_read) stx.add_output(filehash, host, filename) send.close() os.remove(filename) stx.gen_tx_hash() mem.add_transaction(stx) udp.broadcastmessage(json.dumps(stx.to_json()))
def elect_delegate(self): """ This selection of a address is done by Random Probability method based on stakes one provide """ # Electing someone to vote print("Electing someone ...") # Declaring empty variables total_stake = 0 arr = [] select = "" # Creating address array map based on stakes for key, val in self.stakes_map.items(): total_stake += int(val) for i in range(0, int(val)): arr.append(key) # No selection if stakes are empty if total_stake == 0: print("Empty Stakes !!!") return # Selecting a random address from addresses list while True: select = arr[random.randint(0, total_stake - 1)] # Reselect if it selects itself if (select != self.this_node_addr): break # Store own vote self.votes_map[self.this_node_addr] = select print("This node's vote is ...") print(select) print("Broadcasting this vote ...") # UDP broadcast function udphandler = UDPHandler() udphandler.castvote({ "node_addr": self.this_node_addr, "representative": select })
def test_disk_space(self): udp = UDPHandler() udp.get_disk_space()
# "outputs": [ # { # "value": 50, # "n": 0, # "address": addr # } # ], # "hash": "eef9fda50a6bf6c11c5078d8772d94df4f60ce54573c009f145eb047426ad0fb", # "block": "16e8dab3a9185d5329fac9cfdc0a81c7817826f701e747cb3751878061e4dc8c" # }], # "previous_block_hash": "", # "merkle_root": "78bc90dcc3fe2ae1eca8b9d4e09b63653cd18f0b583e002b2b4d43cc09fca9cd", # "height": 0, # "version": "0.0.1", # "size": 1949 # })) for i in range(1): block = Block() block.add_previous_block() block.add_transaction(create_fake_transaction( global_addresses[random.randint(0, 9)])) block.create_coinbase_transaction() block.calculate_merkle_root() block.compute_hash() block.calcalute_block_size() redis_client.rpush("chain", json.dumps(block.to_json())) # print(block.to_json()) udphandler = UDPHandler() udphandler.sendblock(block.to_json())
def response_handler(data): udp = UDPHandler() udp.command_handler(data)