def getblockbyheight(self, data=None): blkc = BlockChain() block = blkc.get_block(data) if block is not None: return json.dumps({"block": block.to_json()}) else: return json.dumps({"error": "Block not found at this height"})
def getblockbyhash(self, data=None): blkc = BlockChain() block = blkc.get_block_by_hash(data) if block is not None: return json.dumps({"block": block.to_json()}) else: return json.dumps({"error": "Block not found"})
def gettxbyhash(self, data=None): blkc = BlockChain() tx = blkc.get_tx_by_hash(data) blkc.close() if tx is not None: return json.dumps({"tx": tx.to_json()}) else: return json.dumps({"error": "Transaction not found"})
def getallutxobyaddress(self, data=None): blkc = BlockChain() utxos_tuple = blkc.get_utxos_by_addr(data) response = [{ "tx": utxo[0], "index": utxo[1], "amount": utxo[2] } for utxo in utxos_tuple] blkc.close() return json.dumps({"utxos": response})
def __init__(self): # Initialization self.primary_representatives = dict() self.blockchain = BlockChain() self.fund_addr = "12345" self.redis_client = redis.Redis(host='localhost', port=6379, db=0) self.redis_client.hmset('fund ' + self.fund_addr, {'total fund': 00}) self.this_node_addr = get_own_address() self.stakes_map = dict() self.verification = Verification()
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 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 create_block(self): block = Block() block.create_coinbase_transaction() mempool = Mempool() blkc = BlockChain() mempool_size = mempool.get_len() if mempool_size == 0: return while mempool_size > 0: tx = mempool.get_transaction() block.add_transaction(tx) mempool_size -= 1 block.calcalute_block_size() block.calculate_merkle_root() block.compute_hash() blkc.add_block(block) return block
def test_txs_by_address(self): blockchain = BlockChain() blockchain.flush_chain() block = Block() tx = Transaction() input1 = TransactionInput() input1.address = "test_address" tx.add_input(input1) tx.generate_hash() block.add_transaction(tx) tx1 = Transaction() output = TransactionOutput() output.address = "fake_address" output1 = TransactionOutput() output1.address = "test_address" tx1.add_output(output) tx1.add_output(output1) tx1.generate_hash() block.add_transaction(tx1) tx2 = Transaction() output2 = TransactionOutput() output2.address = "fake_address" tx2.add_output(output2) tx2.generate_hash() block.add_transaction(tx2) block.compute_hash() blockchain.add_block(block) txs = blockchain.get_txs_by_addr("test_address") getb = blockchain.get_block(-1) print(getb.to_json()) for tx in txs: print(tx.hash, end='\n') # self.assertEqual(len(txs), 2) print(len(txs)) blockchain.close()
def add_block_nondel(): # Running as Non delegate print("Waiting to get blocks made by Delegates :") # ZMQ to recieve block got at UDP Port context = zmq.Context() zsocket = context.socket(zmq.REP) zsocket.bind("tcp://127.0.0.1:%s" % settings.ELECTION_ZMQ_PORT) # ZMQ Poller zpoll = zmq.Poller() zpoll.register(zsocket) start_timestamp = time.time() # Storing all recieved blocks all_blocks = [] # Time to wait for recieving blocks while time.time() - start_timestamp < 3: events = dict(zpoll.poll(1)) for key in events: block = json.loads(key.recv_string()) all_blocks.append(block) zsocket.send_string("Got a block!") zpoll.unregister(zsocket) zsocket.close() context.destroy() print("Recieved " + str(len(all_blocks)) + " Blocks!") # Get most common and add to chain if len(all_blocks) > 0: mr = [] for blk in all_blocks: print("Getting the most common Block ...") mr.append(blk["merkle_root"]) # Add the most common block blkc = BlockChain() Mblock = bestblock(mr) blkc.add_block(Mblock) # Initializing Election Class elec = Election() sync = Sync()
def sendblock(self, request=None, response=None): """ Send block """ if request is None and response is None: # If no data is being passed on by command handler pass if request is not None: # Processing requests UDPHandler.broadcastmessage( json.dumps({ "prev_command": "sendblock", "body": request })) if response is not None: # Processing reaponse blkc = BlockChain() blkc.add_block(Block.from_json(response["body"])) blkc.close()
class Election: """ This class holds the nodes election every 30 seconds. A miner is being chosen from a list of primary representative. """ votes_map = dict() def __init__(self): # Initialization self.primary_representatives = dict() self.blockchain = BlockChain() self.fund_addr = "12345" self.redis_client = redis.Redis(host='localhost', port=6379, db=0) self.redis_client.hmset('fund ' + self.fund_addr, {'total fund': 00}) self.this_node_addr = get_own_address() self.stakes_map = dict() self.verification = Verification() # self.load_election_fund_details() def load_election_fund_details(self): # Open Election fund details file f = open('electionfund.json', 'r') data = json.load(f) # Set fund address self.fund_addr = data["address"] def scan_election_fund(self): # Scan the blockchain to get Stakes in redis fund database txs = self.blockchain.get_txs_by_addr(self.fund_addr) # Define redis pipeline pipe = self.redis_client.pipeline() for tx in txs: for output in tx.outputs: # check if output is in fund address if output.address == self.fund_addr: if len(tx.inputs) > 0: pipe.hincrbyfloat("stakes_map", tx.inputs[0].address, output.value) pipe.execute() def get_stakes(self): # Get stakes from redis self.stakes_map = decode_redis(self.redis_client.hgetall("stakes_map")) print("Scanned stakes ...!") 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 vote_to(self): # Broadcast the selected node to vote UDPHandler.broadcastmessage(json.dumps( {'data': {"voter_addr": self.this_node_addr, "voted_addr": select}, 'command': 'voteto'})) context = zmq.Context() z2socket = context.socket(zmq.REQ) z2socket.connect("tcp://0.0.0.0:%s" % settings.BROADCAST_ZMQ_PORT) z2socket.send_string(json.dumps({'data': { "voter_addr": self.this_node_addr, "voted_addr": select}, 'command': 'voteto'})) message = z2socket.recv() print(message) z2socket.close() return""" def add_vote(self, vote): # Add a foreign vote self.votes_map[vote["node_addr"]] = vote["representative"] def def_value(self): return 0 def delegates(self): # Create Delegates votes_count = defaultdict(self.def_value) print(":...:...: Votes Map :...:...:") print(self.votes_map) for key, val in self.votes_map.items(): print(val) votes_count[val] += 1 votes_count = sorted(votes_count.items(), key=lambda kv: (kv[1], kv[0])) dels = [] if len(votes_count) > 10: dels = list(reversed(list(votes_count)))[0:10] else: dels = list(reversed(list(votes_count))) # Returning selected Delegates return dels
def __init__(self): blockchain = BlockChain() self.block = Block() self.redis_client = redis.Redis(host='localhost', port=6379, db=0) self.chain_length = self.redis_client.llen('chain')
def gettxsbyaddress(self, data=None): blkc = BlockChain() txs = [tx.to_json() for tx in blkc.get_txs_by_addr(data)] blkc.close() return json.dumps({"txs": txs})
def getaddressbalance(self, data=None): blkc = BlockChain() balance = blkc.final_addr_balance(data) blkc.close() return json.dumps({"balance": balance})