Bongani  Ngema

Bongani Ngema

1651388940

Quickly build & zip games created for js13kgames.com

js13kgames-parcel-starter

This repo uses Parcel to build and zip games created for js13kgames.

Requirements

The commands assume Yarn is installed.

Commands

yarn start

Start the Parcel build server at http://localhost:1234.

yarn build

Build, minify, and inline the game to ./dist/inlined/index.html.

yarn party

Build, minify, inline, and zip the game to ./dist/zipped/game.zip. This command finishes with a log message that says if the zip file is under 13k.

Author: mtmckenna
Source Code: https://github.com/mtmckenna/js13kgames-parcel-starter 
License: MIT License

#node #game #javascript 

What is GEEK

Buddha Community

Quickly build & zip games created for js13kgames.com
Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Riyad Amin

Riyad Amin

1571046022

Build Your Own Cryptocurrency Blockchain in Python

Cryptocurrency is a decentralized digital currency that uses encryption techniques to regulate the generation of currency units and to verify the transfer of funds. Anonymity, decentralization, and security are among its main features. Cryptocurrency is not regulated or tracked by any centralized authority, government, or bank.

Blockchain, a decentralized peer-to-peer (P2P) network, which is comprised of data blocks, is an integral part of cryptocurrency. These blocks chronologically store information about transactions and adhere to a protocol for inter-node communication and validating new blocks. The data recorded in blocks cannot be altered without the alteration of all subsequent blocks.

In this article, we are going to explain how you can create a simple blockchain using the Python programming language.

Here is the basic blueprint of the Python class we’ll use for creating the 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

Now, let’s explain how the blockchain class works.

Initial Structure of the Block Class

Here is the code for our initial block class:

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()

As you can see above, the class constructor or initiation method ( init()) above takes the following parameters:

self — just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.

index — it’s used to track the position of a block within the blockchain.

previous_hash — it used to reference the hash of the previous block within the blockchain.

data—it gives details of the transactions done, for example, the amount bought.

timestamp—it inserts a timestamp for all the transactions performed.

The second method in the class, compute_hash , is used to produce the cryptographic hash of each block based on the above values.

As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.

Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.

So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.

Building the Chain

The whole concept of a blockchain is based on the fact that the blocks are “chained” to each other. Now, we’ll create a blockchain class that will play the critical role of managing the entire chain.

It will keep the transactions data and include other helper methods for completing various roles, such as adding new blocks.

Let’s talk about the helper methods.

Adding the Constructor Method

Here is the code:

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

The init() constructor method is what instantiates the blockchain.

Here are the roles of its attributes:

self.chain — this variable stores all the blocks.

self.current_data — this variable stores information about the transactions in the block.

self.build_genesis() — this method is used to create the initial block in the chain.

Building the Genesis Block

The build_genesis() method is used for creating the initial block in the chain, that is, a block without any predecessors. The genesis block is what represents the beginning of the blockchain.

To create it, we’ll call the build_block() method and give it some default values. The parameters proof_number and previous_hash are both given a value of zero, though you can give them any value you desire.

Here is the 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

Confirming Validity of the Blockchain

The confirm_validity method is critical in examining the integrity of the blockchain and making sure inconsistencies are lacking.

As explained earlier, hashes are pivotal for realizing the security of the cryptocurrency blockchain, because any slight alteration in an object will result in the creation of an entirely different hash.

Thus, the confirm_validity method utilizes a series of if statements to assess whether the hash of each block has been compromised.

Furthermore, it also compares the hash values of every two successive blocks to identify any anomalies. If the chain is working properly, it returns true; otherwise, it returns false.

Here is the 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

Declaring Data of Transactions

The get_data method is important in declaring the data of transactions on a block. This method takes three parameters (sender’s information, receiver’s information, and amount) and adds the transaction data to the self.current_data list.

Here is the code:

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

Effecting the Proof of Work

In blockchain technology, Proof of Work (PoW) refers to the complexity involved in mining or generating new blocks on the blockchain.

For example, the PoW can be implemented by identifying a number that solves a problem whenever a user completes some computing work. Anyone on the blockchain network should find the number complex to identify but easy to verify — this is the main concept of PoW.

This way, it discourages spamming and compromising the integrity of the network.

In this article, we’ll illustrate how to include a Proof of Work algorithm in a blockchain cryptocurrency project.

Finalizing With the Last Block

Finally, the latest_block() helper method is used for retrieving the last block on the network, which is actually the current block.

Here is the code:

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

Implementing Blockchain Mining

Now, this is the most exciting section!

Initially, the transactions are kept in a list of unverified transactions. Mining refers to the process of placing the unverified transactions in a block and solving the PoW problem. It can be referred to as the computing work involved in verifying the transactions.

If everything has been figured out correctly, a block is created or mined and joined together with the others in the blockchain. If users have successfully mined a block, they are often rewarded for using their computing resources to solve the PoW problem.

Here is the mining method in this simple cryptocurrency blockchain project:

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)

Summary

Here is the whole code for our crypto blockchain class in 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)

Now, let’s try to run our code to see if we can generate some digital coins…

Wow, it worked!

Conclusion

That is it!

We hope that this article has assisted you to understand the underlying technology that powers cryptocurrencies such as Bitcoin and Ethereum.

We just illustrated the basic ideas for making your feet wet in the innovative blockchain technology. The project above can still be enhanced by incorporating other features to make it more useful and robust.

Learn More

Thanks for reading !

Do you have any comments or questions? Please share them below.

#python #cryptocurrency

Erstellen Sie Ihre eigene Kryptowährungs-Blockchain in Python

Kryptowährung ist eine dezentralisierte digitale Währung, die Verschlüsselungstechniken verwendet, um die Erzeugung von Währungseinheiten zu regulieren und den Geldtransfer zu überprüfen. Anonymität, Dezentralisierung und Sicherheit gehören zu seinen Hauptmerkmalen. Kryptowährung wird von keiner zentralisierten Behörde, Regierung oder Bank reguliert oder verfolgt.

Blockchain, ein dezentralisiertes Peer-to-Peer (P2P)-Netzwerk, das aus Datenblöcken besteht, ist ein wesentlicher Bestandteil der Kryptowährung. Diese Blöcke speichern chronologisch Informationen über Transaktionen und halten sich an ein Protokoll für die Kommunikation zwischen Knoten und die Validierung neuer Blöcke. Die in Blöcken aufgezeichneten Daten können nicht geändert werden, ohne dass alle nachfolgenden Blöcke geändert werden.

In diesem Artikel erklären wir, wie Sie mit der Programmiersprache Python eine einfache Blockchain erstellen können.

Hier ist die grundlegende Blaupause der Python-Klasse, die wir zum Erstellen der Blockchain verwenden:

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

Lassen Sie uns nun erklären, wie die Blockchain-Klasse funktioniert.

Ausgangsstruktur der Blockklasse

Hier ist der Code für unsere anfängliche Blockklasse:

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()

Wie Sie oben sehen können, nimmt der Klassenkonstruktor oder die Initiationsmethode ( init ()) die folgenden Parameter an:

self— Wie jede andere Python-Klasse wird dieser Parameter verwendet, um auf die Klasse selbst zu verweisen. Auf jede Variable, die der Klasse zugeordnet ist, kann über sie zugegriffen werden.

index — Es wird verwendet, um die Position eines Blocks innerhalb der Blockchain zu verfolgen.

previous_hash — Es wurde verwendet, um auf den Hash des vorherigen Blocks innerhalb der Blockchain zu verweisen.

data—it gibt Details zu den getätigten Transaktionen an, zum Beispiel den gekauften Betrag.

timestamp—it fügt einen Zeitstempel für alle durchgeführten Transaktionen ein.

Die zweite Methode in der Klasse, compute_hash , wird verwendet, um den kryptografischen Hash jedes Blocks basierend auf den obigen Werten zu erzeugen.

Wie Sie sehen können, haben wir den SHA-256-Algorithmus in das Kryptowährungs-Blockchain-Projekt importiert, um die Hashes der Blöcke zu erhalten.

Sobald die Werte im Hashing-Modul platziert wurden, gibt der Algorithmus einen 256-Bit-String zurück, der den Inhalt des Blocks angibt.

Das ist es, was der Blockchain Unveränderlichkeit verleiht. Da jeder Block durch einen Hash repräsentiert wird, der aus dem Hash des vorherigen Blocks berechnet wird, führt die Beschädigung eines Blocks in der Kette dazu, dass die anderen Blöcke ungültige Hashes haben, was zum Bruch des gesamten Blockchain-Netzwerks führt.

Aufbau der Kette

Das ganze Konzept einer Blockchain basiert darauf, dass die Blöcke aneinander „verkettet“ sind. Jetzt erstellen wir eine Blockchain-Klasse, die die entscheidende Rolle bei der Verwaltung der gesamten Kette spielt.

Es behält die Transaktionsdaten bei und enthält andere Hilfsmethoden zum Vervollständigen verschiedener Rollen, z. B. das Hinzufügen neuer Blöcke.

Sprechen wir über die Hilfsmethoden.

Hinzufügen der Konstruktormethode

Hier ist der Code:

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

Die Konstruktormethode init () instanziiert die Blockchain.

Hier sind die Rollen seiner Attribute:

self.chain — Diese Variable speichert alle Blöcke.

self.current_data — Diese Variable speichert Informationen über die Transaktionen im Block.

self.build_genesis() — Diese Methode wird verwendet, um den Anfangsblock in der Kette zu erstellen.

Aufbau des Genesis-Blocks

Die build_genesis()Methode wird verwendet, um den Anfangsblock in der Kette zu erstellen, dh einen Block ohne Vorgänger. Der Genesis-Block ist der Anfang der Blockchain.

Um es zu erstellen, rufen wir die build_block()Methode auf und geben ihr einige Standardwerte. Die Parameter proof_numberund previous_hasherhalten beide den Wert Null, Sie können ihnen jedoch jeden beliebigen Wert zuweisen.

Hier ist der 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

Bestätigung der Gültigkeit der Blockchain

Die confirm_validityMethode ist entscheidend, um die Integrität der Blockchain zu überprüfen und sicherzustellen, dass Inkonsistenzen fehlen.

Wie bereits erwähnt, sind Hashes von entscheidender Bedeutung für die Realisierung der Sicherheit der Kryptowährungs-Blockchain, da jede geringfügige Änderung an einem Objekt zur Erstellung eines völlig anderen Hashs führt.

Somit verwendet das confirm_validityVerfahren eine Reihe von if-Anweisungen, um zu beurteilen, ob der Hash jedes Blocks kompromittiert wurde.

Darüber hinaus vergleicht es auch die Hash-Werte von jeweils zwei aufeinanderfolgenden Blöcken, um Anomalien zu identifizieren. Wenn die Kette richtig funktioniert, gibt sie true zurück; Andernfalls wird false zurückgegeben.

Hier ist der 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

Deklarieren von Transaktionsdaten

Die get_dataMethode ist wichtig, um die Daten von Transaktionen in einem Block zu deklarieren. Diese Methode verwendet drei Parameter (Absenderinformationen, Empfängerinformationen und Betrag) und fügt die Transaktionsdaten zur Liste self.current_data hinzu.

Hier ist der Code:

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

Bewirken des Arbeitsnachweises

In der Blockchain-Technologie bezieht sich Proof of Work (PoW) auf die Komplexität, die mit dem Mining oder der Generierung neuer Blöcke auf der Blockchain verbunden ist.

Zum Beispiel kann das PoW implementiert werden, indem eine Zahl identifiziert wird, die ein Problem löst, wenn ein Benutzer eine Rechenarbeit abschließt. Jeder im Blockchain-Netzwerk sollte den Zahlenkomplex identifizieren, aber leicht zu überprüfen finden – dies ist das Hauptkonzept von PoW.

Auf diese Weise verhindert es Spam und gefährdet die Integrität des Netzwerks.

In diesem Artikel veranschaulichen wir, wie Sie einen Proof of Work-Algorithmus in ein Blockchain-Kryptowährungsprojekt einbinden.

Abschluss mit dem letzten Block

Schließlich wird die Hilfsmethode Latest_block() verwendet, um den letzten Block im Netzwerk abzurufen, der tatsächlich der aktuelle Block ist.

Hier ist der Code:

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

Implementieren von Blockchain-Mining

Das ist jetzt der spannendste Abschnitt!

Anfänglich werden die Transaktionen in einer Liste nicht verifizierter Transaktionen geführt. Mining bezieht sich auf den Prozess, die ungeprüften Transaktionen in einen Block zu legen und das PoW-Problem zu lösen. Es kann als die Rechenarbeit bezeichnet werden, die bei der Überprüfung der Transaktionen beteiligt ist.

Wenn alles richtig herausgefunden wurde, wird ein Block erstellt oder abgebaut und mit den anderen in der Blockchain zusammengefügt. Wenn Benutzer einen Block erfolgreich abgebaut haben, werden sie oft dafür belohnt, dass sie ihre Computerressourcen zur Lösung des PoW-Problems verwenden.

Hier ist die Mining-Methode in diesem einfachen Kryptowährungs-Blockchain-Projekt:

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)

Zusammenfassung

Hier ist der gesamte Code für unsere Krypto-Blockchain-Klasse in 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)

Lassen Sie uns nun versuchen, unseren Code auszuführen, um zu sehen, ob wir einige digitale Münzen generieren können ...

Wow, es hat funktioniert!

Abschluss

Das ist es!

Wir hoffen, dass dieser Artikel Ihnen geholfen hat, die zugrunde liegende Technologie zu verstehen, die Kryptowährungen wie Bitcoin und Ethereum antreibt.

Wir haben gerade die Grundideen veranschaulicht, um Ihre Füße in der innovativen Blockchain-Technologie nass zu machen. Das obige Projekt kann noch verbessert werden, indem andere Funktionen integriert werden, um es nützlicher und robuster zu machen.

Создайте свой собственный блокчейн криптовалюты на Python

Криптовалюта - это децентрализованная цифровая валюта, в которой используются методы шифрования для регулирования генерации денежных единиц и проверки перевода средств. Анонимность, децентрализация и безопасность - одни из его основных характеристик. Криптовалюта не регулируется и не отслеживается каким-либо централизованным органом, правительством или банком.

Блокчейн, децентрализованная одноранговая (P2P) сеть, состоящая из блоков данных, является неотъемлемой частью криптовалюты. Эти блоки хранят информацию о транзакциях в хронологическом порядке и придерживаются протокола для межузловой связи и проверки новых блоков. Данные, записанные в блоках, не могут быть изменены без изменения всех последующих блоков.

В этой статье мы собираемся объяснить, как создать простой блокчейн с помощью языка программирования Python.

Вот базовый план класса Python, который мы будем использовать для создания блокчейна:

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

Теперь давайте объясним, как работает класс блокчейна.

Начальная структура класса блоков

Вот код нашего начального класса блока:

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()

Как вы можете видеть выше, конструктор класса или метод инициации ( init ()) выше принимает следующие параметры:

self- как и любой другой класс Python, этот параметр используется для ссылки на сам класс. С его помощью можно получить доступ к любой переменной, связанной с классом.

index - он используется для отслеживания положения блока в цепочке блоков.

previous_hash - он использовался для ссылки на хэш предыдущего блока в цепочке блоков.

data—it предоставляет подробную информацию о проведенных транзакциях, например, купленную сумму.

timestamp—it вставляет отметку времени для всех выполненных транзакций.

Второй метод в классе, compute_hash, используется для создания криптографического хэша каждого блока на основе вышеуказанных значений.

Как видите, мы импортировали алгоритм SHA-256 в проект блокчейна криптовалюты, чтобы помочь в получении хэшей блоков.

Как только значения будут помещены в модуль хеширования, алгоритм вернет 256-битную строку, обозначающую содержимое блока.

Итак, это то, что дает неизменяемость блокчейна. Поскольку каждый блок будет представлен хешем, который будет вычисляться из хеша предыдущего блока, повреждение любого блока в цепочке приведет к тому, что другие блоки будут иметь недопустимые хеши, что приведет к поломке всей сети блокчейна.

Построение цепочки

Вся концепция блокчейна основана на том факте, что блоки «связаны» друг с другом. Теперь мы создадим класс цепочки блоков, который будет играть важную роль в управлении всей цепочкой.

Он будет хранить данные транзакций и включать другие вспомогательные методы для выполнения различных ролей, таких как добавление новых блоков.

Поговорим о вспомогательных методах.

Добавление метода конструктора

Вот код:

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

Метод конструктора init () - это то, что создает экземпляр блокчейна.

Вот роли его атрибутов:

self.chain - в этой переменной хранятся все блоки.

self.current_data - в этой переменной хранится информация о транзакциях в блоке.

self.build_genesis () - этот метод используется для создания начального блока в цепочке.

Создание блока генезиса

build_genesis()Метод используется для создания начального блока в цепочке, то есть, блок без каких - либо предшественников. Блок генезиса - это то, что представляет собой начало блокчейна.

Чтобы создать его, мы вызовем build_block()метод и дадим ему значения по умолчанию. Оба параметра proof_numberи previous_hashимеют нулевое значение, хотя вы можете присвоить им любое значение, которое пожелаете.

Вот код:

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

Подтверждение действительности блокчейна

Этот confirm_validityметод имеет решающее значение для проверки целостности цепочки блоков и проверки отсутствия несоответствий.

Как объяснялось ранее, хэши имеют решающее значение для обеспечения безопасности блокчейна криптовалюты, потому что любое небольшое изменение в объекте приведет к созданию совершенно другого хэша.

Таким образом, confirm_validityметод использует серию операторов if для оценки того, был ли скомпрометирован хэш каждого блока.

Кроме того, он также сравнивает хеш-значения каждых двух последовательных блоков для выявления любых аномалий. Если цепочка работает правильно, возвращается истина; в противном случае возвращается false.

Вот код:

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

Объявление данных транзакций

get_dataМетод имеет важное значение в объявлении данных об операциях на блоке. Этот метод принимает три параметра (информацию об отправителе, информацию о получателе и сумму) и добавляет данные транзакции в список self.current_data.

Вот код:

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

Выполнение доказательства работы

В технологии блокчейн Proof of Work (PoW) относится к сложности, связанной с майнингом или генерацией новых блоков в блокчейне.

Например, PoW может быть реализован путем определения числа, которое решает проблему всякий раз, когда пользователь выполняет некоторую вычислительную работу. Любой в сети блокчейн должен найти номер сложным для идентификации, но легким для проверки - это основная концепция PoW.

Таким образом, это препятствует распространению спама и нарушению целостности сети.

В этой статье мы покажем, как включить алгоритм Proof of Work в проект криптовалюты на блокчейне.

Завершение с последним блоком

Наконец, вспомогательный метод latest_block () используется для получения последнего блока в сети, который на самом деле является текущим блоком.

Вот код:

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

Внедрение Blockchain Mining

Теперь это самый интересный раздел!

Изначально транзакции хранятся в списке непроверенных транзакций. Майнинг относится к процессу размещения непроверенных транзакций в блоке и решения проблемы PoW. Это можно назвать вычислительной работой, связанной с проверкой транзакций.

Если все было правильно выяснено, блок создается или добывается и объединяется вместе с другими в цепочке блоков. Если пользователи успешно добыли блок, они часто получают вознаграждение за использование своих вычислительных ресурсов для решения проблемы PoW.

Вот метод майнинга в этом простом проекте блокчейна криптовалюты:

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)

Резюме

Вот весь код нашего класса криптоблокчейна на 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)

Теперь давайте попробуем запустить наш код, чтобы посмотреть, сможем ли мы сгенерировать несколько цифровых монет ...

Вау, сработало!

Заключение

Вот и все!

Мы надеемся, что эта статья помогла вам понять базовую технологию, на которой работают такие криптовалюты, как Биткойн и Эфириум.

Мы просто проиллюстрировали основные идеи, как сделать ваши ноги влажными в инновационной технологии блокчейн. Вышеупомянутый проект все еще можно улучшить, добавив другие функции, чтобы сделать его более полезным и надежным.

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.