Cree su propia cadena de bloques de criptomonedas en Python

La criptomoneda es una moneda digital descentralizada que utiliza técnicas de cifrado para regular la generación de unidades monetarias y verificar la transferencia de fondos. El anonimato, la descentralización y la seguridad se encuentran entre sus principales características. La criptomoneda no está regulada ni rastreada por ninguna autoridad centralizada, gobierno o banco.

Blockchain, una red descentralizada de igual a igual (P2P), que se compone de bloques de datos, es una parte integral de la criptomoneda. Estos bloques almacenan cronológicamente información sobre transacciones y se adhieren a un protocolo para la comunicación entre nodos y la validación de nuevos bloques. Los datos registrados en bloques no se pueden alterar sin la alteración de todos los bloques posteriores.

En este artículo, explicaremos cómo puede crear una cadena de bloques simple utilizando el lenguaje de programación Python.

Aquí está el plano básico de la clase Python que usaremos para crear la cadena de bloques:

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

Ahora, expliquemos cómo funciona la clase blockchain.

Estructura inicial de la clase de bloque

Aquí está el código para nuestra clase de bloque inicial:

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

Como puede ver arriba, el constructor de la clase o el método de iniciación ( init ()) anterior toma los siguientes parámetros:

self- al igual que cualquier otra clase de Python, este parámetro se utiliza para hacer referencia a la clase en sí. Se puede acceder a cualquier variable asociada con la clase usándola.

index - se usa para rastrear la posición de un bloque dentro de la cadena de bloques.

previous_hash - solía hacer referencia al hash del bloque anterior dentro de la cadena de bloques.

data—it da detalles de las transacciones realizadas, por ejemplo, la cantidad comprada.

timestamp—it inserta una marca de tiempo para todas las transacciones realizadas.

El segundo método de la clase, compute_hash, se utiliza para producir el hash criptográfico de cada bloque basándose en los valores anteriores.

Como puede ver, importamos el algoritmo SHA-256 al proyecto de cadena de bloques de criptomonedas para ayudar a obtener los valores hash de los bloques.

Una vez que los valores se han colocado dentro del módulo hash, el algoritmo devolverá una cadena de 256 bits que denota el contenido del bloque.

Entonces, esto es lo que le da inmutabilidad a la cadena de bloques. Dado que cada bloque estará representado por un hash, que se calculará a partir del hash del bloque anterior, la corrupción de cualquier bloque de la cadena hará que los otros bloques tengan hash no válidos, lo que provocará la rotura de toda la red blockchain.

Construyendo la Cadena

Todo el concepto de una cadena de bloques se basa en el hecho de que los bloques están "encadenados" entre sí. Ahora, crearemos una clase de blockchain que desempeñará el papel fundamental de administrar toda la cadena.

Mantendrá los datos de las transacciones e incluirá otros métodos auxiliares para completar varios roles, como agregar nuevos bloques.

Hablemos de los métodos de ayuda.

Agregar el método constructor

Aquí está el código:

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

El método constructor init () es lo que crea una instancia de la cadena de bloques.

Aquí están los roles de sus atributos:

self.chain : esta variable almacena todos los bloques.

self.current_data : esta variable almacena información sobre las transacciones en el bloque.

self.build_genesis () : este método se utiliza para crear el bloque inicial en la cadena.

Construyendo el Bloque Génesis

El build_genesis()método se utiliza para crear el bloque inicial en la cadena, es decir, un bloque sin predecesores. El bloque de génesis es lo que representa el comienzo de la cadena de bloques.

Para crearlo, llamaremos al build_block()método y le daremos algunos valores predeterminados. A los parámetros proof_numbery se previous_hashles asigna un valor de cero, aunque puede darles el valor que desee.

Aquí está el código:

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

Confirmación de la validez de Blockchain

El confirm_validitymétodo es fundamental para examinar la integridad de la cadena de bloques y asegurarse de que falten inconsistencias.

Como se explicó anteriormente, los hash son fundamentales para darse cuenta de la seguridad de la cadena de bloques de criptomonedas, porque cualquier ligera alteración en un objeto resultará en la creación de un hash completamente diferente.

Por lo tanto, el confirm_validitymétodo utiliza una serie de declaraciones if para evaluar si el hash de cada bloque se ha visto comprometido.

Además, también compara los valores hash de cada dos bloques sucesivos para identificar cualquier anomalía. Si la cadena funciona correctamente, devuelve verdadero; de lo contrario, devuelve falso.

Aquí está el código:

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

Declaración de datos de transacciones

El get_datamétodo es importante para declarar los datos de las transacciones en un bloque. Este método toma tres parámetros (información del remitente, información del destinatario y monto) y agrega los datos de la transacción a la lista self.current_data.

Aquí está el código:

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

Efectuar la prueba de trabajo

En la tecnología blockchain, Proof of Work (PoW) se refiere a la complejidad involucrada en la minería o la generación de nuevos bloques en blockchain.

Por ejemplo, el PoW se puede implementar identificando un número que resuelve un problema cada vez que un usuario completa algún trabajo informático. Cualquiera en la red blockchain debería encontrar el número complejo de identificar pero fácil de verificar: este es el concepto principal de PoW.

De esta manera, desalienta el envío de spam y compromete la integridad de la red.

En este artículo, ilustraremos cómo incluir un algoritmo de Prueba de trabajo en un proyecto de criptomoneda blockchain.

Finalizando con el último bloque

Finalmente, el método auxiliar latest_block () se usa para recuperar el último bloque en la red, que en realidad es el bloque actual.

Aquí está el código:

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

Implementando Blockchain Mining

¡Ahora, esta es la sección más emocionante!

Inicialmente, las transacciones se mantienen en una lista de transacciones no verificadas. La minería se refiere al proceso de colocar las transacciones no verificadas en un bloque y resolver el problema de PoW. Puede denominarse el trabajo informático involucrado en la verificación de las transacciones.

Si todo se ha resuelto correctamente, se crea o extrae un bloque y se une con los demás en la cadena de bloques. Si los usuarios han extraído un bloque con éxito, a menudo se les recompensa por utilizar sus recursos informáticos para resolver el problema de PoW.

Aquí está el método de minería en este simple proyecto de cadena de bloques de criptomonedas:

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)

Resumen

Aquí está el código completo para nuestra clase de cadena de bloques de cifrado 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)

Ahora, intentemos ejecutar nuestro código para ver si podemos generar algunas monedas digitales ...

¡Vaya, funcionó!

Conclusión

¡Eso es!

Esperamos que este artículo le haya ayudado a comprender la tecnología subyacente que impulsa las criptomonedas como Bitcoin y Ethereum.

Acabamos de ilustrar las ideas básicas para mojarse los pies en la innovadora tecnología blockchain. El proyecto anterior aún se puede mejorar incorporando otras características para hacerlo más útil y robusto.

What is GEEK

Buddha Community

Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

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