Build Your Own AdBlocker in (Literally) 10 Minutes

Browser extensions always fascinated me.They are quite underrated these days, especially with the move from desktop to mobile browsing. However, I love the idea of customizing the websites I visit to my own liking, such as to enhance my privacy online.Today I decided to share with you how to build a fully-functional extension to block LinkedIn ads, in just 10 minutes.Believe it or not, extensions are probably the easiest thing you can build, so let’s cut to the chase and in order to really do this in 10 minutes.

_Disclaimer: _This extension will only work for Chromium-based browsers e.g. Chrome, Brave, Opera, Microsoft Edge (yeah, really), etc. In other words, it won’t work on Firefox or Safari.

Setup

_As always, all the code is on GitHub. To make things really simple, our extension will not actually have a pop-up (the little window that appears when you click an extension’s icon) — it will simply be working in the background.
As such, all we really need are 3 files. These are:manifest.json , background.js and linkedin.js.
Thus, Step 1 is: Make an empty repository and create those files inside.Now, let’s go through their content.

manifest.json

manifest.json is the only essential file an extension needs. In our case, it will contain metadata about the extension, the permissions it needs to operate, and the script it should run in the background. Here’s what it looks like:

{
	    "manifest_version": 2,
	    "name": "LinkedIn AdBlocker",
	    "description": "Blocking ads.",
	    "version": "0.0.1",
	    "author": "<AUTHOR_NAME>",
	    "browser_action": {
	        "default_title": "LinkedIn AdBlocker"
	    },
	    "permissions": [
	        "tabs",
	        "webNavigation",
	        "https://www.linkedin.com/"
	    ],
	    "background": {
	        "scripts": [
	            "extension.js"
	        ]
	    }
	}

Besides the metadata, here’s a bit of info on the important things this manifest is setting up for us:

Permissions

permissions establish what your extension is allowed to do, such as getting the URL of the current page, or adding JavaScript to a website.When you’re publishing your extension somewhere like the Chrome Web Store, you’ll be asked to justify each permission you’re requesting access to, in order to ensure the security and privacy of your users.Here, we’re asking for permissions for tabs and webNavigation in order to know when we’re visiting a new website, as well as what that website is. We need this to check if the website is LinkedIn so we can launch our adblocking script.

#javascript #privacy #software-engineering #programming #productivity

What is GEEK

Buddha Community

Build Your Own AdBlocker in (Literally) 10 Minutes

The Best Way to Build a Chatbot in 2021

A useful tool several businesses implement for answering questions that potential customers may have is a chatbot. Many programming languages give web designers several ways on how to make a chatbot for their websites. They are capable of answering basic questions for visitors and offer innovation for businesses.

With the help of programming languages, it is possible to create a chatbot from the ground up to satisfy someone’s needs.

Plan Out the Chatbot’s Purpose

Before building a chatbot, it is ideal for web designers to determine how it will function on a website. Several chatbot duties center around fulfilling customers’ needs and questions or compiling and optimizing data via transactions.

Some benefits of implementing chatbots include:

  • Generating leads for marketing products and services
  • Improve work capacity when employees cannot answer questions or during non-business hours
  • Reducing errors while providing accurate information to customers or visitors
  • Meeting customer demands through instant communication
  • Alerting customers about their online transactions

Some programmers may choose to design a chatbox to function through predefined answers based on the questions customers may input or function by adapting and learning via human input.

#chatbots #latest news #the best way to build a chatbot in 2021 #build #build a chatbot #best way to build a chatbot

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

What is BUILD Finance (BUILD) | What is BUILD Finance token | What is BUILD token

BUILD Finance DAO

The document is non-binding. Some information may be outdated as we keep evolving.

BUILD Philosophy

BUILD Finance is a decentralised autonomous venture builder, owned and controlled by the community. BUILD Finance produces, funds, and manages community-owned DeFi products.

There are five core activities in which the venture BUILDers engage:

  1. Identifying business ideas,
  2. Organising teams,
  3. Sourcing capital,
  4. Helping govern the product entities, and
  5. Providing shared services.

BUILD operates a shared capabilities model, where the DAO provides the backbone support and ensures inter-entity synergies so that the product companies can focus on their own outcomes.

BUILD takes care of all organisational, hiring, back/mid office functions, and the product companies focus on what they can do best, until such time where any individual product outgrows the DAO and becomes fully self-sustainable. At that point, the chick is strong enough to leave the nest and live its own life. The survival of the fittest. No product entity is held within DAO by force.

Along the way, BUILD utilises the investment banking model, which, in its essence, is a process of creating assets, gearing them up, and then flipping them into a fund or setting them as income-generating business systems, all this while taking fees along the way at each step. BUILD heavily focuses on integrating each asset/product with each other to boost productive yield and revenues. For example, BUILD’s OTC Market may be integrated with Metric Exchange to connect the liquidity pools with the trading traffic. The net result – pure synergy that benefits each party involved, acting in a self-reinforcing manner.

El Espíritu de la Colmena (The Spirit of the Beehive)

BUILD is a hive and is always alive. While some members may appear more active than others, there’s no central source of control or “core teams” as such. BUILD is work in progress where everyone is encouraged to contribute.

Following the natural free market forces, BUILD only works on those products that members are wanting to work on themselves and that they believe have economic value. Effectively, every builder is also a user of BUILD’s products. We are DeFi users that fill the gaps in the ecosystem. Any member can contribute from both purely altruistic or ultra-mercantile intentions – it’s up to the wider community to decide what is deemed valuable and what product to support. The BUILD community is a sovereign individual that votes with their money and feet.

BUILD members = BUILD users. It’s that simple.

$BUILD TOKEN

Tokenomics

$BUILD token is used as a governance token for the DAO. It also represents a pro-rata claim of ownership on all DAO’s assets and liabilities (e.g. BUILD Treasury and $bCRED debt token).

The token was distributed via liquidity mining with no pre-sale and zero founder/private allocation. The farming event lasted for 7 days around mid-Sep 2020. At the time, BUILD didn’t have any products and held no value. Arguably, $BUILD has still zero value as it is not a legal instrument and does not guarantee or promise any returns to anyone. See the launch announcement here https://medium.com/@BUILD_Finance/announcing-build-finance-dc08df585e57​

Initial supply was 100,000 $BUILD with 100% distributed via fair launch. Subsequently, the DAO unanimously voted to approve minting of extra 30,000 $BUILD and allocate them as:

  • 15,000 $BUILD (11.5%) to the founding member of the DAO (@0xdev0) with 1-year gradual vesting, and
  • 15,000 $BUILD (11.5%) to the DAO treasury as development funds.

For the proposal of the above see: https://forum.letsbuild.finance/t/proposal-2-fund-the-development-of-defi-lending-platform/24​

The voting took place at a later retired web-page https://vote.letsbuild.finance. The governance has since moved to Snapshot (link below). The results of the old proposals are not visible there, however, on-chain voting contract can be see here: https://etherscan.io/address/0xa8621477645f76b06a41c9393ddaf79ddee63daf#readContract​

$Build Token Repartition

Vesting Schedule

Minting keys are not burnt = $BUILD supply is not fixed as token holders can vote on minting new tokens for specific reasons determined by the token holders. For example, the DAO may mint additional tokens to incentivise usage of its products, which would, in turn, increase the value flow or TVL. Dilution is not in the economic benefit of the token holders, hence any such events has to be considered carefully.

Access to minting function is available via on-chain governance. A safe buffer is established in a form of the contract-enforced 24 hour delay, which should provide a sufficient time for the community to flag. Meaning that before such a transaction could be executed, everyone would be able to act in advance by withdrawing their funds / exiting from BUILD. Any malicious minting would, theoretically, result in an immediate market sell-off of $BUILD, making it economically detrimental to do such an action. This makes it highly improbable that any malicious minting would be performed_._

GOVERNANCE

All components of the BUILD DAO and the control over its have been decentralised:

  • All contracts (incl. the Treasury and Basis Gold) can be operated by $BUILD holders with on-chain proposals (see https://docs.build.finance/build-knowledge-base/on-chain-voting);
  • All social accounts (Discord, Telegram, and Twitter) are managed by multiple moderators;
  • All frontends (Metric Exchange, Basis Gold, and the BUILD homepage) are auto-deployed and managed by multiple devs.

TREASURY & DEVELOPMENT

BUILD DAO Treasury

The BUILD treasury has over $400k that can be managed by on-chain proposals and used in whichever way the community desires. For example, to hire developers. Having a functioning product, enough funds in the treasury and a fully decentralised governance has been a long-term goal since the inception in September 2020, and now it’s finally here.

Current holdings are (might be outdated):

  • Capital budget (dev / incentives fund) - 11,025 $BUILD (~$94k);
  • Operational budget (product development) - 204,300 $aDAI;
  • Ownership stake - 200,000 $METRIC (~$84k);
  • Ownership stake - 199,900 $UPDOWN(~$62k);
  • Ownership stake - 5,400 $HYPE (~$1.3k);
  • Ownership stake - 2% of $BSGS supply.
  • TOTAL: ~$445k

Funding of the Development

In an early stage, the development will be funded by an allocation of bCRED debt tokens for development expenses. After the first product was built (i.e. Metric Exchange), the DAO sold 5,000 $BUILD for 203,849 $DAI which will now be used for funding of other products or a combination of revenue + a smaller token allocation. This is up to the community to decide.

Smart Contract Audit

Contracts are not audited. It’s up to the BUILD community governance to decide how to spend our funds. If the community wants to spend any amount for auditing, a voting proposal can be initiated. As with any decisions and proposals, the cost-benefit analysis must be employed in regards to the economical sense of spending any funds on audit vs developing more products and expanding our revenue streams.

DAO Liabilities and $bCRED

$bCRED is a token that allowed the DAO to reward members for work before the DAO source sufficient funds. Effectively, $bCRED is a promissory note or an IOU to give back $DAI at 1:1 ratio, when the DAO starts generating revenues. Read more about $bCRED here: https://medium.com/@BUILD_Finance/what-is-bcred-b97e4cc75f8c.

“BUILDER” User Role in Discord

Since Discord is our primary coordination mechanism, we need to make effort to keep it focused on producing value. During the launch of METRIC, we’ve doubled our total number of users! This made it very difficult for existing users to explain what BUILD is about to new users and created a lot of confusion.

To help improve the quality of conversations, we’ve introduced a new user role called BUILDer. BUILDers will have write-access to product development channels while everyone else will only be able to read them. This should keep those product changes focused on actual productive conversations and make them more informative.

“GUARDIAN” Role in Discord

To increase our collective output as a community, a governance vote introduced an incentivisation mechanism for community contribution, tipping, and other small projects using our unique bCRED token (but may change in the future as required). These tokens are stewarded by active community members — “guardians’’ — who are free to allocate these funds to tip people for proactive work. Current guardians are @Son of Ishtar and @0xdev0, although anyone can propose the tip for anyone else. For more details see Proposal #15.

Hence, Guardians are defined as members of the DAO who are entrusted with a community budget for tipping other members for performing various small tasks.

PRODUCT SUITE & ROADMAP

  • Metric Exchange - is a DEX aggregator that allows for limit orders trading for any ERC-20 token via 0x relayer. Development continues with the product owner SHA_2048 and inputs from vfat. Live at metric.exchange.
  • Basis Gold - a synthetic, algorythmically-adjusted token pegged to the price of gold (sXAU) with elastic supply. Live at https://basis.gold/.
  • Updown Finance - binary options for volatility trading instrument (alpha is live at updown.finance).
  • Vortex - a lending & borrowing platform, which will target the long tail of assets that are currently not served by the existing DeFi money markets. Aiming to launch by March’2021.

The other immediate focus right now will be to make good use of our newly available funding and hire several product managers for other projects.

Please note that nothing is here set in stone. Just like any other start-up, we’ll keep experimenting, learning, and evolving. What’s listed here is just our current trajectory but it might change at any point.

SOCIAL MEDIA

Would you like to earn BUILD right now! ☞ CLICK HERE

Top exchanges for token-coin trading. Follow instructions and make unlimited money

BinanceBittrexPoloniexBitfinexHuobi

Thank you for reading!

#blockchain #cryptocurrency #build finance #build

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.

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.