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.

bitcoin python algorithme miner minage bitcoin algorithm python

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

bitcoin python algorithme miner minage bitcoin algorithm python

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/

Android SDK Exception in thread “main” java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

When you try to lauchn the utility sdkmanager for android SDK you get the following error : Exception in thread “main” java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

How to solve this error ?

Solution is to install JDK 8 :

brew cask uninstall java
brew tap homebrew/cask-versions
brew cask install java8
touch ~/.android/repositories.cfg
brew cask install android-sdk

In some case the right command is :

brew install openjdk@8
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
https://128mots.com/index.php/2021/02/15/implementation-des-graphes-en-python/

https://formulae.brew.sh/cask/android-sdk

Install Android Command line tools

Little guide to setup android sdk from homebrew and install Android Command line tools

install Android Command line tools

macOS(via Homebrew)

 brew install --cask android-sdk

Test the installation of android SDK

 sdkmanager --help 

https://formulae.brew.sh/cask/android-sdk

https://128mots.com/index.php/2021/02/15/implementation-des-graphes-en-python/

modules/speech_to_text/register_types.cpp:2:10: fatal error: ‘object_type_db.h’ file not found – GODOT Compilation

If you get this error modules/speech_to_text/register_types.cpp:2:10: fatal error: ‘object_type_db.h’ file not found you need to do this :

modules/speech_to_text/register_types.cpp:2:10: fatal error: 'object_type_db.h' file not found - GODOT Compilation

Introduction – modules/speech_to_text/register_types.cpp:2:10: fatal error: ‘object_type_db.h’ file not found

Go into directory source of GODOT and modules/speech_to_text :

File to open is register_types.cpp

You will see use of a header file

#include "object_type_db.h"

It changes between GODOT 2 and 3 from object_type_db.h to class_db.h

So chang it by :

#include "core/object/class_db.h"

Save and execute GODOT source compilation again it will works.

I get similar error on

modules/speech_to_text/stt_config.h:4:10: fatal error: ‘core/resource.h’ file not found

You need to open modules/speech_to_text/stt_config.h and modify :

#include "core/resource.h"

By :

#include "core/io/resource.h"

Also i get modules/speech_to_text/stt_error.h:4:10: fatal error: ‘core/object.h’ file not found

so i do the following in stt_error.h :

#include "core/object.h"
#include "core/ustring.h"
#include "core/object/object.h"
#include "core/string/ustring.h"

Internal links :

https://128mots.com/index.php/en/2021/02/17/typeerror-can_build-takes-1-positional-argument-but-2-were-given/

https://docs.godotengine.org/en/3.0/development/compiling/compiling_for_osx.html

TypeError: can_build() takes 1 positional argument but 2 were given – Godot Compilation

If you get this type of errors TypeError: can_build() takes 1 positional argument but 2 were given when trying to compile Godot you have to do this :

When i tried to compile with scons i got this errors :

scons: Reading SConscript files ...
Automatically detected platform: osx
Building for macOS 10.12+, platform x86-64.
TypeError: can_build() takes 1 positional argument but 2 were given:
  File "/Users/myuser/godot/SConstruct", line 556:
    if config.can_build(env, selected_platform):

How to solve this error ?

First check you version of scons by launching :

scons -v

It will give you the scons path :

SCons path: ['/usr/local/Cellar/scons/4.1.0.post1/libexec/lib/python3.9/site-packages/SCons']

You then notice the use of python 3.9

You have to update your python to 3.9 :

Update Python easy update to Python 3.9 with homebrew – To update Mac os python from an older version to the latest python example python 3.9.1 you can do the folowing :

This article briefly describes how to replace its version of python on Mac. I wrote a similar article some time ago.

python mac Mac os update Python

I used Homebrew to get the latest python as describe on https://formulae.brew.sh/formula/python@3.9:

brew install python@3.9
python --version
Python 3.8.5
python3 --version
Python 3.8.5

You see that it stays on the older version.

Detect where python or python3 is setup

I had to first verify where my python command is pointing, by launching :

which python

It gave me in my case:

/Users/myuser/.pyenv/shims/python

You need also to verify where is python3 command if you have different versions :

which python3  

I get :

/Users/myuser/.pyenv/shims/python3

Replace the version

I need to replace the version of the both command python and python3 by launching :

ln -s -f /usr/local/bin/python3.9 /Users/myuser/.pyenv/shims/python3

And also launch :

ln -s -f /usr/local/bin/python3.9 /Users/myuser/.pyenv/shims/python

The you can test it works :

python --version 
Python 3.9.1
python3 --version 
Python 3.9.1

Come back on GODOT compilation with Scons :

You need to localize the module that is bad in GODOT modules directory

For example i localize speech_to_text that was bad in config.py

So i directly modify config.py from this directory from can_build(env) to can_build(env, platform):

import os  # system()


def can_build(env, platform):
    if platform == "x11":
        has_pulse = os.system("pkg-config --exists libpulse-simple") == 0
        has_alsa = os.system("pkg-config --exists alsa") == 0
        return has_pulse or has_alsa
    elif platform in ["windows", "osx", "iphone", "android"]:
        return True
    else:
        return False


def configure(env):
    pass

And it works :

godot % scons
scons: Reading SConscript files ...
Automatically detected platform: osx
Building for macOS 10.12+, platform x86-64.
YASM is necessary for WebM SIMD optimizations.
WebM SIMD optimizations are disabled. Check if your CPU architecture, CPU bits or platform are supported!
Checking for C header file mntent.h... no
scons: done reading SConscript files.
scons: Building targets ...
[Initial build] Compiling ==> platform/osx/crash_handler_osx.mm
[Initial build] Compiling ==> platform/osx/os_osx.mm
[Initial build] Building RD_GLSL header: "servers/rendering/renderer_rd/shaders/canvas.glsl.gen.h"
[Initial build] Building RD_GLSL header: "servers/rendering/renderer_rd/shaders/canvas_occlusion.glsl.gen.h"
[Initial build] Building RD_GLSL header: "servers/rendering/renderer_rd/shaders/scene_forward.glsl.gen.h"
[Initial build] Building RD_GLSL header: "servers/rendering/renderer_rd/shaders/canvas_sdf.glsl.gen.h"

TypeError: can_build() takes 1 positional argument but 2 were given – Internal links :

This article briefly describes how to replace its version of python on Mac. I wrote a similar article some time ago.

https://128mots.com/index.php/2021/02/15/implementation-des-graphes-en-python/

Mac os update Python easy update to Python 3.9 with homebrew

Update Python easy update to Python 3.9 with homebrew – To update Mac os python from an older version to the latest python example python 3.9.1 you can do the folowing :

This article briefly describes how to replace its version of python on Mac. I wrote a similar article some time ago.

python mac Mac os update Python

Introduction – update to Python 3.9.1 – HOMEBREW

I used Homebrew to get the latest python as describe on https://formulae.brew.sh/formula/python@3.9:

brew install python@3.9
python --version
Python 3.8.5
python3 --version
Python 3.8.5

You see that it stays on the older version.

Detect where python or python3 is setup

I had to first verify where my python command is pointing, by launching :

which python

It gave me in my case:

/Users/myuser/.pyenv/shims/python

You need also to verify where is python3 command if you have different versions :

which python3  

I get :

/Users/myuser/.pyenv/shims/python3

Replace the version

I need to replace the version of the both command python and python3 by launching :

ln -s -f /usr/local/bin/python3.9 /Users/myuser/.pyenv/shims/python3

And also launch :

ln -s -f /usr/local/bin/python3.9 /Users/myuser/.pyenv/shims/python

The you can test it works :

python --version 
Python 3.9.1
python3 --version 
Python 3.9.1

Mac os update Python – Internal links :

This article briefly describes how to replace its version of python on Mac. I wrote a similar article some time ago.

https://128mots.com/index.php/2021/02/15/implementation-des-graphes-en-python/

Comment faire un ping sur Filius ?

Comment faire un ping sur Filius ? Filius est un logiciel de simulation de réseau. Ce premier article présente la création d’un réseau ad hoc entre deux ordinateurs et l’utilisation la commande ping.

Etape 1 :

Ajouter les 2 ordinateurs et les relier par un câble réseau.

Filius ping - Comment faire un ping sur Filius ?
Filius configuration d’un réseau de 2 ordinateurs

Etape 2 :

Configurer le nom et l’adresse IP des ordinateurs, soit “Ordinateur A” : 198.168.0.10 et “Ordinateur B” : 198.168.0.20

Filius ping - Comment faire un ping sur Filius ?

Etape 3 :

Démarrer et installer la ligne de commande sur l’ordinateur A en cliquant dessus.

Filius ping - Comment faire un ping sur Filius ?
FIlius installation de la ligne de commande sur ordinateur A

Etape 4 :

Utiliser la commande ping 192.168.0.20. Ping est une commande qui envoie des paquets réseau vers l’adresse demandée et qui mesure les temps de réponse.

Filius ping - Comment faire un ping sur Filius ?
Commande ping

Filius ping – Liens Externes

https://www.ionos.fr/digitalguide/serveur/outils/commande-ping/

https://fr.wikipedia.org/wiki/Ping_(logiciel)

https://www.cisco.com/c/fr_ca/support/docs/ip/routing-information-protocol-rip/13730-ext-ping-trace.html

Filius ping -Liens Internes

https://128mots.com/index.php/en/category/non-classe-en/

https://128mots.com/index.php/category/non-classe/

https://128mots.com/index.php/2021/01/26/ordinateur-quantique-prix/

starthost failed, but will try again: config: please provide an ip address

starthost failed, but will try again: config: please provide an ip address

❌ Exiting due to GUEST_PROVISION: Failed to start host: config: please provide an IP address : Error with kubernetes and minikube minikube

Exiting due to GUEST_PROVISION: Failed to start host: config: please provide an IP address : Error with kubernetes and minikube minikube

Introduction – Exiting due to GUEST_PROVISION

So, if you are trying to start the kubernetes tutorial from https://kubernetes.io/fr/docs/setup/learning-environment/minikube and you want to start minikube by the command :

minikube start

Then, you are getting this error :

minikube v1.17.1 sur Darwin 10.15.7
✨  Utilisation du pilote ssh basé sur le profil existant
👍  Démarrage du noeud de plan de contrôle minikube dans le cluster minikube
🤦  StartHost failed, but will try again: config: please provide an IP address
😿  Failed to start ssh bare metal machine. Running "minikube delete" may fix it: config: please provide an IP address

❌  Exiting due to GUEST_PROVISION: Failed to start host: config: please provide an IP address

😿  If the above advice does not help, please let us know: 
👉  https://github.com/kubernetes/minikube/issues/new/choose

Solution – starthost failed, but will try again: config: please provide an ip address

And, the best way to solve this problem is to run the following command. Also you can find information on https://minikube.sigs.k8s.io/docs/drivers/ssh/

If you are running with docker you will find on https://minikube.sigs.k8s.io/docs/drivers/docker/ what i have done is to delete the last minkube cluster and rerun with the command specify the docker :

minikube delete

You will get :

🔄  Désinstallation de Kubernetes v1.20.2 à l'aide de kubeadm…
🔥  Trying to delete invalid profile minikube

And then :

minikube start --driver=docker

This is working :

😄  minikube v1.17.1 sur Darwin 10.15.7
✨  Utilisation du pilote docker basé sur la configuration de l'utilisateur
👍  Démarrage du noeud de plan de contrôle minikube dans le cluster minikube
🚜  Pulling base image ...

Internal links :

https://128mots.com/index.php/en/2021/01/31/unable-to-pick-a-default-driver/
https://128mots.com/index.php/en/2021/01/31/unable-to-pick-a-default-driver/
https://128mots.com/index.php/en/2021/01/31/runtimeerror-attempting-to-deserialize-object/
https://128mots.com/index.php/2021/01/31/installer-kubernetes-mac/