SlideShare a Scribd company logo
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

More Related Content

PDF
sizeof(Object): how much memory objects take on JVMs and when this may matter
PDF
Distributed systems at ok.ru #rigadevday
KEY
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
PPTX
Do we need Unsafe in Java?
PPTX
Mythbusting: Understanding How We Measure the Performance of MongoDB
PDF
Everything you wanted to know about Stack Traces and Heap Dumps
PPTX
Gpu programming with java
PDF
Secure .NET programming
sizeof(Object): how much memory objects take on JVMs and when this may matter
Distributed systems at ok.ru #rigadevday
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Do we need Unsafe in Java?
Mythbusting: Understanding How We Measure the Performance of MongoDB
Everything you wanted to know about Stack Traces and Heap Dumps
Gpu programming with java
Secure .NET programming

What's hot (20)

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

Similar to Blockchain - a simple implementation (20)

PDF
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
PPTX
BlockchainConf.tech - Build a private blockchain workshop
PPTX
Lecture 17 (Blockchain Implementation using Python).pptx
PDF
Blockchain - a formal introduction
PDF
Part 3 Introduction to Cryptocurrency.pdf
PDF
Blockchain
PPTX
Introduction to Blockchain
PPTX
block chain.pptx
PDF
Blockchain - a basic overview
PPTX
Introduction to Blockchain & development
PDF
Basics of Block Chain
PDF
Blockchain Fundamental_KIPMI_2022.02.26.pdf
PPTX
blockchain.pptx
PDF
Blockchain, Hyperledger, DeFi, Web 3.0 - understanding and concepts
PPTX
UNIT 1 (1).pptx of block chain technologies
PPTX
Introduction to Blockchain Technology
PPTX
Blockchain ppt
PDF
Blockchain, cryptography and tokens — NYC Bar presentation
PDF
Blockchain and bitcoin
PDF
Introduction to Blockchain
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
BlockchainConf.tech - Build a private blockchain workshop
Lecture 17 (Blockchain Implementation using Python).pptx
Blockchain - a formal introduction
Part 3 Introduction to Cryptocurrency.pdf
Blockchain
Introduction to Blockchain
block chain.pptx
Blockchain - a basic overview
Introduction to Blockchain & development
Basics of Block Chain
Blockchain Fundamental_KIPMI_2022.02.26.pdf
blockchain.pptx
Blockchain, Hyperledger, DeFi, Web 3.0 - understanding and concepts
UNIT 1 (1).pptx of block chain technologies
Introduction to Blockchain Technology
Blockchain ppt
Blockchain, cryptography and tokens — NYC Bar presentation
Blockchain and bitcoin
Introduction to Blockchain
Ad

More from Commit Software Sh.p.k. (18)

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

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
KodekX | Application Modernization Development
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PPTX
Cloud computing and distributed systems.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
MYSQL Presentation for SQL database connectivity
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Per capita expenditure prediction using model stacking based on satellite ima...
KodekX | Application Modernization Development
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
sap open course for s4hana steps from ECC to s4
20250228 LYD VKU AI Blended-Learning.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
Cloud computing and distributed systems.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
The AUB Centre for AI in Media Proposal.docx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation_ Review paper, used for researhc scholars
Advanced methodologies resolving dimensionality complications for autism neur...

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