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)
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
Ejemplo n.º 3
0
def main_test():
	print('Some other testing...')
	test_chunk = "0100000076C470C5F0B3AD4A9F619598B80090549E781AB575EA587F977000000000000064A03C10396CC7F820F8830614E94330C4FCA76642BC6E0ED8C2BC8F"
	test_chunk = "00000001c570c4764aadb3f09895619f549000b8b51a789e7f58ea750000709700000000103ca064f8c76c390683f8203043e91466a7fcc40e6ebc428fbcc2d8"
	test_midstate = midstate.calculateMidstate(test_chunk.decode('hex'))
	print('Sanity midstate: %s' % test_midstate.encode('hex_codec'))
	print('Should match:    %s' % 'e772fc6964e7b06d8f855a6166353e48b2562de4ad037abc889294cea8ed1070')
	print('or:              %s' % '69fc72e76db0e764615a858f483e3566e42d56b2bc7a03adce9492887010eda8')

	# main()

	header_bin = header_hex.decode('hex')
	first_hash = hashlib.sha256(header_bin).digest()
	final_hash = hashlib.sha256(first_hash).digest()

	print('Input: %s' % header_hex)
	print('First hash: %s' % first_hash.encode('hex_codec'))
	print('Final hash: %s' % final_hash.encode('hex_codec'))

	first_bin = header_bin[:64]
	first_midstate = be_calculateMidstate(first_bin)

	rest_of_bin = header_bin[64:]
	padding = ('80' + ''.join(['00' for x in range(45)]) + '0280').decode('hex')
	print('First midstate: %s' % first_midstate.encode('hex_codec'))
	print('Second input: %s' % (rest_of_bin + padding).encode('hex_codec'))
	final_state = be_calculateMidstate(rest_of_bin + padding, state=first_midstate)
	print('Final state one:  %s' % final_state.encode('hex_codec'))
	print('We want to match: %s' % first_hash.encode('hex_codec'))

	print('Second hash with padding: %s' % (final_state.encode('hex_codec') + ('80' + ''.join(['00' for x in range(29)]) + '0100')))
	solution_hash = be_calculateMidstate(final_state + ('80' + ''.join(['00' for x in range(29)]) + '0100').decode('hex'))
	print('Solution: %s' % solution_hash[::-1].encode('hex_codec'))
    def get_hash_info(self):
        if self.debug:
            new_data = util.hex2bin(
                '00000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280'
            )
            second_head = block_header[64:76] + new_data
            data_temp = midstate.calculateMidstate(second_head, my_data, 64)

        return None
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 )
Ejemplo n.º 6
0
    def getwork(self, no_midstate=True):
        '''Miner requests for new getwork'''

        job = self.last_job # Pick the latest job from pool

        # 1. Increase extranonce2
        extranonce2 = job.increase_extranonce2()

        # 2. Build final extranonce
        extranonce = self.build_full_extranonce(extranonce2)

        # 3. Put coinbase transaction together
        coinbase_bin = job.build_coinbase(extranonce)

        # 4. Calculate coinbase hash
        coinbase_hash = utils.doublesha(coinbase_bin)

        # 5. Calculate merkle root
        merkle_root = binascii.hexlify(utils.reverse_hash(job.build_merkle_root(coinbase_hash)))

        # 6. Generate current ntime
        ntime = int(time.time()) + job.ntime_delta

        # 7. Serialize header
        block_header = job.serialize_header(merkle_root, ntime, 0)

        # 8. Register job params
        self.register_merkle(job, merkle_root, extranonce2)

        # 9. Prepare hash1, calculate midstate and fill the response object
        header_bin = binascii.unhexlify(block_header)[:64]
        hash1 = "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000"

        result = {'data': block_header,
                'hash1': hash1}

        if self.use_old_target:
            result['target'] = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000'
        elif self.real_target:
            result['target'] = self.target_hex
        else:
            result['target'] = self.target1_hex

        if calculateMidstate and not (no_midstate or self.no_midstate):
            # Midstate module not found or disabled
            result['midstate'] = binascii.hexlify(calculateMidstate(header_bin))

        return result
 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 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
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 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
Ejemplo n.º 11
0
def block_mine_with_midstate(block_template, coinbase_message, extranonce_start, address, timeout=False, debugnonce_start=False):
    # Add an empty coinbase transaction to the block template
    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'])

    # Mark our mine start time
    time_start = time.clock()

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

    # Loop through the extranonce
    extranonce = extranonce_start
    while extranonce <= 0xffffffff:

        # Update the coinbase transaction with the extra nonce
        coinbase_script = coinbase_message + 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)

        time_stamp = time.clock()

        nonce = 0 if debugnonce_start == False else debugnonce_start
        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)
            header_str = bin2hex(block_header)
            # Recompute the block hash

            #block_hash = block_compute_raw_hash(block_header)
            print "Header:", bin2hex(block_header)
            download_hash = sha256_download.SHA256(block_header).hexdigest()
            print "download_hash", download_hash
            # First is trailing 1 bit, then padding
            my_data = midstate.calculateMidstate(block_header[0:64])
            length = 640
            val = [b''.join((
                block_header[64:80],
                b'\x80',
                b'\x00' * (55 - len(block_header[64:80])),
                struct.pack('>LL', length >> 32, length & 0xffffffff),
                ))]
            #print "val:", bin2hex(val)
            print bin2hex(val[0])
            data_new = midstate.calculateMidstate( val[0], my_data, 64 )
            print "data_new:", bin2hex(data_new)
            break
            nonce += 1
        extranonce += 1
        break

    # If we ran out of extra nonces, return none
    hps_average = 0 if len(hps_list) == 0 else sum(hps_list)/len(hps_list)
    return (None, hps_average)
Ejemplo n.º 12
0
def make_input(block_header): 
    midstate = calculateMidstate(binascii.unhexlify(block_header)[:64])	
    data  = binascii.unhexlify(block_header)[65:76]    
    payload = midstate + data    
    print "Input: %s" % binascii.hexlify(payload)
Ejemplo n.º 13
0
	def work(self, datastr, targetstr):
		# decode work data hex string to binary
		static_data = datastr.decode('hex')
		static_data = bufreverse(static_data)

		# the first 76b of 80b do not change
		blk_hdr = static_data[:76]

		# decode 256-bit target value
		targetbin = targetstr.decode('hex')
		targetbin = targetbin[::-1]	# byte-swap and dword-swap
		targetbin_str = targetbin.encode('hex')
		target = long(targetbin_str, 16)

		# pre-hash first 76b of block header
		static_hash = hashlib.sha256()
		static_hash.update(blk_hdr)

                # calculate midstate
                midstate_bin = calculateMidstate(datastr.decode('hex')[:64])

                # send task to Avalon nano
                icarus_bin = midstate_bin[::-1] + '0'.rjust(40, '0').decode('hex') + datastr.decode('hex')[64:76][::-1]
                if settings['verbose'] == 1:
                        print 'send task:' + icarus_bin.encode('hex')
                workpkg = icarus_bin.encode('hex')[:64]
                work_bin = self.mm_package(TYPE_WORK, "01", "02", pdata = workpkg).decode('hex')
                self.usbdev.write(self.endpout, work_bin)
                workpkg = icarus_bin.encode('hex')[64:128]
                work_bin = self.mm_package(TYPE_WORK, "02", "02", pdata = workpkg).decode('hex')
                self.usbdev.write(self.endpout, work_bin)

                # read nonce back
                rdata = None
                loop = 0
                while (rdata == None):
                    try:
                        rdata = self.usbdev.read(self.endpin, 40)
                    except:
                        pass

                    time.sleep(0.01)
                    loop = loop + 1
                    if loop == 3:
                        break

                if rdata == None or rdata[2] != 0x23:
                        print time.asctime(), "No Nonce found"
                        return (0xffffffff, None)
                else:
                        if settings['verbose'] == 1:
                            print 'nonce:', binascii.hexlify(rdata)[12:20]

                # encode 32-bit nonce value
                nonce = (rdata[6] << 24) | (rdata[7] << 16) | (rdata[8] << 8) | rdata[9]
                nonce = bytereverse(nonce)
                nonce_bin = struct.pack("<I", nonce)

                # hash final 4b, the nonce value
                hash1_o = static_hash.copy()
                hash1_o.update(nonce_bin)
                hash1 = hash1_o.digest()

                # sha256 hash of sha256 hash
                hash_o = hashlib.sha256()
                hash_o.update(hash1)
                hash = hash_o.digest()

                # quick test for winning solution: high 32 bits zero?
                if hash[-4:] != '\0\0\0\0':
                        print time.asctime(), "Invalid Nonce"
                        return (0xffffffff, None)

                # convert binary hash to 256-bit Python long
                hash = bufreverse(hash)
                hash = wordreverse(hash)

                hash_str = hash.encode('hex')
                l = long(hash_str, 16)

                # proof-of-work test:  hash < target
                if l < target:
                        print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,)
                        return (0xffffffff, nonce_bin)
                else:
                        print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,)
		return (0xffffffff, None)
Ejemplo n.º 14
0
    def work(self, datastr, targetstr):
        # decode work data hex string to binary
        static_data = datastr.decode('hex')
        static_data = bufreverse(static_data)

        # the first 76b of 80b do not change
        blk_hdr = static_data[:76]

        # decode 256-bit target value
        targetbin = targetstr.decode('hex')
        targetbin = targetbin[::-1]  # byte-swap and dword-swap
        targetbin_str = targetbin.encode('hex')
        target = long(targetbin_str, 16)

        # pre-hash first 76b of block header
        static_hash = hashlib.sha256()
        static_hash.update(blk_hdr)

        # calculate midstate
        midstate_bin = calculateMidstate(datastr.decode('hex')[:64])

        # send task to Avalon nano
        icarus_bin = midstate_bin[::-1] + '0'.rjust(
            40, '0').decode('hex') + datastr.decode('hex')[64:76][::-1]
        if settings['verbose'] == 1:
            print 'send task:' + icarus_bin.encode('hex')
        workpkg = icarus_bin.encode('hex')[:64]
        work_bin = self.mm_package(TYPE_WORK, "01", "02",
                                   pdata=workpkg).decode('hex')
        self.usbdev.write(self.endpout, work_bin)
        workpkg = icarus_bin.encode('hex')[64:128]
        work_bin = self.mm_package(TYPE_WORK, "02", "02",
                                   pdata=workpkg).decode('hex')
        self.usbdev.write(self.endpout, work_bin)

        # read nonce back
        rdata = None
        loop = 0
        while (rdata == None):
            try:
                rdata = self.usbdev.read(self.endpin, 40)
            except:
                pass

            time.sleep(0.01)
            loop = loop + 1
            if loop == 3:
                break

        if rdata == None or rdata[2] != 0x23:
            print time.asctime(), "No Nonce found"
            return (0xffffffff, None)
        else:
            if settings['verbose'] == 1:
                print 'nonce:', binascii.hexlify(rdata)[12:20]

    # encode 32-bit nonce value
        nonce = (rdata[6] << 24) | (rdata[7] << 16) | (
            rdata[8] << 8) | rdata[9]
        nonce = bytereverse(nonce)
        nonce_bin = struct.pack("<I", nonce)

        # hash final 4b, the nonce value
        hash1_o = static_hash.copy()
        hash1_o.update(nonce_bin)
        hash1 = hash1_o.digest()

        # sha256 hash of sha256 hash
        hash_o = hashlib.sha256()
        hash_o.update(hash1)
        hash = hash_o.digest()

        # quick test for winning solution: high 32 bits zero?
        if hash[-4:] != '\0\0\0\0':
            print time.asctime(), "Invalid Nonce"
            return (0xffffffff, None)

    # convert binary hash to 256-bit Python long
        hash = bufreverse(hash)
        hash = wordreverse(hash)

        hash_str = hash.encode('hex')
        l = long(hash_str, 16)

        # proof-of-work test:  hash < target
        if l < target:
            print time.asctime(), "PROOF-OF-WORK found: %064x" % (l, )
            return (0xffffffff, nonce_bin)
        else:
            print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l, )
        return (0xffffffff, None)