help me to understand this mining code

Help me to understand this code, spend all day to understand this code, and learned python from scratch, now I understand what operators do, but still some parts are complex to me.

import hashlib, struct

ver = 2
mrkl_root = "871714dcbae6c8193a2bb9b2a69fe1c0440399f38d94b3a0f1b447275a29978a"
time_ = 0x53058b35 # 2014-02-20 04:57:25
bits = 0x19015f53

# https://en.bitcoin.it/wiki/Difficulty
exp = bits >> 24
mant = bits & 0xffffff
target_hexstr = '%064x' % (mant * (1<<(8*(exp - 3))))
target_str = target_hexstr.decode('hex')

nonce = 0
while nonce < 0x100000000:
header = ( struct.pack("<L", ver) + prev_block.decode('hex')[::-1] +
mrkl_root.decode('hex')[::-1] + struct.pack("<LLL", time_, bits, nonce))
print nonce, hash[::-1].encode('hex')
if hash[::-1] < target_str:
print 'success'
break
nonce += 1

In this code does the

is in SHA256 and then later it's decoded in to hexadecimal by using

prev_block.decode('hex')[::-1]

?

I just want to create a full "header" using the data I already have.

• Any chance you can mark my answer as accepted, if that was the answer that helped you? – Brandon Jul 16 '16 at 20:20

This is simply setting a variable called "prev_block" to the hexadecimal text hash of the previous block. It could have been stored as the raw byte hash, but for ease of use it is stored as hexadecimal text.

prev_block.decode('hex')[::-1]

This converts the hexadecimal text stored in prev_block into it's binary representation as a string/array of bytes.

If you simply want to create a header then this code will accomplish that as long as you provide all the variables (ver, prev_block, mrkl_root, time_, bits, and nonce):

ver = 2
mrkl_root = "871714dcbae6c8193a2bb9b2a69fe1c0440399f38d94b3a0f1b447275a29978a"
time_ = 0x53058b35 # 2014-02-20 04:57:25
bits = 0x19015f53
nonce = 1 # make sure to change this to the correct nonce
header = ( struct.pack("<L", ver) + prev_block.decode('hex')[::-1] +
mrkl_root.decode('hex')[::-1] + struct.pack("<LLL", time_, bits, nonce))