# USTclient.py
# 6.857 spring 2013
# staff: Rivest, Wilson, Popa
# Note: this code is ``naive'' and not commercial-grade or bullet-proof...

import hashlib
import random
import requests

SERVER_URL = "http://kagu.csail.mit.edu:6857"


# HASHING

def H(m):
    """ 
    return hash (256-bit integer) of string m, as long integer.
    If the input is an integer, treat it as a string.
    """
    m = str(m)
    return int(hashlib.sha256(m).hexdigest(),16)

def main():

    # This is the server's public key
    (n,e) = (93715031694904665096888055002697470198252335679677901252409323176141222036432351101554951123733435495725006414347083088768193707960233779092919096492766147696692504661585300430366015573333244992219235624452140405877359765323303762553750772802856716366564360322106221631390511413624945975038695313305553516297, 65537)

    # Replace this with the values you got from the course staff.  
    # This is the nonce and sig(hash(nonce)) that would be received 
    # through "subscription".
    (nonce, sig) = (0,0) 

    # Number of iterations.  Please don't make this very large.
    num_iterations = 10

    for i in xrange(0,num_iterations):
        #generate a new nonce (new_nonce) and blinded object (blinded_new_hash) to sign
        # FILL IN HERE

        #make a request to the server
        (text_string, new_blinded_sig) = send_request(sig, nonce, blinded_new_hash)
        new_blinded_sig = long(new_blinded_sig)

        #unblind the new sig (yielding new_sig)
        # FILL IN HERE

        # If you feel like printing out any other information, here's 
        # a good place to do it...
        print text_string

        #change to next nonce/signature for next iteration
        (nonce, sig) = (new_nonce, new_sig)
    
# Send a request of the form sig(hash(nonce)), nonce, blind(hash(new_nonce))
def send_request(signed_hash, nonce, blinded_new_hash):
    payload = {'sig': signed_hash, 'nonce': nonce, 'blinded': blinded_new_hash}
    r = requests.get(SERVER_URL, params=payload)
    if(r.status_code != 200):
        raise Exception(r.text)
    return r.text.splitlines()

main()

