# Calculating Midstate in Python

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]
swapped_string.append(binascii.hexlify(binary_r))
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:

``````69FC72E76DB0E764615A858F483E3566E42D56B2BC7A03ADCE9492887010EDA8
``````

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

``````e772fc6964e7b06d8f855a6166353e48b2562de4ad037abc889294cea8ed1070
``````

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:

``````d3092f90cd1940d050b7a6f43063b081a82bc43c7fe202a5920721b858462a49
``````

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

``````b55c86ea0314d1dea431923d46a18feed832f15ad535256516b796f6909e0dd0
``````

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