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 .
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)
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()
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
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)
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