Construisez votre propre blockchain de crypto-monnaie en Python

La crypto-monnaie est une monnaie numérique décentralisée qui utilise des techniques de cryptage pour réguler la génération d'unités monétaires et vérifier le transfert de fonds. L'anonymat, la décentralisation et la sécurité font partie de ses principales caractéristiques. La crypto-monnaie n'est réglementée ou suivie par aucune autorité centralisée, gouvernement ou banque.

Blockchain, un réseau peer-to-peer décentralisé (P2P), composé de blocs de données, fait partie intégrante de la crypto-monnaie. Ces blocs stockent chronologiquement des informations sur les transactions et adhèrent à un protocole de communication inter-nœuds et de validation de nouveaux blocs. Les données enregistrées dans les blocs ne peuvent pas être modifiées sans la modification de tous les blocs suivants.

Dans cet article, nous allons expliquer comment créer une blockchain simple à l'aide du langage de programmation Python.

Voici le plan de base de la classe Python que nous utiliserons pour créer la blockchain :

class Block(object):
    def __init__():
        pass
    #initial structure of the block class 
    def compute_hash():
        pass
    #producing the cryptographic hash of each block 
  class BlockChain(object):
    def __init__(self):
    #building the chain
    def build_genesis(self):
        pass
    #creating the initial block
    def build_block(self, proof_number, previous_hash):
        pass
    #builds new block and adds to the chain
   @staticmethod
    def confirm_validity(block, previous_block):
        pass
    #checks whether the blockchain is valid
    def get_data(self, sender, receiver, amount):
        pass
    # declares data of transactions
    @staticmethod
    def proof_of_work(last_proof):
        pass
    #adds to the security of the blockchain
    @property
    def latest_block(self):
        pass
    #returns the last block in the chain

Maintenant, expliquons comment fonctionne la classe blockchain.

Structure initiale de la classe Block

Voici le code de notre classe de bloc initiale :

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()

Comme vous pouvez le voir ci-dessus, le constructeur de classe ou la méthode d'initiation ( init ()) ci-dessus prend les paramètres suivants :

self— comme toute autre classe Python, ce paramètre est utilisé pour faire référence à la classe elle-même. Toute variable associée à la classe est accessible en l'utilisant.

index - il est utilisé pour suivre la position d'un bloc dans la blockchain.

previous_hash — il faisait référence au hachage du bloc précédent dans la blockchain.

data—it donne des détails sur les transactions effectuées, par exemple, le montant acheté.

timestamp—it insère un horodatage pour toutes les transactions effectuées.

La deuxième méthode de la classe, compute_hash , est utilisée pour produire le hachage cryptographique de chaque bloc en fonction des valeurs ci-dessus.

Comme vous pouvez le voir, nous avons importé l'algorithme SHA-256 dans le projet de blockchain de crypto-monnaie pour aider à obtenir les hachages des blocs.

Une fois les valeurs placées dans le module de hachage, l'algorithme renvoie une chaîne de 256 bits indiquant le contenu du bloc.

C'est donc ce qui donne à la blockchain l'immuabilité. Étant donné que chaque bloc sera représenté par un hachage, qui sera calculé à partir du hachage du bloc précédent, la corruption de n'importe quel bloc de la chaîne fera que les autres blocs auront des hachages invalides, entraînant la rupture de l'ensemble du réseau blockchain.

Construire la chaîne

Tout le concept d'une blockchain est basé sur le fait que les blocs sont « enchaînés » les uns aux autres. Maintenant, nous allons créer une classe blockchain qui jouera le rôle essentiel de gestion de l'ensemble de la chaîne.

Il conservera les données des transactions et inclura d'autres méthodes d'assistance pour remplir divers rôles, tels que l'ajout de nouveaux blocs.

Parlons des méthodes d'aide.

Ajout de la méthode constructeur

Voici le code :

class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()

La méthode constructeur init () est ce qui instancie la blockchain.

Voici les rôles de ses attributs :

self.chain — cette variable stocke tous les blocs.

self.current_data — cette variable stocke des informations sur les transactions dans le bloc.

self.build_genesis() — cette méthode est utilisée pour créer le bloc initial de la chaîne.

Construire le bloc Genesis

La build_genesis()méthode est utilisée pour créer le bloc initial dans la chaîne, c'est-à-dire un bloc sans aucun prédécesseur. Le bloc de genèse est ce qui représente le début de la blockchain.

Pour le créer, nous appellerons la build_block()méthode et lui donnerons des valeurs par défaut. Les paramètres proof_numberet previous_hashreçoivent tous deux une valeur de zéro, bien que vous puissiez leur donner la valeur que vous désirez.

Voici le code :

def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
 def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block

Confirmation de la validité de la blockchain

La confirm_validityméthode est essentielle pour examiner l'intégrité de la blockchain et s'assurer qu'il n'y a pas d'incohérences.

Comme expliqué précédemment, les hachages sont essentiels pour assurer la sécurité de la blockchain de crypto-monnaie, car toute légère modification d'un objet entraînera la création d'un hachage entièrement différent.

Ainsi, le confirm_validityprocédé utilise une série d'instructions if pour évaluer si le hachage de chaque bloc a été compromis.

De plus, il compare également les valeurs de hachage de tous les deux blocs successifs pour identifier toute anomalie. Si la chaîne fonctionne correctement, elle renvoie true ; sinon, il retourne faux.

Voici le code :

def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True

Déclaration des données des transactions

La get_dataméthode est importante pour déclarer les données des transactions sur un bloc. Cette méthode prend trois paramètres (informations de l'expéditeur, informations du destinataire et montant) et ajoute les données de transaction à la liste self.current_data.

Voici le code :

def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True

Effectuer la preuve de travail

Dans la technologie blockchain, la preuve de travail (PoW) fait référence à la complexité impliquée dans l'extraction ou la génération de nouveaux blocs sur la blockchain.

Par exemple, le PoW peut être mis en œuvre en identifiant un numéro qui résout un problème chaque fois qu'un utilisateur effectue un travail informatique. Toute personne sur le réseau blockchain devrait trouver le numéro complexe à identifier mais facile à vérifier - c'est le concept principal de PoW.

De cette façon, cela décourage le spam et compromet l'intégrité du réseau.

Dans cet article, nous allons illustrer comment inclure un algorithme de preuve de travail dans un projet de crypto-monnaie blockchain.

Finaliser avec le dernier bloc

Enfin, la méthode helper last_block() est utilisée pour récupérer le dernier bloc sur le réseau, qui est en fait le bloc actuel.

Voici le code :

def latest_block(self):
        return self.chain[-1]

Mise en œuvre du minage de la blockchain

Maintenant, c'est la section la plus excitante!

Initialement, les transactions sont conservées dans une liste de transactions non vérifiées. Le minage fait référence au processus consistant à placer les transactions non vérifiées dans un bloc et à résoudre le problème de PoW. Il peut être appelé le travail informatique impliqué dans la vérification des transactions.

Si tout a été compris correctement, un bloc est créé ou extrait et joint aux autres dans la blockchain. Si les utilisateurs ont réussi à exploiter un bloc, ils sont souvent récompensés pour avoir utilisé leurs ressources informatiques pour résoudre le problème de PoW.

Voici la méthode de minage dans ce projet simple de blockchain de crypto-monnaie :

def block_mining(self, details_miner):
            self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)

Sommaire

Voici le code complet de notre classe crypto blockchain en Python :

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()
    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()
    def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
    def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block
    @staticmethod
    def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True
    def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True        
    @staticmethod
    def proof_of_work(last_proof):
        pass
    @property
    def latest_block(self):
        return self.chain[-1]
    def chain_validity(self):
        pass        
    def block_mining(self, details_miner):       
        self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awared with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)  
    def create_node(self, address):
        self.nodes.add(address)
        return True
    @staticmethod
    def get_block_object(block_data):        
        return Block(
            block_data['index'],
            block_data['proof_number'],
            block_data['previous_hash'],
            block_data['data'],
            timestamp=block_data['timestamp']
        )
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
    sender="0", #this means that this node has constructed another block
    receiver="LiveEdu.tv", 
    amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)

Maintenant, essayons d'exécuter notre code pour voir si nous pouvons générer des pièces numériques…

Waouh, ça a marché !

Conclusion

C'est ça!

Nous espérons que cet article vous a aidé à comprendre la technologie sous-jacente qui alimente les crypto-monnaies telles que Bitcoin et Ethereum.

Nous venons d'illustrer les idées de base pour se mouiller les pieds dans la technologie innovante de la blockchain. Le projet ci-dessus peut encore être amélioré en incorporant d'autres fonctionnalités pour le rendre plus utile et robuste.

What is GEEK

Buddha Community

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips

Devin Pinto

1606217442

Blockchain Certification | Blockchain Training Course | Blockchain Council

In all the market sectors, Blockchain technology has contributed to the redesign. The improvements that were once impossible have been pushed forward. Blockchain is one of the leading innovations with the ability to influence the various sectors of the industry. It also has the ability to be one of the career-influencing innovations at the same time. We have seen an increasing inclination towards the certification of the Blockchain in recent years, and there are obvious reasons behind it. Blockchain has everything to offer, from good packages to its universal application and futuristic development. Let’s address the reasons why one should go for Blockchain certification.

5 advantages of certification by Blockchain:

1. Lucrative packages- Everyone who completes their education or upskills themselves wants to end up with a good bundle, not only is one assured of a good learning experience with Blockchain, but the packages are drool-worthy at the same time. A Blockchain developer’s average salary varies between $150,000 and $175,000 per annum. Comparatively, a software developer gets a $137,000 per year salary. For a Blockchain developer, the San Francisco Bay area provides the highest bundle, amounting to $162,288 per annum. There’s no point arguing that learning about Blockchain is a smart decision with such lucrative packages.

2. Growing industry- When you select any qualification course, it becomes important that you choose a growing segment or industry that promises potential in the future. You should anticipate all of these with Blockchain. The size of the blockchain market is expected to rise from USD 3.0 billion in 2020 to USD 39.7 billion by 2025. This will see an incredible 67.3 percent CAGR between 2020-2025. To help business processes, several businesses are outsourcing Blockchain technologies. This clearly demonstrates that there will be higher demand in the future for Blockchain developers and certified Blockchain professionals.

3. Universal application- One of the major reasons for the success of Blockchain is that it has a global application. It is not sector-specific. Blockchain usage cases are discovered by almost all market segments. In addition, other innovations such as AI, big data, data science and much more are also supported by Blockchain. It becomes easier to get into a suitable industry once you know about Blockchain.

**4. Work protection-**Surely you would like to invest in an ability that ensures job security. You had the same chance for Blockchain. Since this is the technology of the future, understanding that Blockchain can keep up with futuristic developments will help in a successful and safe job.

**5.**After a certain point of your professional life, you are expected to learn about new abilities that can help enhance your skills. Upskilling is paramount. Upskilling oneself has become the need for the hour, and choosing a path that holds a lot of potential for the future is the best way to do this. For all computer geeks and others who want to gain awareness of emerging technology, Blockchain is a good option.

Concluding thoughts- opting for Blockchain certification is a successful career move with all these advantages. You will be able to find yourself in a safe and secured work profile once you have all the knowledge and information. Link for Blockchain certification programme with the Blockchain Council.

#blockchain certificate #blockchain training #blockchain certification #blockchain developers #blockchain #blockchain council

Aylin Hazel

Aylin Hazel

1648115675

Germany: 44% Will Invest in #Crypto and Join ‘The Future of Finance’

Germany was the first country to recognize #Bitcoins as “units of value” and that they could be classified as a “financial instrument.”

Legal regulation for the decentralized industry in Germany is ongoing. Now, 16% of the German population 18 to 60 are #crypto investors.

These people who own #cryptocurrencies or have traded cryptocurrencies in the past six months.

41% of these #crypto investors intend to increase the share of their investments in #crypto in the next six months. Another 13% of Germans are #crypto-curious.

They intend to invest in #cryptocurrencies too. Yet, only 23% of the #crypto-curious said they are highly likely to invest, with the rest remaining hesitant.