Crie seu próprio blockchain de criptomoeda em Python

A criptomoeda é uma moeda digital descentralizada que usa técnicas de criptografia para regular a geração de unidades monetárias e para verificar a transferência de fundos. Anonimato, descentralização e segurança estão entre suas principais características. A criptomoeda não é regulamentada ou rastreada por nenhuma autoridade centralizada, governo ou banco.

Blockchain, uma rede ponto a ponto descentralizada (P2P), que é composta por blocos de dados, é parte integrante da criptomoeda. Esses blocos armazenam cronologicamente informações sobre transações e aderem a um protocolo para comunicação entre nós e validação de novos blocos. Os dados gravados em blocos não podem ser alterados sem a alteração de todos os blocos subsequentes.

Neste artigo, vamos explicar como você pode criar um blockchain simples usando a linguagem de programação Python.

Aqui está o projeto básico da classe Python que usaremos para criar o 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

Agora, vamos explicar como a classe blockchain funciona.

Estrutura Inicial da Classe de Bloco

Aqui está o código para nossa classe de bloco 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 você pode ver acima, o construtor de classe ou método de iniciação ( init ()) acima usa os seguintes parâmetros:

self- assim como qualquer outra classe Python, este parâmetro é usado para se referir à própria classe. Qualquer variável associada à classe pode ser acessada usando-a.

index - é usado para rastrear a posição de um bloco dentro do blockchain.

previous_hash - usado para fazer referência ao hash do bloco anterior dentro do blockchain.

data—it dá detalhes das transações realizadas, por exemplo, a quantidade comprada.

timestamp—it insere um carimbo de data / hora para todas as transações realizadas.

O segundo método da classe, compute_hash, é usado para produzir o hash criptográfico de cada bloco com base nos valores acima.

Como você pode ver, importamos o algoritmo SHA-256 para o projeto blockchain de criptomoeda para ajudar a obter os hashes dos blocos.

Uma vez que os valores tenham sido colocados dentro do módulo de hashing, o algoritmo retornará uma string de 256 bits denotando o conteúdo do bloco.

Então, é isso que dá imutabilidade ao blockchain. Como cada bloco será representado por um hash, que será calculado a partir do hash do bloco anterior, corromper qualquer bloco da cadeia fará com que os outros blocos tenham hashes inválidos, resultando na quebra de toda a rede do blockchain.

Construindo a Rede

Todo o conceito de blockchain é baseado no fato de que os blocos são “encadeados” entre si. Agora, criaremos uma classe blockchain que desempenhará a função crítica de gerenciar toda a cadeia.

Ele manterá os dados das transações e incluirá outros métodos auxiliares para completar várias funções, como adicionar novos blocos.

Vamos falar sobre os métodos auxiliares.

Adicionando o Método do Construtor

Aqui está o código:

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

O método do construtor init () é o que instancia o blockchain.

Aqui estão as funções de seus atributos:

self.chain - esta variável armazena todos os blocos.

self.current_data - esta variável armazena informações sobre as transações no bloco.

self.build_genesis () - este método é usado para criar o bloco inicial na cadeia.

Construindo o Bloco Genesis

O build_genesis()método é usado para criar o bloco inicial da cadeia, ou seja, um bloco sem predecessores. O bloco de gênese é o que representa o início do blockchain.

Para criá-lo, chamaremos o build_block()método e forneceremos alguns valores padrão. Os parâmetros proof_numbere previous_hashrecebem o valor zero, embora você possa fornecer qualquer valor que desejar.

Aqui está o 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

Confirmando a Validade do Blockchain

O confirm_validitymétodo é fundamental para examinar a integridade do blockchain e garantir que haja inconsistências.

Conforme explicado anteriormente, os hashes são essenciais para realizar a segurança do blockchain da criptomoeda, porque qualquer pequena alteração em um objeto resultará na criação de um hash totalmente diferente.

Assim, o confirm_validitymétodo utiliza uma série de declarações if para avaliar se o hash de cada bloco foi comprometido.

Além disso, ele também compara os valores de hash de cada dois blocos sucessivos para identificar quaisquer anomalias. Se a cadeia estiver funcionando corretamente, ele retorna verdadeiro; caso contrário, retorna falso.

Aqui está o 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

Declaração de dados de transações

O get_datamétodo é importante para declarar os dados das transações em um bloco. Este método usa três parâmetros (informações do remetente, informações do receptor e quantidade) e adiciona os dados da transação à lista self.current_data.

Aqui está o código:

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

Efetuando a Prova de Trabalho

Na tecnologia blockchain, Prova de Trabalho (PoW) se refere à complexidade envolvida na mineração ou geração de novos blocos no blockchain.

Por exemplo, o PoW pode ser implementado identificando um número que resolve um problema sempre que um usuário conclui algum trabalho de computação. Qualquer pessoa na rede blockchain deve achar o número complexo de identificar, mas fácil de verificar - este é o conceito principal de PoW.

Dessa forma, desestimula o spamming e compromete a integridade da rede.

Neste artigo, ilustraremos como incluir um algoritmo de Prova de Trabalho em um projeto de criptomoeda blockchain.

Finalizando com o Último Bloco

Finalmente, o método auxiliar latest_block () é usado para recuperar o último bloco na rede, que é na verdade o bloco atual.

Aqui está o código:

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

Implementando Blockchain Mining

Agora, esta é a seção mais emocionante!

Inicialmente, as transações são mantidas em uma lista de transações não verificadas. Mineração se refere ao processo de colocar as transações não verificadas em um bloco e resolver o problema de PoW. Pode ser referido como o trabalho de computação envolvido na verificação das transações.

Se tudo foi descoberto corretamente, um bloco é criado ou extraído e unido com os outros no blockchain. Se os usuários extraíram um bloco com sucesso, eles geralmente são recompensados ​​por usar seus recursos de computação para resolver o problema de PoW.

Aqui está o método de mineração neste projeto simples de blockchain de criptomoeda:

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)

Resumo

Aqui está todo o código para nossa classe crypto blockchain em 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)

Agora, vamos tentar executar nosso código para ver se podemos gerar algumas moedas digitais ...

Uau, funcionou!

Conclusão

É isso!

Esperamos que este artigo tenha ajudado você a entender a tecnologia subjacente que alimenta criptomoedas como Bitcoin e Ethereum.

Acabamos de ilustrar as idéias básicas para deixar seus pés molhados na tecnologia inovadora de blockchain. O projeto acima ainda pode ser aprimorado incorporando outros recursos para torná-lo mais útil e robusto.

What is GEEK

Buddha Community

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

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