The algorithm for mining bitcoin in Python

This article describes a python implementation of bitcoin mining that relies on an algorithm based on a double hash SHA-256.

Introduction – Principle of the bitcoin mining agorithm

Miners on the bitcoin network should look for the nonce which is a 32-bit number. The miner will successively test several NONCEs (1,2,3 …. 10 ^ 32-1), for each of the nonce he creates the following header and hasher twice with a SHA-256 bit hash function.

FieldDescriptionSize
versionVersion 4
Hash previous block256-bit hash of the previous block32
Merkle rootThis is a hash on the data in the block. It is provided to the miner and it contains a summary of the transactions that are contained in the block.32
timeA digital timestamp that represents the number of seconds since 1970-01-01T00: 00 UTC4
bitsThe current target in compacted format4
nonce32-bit number (starts at 0)4

Once the hash obtained, the miner must then check that the hash obtained is lower than the target difficulty factor of the block. If the hash obtained is greater then the nonce is not the correct one, another must be tested.

Example on block 671712

If you are using a blockhain bitoin explorer (for example blocstream info), if we take for example block 671712:

https://blockstream.info/block/000000000000000000062a949bc297739a12e639ba9e2107638b469afe11d0f8?expand

In this case here is an algorithm in python which allows to mine this block:

In this simulation I display the header and the calculated hash as well as the hash rate.

The nonce to find for block 671712 was 4107802144

in hexadecimal : 0xf4d81620

This algorithm starts with a nonce = 4107802144 – 400 we will act as if we were very close to finding the block (400 double hashes are missing to find the block):

import hashlib
from hashlib import sha256
import time
import struct
import binascii
import datetime
from binascii import unhexlify, hexlify
from dateutil import parser
from datetime import datetime
from datetime import timedelta 

nontrouve = True
dtprec = datetime.now()
inonc = 4107802134 - 400 #Starting 400 before the good nonce
resultat = []

while(nontrouve):
    inonc +=1
    if(inonc%50==0):
        print(str(round(timedelta(seconds=1)/(datetime.now() - dtprec))) + ' H/s')
    dtprec = datetime.now()
    header_hex = (binascii.hexlify(struct.Struct('<L').pack(int('0x2fffe000',16))).decode()  + 
     binascii.hexlify(binascii.unhexlify('000000000000000000078908d256fa7a9f97b2e1ea532fb1ce45ee4bf050d221')[::-1]).decode()+
     binascii.hexlify(binascii.unhexlify('c504fc3a406f11c7c5b598da7f50916f4e298041e6f9b91535a80db113af109a')[::-1]).decode() +
     binascii.hexlify(struct.Struct('<L').pack(int(hex(int(parser.parse('2021-02-22 15:14:22 GMT +1').timestamp())-3600),16))).decode() +
     binascii.hexlify(struct.Struct('<L').pack(int("0x170cf4e3",16))).decode() + 
     binascii.hexlify(struct.Struct('<L').pack(int(hex(inonc),16))).decode()) 
    header_bin = unhexlify(header_hex)
    dt1 = datetime.now().strftime("%H:%M:%S.%f")
    hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest()
    hexlify(hash).decode("utf-8")
    hexlify(hash[::-1]).decode("utf-8")
    hash=hexlify(hash[::-1]).decode("utf-8") 
    resultat.append([round(int(hash,16)/10**65)])
    
    MAX_TARGET = int("00000000FFFF0000000000000000000000000000000000000000000000000000", 16)           
    Difficulty = 21724134900047.27                     
    target = int(MAX_TARGET / Difficulty)
    target32 = '{:0>64x}'.format(target)    
    if(int(hash,16) < int(target32,16)):
        print('###########BLOC MINED###################')
        print('HEADER=' + header_hex)
        print('HASH=' + hash)
        print('NONCE=' + str(inonc))
        print('NONCE (hex)=' + hex(inonc))
        print('###########BLOC MINED###################')
        break

The output is :

1149 H/s
4405 H/s
4115 H/s
1534 H/s
3831 H/s
2392 H/s
4386 H/s
3165 H/s
###########BLOC MINED###################
HEADER=00e0ff2f21d250f04bee45ceb12f53eae1b2979f7afa56d20889070000000000000000009a10af13b10da83515b9f9e64180294e6f91507fda98b5c5c7116f403afc04c53ebc3360e3f40c172016d8f4
HASH=000000000000000000062a949bc297739a12e639ba9e2107638b469afe11d0f8
NONCE=4107802144
NONCE (hex)=0xf4d81620
###########BLOC MINED###################

External link- bitcoin mining with python

https://en.bitcoin.it/wiki/Block_hashing_algorithm

Internal link – bitcoin algorithm python

https://128mots.com/index.php/2020/03/30/construire-une-application-decentralisee-full-stack-pas-a-pas-ethereum-blockchain-dapp-en-plus-de-128-mots-partie-1/

Leave a Reply

Your email address will not be published. Required fields are marked *