SlideShare uma empresa Scribd logo
1 de 39
Blockchaina simple implementation
Tirana, 31 January 2018
Topics
• Intro
• What is a Blockchain?
• Why do we need such technology? What can it do for us…
• How does Blockchain work…
• Python Implementation of a Blockchain.
• Intro to IBM Hyperledger.
• Use case scenarios and real world usage, besides digital money ;)
• Open discussion, Q&A (as much as we can ☺)
What blockchain?!
• “A ledger”, public or private to record any type of transaction you are
able to express in terms of notable data.
• Ability to distribute it and maintain it through certain rules.
• In essence a data-structure and a set of rules defined by code.
“Jenny from the BLOCK”
The novelty and simplicity of the block that provide the full novelty of the blockchain. A simple head/body structure
that like in many data structures can store the relation and the data corresponding to that particular block.
A reference
from
Linked Lists ;)
references at the end
(1)
(2)
Do we really, really, really need it? What
for?
• Trust does not need to be asked, is given and is easily verified.
Saves
time
Reduces
cost
Reduces
risk
Increases
trust
Transaction time
from days to near
instantaneous
Overheads and
cost intermediaries
Tampering,
fraud, & cyber
crime
Through shared
processes and
recordkeeping
(3)
Hmm…and how does it work?
Hmm…and how does it work? 1.
Transactions
Tx:{
TxnID:String,
Input:TxIn[],
Output:TxOut[]
}
TxnID= function(public1,public2,amount){
return HashFunction1(public1,public2,amount);}
TxIn:{
PrevTxId:String,
PrevTxIndex:Int,
Signature:signature()
}
TxOut{
PublicAddress:String,
Amount:Int
}
function signature(TxnID,Private1){
return HashFunction2(TxnID,Private1);}
1. Transactions
2. T. Validation
• Amount Validation
• ID Validation
• Signature Validation
• Chain Validation
“This is a JavaScript's world, this is a JavaScript's
world; But it wouldn't be nothing, nothing
without some Python in it” James B. Coder the 3rd :P
In the next example we will try to demonstrate a minimal and simple
chain for a supposed scenario for storing any data into it.
Each block has the timestamp along with the index and a self-
identifying hash = where each hash will be a cryptographic hash of the
block’s index, timestamp, *data (random anything, notes), and the
hash of the previous block’s hash.
Requirements
• Python 3.6
• Python IDE (of your choice, we prefer IntelliJ PyCharm)
• Usage of hashlib library (no need for install in Virtual Env., only import it on Python 3.6 and PyCharm)
• Documentation: http://code.krypto.org/python/hashlib/
• Source: https://github.com/python/cpython/blob/2.7/Lib/hashlib.py
• …some spare time
1. Implementing the BLOCK
The number of variables inserted to the block is custom and you can change it according to your needs.
class Block:
def __init__(self, index, timestamp, previous_hash):
self.index = index
self.timestamp = timestamp
self.previous_hash = previous_hash
self.hash = self.hash_block()
def hash_block(self):
sha = hash_maker.sha256()
sha.update(str(self.index).encode('utf-8') +
str(self.timestamp).encode('utf-8') +
str(self.previous_hash).encode('utf-8'))
return sha.hexdigest()
2. Implementing the Genesis BLOCK
Having the block is not enough because if you put some focus into the
relation hash-to-hash, where does the first block related to? ☺
For that, the first block is called Genesis and
@staticmethod
def create_genesis_block():
return Block(0, datetime.datetime.now(), "0")
3. Giving birth to new BLOCKS
def next_block(last_block):
this_index = last_block.index + 1 # raise the index by one
this_timestamp = datetime.datetime.now() # current timestamp from the system
previous_hash = last_block.hash # relation among the block inside the chain
return Block(this_index, this_timestamp, previous_hash)
Remember: Relation is very important! It guarantees the continuity of consensus
;)
So… complete implementation of block.py
looks like this:
import hashlib as hash_maker
import datetime
class Block:
def __init__(self, index, timestamp, previous_hash):
self.index = index
self.timestamp = timestamp
self.previous_hash = previous_hash
self.hash = self.hash_block()
def hash_block(self):
sha = hash_maker.sha256()
sha.update(str(self.index).encode('utf-8') +
str(self.timestamp).encode('utf-8') +
str(self.previous_hash).encode('utf-8'))
return sha.hexdigest()
@staticmethod
def create_genesis_block():
return Block(0, datetime.datetime.now(), "0")
def next_block(last_block):
this_index = last_block.index + 1 # raise the index by one
this_timestamp = datetime.datetime.now() # current timestamp from the system
previous_hash = last_block.hash # relation among the block inside the chain
return Block(this_index, this_timestamp, previous_hash)
…and the actual simulation of the chain, in
test.py
import block
blockchain = [block.Block.create_genesis_block()] # Initialize the Blockchain with the genesis block
previous_block = blockchain[0] # Set the "head" / previous block to the first block
total_blocks = 5 # x = 5, where x is the number of simulated blocks
# Blockchain is filled
for i in range(0, total_blocks):
block_to_add = block.next_block(previous_block)
blockchain.append(block_to_add)
previous_block = block_to_add
print("Block #{} created".format(block_to_add.index - 1) + " with Hash: {}".format(block_to_add.hash))
Results, of course…after the first two or three fails ☺
Note:
sha = hash_maker.sha256()
sha.update()
Generally and with SHA-1
In the above example we used SHA-256, even harder to brake than SHA-1. Same input produces the same hash always. Is hard
to compute the initial state and one method would be to brute force manually all the possible combinations.
Question
What are we missing so far from the main
philosophy explained before in the current
primitive state solution?
no distribution – no decentralization
Answer
Distribution and Decentralization
Requirements
• above example +
• Flask Micro-Framework (to speed up the development)
In the following example we will demonstrate the ability to distribute
digital coins through proof-of-work.
Distribution 1. Flask Integration
from flask import Flask
from flask import request, Response
import stage_two.block
import datetime
import json
node = Flask(__name__)
miner_address = "for-testing-purposes-this-is-completely-random-but-should-be-unique" # miner's address in the
network
blockchain = []
blockchain.append(stage_two.block.Block.create_genesis_block()) # Initialize the Blockchain with the genesis
block
this_nodes_transactions = []
.
.
.
.
node.run()
2. Mining
@node.route('/mine', methods = ['GET'])
def mine():
last_block = blockchain[len(blockchain) - 1]
last_proof = last_block.notes['proof-of-work']
proof = proof_of_work(last_proof)
this_nodes_transactions.append({"from": "network", "to": miner_address, "amount": 1}) # grand new ccoins
new_block_notes = {"proof-of-work": proof, "transactions": list(this_nodes_transactions)}
new_block_index = last_block.index + 1
new_block_timestamp = datetime.datetime.now()
last_block_hash = last_block.hash
this_nodes_transactions[:] = []
mined_block = stage_two.block.Block(new_block_index, new_block_timestamp, last_block_hash, new_block_notes)
blockchain.append(mined_block)
response = Response(json.dumps({"index": new_block_index, "timestamp": str(new_block_timestamp),
"hash": last_block_hash,
"notes": new_block_notes}),
status=200, mimetype='application/json')
return response
3. Proof-of-work
def proof_of_work(last_proof):
incrementer = last_proof + 1
while not (incrementer % 29 == 0 and incrementer % last_proof == 0):
incrementer = incrementer + 1
return incrementer
4. Blockchain Explorer
@node.route('/blocks', methods=['GET'])
def get_blocks():
chain_to_send = blockchain
for i in range(len(chain_to_send)):
block = chain_to_send[i]
block_index = str(block.index)
block_timestamp = str(block.timestamp)
block_hash = block.hash
block_notes = str(block.notes)
chain_to_send[i] = {"index": block_index, "timestamp": block_timestamp, "hash": block_hash, "notes": block_notes}
chain_to_send = json.dumps(chain_to_send)
response = Response(chain_to_send, status=200, mimetype='application/json')
return response
Decentralization (theoretical)
• Distribute the node to many users and allow them to compete on
mining and storing a local copy of the blockchain.
def find_new_chains():
other_chains = []
for node_url in peer_nodes:
block = requests.get(node_url + "/blocks").content
block = json.loads(block)
other_chains.append(block)
return other_chains
def consensus():
other_chains = find_new_chains()
longest_chain = blockchain
for chain in other_chains:
if len(longest_chain) < len(chain):
longest_chain = chain
blockchain = longest_chain
API Endpoints
•Mining: localhost:5000/mine
•Block Explorer: localhost:5000/blocks
IBM Hyperledger (example)
A trusted distributed
ledger with shared
business processes.
Security: Public vs Private Blockchains
• Some use cases require anonymity, others require privacy
– Some may require a mixture of the two, depending on the characteristics of each participant
Private blockchains
• For example, Hyperledger
Fabric
• Network members are known
but transactions are secret
• Most business use cases require private, permissioned blockchains
– Network members know who they’re dealing with (required for KYC, AML, etc.)
– Transactions are (usually) confidential between the participants concerned
– Membership is controlled
Public blockchains
• For example, Bitcoin
• Transactions are viewable by
anyone
• Participant identity is more
difficult to control
B.Ch. Recap
– Blockchain builds on basic business concepts
– Business Networks connect businesses
– Participants with Identity
– Assets flow over business networks
– Transactions describe asset exchange
– Contracts underpin transactions
– The ledger is a log of transactions
– Blockchain is a shared, replicated ledger
(3)
Shared Ledger Records all transactions across business network
Shared between participants
Participants have own copy through replication
Permissioned, so participants see only appropriate transactions
THE shared system of record
(3)
Smart Contracts
Business rules implied by the contract…embedded in the Blockchain and
executed with the transaction. Verifiable, signed Encoded in programming
language. Example Defines contractual conditions under which corporate
Bond transfer occurs.
(3)
Example Business Network (Cars Auction)
(3)
Benefits of IBM Hyperledger Composer
Increases
understanding
Saves
time
Reduces
risk
Increases flexibility
Bridges simply from
business concepts to
blockchain
Develop blockchain
applications more
quickly and cheaply
Well tested, efficient
design conforms to best
practice
Higher level abstraction
makes it easier to
iterate
(3)
Other implementations (industries)
• Banking, Payments & Donations (the fame of blockchain technology)
• Medical Records
• Store the files into the blockchain (produce enormous traffic bandwidth/consumption).
• Store the files into a file server and store the hash of a file into the blockchain to verify the integrity of the file (if is changed or not?).
• Biding and Offerings
• Digital Rights Management (DRM)
• Supply Chain (the search for transparency and accountability)
• Insurance
• Cloud Storage
• Patents
• Smart Contract (code as law)
• Decentralized Autonomous Organizations (A.I. as independent entities)
• Public Services (ownership, citizenship, etc.)
• VOTING!
Banking, Payments & Donations
● Advantages: Anonymous ( sometimes pseudo anonymity); Transparent (removal of banks or other intermediary institutions; Indirectly
pushing blockchain technology forward; Reduced fees / cheap usage; Piggybacking of new functionalities.
● Disadvantages: Illegal actions (since they are untraceable); Price fluctuations and volatility; Risk of being implemented by governments in a
centralized way.
Examples: Crypto Currencies (Digital Assets), Digital Banking
DRM
All sales, loans, donations and other such transfers of individual digital artefacts are witnessed and agreed by all users of the ledger
(blockchain).
● Advantages: Ownership can be transferred digitally (like physical copies of audiovisual media); Royalty payments through smart contracts;
Entitlements are digitally encoded.
● Disadvantages: Implementation.
Patents
The patent system must balance protection of innovators against the protection of competitors. If innovators are not protected, then exposure
to freeriding competition will deter investment in new innovations.
● Advantages: Minimize the bureaucracies (lack of a unified patent system); Minimize the costs; “Encryption” of the original idea (through
hashing of the original document, or part of it, proof of existence)
● Disadvantages: Encryption means hiding of the idea from competitors who could improve it; Not everything can be patented and some
regulations have to be taken into account, so a human officer still can not be replaced
VOTING!
E-voting could take many forms: using the internet or a dedicated, isolated network; requiring voters to attend a polling station or
allowing unsupervised voting; using existing devices, such as mobile phones and laptops, or requiring specialist equipment. Cases:
Denmark Liberal Alliance, Estonia shareholder voting
● Advantages: Decentralized authority that manages the votes (BEV would empower voters to hold a copy of the voting record and not
tamper with other records); Electoral promises could be implemented as smart contracts
● Disadvantages: Anonymity; Accessibility; Lack of confidence due to the difficulty of understanding
Smart Contracts
Transactions can be executed automatically in response to certain conditions being met, providing a 'guarantee of execution'.
● Advantages: Automation of a chain of actions; Trustworthy actions; Reducing legal fees of notaries and lawyers
● Disadvantages: Rigid; Prone to bugs; Complexity of real life scenarios turned into code
Supply Chain (distribution)
The scale and complexity of the systems involved in the supply chain of a final product leads to high transactional costs, frequent
mismatches and errors in manual paperwork, as well as losses through degradation and theft along the way. Other issues include abusive
or unsafe working conditions; environmental damage through inefficacies, illegal extraction and production processes; forgery and
imitation and health risks through poor supply chain management.
● Advantages: Transfer of “clean” provenance products; Avoiding fraud or selling of stolen goods; Efficiency of delivery
● Disadvantages: Still prone to errors; Lack of anonymity for the end user after he receives the product; Still the information could be
manipulated prior to being inserted in the blockchain
Public Services
Blockchain-based technologies could provide new tools to reduce fraud, avoid errors, cut operational costs, boost productivity, support
compliance and force accountability in many public services.
Cases: Estonian government utilities, African land registries
● Advantages: Facilitation of public services (fast, efficient); Transparency; Accountability; Removal of most intermediary steps and
bureaucracies
● Disadvantages: Migration costs; Hash vs the actual document means alternative solutions for saving the documents; Errors could be
difficult to revert; Reducing of white collar jobs
DAOs
Decentralized autonomous organizations (DAOs) can be understood as bundles of smart contracts, culminating in a set of governance rules
that are automatically enforced and executed through blockchains.
● Advantages: Autonomy and independence for all parties involved in the organization;Pure democracy; Independent programmable
entities.
● Disadvantages: Malicious users could abuse; Bugs could make illegal actions legal.
References
Media References
(1), (2) Wikimedia Commons; (3), IBM Hyperledger, “A simple blockchain implementation”, all others are created by TDB Team (Lefter Mita)
GitHub Fork (for the code example)
Gerald Nash (aunyks)
Repository URL: https://github.com/aunyks
Blockchain Usage (EU Parliament)
Philip Boucher, Scientific Foresight Unit (STOA)m PE 581.948, EPRS
European Parliamentary Research Service
“How blockchain technology could change our lives.”, In depth analysis, February 2017
IBM Hyperledger References
Hyperledger Composer (https://hyperledger.github.io/composer) is an open-source set of tools
designed to make building blockchain applications easier.
The blockchain applications run on instances of Linux Foundation Hyperledger Fabric
(www.hyperledger.org)
Web browser instance http://composer-playground.mybluemix.net.
Anthony O’Dowd, 2017 Introduction to Fabric Compose, IBM Corporation
Dave Gorman, 2017 Global Blockchain Labs Engagement, IBM Blockchain
Dave Gorman, 2017 Global Blockchain Labs Engagement, IBM Industry Platform
Thank you all!
We will try our best to answer your questions. Anything you’d like to share
speak freely…
Q&AAnything you missed or forgot email us at contact@thedancingbits.com

Mais conteúdo relacionado

Mais procurados

The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196Mahmoud Samir Fayed
 
JNI - Java & C in the same project
JNI - Java & C in the same projectJNI - Java & C in the same project
JNI - Java & C in the same projectKarol Wrótniak
 
Java Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVMJava Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVModnoklassniki.ru
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesFranco Lombardo
 
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)Ontico
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM ProfilingAndrei Pangin
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra Max Penet
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with nettyZauber
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsShinpei Hayashi
 
Mongodb index 讀書心得
Mongodb index 讀書心得Mongodb index 讀書心得
Mongodb index 讀書心得cc liu
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsAndrei Pangin
 
The Ring programming language version 1.10 book - Part 59 of 212
The Ring programming language version 1.10 book - Part 59 of 212The Ring programming language version 1.10 book - Part 59 of 212
The Ring programming language version 1.10 book - Part 59 of 212Mahmoud Samir Fayed
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 

Mais procurados (20)

The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196
 
Down the Rabbit Hole
Down the Rabbit HoleDown the Rabbit Hole
Down the Rabbit Hole
 
JNI - Java & C in the same project
JNI - Java & C in the same projectJNI - Java & C in the same project
JNI - Java & C in the same project
 
Java
JavaJava
Java
 
Java Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVMJava Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVM
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
 
Mongodb railscamphh
Mongodb railscamphhMongodb railscamphh
Mongodb railscamphh
 
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring Effects
 
Mongodb index 讀書心得
Mongodb index 讀書心得Mongodb index 讀書心得
Mongodb index 讀書心得
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
The Ring programming language version 1.10 book - Part 59 of 212
The Ring programming language version 1.10 book - Part 59 of 212The Ring programming language version 1.10 book - Part 59 of 212
The Ring programming language version 1.10 book - Part 59 of 212
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 

Semelhante a Blockchain - a simple implementation

A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...Mariya James
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by pythonwonyong hwang
 
BlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshopBlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshopPad Kankipati
 
Lecture 17 (Blockchain Implementation using Python).pptx
Lecture 17 (Blockchain Implementation using Python).pptxLecture 17 (Blockchain Implementation using Python).pptx
Lecture 17 (Blockchain Implementation using Python).pptxMayankAgarwal65451
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Let's build a blockchain.... in 40 minutes!
Let's build a blockchain.... in 40 minutes!Let's build a blockchain.... in 40 minutes!
Let's build a blockchain.... in 40 minutes!Michel Schudel
 
20190606 blockchain101
20190606 blockchain10120190606 blockchain101
20190606 blockchain101Hu Kenneth
 
Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!Michel Schudel
 
create your own cryptocurrency
create your own cryptocurrencycreate your own cryptocurrency
create your own cryptocurrencyBellaj Badr
 
Node.js Blockchain Implementation
Node.js Blockchain ImplementationNode.js Blockchain Implementation
Node.js Blockchain ImplementationGlobalLogic Ukraine
 
Blockchain meets database
Blockchain meets databaseBlockchain meets database
Blockchain meets databaseYongraeJo
 
Introduction to Blockchain Web3 Session
Introduction to Blockchain Web3 SessionIntroduction to Blockchain Web3 Session
Introduction to Blockchain Web3 SessionDSCIITPatna
 
Blockchain Technologies for Data Science
Blockchain Technologies for Data ScienceBlockchain Technologies for Data Science
Blockchain Technologies for Data ScienceBruno Gonçalves
 
How to Build Your Own Blockchain
How to Build Your Own BlockchainHow to Build Your Own Blockchain
How to Build Your Own BlockchainLeonid Beder
 
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ libraryInterview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ libraryPVS-Studio
 

Semelhante a Blockchain - a simple implementation (20)

A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by python
 
BlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshopBlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshop
 
Lecture 17 (Blockchain Implementation using Python).pptx
Lecture 17 (Blockchain Implementation using Python).pptxLecture 17 (Blockchain Implementation using Python).pptx
Lecture 17 (Blockchain Implementation using Python).pptx
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Let's build a blockchain.... in 40 minutes!
Let's build a blockchain.... in 40 minutes!Let's build a blockchain.... in 40 minutes!
Let's build a blockchain.... in 40 minutes!
 
Basics of Block Chain
Basics of Block ChainBasics of Block Chain
Basics of Block Chain
 
Day 1.pptx
Day 1.pptxDay 1.pptx
Day 1.pptx
 
20190606 blockchain101
20190606 blockchain10120190606 blockchain101
20190606 blockchain101
 
Blockchain Fundamentals
Blockchain FundamentalsBlockchain Fundamentals
Blockchain Fundamentals
 
Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!
 
create your own cryptocurrency
create your own cryptocurrencycreate your own cryptocurrency
create your own cryptocurrency
 
Node.js Blockchain Implementation
Node.js Blockchain ImplementationNode.js Blockchain Implementation
Node.js Blockchain Implementation
 
Blockchain meets database
Blockchain meets databaseBlockchain meets database
Blockchain meets database
 
Introduction to Blockchain Web3 Session
Introduction to Blockchain Web3 SessionIntroduction to Blockchain Web3 Session
Introduction to Blockchain Web3 Session
 
Blockchain Technologies for Data Science
Blockchain Technologies for Data ScienceBlockchain Technologies for Data Science
Blockchain Technologies for Data Science
 
How to Build Your Own Blockchain
How to Build Your Own BlockchainHow to Build Your Own Blockchain
How to Build Your Own Blockchain
 
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ libraryInterview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ library
 
Flowchain: A case study on building a Blockchain for the IoT
Flowchain: A case study on building a Blockchain for the IoTFlowchain: A case study on building a Blockchain for the IoT
Flowchain: A case study on building a Blockchain for the IoT
 
ChainerX and How to Take Part
ChainerX and How to Take PartChainerX and How to Take Part
ChainerX and How to Take Part
 

Mais de Commit Software Sh.p.k.

Building real time app by using asp.Net Core
Building real time app by using asp.Net CoreBuilding real time app by using asp.Net Core
Building real time app by using asp.Net CoreCommit Software Sh.p.k.
 
Arduino and raspberry pi for daily solutions
Arduino and raspberry pi for daily solutionsArduino and raspberry pi for daily solutions
Arduino and raspberry pi for daily solutionsCommit Software Sh.p.k.
 
Building modern applications in the cloud
Building modern applications in the cloudBuilding modern applications in the cloud
Building modern applications in the cloudCommit Software Sh.p.k.
 
Design patterns: Understand the patterns and design your own
Design patterns: Understand the patterns and design your ownDesign patterns: Understand the patterns and design your own
Design patterns: Understand the patterns and design your ownCommit Software Sh.p.k.
 
Intro to Hybrid Mobile Development && Ionic
Intro to Hybrid Mobile Development && IonicIntro to Hybrid Mobile Development && Ionic
Intro to Hybrid Mobile Development && IonicCommit Software Sh.p.k.
 
Laravel - The PHP framework for web artisans
Laravel - The PHP framework for web artisansLaravel - The PHP framework for web artisans
Laravel - The PHP framework for web artisansCommit Software Sh.p.k.
 
Automation using RaspberryPi and Arduino
Automation using RaspberryPi and ArduinoAutomation using RaspberryPi and Arduino
Automation using RaspberryPi and ArduinoCommit Software Sh.p.k.
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Commit Software Sh.p.k.
 

Mais de Commit Software Sh.p.k. (18)

Building real time app by using asp.Net Core
Building real time app by using asp.Net CoreBuilding real time app by using asp.Net Core
Building real time app by using asp.Net Core
 
Let's talk about GraphQL
Let's talk about GraphQLLet's talk about GraphQL
Let's talk about GraphQL
 
Arduino and raspberry pi for daily solutions
Arduino and raspberry pi for daily solutionsArduino and raspberry pi for daily solutions
Arduino and raspberry pi for daily solutions
 
Lets build a neural network
Lets build a neural networkLets build a neural network
Lets build a neural network
 
Hacking a WordPress theme by its child
Hacking a WordPress theme by its childHacking a WordPress theme by its child
Hacking a WordPress theme by its child
 
Magento 2 : development and features
Magento 2 : development and featuresMagento 2 : development and features
Magento 2 : development and features
 
Building modern applications in the cloud
Building modern applications in the cloudBuilding modern applications in the cloud
Building modern applications in the cloud
 
Design patterns: Understand the patterns and design your own
Design patterns: Understand the patterns and design your ownDesign patterns: Understand the patterns and design your own
Design patterns: Understand the patterns and design your own
 
Laravel and angular
Laravel and angularLaravel and angular
Laravel and angular
 
Drupal 7: More than a simple CMS
Drupal 7: More than a simple CMSDrupal 7: More than a simple CMS
Drupal 7: More than a simple CMS
 
Intro to Hybrid Mobile Development && Ionic
Intro to Hybrid Mobile Development && IonicIntro to Hybrid Mobile Development && Ionic
Intro to Hybrid Mobile Development && Ionic
 
Wordpress development 101
Wordpress development 101Wordpress development 101
Wordpress development 101
 
Ruby on rails
Ruby on rails   Ruby on rails
Ruby on rails
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
Web apps in Python
Web apps in PythonWeb apps in Python
Web apps in Python
 
Laravel - The PHP framework for web artisans
Laravel - The PHP framework for web artisansLaravel - The PHP framework for web artisans
Laravel - The PHP framework for web artisans
 
Automation using RaspberryPi and Arduino
Automation using RaspberryPi and ArduinoAutomation using RaspberryPi and Arduino
Automation using RaspberryPi and Arduino
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 

Último

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Blockchain - a simple implementation

  • 2. Topics • Intro • What is a Blockchain? • Why do we need such technology? What can it do for us… • How does Blockchain work… • Python Implementation of a Blockchain. • Intro to IBM Hyperledger. • Use case scenarios and real world usage, besides digital money ;) • Open discussion, Q&A (as much as we can ☺)
  • 3. What blockchain?! • “A ledger”, public or private to record any type of transaction you are able to express in terms of notable data. • Ability to distribute it and maintain it through certain rules. • In essence a data-structure and a set of rules defined by code.
  • 4. “Jenny from the BLOCK” The novelty and simplicity of the block that provide the full novelty of the blockchain. A simple head/body structure that like in many data structures can store the relation and the data corresponding to that particular block. A reference from Linked Lists ;) references at the end (1) (2)
  • 5. Do we really, really, really need it? What for? • Trust does not need to be asked, is given and is easily verified. Saves time Reduces cost Reduces risk Increases trust Transaction time from days to near instantaneous Overheads and cost intermediaries Tampering, fraud, & cyber crime Through shared processes and recordkeeping (3)
  • 7. Hmm…and how does it work? 1. Transactions Tx:{ TxnID:String, Input:TxIn[], Output:TxOut[] } TxnID= function(public1,public2,amount){ return HashFunction1(public1,public2,amount);}
  • 9. 2. T. Validation • Amount Validation • ID Validation • Signature Validation • Chain Validation
  • 10. “This is a JavaScript's world, this is a JavaScript's world; But it wouldn't be nothing, nothing without some Python in it” James B. Coder the 3rd :P In the next example we will try to demonstrate a minimal and simple chain for a supposed scenario for storing any data into it. Each block has the timestamp along with the index and a self- identifying hash = where each hash will be a cryptographic hash of the block’s index, timestamp, *data (random anything, notes), and the hash of the previous block’s hash.
  • 11. Requirements • Python 3.6 • Python IDE (of your choice, we prefer IntelliJ PyCharm) • Usage of hashlib library (no need for install in Virtual Env., only import it on Python 3.6 and PyCharm) • Documentation: http://code.krypto.org/python/hashlib/ • Source: https://github.com/python/cpython/blob/2.7/Lib/hashlib.py • …some spare time
  • 12. 1. Implementing the BLOCK The number of variables inserted to the block is custom and you can change it according to your needs. class Block: def __init__(self, index, timestamp, previous_hash): self.index = index self.timestamp = timestamp self.previous_hash = previous_hash self.hash = self.hash_block() def hash_block(self): sha = hash_maker.sha256() sha.update(str(self.index).encode('utf-8') + str(self.timestamp).encode('utf-8') + str(self.previous_hash).encode('utf-8')) return sha.hexdigest()
  • 13. 2. Implementing the Genesis BLOCK Having the block is not enough because if you put some focus into the relation hash-to-hash, where does the first block related to? ☺ For that, the first block is called Genesis and @staticmethod def create_genesis_block(): return Block(0, datetime.datetime.now(), "0")
  • 14. 3. Giving birth to new BLOCKS def next_block(last_block): this_index = last_block.index + 1 # raise the index by one this_timestamp = datetime.datetime.now() # current timestamp from the system previous_hash = last_block.hash # relation among the block inside the chain return Block(this_index, this_timestamp, previous_hash) Remember: Relation is very important! It guarantees the continuity of consensus ;)
  • 15. So… complete implementation of block.py looks like this: import hashlib as hash_maker import datetime class Block: def __init__(self, index, timestamp, previous_hash): self.index = index self.timestamp = timestamp self.previous_hash = previous_hash self.hash = self.hash_block() def hash_block(self): sha = hash_maker.sha256() sha.update(str(self.index).encode('utf-8') + str(self.timestamp).encode('utf-8') + str(self.previous_hash).encode('utf-8')) return sha.hexdigest() @staticmethod def create_genesis_block(): return Block(0, datetime.datetime.now(), "0") def next_block(last_block): this_index = last_block.index + 1 # raise the index by one this_timestamp = datetime.datetime.now() # current timestamp from the system previous_hash = last_block.hash # relation among the block inside the chain return Block(this_index, this_timestamp, previous_hash)
  • 16. …and the actual simulation of the chain, in test.py import block blockchain = [block.Block.create_genesis_block()] # Initialize the Blockchain with the genesis block previous_block = blockchain[0] # Set the "head" / previous block to the first block total_blocks = 5 # x = 5, where x is the number of simulated blocks # Blockchain is filled for i in range(0, total_blocks): block_to_add = block.next_block(previous_block) blockchain.append(block_to_add) previous_block = block_to_add print("Block #{} created".format(block_to_add.index - 1) + " with Hash: {}".format(block_to_add.hash))
  • 17. Results, of course…after the first two or three fails ☺ Note: sha = hash_maker.sha256() sha.update() Generally and with SHA-1 In the above example we used SHA-256, even harder to brake than SHA-1. Same input produces the same hash always. Is hard to compute the initial state and one method would be to brute force manually all the possible combinations.
  • 18. Question What are we missing so far from the main philosophy explained before in the current primitive state solution? no distribution – no decentralization Answer
  • 19. Distribution and Decentralization Requirements • above example + • Flask Micro-Framework (to speed up the development) In the following example we will demonstrate the ability to distribute digital coins through proof-of-work.
  • 20. Distribution 1. Flask Integration from flask import Flask from flask import request, Response import stage_two.block import datetime import json node = Flask(__name__) miner_address = "for-testing-purposes-this-is-completely-random-but-should-be-unique" # miner's address in the network blockchain = [] blockchain.append(stage_two.block.Block.create_genesis_block()) # Initialize the Blockchain with the genesis block this_nodes_transactions = [] . . . . node.run()
  • 21. 2. Mining @node.route('/mine', methods = ['GET']) def mine(): last_block = blockchain[len(blockchain) - 1] last_proof = last_block.notes['proof-of-work'] proof = proof_of_work(last_proof) this_nodes_transactions.append({"from": "network", "to": miner_address, "amount": 1}) # grand new ccoins new_block_notes = {"proof-of-work": proof, "transactions": list(this_nodes_transactions)} new_block_index = last_block.index + 1 new_block_timestamp = datetime.datetime.now() last_block_hash = last_block.hash this_nodes_transactions[:] = [] mined_block = stage_two.block.Block(new_block_index, new_block_timestamp, last_block_hash, new_block_notes) blockchain.append(mined_block) response = Response(json.dumps({"index": new_block_index, "timestamp": str(new_block_timestamp), "hash": last_block_hash, "notes": new_block_notes}), status=200, mimetype='application/json') return response
  • 22. 3. Proof-of-work def proof_of_work(last_proof): incrementer = last_proof + 1 while not (incrementer % 29 == 0 and incrementer % last_proof == 0): incrementer = incrementer + 1 return incrementer
  • 23. 4. Blockchain Explorer @node.route('/blocks', methods=['GET']) def get_blocks(): chain_to_send = blockchain for i in range(len(chain_to_send)): block = chain_to_send[i] block_index = str(block.index) block_timestamp = str(block.timestamp) block_hash = block.hash block_notes = str(block.notes) chain_to_send[i] = {"index": block_index, "timestamp": block_timestamp, "hash": block_hash, "notes": block_notes} chain_to_send = json.dumps(chain_to_send) response = Response(chain_to_send, status=200, mimetype='application/json') return response
  • 24. Decentralization (theoretical) • Distribute the node to many users and allow them to compete on mining and storing a local copy of the blockchain. def find_new_chains(): other_chains = [] for node_url in peer_nodes: block = requests.get(node_url + "/blocks").content block = json.loads(block) other_chains.append(block) return other_chains def consensus(): other_chains = find_new_chains() longest_chain = blockchain for chain in other_chains: if len(longest_chain) < len(chain): longest_chain = chain blockchain = longest_chain
  • 25. API Endpoints •Mining: localhost:5000/mine •Block Explorer: localhost:5000/blocks
  • 26. IBM Hyperledger (example) A trusted distributed ledger with shared business processes.
  • 27. Security: Public vs Private Blockchains • Some use cases require anonymity, others require privacy – Some may require a mixture of the two, depending on the characteristics of each participant Private blockchains • For example, Hyperledger Fabric • Network members are known but transactions are secret • Most business use cases require private, permissioned blockchains – Network members know who they’re dealing with (required for KYC, AML, etc.) – Transactions are (usually) confidential between the participants concerned – Membership is controlled Public blockchains • For example, Bitcoin • Transactions are viewable by anyone • Participant identity is more difficult to control
  • 28. B.Ch. Recap – Blockchain builds on basic business concepts – Business Networks connect businesses – Participants with Identity – Assets flow over business networks – Transactions describe asset exchange – Contracts underpin transactions – The ledger is a log of transactions – Blockchain is a shared, replicated ledger (3)
  • 29. Shared Ledger Records all transactions across business network Shared between participants Participants have own copy through replication Permissioned, so participants see only appropriate transactions THE shared system of record (3)
  • 30. Smart Contracts Business rules implied by the contract…embedded in the Blockchain and executed with the transaction. Verifiable, signed Encoded in programming language. Example Defines contractual conditions under which corporate Bond transfer occurs. (3)
  • 31. Example Business Network (Cars Auction) (3)
  • 32. Benefits of IBM Hyperledger Composer Increases understanding Saves time Reduces risk Increases flexibility Bridges simply from business concepts to blockchain Develop blockchain applications more quickly and cheaply Well tested, efficient design conforms to best practice Higher level abstraction makes it easier to iterate (3)
  • 33. Other implementations (industries) • Banking, Payments & Donations (the fame of blockchain technology) • Medical Records • Store the files into the blockchain (produce enormous traffic bandwidth/consumption). • Store the files into a file server and store the hash of a file into the blockchain to verify the integrity of the file (if is changed or not?). • Biding and Offerings • Digital Rights Management (DRM) • Supply Chain (the search for transparency and accountability) • Insurance • Cloud Storage • Patents • Smart Contract (code as law) • Decentralized Autonomous Organizations (A.I. as independent entities) • Public Services (ownership, citizenship, etc.) • VOTING!
  • 34. Banking, Payments & Donations ● Advantages: Anonymous ( sometimes pseudo anonymity); Transparent (removal of banks or other intermediary institutions; Indirectly pushing blockchain technology forward; Reduced fees / cheap usage; Piggybacking of new functionalities. ● Disadvantages: Illegal actions (since they are untraceable); Price fluctuations and volatility; Risk of being implemented by governments in a centralized way. Examples: Crypto Currencies (Digital Assets), Digital Banking DRM All sales, loans, donations and other such transfers of individual digital artefacts are witnessed and agreed by all users of the ledger (blockchain). ● Advantages: Ownership can be transferred digitally (like physical copies of audiovisual media); Royalty payments through smart contracts; Entitlements are digitally encoded. ● Disadvantages: Implementation.
  • 35. Patents The patent system must balance protection of innovators against the protection of competitors. If innovators are not protected, then exposure to freeriding competition will deter investment in new innovations. ● Advantages: Minimize the bureaucracies (lack of a unified patent system); Minimize the costs; “Encryption” of the original idea (through hashing of the original document, or part of it, proof of existence) ● Disadvantages: Encryption means hiding of the idea from competitors who could improve it; Not everything can be patented and some regulations have to be taken into account, so a human officer still can not be replaced VOTING! E-voting could take many forms: using the internet or a dedicated, isolated network; requiring voters to attend a polling station or allowing unsupervised voting; using existing devices, such as mobile phones and laptops, or requiring specialist equipment. Cases: Denmark Liberal Alliance, Estonia shareholder voting ● Advantages: Decentralized authority that manages the votes (BEV would empower voters to hold a copy of the voting record and not tamper with other records); Electoral promises could be implemented as smart contracts ● Disadvantages: Anonymity; Accessibility; Lack of confidence due to the difficulty of understanding
  • 36. Smart Contracts Transactions can be executed automatically in response to certain conditions being met, providing a 'guarantee of execution'. ● Advantages: Automation of a chain of actions; Trustworthy actions; Reducing legal fees of notaries and lawyers ● Disadvantages: Rigid; Prone to bugs; Complexity of real life scenarios turned into code Supply Chain (distribution) The scale and complexity of the systems involved in the supply chain of a final product leads to high transactional costs, frequent mismatches and errors in manual paperwork, as well as losses through degradation and theft along the way. Other issues include abusive or unsafe working conditions; environmental damage through inefficacies, illegal extraction and production processes; forgery and imitation and health risks through poor supply chain management. ● Advantages: Transfer of “clean” provenance products; Avoiding fraud or selling of stolen goods; Efficiency of delivery ● Disadvantages: Still prone to errors; Lack of anonymity for the end user after he receives the product; Still the information could be manipulated prior to being inserted in the blockchain
  • 37. Public Services Blockchain-based technologies could provide new tools to reduce fraud, avoid errors, cut operational costs, boost productivity, support compliance and force accountability in many public services. Cases: Estonian government utilities, African land registries ● Advantages: Facilitation of public services (fast, efficient); Transparency; Accountability; Removal of most intermediary steps and bureaucracies ● Disadvantages: Migration costs; Hash vs the actual document means alternative solutions for saving the documents; Errors could be difficult to revert; Reducing of white collar jobs DAOs Decentralized autonomous organizations (DAOs) can be understood as bundles of smart contracts, culminating in a set of governance rules that are automatically enforced and executed through blockchains. ● Advantages: Autonomy and independence for all parties involved in the organization;Pure democracy; Independent programmable entities. ● Disadvantages: Malicious users could abuse; Bugs could make illegal actions legal.
  • 38. References Media References (1), (2) Wikimedia Commons; (3), IBM Hyperledger, “A simple blockchain implementation”, all others are created by TDB Team (Lefter Mita) GitHub Fork (for the code example) Gerald Nash (aunyks) Repository URL: https://github.com/aunyks Blockchain Usage (EU Parliament) Philip Boucher, Scientific Foresight Unit (STOA)m PE 581.948, EPRS European Parliamentary Research Service “How blockchain technology could change our lives.”, In depth analysis, February 2017 IBM Hyperledger References Hyperledger Composer (https://hyperledger.github.io/composer) is an open-source set of tools designed to make building blockchain applications easier. The blockchain applications run on instances of Linux Foundation Hyperledger Fabric (www.hyperledger.org) Web browser instance http://composer-playground.mybluemix.net. Anthony O’Dowd, 2017 Introduction to Fabric Compose, IBM Corporation Dave Gorman, 2017 Global Blockchain Labs Engagement, IBM Blockchain Dave Gorman, 2017 Global Blockchain Labs Engagement, IBM Industry Platform
  • 39. Thank you all! We will try our best to answer your questions. Anything you’d like to share speak freely… Q&AAnything you missed or forgot email us at contact@thedancingbits.com