0
Anyone can give step-by-step explanation about the code below (if possible, with a c/c++ equivalent)?
import hashlib, struct
ver = 2
prev_block = "000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717"
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))
hash = hashlib.sha256(hashlib.sha256(header).digest()).digest()
print nonce, hash[::-1].encode('hex')
if hash[::-1] < target_str:
print 'success'
break
nonce += 1
I am trying create my own implementation; I already read the block data with json-rpc and stored in this struct:
struct block {
unsigned char* hash;
int confirmations;
long strippedsize;
long size;
long weight;
long height;
long version;
unsigned char* versionHex;
unsigned char* merkleroot;
long blocktime;
long mediantime;
long nonce;
unsigned char* bits;
double difficulty;
unsigned char* chainwork;
unsigned char* previousblockhash;
};
Now I want extract the data from this struct and use to execute the same calculations in this code, but I need to understand what the code does with more details.
how I get the data which will goes on the block? If I get some block from the bitcoin network (with
getbestblokchashjson-rpc command, for instance) I can use the data extract from this block as a base for the generated header? Or I just need create all new data for a completely new block? In this last case, how I get this transactions for generate de merkle root? Or is it generated only with the coinbase transaction? – Kleber Mota – 2017-08-21T14:12:56.787getbestblockhashwill give youprev_block. The difficulty is found using the difficulty retargeting algorithm. Transactions are picked up over time by nodes connected to the network, in the mempool. Please don't ask multiple questions as comments, either edit your original question or post a new one. – MeshCollider – 2017-08-21T20:46:14.953