The Blockchain Technology

The Blockchain Technology

We can say that blockchain is the technology of bitcoin and other cryptocurrencies, but these are only part of the entire spectrum that encompasses both concept and technology.

The technology really has its origins in 1991, when Stuart Haber and W. Scott Stornetta described the first process on a chain of insured blocks cryptographically, later, in 2008 it began to be popular with the arrival of bitcoin and today the demand for this technology is covering other scenarios such as commercial applications, which predicts an annual growth of 51% by 2022 in several markets, such as the financial sector and the Internet of Things (IoT) among others. agreement with publications of MarketWatch.

In 2008, an article entitled Bitcoin: a peer-to-peer electronic money system It was published by Satoshi Nakamoto. The article describes the combination of cryptographic techniques and a peer-to-peer network without the need to rely on a centralized authority (as banks do) to make payments from one person to another.

The same article introduces a distributed system for storing information (now called "blockchain"), which has a much wider field of application than just payments or cryptocurrencies.

Since then, interest in the blockchain has grown practically in all sectors. So Blockchain is now the technology under fully digital cryptocurrencies like Bitcoin, distributed computing technologies like Ethereum, and open source frameworks like Hyperledger Fabric, on which the IBM Blockchain Platform.

The term Blockchain refers to a chain of blocks that establish a record only, agreed upon Y distributed in several nodes of a network. In the case of cryptocurrencies, it could be said that it is the accounting bitacora where all transactions are recorded. That is, in each block it is stored:

  • A number of valid records or transactions
  • Information regarding that block
  • Your link with the previous block and the next block

Each block has a unique identifier of the type hash which represents the fingerprint of the block.

In this sense, each block has a specific place and immovable within the chain, since in each block there is information from the hash of the previous block, and the one linked to the later one.

The entire chain is stored in each node of the network that makes up the blockchain, an exact copy of the chain is stored in everyone the participating nodes of the network.

As new transactions or registrations are created, these are verified Y validated by the nodes of the network and later added to a new block that is linked to the chain.

Diagram of the block chain

Since it is a technology distributed where each node in the network stores an exact copy of the string, the availability of information is guaranteed at all times. If a node in the network suffers breakdowns or attacks, the information is available in the other nodes.

The integrity of the information is also insured given that being a record agreed upon, all the nodes contain the same information and to alter the information it would be necessary to modify it in the whole chain or in at least 51% of the nodes.

At the same time, since each block is linked to the next block, once a new block is added to the chain, it becomes unalterable, if a block is modified, its relation with the chain is broken, therefore, all the information registered in the blocks is immutable Y life.

In this sense, blockchain allows you to store information that can never be lose, modify or eliminate.

Certificates and digital signatures are used in each node of the network to verify the information and validate the transactions, as well as the data stored in the chain, thus enabling the authenticity of the information.

Uses of Blockchain

Blockchain can be used to certify and validate any type of information, as well as store important documents, such as deeds without relying on third parties.

In general, any type of information that needs to be preserved intact and that must remain available in a secure, decentralized and cheaper way than through intermediaries. If this information is stored encrypted, its confidentiality can be guaranteed since only those who have the encryption key will be able to access it.

Health sector

Health records could be unified and stored in blockchain so that patients' medical records are kept safe and at the same time available to each authorized physician, regardless of health service.

The pharmaceutical industry could use blockchain to validate and verify medicines and thereby avoid counterfeiting.

Internet of Things (IoT)

The challenge for blockchain rests with the millions of devices connected to the Internet, given that the centralized model will not support the number of devices that are increasing every time. With blockchain devices can communicate through the network safely, directly and reliably, without intermediaries.

As it mentioned above, Blockchain allows to verify, validate, track and store all types of information, from digital certificates, logistics and messaging services, smart contracts, money, financial transactions, as well as democratic election systems, among others.

The Blockchain Council

The Blockchain Council (Blockchain Council) is an authorized group of experts and enthusiasts whose work is to promote research, development and evangelize about cases of use, products and knowledge related to technology. Blockchain to achieve a better world.

The Blockchain technology is emerging rapidly with a wide scope in the future.

Blockchain acts as a financial network, a software, a distributed ledger, etc. Due to this great variety of benefits and characteristics, companies are now changing their centralized and traditional work system to this futuristic technology.

The Blockchain board creates an environment and creates awareness among companies, developers and society by educating them on Blockchain topics. 

Programming for Blockchain

The blockchain council has several courses and certifications interesting to develop applications for blockchain, there are even tutorials to develop and implement a public blockchain from scratch with a simple application to deploy it.

Create access points for different blockchain functions, such as adding a transaction using the Flask microframework, running the programs on multiple machines to create a decentralized network. The examples also show the development of a user interface to interact with the blockchain and store information for any use such as payments, peer-to-peer, conversations, electronic commerce, etc.


Blockchain with Python

In this example, a public blockchain is created, managed by the server_id application, and information is stored in JSON format

{"author": "author_name", "content": "Information the author wants to share", "timestamp": "The time the content was created"}

server_host.py

266 lines (203 sloc) 7.44 KB
desde hashlib import sha256
import json
import time
desde flask import Flask, request
import requests
class Block:
def __init__(self, index, transactions, timestamp, previous_hash):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous_hash = previous_hash
self.nonce = 0
def compute_hash(self):
"" "
A function that return the hash of the block contents.
"" "
block_string = json.dumps (self.__dict__, sort_keys=True)
return sha256 (block_string.encode ()). hexdigest ()
class Blockchain:
# difficulty of our PoW algorithm
difficulty = 2
def __init__(self):
self.unconfirmed_transactions = []
self.chain = []
self.create_genesis_block ()
def create_genesis_block(self):
"" "
A function to generate genesis block and appends it to
the chain. The block has index 0, previous_hash as 0, and
a valid hash.
"" "
genesis_block = Block (0, [], time.time (), "0")
genesis_block.hash = genesis_block.compute_hash ()
self.chain.append (genesis_block)
@property
def last_block(self):
return self.chain [1]
def add_block(self, block, proof):
"" "
A function that adds the block to the chain after verification.
Verification includes:
* Checking if the proof is valid.
* The previous_hash referred to in the block and the hash of the last block
in the chain match.
"" "
previous_hash = self.last_block.hash
if previous_hash != block.previous_hash:
return False
if not Blockchain.is_valid_proof (block, proof):
return False
block.hash = proof
self.chain.append (block)
return True
def proof_of_work(self, block):
"" "
Function that tries different values ​​of nonce to get a hash
that satisfies our difficulty criteria.
"" "
block.nonce = 0
computed_hash = block.compute_hash ()
while not computed_hash.startswith ('0' * Blockchain.difficulty):
block.nonce += 1
computed_hash = block.compute_hash ()
return computed_hash
def add_new_transaction(self, transaction):
self.unconfirmed_transactions.append (transaction)
@classmethod
def is_valid_proof(cls, block, block_hash):
"" "
Check if block_hash is valid hash of block and satisfies
the difficulty criteria
"" "
return (block_hash.startswith ('0' * Blockchain.difficulty) and
block_hash == block.compute_hash ())
@classmethod
def check_chain_validity(cls, chain):
result = True
previous_hash = "0"
for block in chain:
block_hash = block.hash
# remove the hash field to recompute the hash again
# using `compute_hash` method.
delattr(block, "hash")
if not cls.is_valid_proof (block, block.hash) or \
previous_hash != block.previous_hash:
result = False
break
block.hash, previous_hash = block_hash, block_hash
return result
def mine(self):
"" "
This function serves as an interface to add the pending
transactions to the blockchain by adding them to the block
and figuring out Proof Of Work.
"" "
if not self.unconfirmed_transactions:
return False
last_block = self.last_block
new_block = Block (index=last_block.index + 1,
transactions=self.unconfirmed_transactions,
timestamp=time.time (),
previous_hash=last_block.hash)
proof = self.proof_of_work (new_block)
self.add_block (new_block, proof)
self.unconfirmed_transactions = []
# announce it to the network
announce_new_block (new_block)
return new_block.index
app = Flask (__yam__)
# the node's copy of blockchain
blockchain = Blockchain ()
# the address to other participating members of the network
peers = set()
# endpoint to submit a new transaction. This will be used by
# our application to add new data (posts) to the blockchain
@ app.route('/ new_transaction', methods=['POST'])
def new_transaction():
tx_data = request.get_json ()
required_fields = ["author", "content"]
for field in required_fields:
if not tx_data.get (field):
return "Invlaid transaction data", 404
tx_data ["timestamp"] = time.time ()
blockchain.add_new_transaction (tx_data)
return "Success", 201
# endpoint to return the node's copy of the chain.
# Our application will be using this endpoint to query
# all the posts to display.
@ app.route('/ chain', methods=['GET'])
def get_chain():
# make sure we've the longest chain
consensus ()
chain_data = []
for block in blockchain.chain:
chain_data.append (block.__dict__)
return json.dumps ({"length": len(chain_data),
"chain": chain_data})
# endpoint to request the node to mine the unconfirmed
# transactions (if any). We'll be using it to initiate
# a command to mine from our application itself.
@ app.route('/ mine', methods=['GET'])
def mine_unconfirmed_transactions():
result = blockchain.mine ()
if not result:
return "No transactions to mine"
return "Block #{} is mined.".format (result)
# endpoint to add new peers to the network.
@ app.route('/ add_nodes', methods=['POST'])
def register_new_peers():
do not give = request.get_json ()
if not do not give:
return "Invalid data", 400
for do not give in do not give:
peers.add (node)
return "Success", 201
# endpoint to add a block mined by someone else to
# the node's chain. The block is first verified by the node
# and then added to the chain.
@ app.route('/ add_block', methods=['POST'])
def validate_and_add_block():
block_data = request.get_json ()
block = Block (block_data ["index"],
block_data ["transactions"],
block_data ["timestamp",
block_data ["previous_hash"]])
proof = block_data ['hash']
added = blockchain.add_block (block, proof)
if not added:
return "The block was discarded by the node", 400
return "Block added to the chain", 201
# endpoint to query unconfirmed transactions
@ app.route('/ pending_tx')
def get_pending_tx():
return json.dumps (blockchain.unconfirmed_transactions)
def consensus():
"" "
Our simple consnsus algorithm. If a longer valid chain is
found, our chain is replaced with it.
"" "
global blockchain
longest_chain = None
current_len = len(blockchain.chain)
for do not give in peers:
response = requests.get ('http: //{}/ chain'.format (node))
length = response.json () ['length']
chain = response.json () ['chain']
if length > current_len and blockchain.check_chain_validity (chain):
current_len = length
longest_chain = chain
if longest_chain:
blockchain = longest_chain
return True
return False
def announce_new_block(block):
"" "
A function to announce to the network once a block has been mined.
Other blocks can simply verify the proof of work and add it to their
respective chains.
"" "
for peer in peers:
url = "http: //{}/ add_block".format (peer)
requests.post (url, data=json.dumps (block.__dict__, sort_keys=True))
app.run (debug=True, port=8000)

The view of the client application is as follows with the view.py file

73 lines (55 sloc) 1.96 KB
import datetime
import json
import requests
desde flask import render_template, redirect, request
desde app import app
# The node with which our application interacts, there can be multiple
# such nodes as well.
CONNECTED_NODE_ADDRESS = "http://127.0.0.1:8000"
posts = []
def fetch_posts():
"" "
Function to fetch the chain from a blockchain node, parse the
data and store it locally.
"" "
get_chain_address = "{}/ chain".format (CONNECTED_NODE_ADDRESS)
response = requests.get (get_chain_address)
if response.status_code == 200:
content = []
chain = json.loads (response.content)
for block in chain ["chain"]:
for tx in block ["transactions"]:
tx ["index"] = block ["index"]
tx ["hash"] = block ["previous_hash"]
content.append (tx)
global posts
posts = sorted(content, key=lambda k: k ['timestamp'],
reverse=True)
@ app.route('/')
def index():
fetch_posts ()
return render_template ('index.html',
title='YourNet: Decentralized '
'content sharing',
posts=posts,
node_address=CONNECTED_NODE_ADDRESS,
readable_time=timestamp_to_string)
@ app.route('/ submit', methods=['POST'])
def submit_textarea():
"" "
Endpoint to create a new transaction via our application.
"" "
post_content = request.form ["content"]
author = request.form ["author"]
post_object = {
'author'Author
'content': post_content,
}
# Submit a transaction
new_tx_address = "{}/ new_transaction".format (CONNECTED_NODE_ADDRESS)
requests.post (new_tx_address,
json=post_object,
headers={'Content-type': 'application / json'})
return redirect ('/')
def timestamp_to_string(epoch_time):
return datetime.datetime.fromtimestamp (epoch_time) .strftime ('% H:% M')

conclusion

This example covers the basics of a public blockchain. It implements a blockchain from scratch and creates a simple application allowing users to share information in it.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x

JacobSoft

Receive notifications of new articles and tutorials every time a new one is added

Thank you, you have subscribed to the blog and the newsletter

There was an error while trying to send your request. Please try again.

JacobSoft will use the information you provide to be in contact with you and send you updates.