예제 #1
0
파일: tinfoil.py 프로젝트: abaur/TinfoilP2P
 def share(self, resourceID, friendsID):
   """Share some stored resource with one or more users.
   Allow other user(s) to access store resource by issuing sharing key
   unique to the user-resource pair.
   Code Sketch:
     sharingKey[resourceID][otherUserID] = encrypt(
     publicKeys[otherUserID],
     resourceKeys[resourceID])
     store(
       "SharingKey(resourceID, otherUserID)",
       sharingKeys[resourceID][otherUserID])
   """
   if not resourceID in self.sharingKeys:
     print('Error: Can\'t share. Post sharing key not found (yet).')
   else:
     sharingKeyName = ('%s:share:%s' % (resourceID, friendsID))
     sharingKeyEncrypted = self._encryptForUser(
         self.sharingKeys[resourceID],
         friendsID)
     # We might not have user's public key yet..
     if sharingKeyEncrypted is not None:
       print('Storing sharing key for: %s : %s' % (
           util.bin2hex(resourceID),
           util.bin2hex(friendsID),
           ))
       self.node.publishData(sharingKeyName, sharingKeyEncrypted)
     else:
       print('Couldn\'t share. Friend\'s public key not found.')
def local_sha256(secondhalf, midstate_data, target_hash):
    #TODO: make sure the nonce is started with 0x00000fff so that it can be started properly
    print "Local sha256"
    new_target = serial.get_target()
    print "Target received:", new_target
    nonce = 0
    while nonce <= 0xffffffff:
        nonce_str = chr(nonce & 0xff) + chr((nonce >> 8) & 0xff) + chr(
            (nonce >> 16) & 0xff) + chr((nonce >> 24) & 0xff)
        new_data = nonce_str + util.hex2bin(
            '800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280'
        )
        second_head = secondhalf + new_data
        temp_hash = midstate.calculateMidstate(second_head, midstate_data, 64)
        block_hash = hashlib.sha256(temp_hash).digest()
        if util.block_check_target(util.bin2hex(block_hash), new_target):
            print 'nonce_str: ', nonce_str
            print 'Target hash found for nonce = ', nonce
            print 'block_hash = ', util.bin2hex(block_hash)
            print 'target_hash = ', new_target
            return None, 0

        nonce += 1

    return None, 0
def local_sha256_with_nonce( secondhalf, midstate_data, target_hash ):
    print 'SHA with nonce'
    new_target = serial.get_target()
    nonce_str = util.hex2bin( serial.get_nonce() )
    new_data = nonce_str + util.hex2bin('800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280')
    second_head = secondhalf + new_data
    temp_hash = midstate.calculateMidstate( second_head, midstate_data, 64 )
    block_hash = hashlib.sha256(temp_hash).digest()
    print "target:", new_target
    print util.bin2hex( block_hash )
def local_hash_big(block_header):
    print "Lib Hash:", hashlib.sha256(hashlib.sha256(block_header).digest()).hexdigest()
    my_data = midstate.calculateMidstate(block_header[0:64])
    new_data = util.hex2bin('00000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280')
    second_head = block_header[64:76] + new_data
    temp_hash = midstate.calculateMidstate( second_head, my_data, 64 )
    print "Level 1: ", util.bin2hex(hashlib.sha256(temp_hash).digest())
    print "Just Level 1:", util.bin2hex(temp_hash)
    new_data = temp_hash + util.hex2bin('800000000000000000000000000000000000000000000000') + util.hex2bin('0000000000000100')
    hash_calc = midstate.calculateMidstate( new_data )
    print util.bin2hex(hash_calc)
예제 #5
0
파일: tinfoil.py 프로젝트: abaur/TinfoilP2P
 def _processSharingKeyResult(result):
   if type(result) == dict:
     for r in result:
       if not isinstance(result[r], entangled.kademlia.contact.Contact):
         self.sharingKeys[postID] = self.node.rsaKey.decrypt(
             result[r][0])
   else:
     print('Could not find sharing key for: %s : %s' % (
         util.bin2hex(postID),
         util.bin2hex(self.node.id),
         ))
def double_hash(block_header, target_hash):
    print 'Double hash'
    nonce = 0
    while nonce <= 0xffffffff:
        # Update the block header with the new 32-bit nonce
        block_header = block_header[0:76] + chr(nonce & 0xff) + chr((nonce >> 8) & 0xff) + chr((nonce >> 16) & 0xff) + chr((nonce >> 24) & 0xff)
        #block_header = block_header[0:76] + chr(nonce >> 24 & 0xff) + chr((nonce >> 16) & 0xff) + chr((nonce >> 8) & 0xff) + chr(nonce  & 0xff)
        # Recompute the block hash
        block_hash = compute_double_hash_lib_call(block_header)
        if util.block_check_target(block_hash, target_hash):
            print "nonce: ", nonce
            print util.bin2hex(block_hash)
            break
        nonce += 1
def local_hash_little(block_header):
    print len(block_header[0:64])
    new_block = util.convetToLittleEndian(block_header[0:64])
    print "Block header:", util.bin2hex(block_header[:64])
    print "New Block   :", util.bin2hex(new_block)

    my_data = midstate_little.calculateMidstate(new_block[0:64])
    new_data = util.hex2bin(
        '00000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280'
    )
    second_head = block_header[64:76] + new_data
    new_block = util.convetToLittleEndian(second_head)
    new_temp = midstate_little.calculateMidstate(new_block, my_data, 64)
    print "Loop2:  ", util.bin2hex(second_head)
    print "Little: ", util.bin2hex(new_block)
    print "New Temp(hash)1", util.bin2hex(new_temp)
    print "Level 1 hash  1", hashlib.sha256(block_header).hexdigest()
    new_data = util.hex2bin('800000000000000000000000000000000000000000000000'
                            ) + util.hex2bin('0000000000000100')
    new_block = new_temp + util.convetToLittleEndian(new_data)
    hash_calc = midstate_little.calculateMidstate(new_block)
    print "New Temp(hash)2", util.bin2hex(hash_calc)
    print "Level 1 hash  2", hashlib.sha256(
        hashlib.sha256(block_header).digest()).hexdigest()
    print util.bin2hex(hash_calc)
예제 #8
0
 def render_GET(self, request):
   """Renders the result of the GET request."""
   self._handleRequest(request)
   self.numberRequests += 1
   request.setHeader("content-type", "text/html")
   return (
     '''<h1>Welcome to <a href="/">TinFoil Net</a></h1>
     Your ID is: %(id)s
     <form action="/post" method="get">
       <input type="text" name="content" placeholder="What's on your mind?" />
     </form>
     Digest:
     <ul>
       %(digest)s
     </ul>
     <form action="/addfriend" method="get">
       <input type="text" name="friendsid" placeholder="Add friend by ID" />
     </form>
     Share:
     <form action="/share" method="get">
       <input type="text" name="postid" placeholder="Post's ID" />
       <input type="text" name="friendsid" placeholder="Friend's ID" />
       <input type="submit" value="Share" />
     </form>
     ''' % {
       'digest': self.getDigestRender(self.node.getDigest()),
       'id': util.bin2hex(self.node.node.id),
     })
def tx_compute_merkle_root(tx_hashes):
    # Convert each hash into a binary string
    for i in range(len(tx_hashes)):
        # Reverse the hash from big endian to little endian
        tx_hashes[i] = util.hex2bin(tx_hashes[i])[::-1]

    # Iteratively compute the merkle root hash
    while len(tx_hashes) > 1:
        # Duplicate last hash if the list is odd
        if len(tx_hashes) % 2 != 0:
            tx_hashes.append(tx_hashes[-1][:])

        tx_hashes_new = []
        for i in range(len(tx_hashes) / 2):
            # Concatenate the next two
            concat = tx_hashes.pop(0) + tx_hashes.pop(0)
            # Hash them
            concat_hash = hashlib.sha256(
                hashlib.sha256(concat).digest()).digest()
            # Add them to our working list
            tx_hashes_new.append(concat_hash)
        tx_hashes = tx_hashes_new

    # Format the root in big endian ascii hex
    return util.bin2hex(tx_hashes[0][::-1])
예제 #10
0
파일: tinfoil.py 프로젝트: abaur/TinfoilP2P
 def _addPublicKeyToLocalCache(result):
   if type(result) == dict:
     for r in result:
       self.node.keyCache[userID] = pickle.loads(result[r])
   else:
     print('Could not find public key for: %s' % (
         util.bin2hex(userID)
         ))
예제 #11
0
 def getDigestRender(self, digest):
   import urllib
   result = ''
   for friendsID in digest:
     result += ('<li><h2>%s</h2></li>\n' % (util.bin2hex(friendsID)))
     for postNumber, postDict in digest[friendsID]:
       if 'postp' in postDict:
         result += ('<li><p>%s: %s</p><small>%s</small></li>\n' % (
             postNumber,
             urllib.unquote_plus(postDict['postp']),
             util.bin2hex(postDict['id'])))
       else:
         result += ('<li><p>%s: <i>%s</i></p><small>%s</small></li>\n' % (
             postNumber,
             util.bin2hex(postDict['post']),
             util.bin2hex(postDict['id'])))
   return result
def create_block_for_submission(block):
    submission_block = ""

    submission_block += util.bin2hex(make_header_from_template(block))
    submission_block += util.int2varinthex(len(block['transactions']))
    for tx in block['transactions']:
        submission_block += tx['data']

    return submission_block
def block_submission(block_template, block_header, nonce, target_hash):
    nonce_str = chr(nonce & 0xff) + chr((nonce >> 8) & 0xff) + chr((nonce >> 16) & 0xff) + chr((nonce >> 24) & 0xff)
    block_hash = compute_double_hash_lib_call(block_header+nonce_str)
    if util.block_check_target(util.bin2hex(block_hash), target_hash):
        #Submit the data again
        block_template['nonce'] = nonce
        block_template['hash'] = bin2hex(block_hash)
        print "Solved a block! Block hash:", mined_block['hash']
        submission = create_block_for_submission(mined_block)
        print "Submitting:", submission, "\n"
        rpc_submitblock(submission)
    return
def performance_measurement_for_different_difficulty():
    block_header_str = "000000202fa8edaec2e28b3b6a9f81b2f4dc572e3b76ba87ffd934fe8001000000000000821e03b6e528af7cdeea67e2c59373a4d6b351e036acf6a3f23712df3f08c2f5d0a88857e28a011a"
    target_hash_str = "000000000000018ae20000000000000000000000000000000000000000000000"
    block_header = util.hex2bin(block_header_str)
    target_hash = util.hex2bin(target_hash_str)
    my_data = midstate.calculateMidstate(block_header[0:64])
    midstatesw = util.bin2hex(my_data)
    targetsw = util.bin2hex(target_hash)
    secondhalf = util.bin2hex(block_header[64:76])
    value = ["FFFFFFFF", "0FFFFFFF", "07FFFFFF", "00FFFFFF", "007FFFFF", "000FFFFF", "0007FFFF", "0000FFFF", "00007FFF",
    "00000FFF", "000007FF", "000000FF", "0000007F", "0000000F"]
    count = 0 #Increase the value of target by starting from
    while(count < (len(value))):
        targetsw = value[count] + targetsw[8:len(targetsw)]
        target_hash = util.hex2bin(targetsw)
        time_stamp = time.time()
        serial.write_data(secondhalf, midstatesw, targetsw)
        new_time_stamp = time.time()
        time_elapsed = new_time_stamp - time_stamp
        print "Time Elapsed( FPGA - Miner ):", time_elapsed
        count += 1
def block_make_submit(block):
    subm = ""

    # Block header
    subm += util.bin2hex(block_form_header(block))
    # Number of transactions as a varint
    subm += util.int2varinthex(len(block['transactions']))
    # Concatenated transactions data
    for tx in block['transactions']:
        subm += tx['data']

    return subm
def fpga_miner_with_debug_data():
    block_header_str = "000000202fa8edaec2e28b3b6a9f81b2f4dc572e3b76ba87ffd934fe8001000000000000821e03b6e528af7cdeea67e2c59373a4d6b351e036acf6a3f23712df3f08c2f5d0a88857e28a011a"
    target_hash_str = "000000000000018ae20000000000000000000000000000000000000000000000"
    block_header = util.hex2bin(block_header_str)
    target_hash = util.hex2bin(target_hash_str)
    my_data = midstate.calculateMidstate(block_header[0:64])
    midstatesw = util.bin2hex(my_data)
    targetsw = util.bin2hex(target_hash)
    secondhalf = util.bin2hex(block_header[64:76])

    if True:
        targetsw = TARGET_REDUCE + targetsw[8:len(targetsw)]
        target_hash = util.hex2bin(targetsw)
    time_stamp = time.clock()
    serial.write_data(secondhalf, midstatesw, targetsw)
    time_elapsed = time.clock() - time_stamp
    print "Time Elapsed( FPGA - MINER ):", time_elapsed
    time_stamp = time.clock()
    double_hash(block_header[:76], target_hash)
    time_elapsed = time.clock() - time_stamp
    print "Time Elapsed( PC - MINER ):", time_elapsed
예제 #17
0
파일: tinfoil.py 프로젝트: abaur/TinfoilP2P
 def _processSequenceNumber(result):
   if type(result) == dict:
     lastSequenceNumber = int(result[keyID])
     for n in range(lastKnownSequenceNumber, (lastSequenceNumber + 1)):
       # There isn't actually any post 0 (which is kinda stupid..)
       if n == 0:
         continue
       postName = ('%s:post:%s' % (friendsID, n))
       postID = self.node.getNameID(postName)
       self.postIDNameTuple[postID] = (friendsID, n)
       # ask network for updates
       self.node.iterativeFindValue(postID).addCallback(
           self._processUpdatesResult)
   else:
     print('Could not find sequence number for: %s' % (
         util.bin2hex(friendsID)))
 def debug_hash(self, nonce):
     n_nonce = struct.pack("<L", nonce)
     new_data = util.hex2bin(
         '800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280'
     )
     new_data = n_nonce + new_data
     second_head = util.hex2bin(self.data_remaining) + new_data
     data_temp = midstate.calculateMidstate(second_head,
                                            util.hex2bin(self.midstate_hex),
                                            64)
     final_hash = hashlib.sha256(data_temp).digest()[::-1]
     print DEBUG_STRING, util.bin2hex(final_hash)
     # Check if it the block meets the target target hash
     if util.block_check_target(final_hash, util.hex2bin(self.target_hex)):
         return (final_hash, nonce)
     return (None, nonce)
def create_merkle_root(tx_hashes):
    # Convert each hash into a binary string
    for i in range(len(tx_hashes)):
        # Reverse the hash from big endian to little endian
        tx_hashes[i] = util.hex2bin(tx_hashes[i])[::-1]

    while len(tx_hashes) > 1:
        # Duplicate last hash if the list is odd
        if len(tx_hashes) % 2 != 0:
            tx_hashes.append(tx_hashes[-1][:])

        tx_hashes_new = []
        for i in range(len(tx_hashes)/2):
            concat = tx_hashes.pop(0) + tx_hashes.pop(0)
            concat_hash = hashlib.sha256(hashlib.sha256(concat).digest()).digest()
            tx_hashes_new.append(concat_hash)
        tx_hashes = tx_hashes_new

    return util.bin2hex(tx_hashes[0][::-1])
예제 #20
0
def recvdata(ip,port):
        """ 接收转发客户端数据并以十六进制打印 """
        print("ip : " + ip)
        print("port : " + str(port))

	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((ip, port))

	data93 = '7e 7e 10 00 00 00 00 00 00 10 00 00 00 00 00 FF 00 02 93 00 66'
        data93 = util.str2hex(data93)

	s.send(result)

	while True:
		data = s.recv(18)     # 接收报文头
		if not data:
			break

		taillen = int(ord(data[16]) * 256 + ord(data[17]) ) + 1     # 报文剩下部分的长度
		data += s.recv(taillen)
		print(util.bin2hex(data))    # 打印结果
예제 #21
0
def recvdata(ip, port):
    """ 接收转发客户端数据并以十六进制打印 """
    print("ip : " + ip)
    print("port : " + str(port))

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))

    data93 = "7e 7e 10 00 00 00 00 00 00 10 00 00 00 00 00 FF 00 02 93 00 66"
    data93 = util.str2hex(data93)

    s.send(result)

    while True:
        data = s.recv(18)  # 接收报文头
        if not data:
            break

        taillen = int(ord(data[16]) * 256 + ord(data[17])) + 1  # 报文剩下部分的长度
        data += s.recv(taillen)
        print(util.bin2hex(data))  # 打印结果
예제 #22
0
def gprsThread(num,mod):
        """ num 最大为 0xFFFF """
        print("mac : " + str(num))
        if num < 0:
            return

        if num <= 0xFF:
            srcmac = '10 00 00 00 00 00 ' + hex(num)
        elif num <= 0xFFFF:
            srcmac = '10 00 00 00 00 ' + hex((num & 0xFF00)>>8) + ' ' + hex(num & 0x00FF)
        else:
            return

	data90 = '7e 7e 10 00 10 00 00 00 01 ' + srcmac + ' 00 06 90 06 5F 00 01 41 42'
	data91 = '7e 7e 10 00 10 00 00 00 01 ' + srcmac + ' 00 06 91 ' + hex(mod) + ' 5F 00 01 41 42'

	# dataF3 = '10 00 10 00 00 00 01 10 00 00 00 00 00 ' + str(num) + ' 00 02 F3 11 66'
        data = '7e 7e 22 22 22 22 22 22 22 66 10 40 20 28 02 39 03 ED 96 73 0A 06 0F 24 35 02 01 00 AA AA 82 F6 7F 49 12 14 06 42 FF 00 AA AA 87 D6 7F 49 12 14 00 00 00 00 00 00 61 FF 00 AA AA 82 F6 7F 4A 12 0D 07 59 FF 00 AA AA 82 F6 7F 4A 12 14 06 41 FF 00 AA AA 87 D6 7F 4A 12 14 00 00 00 00 00 00 62 FF 00 AA AA 82 F6 7F 55 12 0D 07 46 FF 00 AA AA 82 F6 7F 55 12 14 06 5E FF 01 AA AA 82 F6 7F 5D 12 0D 07 4E FF 01 AA AA 82 F6 7F 5D 12 14 06 56 FF 01 AA AA 87 D6 7F 4B 12 14 00 00 00 00 00 00 63 FF 01 AA AA 82 F6 7F 42 12 0D 07 51 FF 01 AA AA 88 D6 7F 42 12 0D 00 00 00 00 00 00 00 7C FF 01 AA AA 82 F6 7F 42 12 14 06 49 FF 01 AA AA 87 D6 7F 42 12 14 00 00 00 00 00 00 6A FF 01 AA AA 82 F6 7F 4D 12 0D 07 5E FF 01 AA AA 82 F6 7F 4D 12 14 06 46 FF 01 AA AA 82 F6 7F 50 12 0D 07 43 FF 01 AA AA 82 F6 7F 50 12 14 06 5B FF 01 AA AA 82 F6 7F 51 12 0D 07 42 FF 01 AA AA 87 D6 7F 4D 12 14 00 00 00 00 00 00 65 FF 01 AA AA 82 F6 7F 51 12 14 06 5A FF 01 AA AA 82 F6 7F 52 12 0D 07 41 FF 01 AA AA 88 D6 7F 52 12 0D 00 00 00 00 00 00 00 6C FF 01 AA AA 82 F6 7F 52 12 14 06 59 FF 01 AA AA 87 D6 7F 52 12 14 00 00 00 00 00 00 7A FF 01 AA AA 87 D6 7F 4E 12 14 00 00 00 00 00 00 66 FF 01 AA AA 82 F6 7F 53 12 0D 07 40 FF 01 AA AA 82 F6 7F 53 12 14 06 58 FF 01 AA AA 82 F6 7F 54 12 0D 07 47 FF 01 AA AA 82 F6 7F 54 12 14 06 5F FF 01 AA AA 88 D6 7F 50 12 0D 00 00 00 00 00 00 00 6E FF 01 AA AA 87 D6 7F 50 12 14 00 00 00 00 00 00 78 FF 01 AA AA 82 F6 7F 56 12 0D 07 45 FF 01 AA AA' 
        data = data + ' 82 F6 7F 56 12 14 06 5D FF 01 AA AA 82 F6 7F 57 12 0D 07 44 FF 01 AA AA 87 D6 7F 51 12 14 00 00 00 00 00 00 79 FF 01 AA AA 82 F6 7F 57 12 14 06 5C FF 01 AA AA 88 F7 7F 53 20 00 7E 84 46 85 46 7D 7E 0F FF 02 AA AA 82 F6 7F 58 12 0D 07 4B FF 02 AA AA 82 F6 7F 58 12 14 06 53 FF 02 AA AA 87 D6 7F 53 12 14 00 00 00 00 00 00 7B FF 02 AA AA 82 F6 7F 59 12 0D 07 4A FF 02 AA AA 82 F6 7F 59 12 14 06 52 FF 02 AA AA 82 F6 7F 5A 12 0D 07 49 FF 02 AA AA 87 D6 7F 54 12 14 00 00 00 00 00 00 7C FF 02 AA AA 82 F6 7F 5A 12 14 06 51 FF 02 AA AA 82 F6 7F 5B 12 0D 07 48 FF 02 AA AA 82 F6 7F 5B 12 14 06 50 FF 02 AA AA 82 F6 7F 5C 12 0D 07 4F FF 02 AA AA 87 D6 7F 55 12 14 00 00 00 00 00 00 7D FF 02 AA AA 82 F6 7F 5C 12 14 06 57 FF 02 AA AA 88 D6 7F 56 12 0D 00 00 00 00 00 00 00 68 FF 02 AA AA 87 D6 7F 56 12 14 00 00 00 00 00 00 7E FF 02 AA AA 82 F6 7F 5F 12 0D 07 4C FF 02 AA AA 82 F6 7F 5F 12 14 06 54 FF 02 AA AA 82 F6 7F 60 12 0D 07 73 FF 02 AA AA 87 D6 7F 57 12 14 00 00 00 00 00 00 7F FF 02 AA AA 82 F6 7F 60 12 14 06 6B FF 02 AA AA 82 F6 7F 62 12 0D 07 71 FF 02 AA AA 82 F6 7F 62 12 14 06 69 FF 02 AA AA 87 D6 7F 58 12 14 00 00 00 00 00 00 70 FF 02 AA AA 82 F6 7F 63 12 0D 07 70 FF 02 AA AA 82 F6 7F 63 12 14 06 68 FF 02 AA AA 82 F6 7F 27 12 0D 07 34 FF 02 AA AA 88 D6 7F 27 12 0D 00 00 00 00 00 00 00 19 FF 02 AA AA 82 F6 7F 27 12 14 06 2C FF 02 AA AA 87 D6 7F 27 12 14 00 00 00 00 00 00 0F FF 02 AA AA 87 D6 7F 59 12 14 00 00 00 00 00 00 71 FF 02 AA AA 82 F6 7F 2F 12 0D 07 3C FF 02 AA AA 88 D6 7F 2F 12 0D 00 00 00 00 00 00 00 11 FF 02 AA AA' + ' 82 F6 7F 2F 12 14 06 24 FF 03 AA AA 87 D6 7F 2F 12 14 00 00 00 00 00 00 07 FF 83'

        sendData90 = util.str2hex(data90)
        sendData91 = util.str2hex(data91)
        sendData = util.str2hex(data)

        print(util.bin2hex(sendData90))
        return

	address = '127.0.0.1'
	port = 7103    #GPRS 7101
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

	s.connect((address, port))
	s.send(result90)
	s.send(result91)

	while True:
		len = s.send(result)
                time.sleep(0.1)
def tx_compute_hash(tx):
    h1 = hashlib.sha256(util.hex2bin(tx)).digest()
    h2 = hashlib.sha256(h1).digest()
    return util.bin2hex(h2[::-1])
예제 #24
0
        target_hash = util.hex2bin(targetsw)
        time_stamp = time.time()
        serial.write_data(secondhalf, midstatesw, targetsw)
        new_time_stamp = time.time()
        time_elapsed = new_time_stamp - time_stamp
        print "Time Elapsed( FPGA - Miner ):", time_elapsed
        count += 1


def start_miner(coinbase_message, address):
    print "FPGA Miner"
    if DEBUG_LOCAL_DATA:
        fpga_miner_with_debug_data()
        #performance_measurement_for_different_difficulty()
    else:
        if SUBMIT_DATA:
            while True:
                block_template1 = util.rpc_getblocktemplate()
                fpga_miner(block_template1,
                           coinbase_message,
                           address,
                           debug=False)
        else:
            block_template1 = util.rpc_getblocktemplate()
            fpga_miner(block_template1, coinbase_message, address, debug=False)


if __name__ == "__main__":
    #serial = serial_comm.MySerial(serial_port=PORT_ADDRESS, debug=False)
    start_miner(util.bin2hex(COINBASE_MSG), PUBLIC_KEY)
def fpga_miner(block_template,
               coinbase_message,
               extranonce_start,
               address,
               timeout=False,
               debugnonce_start=False,
               debug=False):
    # Add an empty coinbase transaction to the block template
    if debug:
        print ""
        print "Algorithm start:"
        print ""
    coinbase_tx = {}
    block_template['transactions'].insert(0, coinbase_tx)
    # Add a nonce initialized to zero to the block template
    block_template['nonce'] = 0

    # Compute the target hash
    target_hash = block_bits2target(block_template['bits'])
    if debug == True:
        print block_template['bits']
        print "target_hash", util.bin2hex(target_hash)

    # Initialize our running average of hashes per second
    hps_list = []

    # Loop through the extranonce
    extranonce = extranonce_start
    coinbase_script = coinbase_message + util.int2lehex(extranonce, 4)
    coinbase_tx['data'] = tx_make_coinbase(coinbase_script, address,
                                           block_template['coinbasevalue'])
    coinbase_tx['hash'] = tx_compute_hash(coinbase_tx['data'])

    # Recompute the merkle root
    tx_hashes = [tx['hash'] for tx in block_template['transactions']]
    block_template['merkleroot'] = tx_compute_merkle_root(tx_hashes)

    # Reform the block header
    block_header = block_form_header(block_template)
    #Block header should be in big endian#
    #local_hash_little(block_header)
    #local_hash_big(block_header)
    my_data = midstate.calculateMidstate(block_header[0:64])

    midstatesw = util.bin2hex(my_data)
    targetsw = util.bin2hex(target_hash)
    secondhalf = util.bin2hex(block_header[64:76])
    if True:
        targetsw = TARGET_REDUCE + targetsw[8:len(targetsw)]
        target_hash = util.hex2bin(targetsw)
    if debug == True:
        '''
        This is used to checking the hash generation through the local information!!!
        '''
        new_data = util.hex2bin(
            '00000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280'
        )
        second_head = block_header[64:76] + new_data
        data_temp = midstate.calculateMidstate(second_head, my_data, 64)
        print "fpga_mine-> block_header:", util.bin2hex(block_header)
        print "midstate_calc:[1]", util.bin2hex(data_temp)
        print "fpga_mine->header_hash first round[1]", hashlib.sha256(
            block_header).hexdigest()
        print "fpga_mine-> header_hash:[2]", hashlib.sha256(
            data_temp).hexdigest()
        print "fpga_mine->header_hash two round[2]", hashlib.sha256(
            hashlib.sha256(block_header).digest()).hexdigest()
        return None, 0

    time_stamp = time.clock()
    serial.write_data(secondhalf, midstatesw, targetsw)
    time_elapsed = time.clock() - time_stamp
    print "Time Elapsed( FPGA - MINER ):", time_elapsed
    time_stamp = time.clock()
    double_hash(block_header[:76], target_hash)
    time_elapsed = time.clock() - time_stamp
    print "Time Elapsed( PC - MINER ):", time_elapsed
    if SUBMIT_DATA:
        block_submission(block_template, block_header, ser.get_nonce(),
                         target_hash)
    return
    print "Time Elapsed( PC - MINER ):", time_elapsed


def standalone_miner(coinbase_message, address):
    print "Mining new block template..."
    if DEBUG_LOCAL_DATA:
        fpga_miner_with_debug_data()
    else:
        if SUBMIT_DATA:
            while True:
                block_template1 = util.rpc_getblocktemplate()
                fpga_miner(block_template1,
                           coinbase_message,
                           0,
                           address,
                           timeout=60,
                           debug=False)
        else:
            block_template1 = util.rpc_getblocktemplate()
            fpga_miner(block_template1,
                       coinbase_message,
                       0,
                       address,
                       timeout=60,
                       debug=False)


if __name__ == "__main__":
    serial = serial_comm.MySerial(serial_port=PORT_ADDRESS, debug=False)
    standalone_miner(util.bin2hex(COINBASE_MSG), PUBLIC_KEY)
def compute_hash_of_transaction(tx):
    h1 = hashlib.sha256(util.hex2bin(tx)).digest()
    h2 = hashlib.sha256(h1).digest()
    return util.bin2hex(h2[::-1])