I'm trying to figure out the internals of hashing. I've read through a lot of the documentation but unfortunately most of it tends to gloss over the details. In fact I've yet to find a complete and accurate portrayal of a hashing procedure in an easy-to-read language like Python. So I thought I would try to do it myself. I am starting off by trying to verify the "midstate" that comes in every call to getwork (although soon to be removed completely as I understand).

I have been referencing this example in Go: https://stackoverflow.com/questions/9245235/golang-midstate-sha-256-hash/9322486#9322486

So I just hardcoded in the first half of the "data" field which would be returned by the getwork call

So here's what I've got so far:

#!/usr/bin/env python
import json
import binascii
import hashlib

#This function takes a hex string and reverses the order of bytes in every slice of 4 bytes
def hexbyteswap(string):
  swapped_string = []
  n = 8
  split_string = [string[i:i+n] for i in range(0, len(string),n)]
  for piece in split_string:
    binary = binascii.unhexlify(piece)
    binary_r = binary[::-1]
  return "".join(swapped_string)

#This is the first half of the data string, i.e. the first 64 bytes of the data field

# run the byteswap
fhalf_bin_r_hex = hexbyteswap(fhalf)

#These following steps are where I'm having the problem
print hashlib.sha256(binascii.unhexlify(fhalf_bin_r_hex)).hexdigest()
print hashlib.sha256(fhalf_bin_r_hex).hexdigest()

So according to the Go article referenced earlier, I should get this out of my SHA function:


Then if I run the byte swap again I will get the real midstate which is:


But I am NOT getting anything resembling that at all. I've tried two ways first putting the hex string into the Sha function and getting:


Then I also tried running unhexlify first and putting it into Sha (shown in the code above) which yields:


Neither one of these is correct. What am I missing?

1 Answer 1


Trying to find this answer myself. Noticed that the stratum_proxy is written in python and thus has the answer we are looking for. https://github.com/slush0/stratum-mining-proxy/blob/master/mining_libs/midstate.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.