def fitness(pop):  # TODO: Add later (fairness, non_manipulablity, others) as args -> or maybe **kwargs?
    """ Evaluate the fitness of the weight population by running an election
        and a test of the results based on the input fairness and non-manipulability constraints """

    # Profile for election
    profile, profile_df, profile_matrix = create_profile(500, origin="distribution",
                                                         params="spheroid", candidates=["Adam", "Bert",
                                                                                        "Chad", "Derek", "Elon"])
    fitness_pop = []

    for weights in pop:
        results = election(profile, weights)
        #     for result, value in results.items():
        #         print(f"{result}: {value}")

        # Score = condorcet compliance + majority rule
        condorcet_score = check_condorcet(profile, results)
        majority_score = check_majority(profile_df, results)

        fitness_pop.append(condorcet_score + majority_score)

    #     print("Is Condorcet compliant?:", check_condorcet(profile, results))
    #     print("Satisfies majority criterion?", check_majority(profile_df, results))

    return np.array(fitness_pop)
Ejemplo n.º 2
0
    def process(self, data, elec, user):
        if elec == None:
            elec = election()
        f = data["ans"]
        cwd = os.getcwd()
        f = cwd + "\\" + f
        file2 = open(f, 'rb')
        new_d = pickle.load(file2)
        file2.close()
        elec.setVotes(new_d["votes"])
        elec.setVoteActions(new_d["voteActions"])
        server_data.set_user_objs(new_d["userObjs"])

        return elec, user
Ejemplo n.º 3
0
def main(sk_filename):
    global processed_txids, transaction_id

    sk = SigningKey.from_pem(open(sk_filename).read())

    vk = sk.get_verifying_key()
    pk = str(base64.b64encode(vk.to_string()), encoding='utf8')

    timestamp = str(int(time.time()-300))
    leaders = db.query("SELECT * FROM leaders WHERE pk = %s AND timestamp > %s", pk, timestamp)

    if not leaders:
        election(sk_filename)
    else:
        # leader = leaders[0]

        transactions = db.query("SELECT * FROM transactions WHERE id > %s ORDER BY id ASC LIMIT 20", transaction_id)
        random.shuffle(transactions)
        for transaction in transactions:
            if transaction.txid in processed_txids:
                continue

            data = json.loads(transaction.data)
            sender = data["transaction"]["sender"]
            receiver = data["transaction"]["receiver"]
            amount = data["transaction"]["amount"]
            signature = data["signature"]

            chain_txids = set()
            sender_blocks = lastest_block(sender)
            receiver_blocks = lastest_block(receiver)
            if len(set(sender_blocks+receiver_blocks)) >= 1:
                if len(set(sender_blocks+receiver_blocks)) == 1:
                    txs = db.query("SELECT * FROM graph WHERE hash = %s", (sender_blocks+receiver_blocks)[0])
                else:
                    txs = db.query("SELECT * FROM graph WHERE hash IN %s", set(sender_blocks+receiver_blocks))
                for tx in txs:
                    tx_data = json.loads(tx.data)
                    txid = tx_data["transaction"]["txid"]
                    chain_txids.add(txid)
                    processed_txids.add(txid)

            if transaction.txid in chain_txids:
                continue

            from_block = sender_blocks[-1] if sender_blocks else sender
            to_block = receiver_blocks[-1] if receiver_blocks else receiver


            # query from_block and to_block
            # get balance and calcuate
            # update transaction's from_block and to_block

            data["from_block"] = from_block
            data["to_block"] = to_block
            data["sender_balance"] = ""
            data["receiver_balance"] = ""
            data["leader_publickey"] = pk

            vk2 = VerifyingKey.from_string(base64.b64decode(sender), curve=NIST384p)
            assert vk2.verify(base64.b64decode(signature), json.dumps(data["transaction"]).encode('utf-8'))

            # signature = sk.sign(json.dumps(transaction).encode('utf-8'))
            # data = {"transaction": transaction, "signature": str(base64.b64encode(signature), encoding="utf-8")}

            for nonce in range(100000000):
                block_hash = hashlib.sha256((json.dumps(data) + pk + str(nonce)).encode('utf8')).hexdigest()
                if block_hash < certain_value:
                    print("tx", nonce, block_hash)
                    try:
                        # query if any node taken from_block or to_block
                        db.execute("INSERT INTO graph (hash, from_block, to_block, sender, receiver, nonce, data) VALUES (%s, %s, %s, %s, %s, %s, %s)", block_hash, from_block, to_block, sender, receiver, nonce, transaction.data)
                        # db.execute("INSERT INTO graph (hash, from_block, to_block, sender, receiver, nonce, data, transaction_id, timestamp) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", block_hash, from_block, to_block, sender, receiver, nonce, transaction.data, transaction.id, int(time.time()))
                        processed_txids.add(transaction.txid)
                        break
                    except:
                        pass

            time.sleep(1)
        transaction_id += 20
        time.sleep(0.1)
Ejemplo n.º 4
0
from election import election


choices = ['Salad', 'Burger', 'Pizza', 'Curry', 'Pasta', 'BLT']

campaign = election(300, choices)  


print('NEW ELECTION')
print(f'Number of voters is {campaign.voter_count}')
print(campaign.vote_counts)


Ejemplo n.º 5
0
    def handle(self):
        authenticated_requst=authenticate(file_server_key,self.request.recv(1024))
        print "FS {}: AuthenticatedReply below".format(file_port)
        print(authenticated_requst)


        if ("KILL_SERVICE" in authenticated_requst):
            #print ("Service killed by Client\n")
            self.client_connected=False
            file_server.server_alive = False


        elif ("HELO" in authenticated_requst):
            #print(authenticated_requst)
            lines=authenticated_requst.split()
            authenticated_requst = ("HELO {}\nIP:{}\nPort:{}\nStudentID:{}\n".format(lines[1], my_ip, p, studentNumber))
            self.request.send(authenticated_requst)


        elif("WRITE" in authenticated_requst):
            #print(authenticated_requst)
            write_file(self, authenticated_requst)
            #if it is a primary copy then the server propagates the updated file
            #to replicas, if a server can not be progagate too it is deamed failed and removed from
            #the replica server list
            if(file_server.primary_copy==True):
                file_name=authenticated_requst.split("\n")[1]
                failed_servers=propagate_write_2(file_server.server_list,file_name, auth_port)
                file_server.server_list.remove(failed_servers)


        elif("READ" in authenticated_requst):
            if(file_server.primary_copy==True):
                #send replica server info to client
                self.request.send(file_server.server_list[file_server.last_replica])
                #iterates to the next replica server, so that the following read requests are distributed fairly bewtween the replicas
                if(len(file_server.server_list)==file_server.last_replica):
                    file_server.last_replica=0
                else:
                    file_server.last_replica+=1
            else:
                #print(authenticated_requst)
                read_file(self, authenticated_requst)

        elif("Expired Ticket"):
            self.request("Your can not be completed, your ticket has expired")


        elif("PING" in authenticated_requst):
            #if the primary copy receives a ping
            #then return the serverlist
            if(file_server.primary_copy==True):
                string_server_list=parse_tuple_server_list(file_server.server_list)
                self.request.send(string_server_list)
            else:
                #else send none
                self.request.send(None)


        elif("ELECTION" in authenticated_requst):
            #checks if the id in the message is larger then mine
            #id is extracted by spliting the request

            #If the election requests Id is larger reply with a \n
            if(int(authenticated_requst.split("\n")[1])>file_server.server_id):
                self.request.send("\n")
            else:
                #else send dont send \n
                self.request.send("Whoa, I have a bigger Id, I'm a bully")
                #this server should then start an election
                election(file_server.server_id,file_server.server_list, file_host,file_port,auth_port)

        elif("ELECTED" in authenticated_requst):
            file_server.primary_copy=parse_elected(authenticated_requst)
Ejemplo n.º 6
0
        server_thread.daemon = True
        server_thread.start()

        #fileserver closes after 10 minutes
        while(file_server.server_alive==True and current_min> datetime.now().minute-10):

            #print datetime.now().second            #if replica then ping_primary


            #if replication was working then the the pings would happen here
            if():#file_server.primary_copy==False and datetime.now().second==file_server.ping_interval):
                print "FS {}  Pinged!".format(file_port)

                ping_reply=ping_primary_copy(file_server.primary_copy_address, auth_port, file_port)
                #if ping fails hold, then an election
                if(ping_reply==None):
                    election(file_server.server_id,file_server.server_list,file_host, file_port,auth_port)
                    pass
                else:
                    #the Primary copy replys with the currently connected replicas
                    file_server.server_list=ping_reply

        file_server.shutdown()
        file_server.server_close()
        exit()

    except KeyboardInterrupt:
        print("Key board interrupt \nServer Shutting Down")
        file_server.shutdown()
        file_server.server_close()
        exit()
Ejemplo n.º 7
0
 def process(self, data, elec, user):
     dict = data
     ans = dict["ans"]
     elec = election()
     elec.name = ans
     return (elec, user)