Slides NPTEL BlockchainTechnologyApplications
Slides NPTEL BlockchainTechnologyApplications
Applications
Sandeep K. Shukla
IIT Kanpur
C3I Center
Acknowledgement
CryptoCoin‐v.1
Can you create your own digital coin?
How about ?
pkyou ‐‐ your private key
CreateCoin [uniqueCoinID]
Give your friend a coin you created
signed by pkfriend
Arvind owns it now
Pay to pukArvind : H( )
signed by pkyou
Pay to pukfriend : H( )
signed by pkyou
CreateCoin [uniqueCoinID]
double-spending attack
signed by pkyou
Pay to pukfriend : H( ) Who owns the coin now?
Arvind or Ravi?
signed by pkyou
CreateCoin [uniqueCoinID]
Major challenge in Digital Currency Design
CryptoCoin‐v.2
Transaction History Tracking
H( )
consumed
transID: 73 coinIDs:
type:PayCoins
68(1), 42(0), 72(3) Valid if:
-- consumed coins valid,
coins created -- not already consumed,
-- total value out = total value
num value recipient in, and
-- signed by owners of all
0 3.2 0x...
consumed coins
1 1.4 0x...
2 7.1 0x...
signatures
Immutable coins
Coins can’t be transferred, subdivided, or combined.
Crucial question:
Delivery Truck of B
Delivery Truck of B
Delivery Truck of B
●So restaurant A will not be able to pinpoint any one in the supply chain
with full confidence!!
What can be done?
● Use a message integrity proof (Hashing)
● Use digital signature of the individual IoT devices (Authenticity and non‐
repudiation)
○ assuming the digital signatures cannot be forged
○ private keys are kept safe
●Use authentic time stamping with the IoT data before hashing for
integrity (avoid replay attacks)
●So now factory A can pinpoint with some basic security assumptions
about this infrastructure
Concurrency Issue
●A has other suppliers for other goods required for its business (multiple
concurrent supply chains)
●B and C has multiple other consumers of their services
● So if there are N suppliers who are also consumers of some of these
entities, we have an N2 messaging problem
A offers that every one can look up their data from my server, so you can
get linear number of messaging
C3I Center
Acknowledgement
• Much material in this course owe their ideas and existence to
• Prof. Maurice Herlihy, Brown University
• Prof. Hagit Attiya, Hebrew University
• Prof. Arvind Narayanan, Princeton University
• Prof. Joseph Bonneau, NYU
• Dan Boneh (Stanford University)
• John C. Mitchell (Stanford University)
• Nicolai Zeldovich (MIT)
• Jungmin Park (Virginia Tech)
• Patrick Schaumont (Virginia Tech)
• C. Edward Chow
• Arun Hodigere
• Mike Freedman, Princeton University
Today is all about essential Cryptography for Blockchain
5
Encryption and Decryption
M C M
E D
6
Cryptography: Algorithms and Keys
• A method of encryption and decryption is called a cipher.
• Generally there are two related functions: one for encryption and
other for decryption.
• Some cryptographic methods rely on the secrecy of the algorithms.
• Such methods are mostly of historical interest these days.
• All modern algorithms use a key to control encryption and
decryption.
• Encryption key may be different from decryption key.
7
Key Based Encryption/Decryption
K1 K2
M C M
E D
Symmetric Case: both keys are the same or derivable from each other. K1 = K2.
Asymmetric Case: keys are different and not derivable from each other. K1 != K2
8
Secrete Key Cryptography
K K
M C M
S E D R
K is the secret key shared by both the sender (S) and receiver (R).
9
Secret Key Cryptography
• Also called symmetric or single‐key algorithms.
• The encryption and the decryption key are the same.
• Techniques based on a combination of substitution and permutation.
• Stream ciphers: operate on single bit or byte.
• Block ciphers: operate on blocks (typically 64/128/256… bits)
• Advantage: simple, fast.
• Disadvantage: key exchange, key management.
• Examples: DES,RC4, IDEA, Blowfish, AES, etc.
10
Private Key Cryptosystem (Symmetric)
11
Symmetric Key ‐ Issues
Key management, keys required = (p*(p‐1))/2 or:
12
Secrete Key Assurances
• Confidentiality
• is assurance that only owners of a shared secrete key can decrypt a message that
has been encrypted with the shared secrete key
• Authentication
• is assurance of the identify of the person at the other end of the line (use
challenge and response protocols)
• Integrity
• is assurance that a message has not been changed during transit and is also called
message authentication (use message fingerprint)
• Non‐repudiation
• is assurance that the sender cannot deny a file was sent. This cannot be done
with secrete key alone (need trusted third party or public key technology)
13
Example: non‐repudiation
• Scenario 1:
• Alice sends a stock buy request to Bob
• Bob does not buy and claims that he never received the request
• Scenario 2:
• Alice sends a stock buy request to Bob
• Bob sends back an acknowledge message
• Again, Bob does not buy and claims that he never received it
• Alice presents the ack message as proof
• Can she prove that the ack message was created by him?
14
DES (Data Encryption Standard)
• In 1972, NIST (National Institute of Standards and Technology)
decides to assist the development of a secure cryptographic method.
• In 1974, it settled on DES, which was submitted by IBM and is the
Data Encryption Algorithm developed by Horst Feistel.
• NSA shortened the secrete key to 56 bits from 128 bits originally
proposed by IBM.
• Initially intended for 10 years. DES reviewed in 1983, 1987, 1993.
• In 1997, NIST solicited candidates for a new secrete key encryption
standard, Advanced Encryption Standard (AES).
• In Oct 2000, NIST selected Rijndael. (www.nist.gov/AES)
15
Cycling through DES keys
• In 1977, a 56‐bit key was considered good enough.
• Takes 1,000 years to try all keys with 56 1’s and 0’s at one million keys per second
• In Jan 1997, RSA Data Security Inc. issued “DES challenge”
• DES cracked in 96 days
• In Feb 1998, distributed.net cracked DES in 41 days
• In July 1998, the Electroic Frontier Foundation (EFF) and distributed.net cracked
in 56 hours using a $250K machine
• In Jan 1999, the team did in less than 24 hours
• Double and Triple DES
• Double DES only gives 2**57 = 2 x 2**56, instead of 2**112, due to meet‐in‐the‐
middle attack.
• Triple DES recommended, but managing three keys more difficult
16
Public Key Cryptography
KR(pub) KR(pri)
M C M
S E D R
17
Establishing Shared Secrete
Internet
19
Public Key Cryptographic Algorithms
20
Public Key Cryptosystem
22
Asymmetric Algorithms
• Also called public‐key algorithms.
• Encryption key is different from decryption key.
• Furthermore, one cannot be calculated from other.
• Encryption key is often called the public key and decryption key is often
called the private key.
• Advantages: better key management.
• Disadvantages: slower, more complex.
• Both techniques are complementary.
• Examples: RSA, Diffie‐Hellman, El Gamal, etc. 23
Cryptographic Hash Functions
Hash function:
takes an arbitrary length string as input
produces a fixed‐size output (e.g 256 bits)
Easy to compute
Almost impossible to reverse
Security properties:
collision‐resistant
Hides the original String
Almost impossible to get the original string from the output
puzzle‐friendly
Hash property 1: Collision‐resistance
It is computationally NOT feasible to find x and y
such that
x != y and H(x)=H(y)
H(x) = H(y)
y
However, for a weak hash function collisions may be feasible to find:
possible outputs
possible inputs
Even if each input checking takes 100 ms, we are talking about 2
0.1 which is 2 4.3 10
Are there any hash functions for which efficient collision
finding algorithms exist?
● For some H
● But for others none known yet (SHA‐256, SHA3 etc)
Security properties:
Hiding: Given com, infeasible to find msg.
Binding: Infeasible to find msg != msg’ such that
verify(commit(msg), msg’) == true
Commitment API
commit(msg) := ( H(key | msg), H(key) )
where key is a random 256‐bit value
verify(com, key, msg) := ( H(key | msg) == com )
Security properties:
Hiding: Given H(key | msg), infeasible to find msg.
Binding: Infeasible to find msg != msg’ such that
H(key | msg) == H(key | msg’)
Hash property 3: Puzzle‐friendly
Puzzle‐friendly:
For every possible output value y,
if k is chosen from a distribution with high min‐entropy,
then it is infeasible to find x such that H(k | x) = y.
Application: Search puzzle
Given a “puzzle ID” id (from high min‐entropy distrib.),
and a target set Y:
Try to find a “solution” x such that
H(id | x) Y.
256 256
bits bits
c c c
IV Hash
H( )
(data)
H( ) H( )
H( ) H( ) H( ) H( )
H( ) H( ) H( ) H( ) H( ) H( ) H( ) H( )
H( ) H( )
H( ) H( )
(data)
Advantages of Merkle trees
• Tree holds many items
• but just need to remember the root hash
• Can verify membership in O(log n) time/space
C3I Center
Acknowledgement
3
in the rest of this lecture
4
what is a ledger?
5
a ledger records transactions
6
now suppose bob pays alice ₿100
7
and alice pays carol ₿125
8
and so on ..
9
ledger to account balances?
sender receiver amount
initial deposit alice 100
initial deposit bob 200
initial deposit carol 300
initial deposit dan 400
bob alice 100
alice carol 125
account amount
alice 100+100‐125=75
bob 200‐100=100
carol 300+125=425
dan 400
10
but not all transactions are valid
sender receiver amount account amount
initial deposit alice 100
alice 75
initial deposit bob 200
bob 100
initial deposit carol 300
initial deposit dan 400
carol 425
bob alice 100 dan 400
alice carol 125
bob dan 200
11
definition: transaction validity (v1)
12
definition: ledger validity (v1)
13
blockchain: ledger of transactions
14
let’s see some code
class txn_t {
account_t sender;
account_t receiver; …
uint64_t amount;
};
class block_t {
std::vector<txn_t*> txns;
block_t* prev_block;
};
std::list<block_t*> blockchain;
15
std::vector<T>: resizeable array
• insertion
vec.push_back(elem); • resize to have n elements:
vec.resize(n);
• size
vec.size() • delete all elems and set size = 0
vec.clear();
• element access
vec[i] = blah; • iteration
for (auto elem : vec) {
• access to raw array inside // do something with elem;
vec.data() }
16
std::list<T>: linked list
• iteration (v1):
• insertion for (auto p = lst.begin();
lst.push_back(elem); p != lst.end(); p++)
{
• size // do something with *p;
}
lst.size()
• iteration (v2)
• delete all elems and set size = 0 for (auto elem : vec) {
lst.clear(); // do something with elem;
}
17
in modern c++ (c++’11 and c++’14)
class txn_t {
account_t sender;
…
account_t receiver;
uint64_t amount;
};
class block_t {
std::vector<std::shared_ptr<txn_t> > txns;
std::shared_ptr<block_t> prev_block;
};
19
blockchain validation code (v1)
bool validate(list<shared_ptr<block_t> >& blockchain) {
balances.clear();
for (auto blk : blockchain) { iterate over
for (auto tx : blk.txns) { each transaction
if (tx.sender == INIT_DEPOSIT ||
balances[tx.sender] >= tx.amount) check balance
{
balances[tx.sender] ‐= tx.amount; update balances
balances[tx.receiver] += tx.amount;
} else {
return false;
}
}
}
return true;
}
20
unordered_map<K,V>: hashtable
• iteration:
• insertion for (auto p = m.begin();
p != m.end(); p++)
m [key] = elem; {
// use p.first (key)
• size // and p.second (val)
m.size() }
21
set<T>: set of elements
• iteration:
• insertion for (auto p = m.begin();
m.insert(elem) p != m.end(); p++)
{
• size // use *p or p‐>fld;
}
m.size()
• search
• delete all elems and set auto p = m.find(elm);
size = 0 // returns m.end() or can
// use *p or p‐>fld
m.clear();
22
but we said that
23
verifiability problem #1: repudiation
sender receiver amount
initial deposit alice 100 hey SBI, I
initial deposit bob 200 never paid
initial deposit carol 300 dan ₿100!
initial deposit dan 400
bob alice 100
alice carol 125
carol dan 100
dan alice 50
alice bob 25
bob dan 75
24
solution in today’s banks?
yes, you did!
hey SBI, I here is your
never paid signature
TS ₹6493!
25
in blockchains: digital signatures
alice’s private key
alice pays
sign signature
dan ₿100
verify
26
in blockchains: digital signatures
bob’s private key
alice pays
sign signature
dan ₿100
verify
27
in blockchains: digital signatures
alice’s private key
alice pays
sign signature
dan ₿100
alice pays
verify
dan ₿200
28
a non‐repudiable ledger
29
definition: transaction validity (v2)
transaction is valid if
• sender’s balance is >= the amount being
sent to receiver and
• and tx signature validation with sender’s
public key succeeds
30
code for verifying signatures
rsa_public_key_t pubkey(
DEREncodedKey.data(),
DEREncodedKey.size());
31
what’s the problem with the scheme?
32
solution: tie a/c nos. and pubkeys
33
what is a cryptographic hash fn?
space of
messages
hashes (fixed
with
size digests)
arbitrary
sizes
pre‐image resistance
• can’t find message given a hash
collision resistance
• if two messages are different, very likely hashes are
different
35
blockchain transactions
36
problem: replay attacks
37
problem: replay attacks
38
what’s the fix?
send pubkey send addr recv addr change amt digital signature
addr
0xFFA1288… 0x18471C… 0x13831… 0x4AC1.. 100 0xFAD10A8..
0x98B5B33… 0x13831… 0x32112… 0xD1A2… 50 0x98B5B33..
… … … … …
39
one last minor detail
41
definition: transaction validity (v3)
send pubkey send addr recv addr amt tx hash digital signature
0xFFA1288… 0x18471C 0x13831… 100 0x331A… 0xFAD10A8DC
…
… … … … …
… … … … …
your first task is to implement these two checks in transaction.cpp
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, public_key.data(), public_key.size());
SHA256_Update(&sha256, source_addr.data(), source_addr.size());
SHA256_Update(&sha256, dest_addr.data(), dest_addr.size());
SHA256_Update(&sha256, change_addr.data(), change_addr.size());
SHA256_Update(&sha256, &amount, sizeof(amount));
SHA256_Final(tx_hash.data(), &sha256);
43
back to the blockchain
44
permanence via public distribution
45
but now we have a problem
…
class block_t {
vector<shared_ptr<txn_t> > txns;
shared_ptr<block_t> prev_block;
};
46
solution: hash pointers
48
final block structure
class block_t {
vector<shared_ptr<txn_t> > transactions;
hash_result_t reward_addr;
hash_result_t prev_hash;
shared_ptr<block_t> prev_ptr; // why?
};
49
your tasks
50
task #1: txn_t::validate()
51
task #2: block_t::validate()
52
testing your code
53
Outline of blockchain.h
class block_t {
private:
bool valid;
balance_map_t balances;
public:
unsigned length;
block_t();
block_t(std::shared_ptr<block_t> prev_block);
hash_result_t reward_addr;
std::vector< std::shared_ptr<txn_t> > transactions;
hash_result_t prev_hash;
hash_result_t blk_hash;
std::shared_ptr<block_t> prev_block; ….
Outline of transactions.h
typedef std::map<hash_result_t, uint64_t> balance_map_t;
struct txn_t {
uint8_vector_t public_key;
hash_result_t source_addr;
hash_result_t dest_addr;
hash_result_t change_addr;
uint64_t amount;
hash_result_t tx_hash;
uint8_vector_t tx_sign;
bool valid;
……
Outline of crypto.h
typedef std::vector<uint8_t> uint8_vector_t;
class hash_result_t {
uint8_t bytes[SHA256_DIGEST_LENGTH];
public:
static const int SIZE;
hash_result_t();
hash_result_t(uint8_t bytesIn[SHA256_DIGEST_LENGTH]);
hash_result_t(const hash_result_t& other);
void set_hash_from_data(const uint8_vector_t& data);
void set_hash_from_data(const uint8_t* data, size_t sz);
hash_result_t& operator=(const hash_result_t& other) {
std::copy(other.bytes, other.bytes + size(), bytes);
return *this;
}
bool operator==(const hash_result_t& other) const;
bool operator!=(const hash_result_t& other) const { return !(*this == other); }
bool operator<(const hash_result_t& other) const;
uint8_t& operator[](unsigned i);
Creating coinbase Block & Regular Block
block_t::block_t()
: valid(false)
, length(1)
, prev_block(NULL)
{
reset_balances();
}
block_t::block_t(std::shared_ptr<block_t> prev)
: valid(false)
, length(prev‐>length + 1)
, prev_hash(prev‐>blk_hash)
, prev_block(prev)
{
reset_balances();
}
Steps you need to do
• Download Ubuntu 18.04 from ubuntu site if you are already not using
ubuntu
• If you do not want your machine to be dual‐booted, install Vbox from
oracle and use virtual machine to run Ubuntu
• When you get into ubuntu, please clone openressl library from github
https://github.com/libressl‐portable/portable
• Use sudo apt‐get install for the followings libboost‐dev, automake,
autoconf, git, libtool, perl, g++
• After you have installed the above, you have to follow the instructions in
README.md that is in the directory portable‐manager to build and install
this library
• This is the SSL and Crypto library that you will need to do all the crypto
functions required
Steps (2)
• Then download the code for blockchain exercise – and follow the
README.md file within the src directory to build it
• You will need to then write the functions required for the homework.
Blockchain Technology
And Applications
Sandeep K. Shukla
IIT Kanpur
C3I Center
Acknowledgement
• The material of this lecture is mostly due to Prof.
Arvind Narayanan’s Lecture at Princeton and his book
on Bitcoin (Chapter 3)
Mechanics of Bitcoin
Recap: Bitcoin consensus
Bitcoin consensus enables us to have:
●An Append‐only ledger of transactions
●Decentralized consensus with probabilistic
guarantee
●Miners incentivized to validate transactions
time
1 Inputs: ...
Outputs: 17.0→Bob, 8.0→Alice
.. SIGNED(Alice)
.
2 Inputs: 1[1]
Outputs: 6.0→Carol, 2.0→Bob
SIGNED(Carol)
..
.
3 Inputs: 1[0], 2[1]
Outputs: 19.0→Bob
SIGNED(Bob)
.
2 Inputs: 1[1]
Outputs: 6.0→Carol, 2.0→Bob
SIGNED(Carol)
..
.
3 Inputs: 2[0], 2[1]
two signatures!
Outputs: 8.0→David
SIGNED(Carol), SIGNED(Bob)
"in":[
{
Previous "prev_out":{
transaction "hash":"3be4...80260",
"n":0
},
signature "scriptSig":"30440....3f3a4ce81"
},
(more
...
inputs)
],
The real deal: transaction outputs
"out":[
{
output value "value":"10.12287097",
"scriptPubKey":"OP_DUP OP_HASH160 69e...3d42e OP_EQUALVERIFY OP_CHECKSIG"
recipient },
address?? ...
]
(more
outputs)
Bitcoin scripts
Output “addresses” are really scripts
OP_DUP
OP_HASH160
69e02e18...
OP_EQUALVERIFY OP_CHECKSIG
Input “addresses” are also scripts
30440220...
scriptSig
0467d2c9...
OP_DUP
OP_HASH160
scriptPubKey
69e02e18...
OP_EQUALVERIFY OP_CHECKSIG
✓
<pubKeyHash?>
<pubKey>
<pubKeyHash>
<pubKey>
<sig>
true
OP_RETURN
<arbitrary data>
Should senders specify scripts?
?
I’m ready to pay for my Big Box
purchases!
<signature>
<signature>
<<pubkey> OP_CHECKSIG>
OP_HASH160
<pubkey>
<hash of redemption script>
OP_CHECKSIG
OP_EQUAL
(disputed
(normal case)case)
Pay x to Alice
Bob
Judy SIGNED(ALICE,JUDY)
BOB)
SIGNED(ALICE,
To: Alice
From:
Bob
Alice PROBLEM:
Pay Alice
x to 2-of-3 ofwants
Alice,to buyJudy
Bob, online from Bob.
(MULTISIG) Bob
Alice doesn’t want to pay until after Bob ships.
SIGNED(ALICE)
H( ) H( )
data
The real deal: a Bitcoin block header
{
"hash":"00000000000000001aad2...",
"ver":2,
"prev_block":"00000000000000003043...",
"time":1391279636,
mining "bits":419558700, hashed
puzzle "nonce":459459841, during
information "mrkl_root":"89776...", mining
...
}
not hashed
The real deal: coinbase transaction
"in":[
{
"prev_out":{ Null hash pointer
"hash":"000000.....0000000",
redeeming "n":4294967295
nothing }, First ever coinbase parameter:
"coinbase":"..." “The Times 03/Jan/2009 Chancellor
arbitrary }, on brink of second bailout for banks”
"out":[block reward
{ transaction fees
"value":"25.03371419",
"scriptPubKey":"OPDUP OPHASH160 ... ”
}
See for yourself!
Hello World!
I’m ready to 5
1 Bitcoin!
7
getaddr() getaddr()
1, 7 getaddr()
8
3
6
2
4
Transaction propagation (flooding)
Already
heard
5 that!
1
7
A→B
8
A→B A→B
A→B New
tx! 3
6 A→B
A→B A→B 2
A→B
A→B A→B
4
A→B
Should I relay a proposed transaction?
3
6 A→B
A→B 2
A→B
4
A→B
Race conditions
Transactions or blocks may conflict
●Default behavior: accept what you hear first
●Network position matters
●Miners may implement other logic!
Block propagation nearly identical
Source: Yonatan Sompolinsky and Aviv Zohar: “Accelerating Bitcoin’s Transaction Processing” 2014
How big is the network?
Compare to:
●VISA: 2,000‐10,000 transactions/sec
●PayPal: 50‐100 transaction/sec
Cryptographic limits in Bitcoin
5
1 Block 23
24
Block 23
7
That’s Block 23
24
8 That’s
crazy Block 23
24
Block crazy
talk!! 24 talk!!
I found a nifty 3
6 24 new block! Block
Block 23
24
Block 23 2
Block 23
24
24
4
24
Block 23 PROBLEM: Old nodes will never catch up
Soft forks
Observation: we can add new features which only limit
the set of valid transactions
<signature>
<<pubkey> OP_CHECKSIG>
OP_HASH160
<hash of redemption script>
OP_EQUAL
Old nodes will just approve the hash, not run the
embedded script
Soft fork possibilities
C3I Center
Acknowledgement
centralized approach
• Can be manipulated from inside
and outside
• We have to trust the owners of the
database and servers to keep data
secure and with integrity
• Hackers can also infiltrate the
server and change data
• Centralized backup and restore can
not be necessarily trusted
Mitigating security/integrity issues in Centralized Data stores
Bob attempts to send Alice 1 ETH Bob and Alice's transaction is combined with other
transactions that have occurred since the last block
Blockchain in Pictures (2)
module.exports = function(deployer) {
deployer.deploy(HelloWorld);
}
Configuring to deploy on local Ethereum network
● Motivation
● Collection of on-chain smart contracts
● Analysis of on-chain smart contracts - identification of
the ‘Contracts of Importance’
● Results of the tools based analysis on these contracts
52
Recall
● Ethereum is the second most valuable cryptocurrency
● It is the brainchild of Vitalik Buterin who wrote the white paper
● Ethereum also uses PoW (migrating to Casper soon)
● Ethereum can also store and run small computer programs
called smart contracts
● The Ethereum Protocol is maintained by the Ethereum
Foundation
● Unlike Bitcoin, Ethereum has two kinds of addresses -
○ Externally Owned Accounts (EOA)
○ Contract Accounts
53
Image Source - https://commons.wikimedia.org/
Recall (2)
● The term smart contracts was coined by Nick Szabo in 1997
● They are small programs that exist on the blockchain and are
executed by the Ethereum Virtual Machine (EVM).
● All the functionality required is implemented in the smart
contract logic, and since the code itself resides on the
blockchain it becomes highly tamper resistant.
● This property is crucial in applications like escrow payments,
voting systems, etc.
● Finding new application areas for smart contracts is an active
research area.
54
Recall: Ethereum Virtual Machine (EVM)
● Provides a layer of abstraction between the code and the
machine
● Also makes the code portable across different machines
● The EVM has 140 opcodes which allow it to be Turing complete
● Each opcode takes 1 byte of storage space.
● The EVM also uses a 256 bit register stack which holds 1024
items.
● It also has a contract memory (non-persistent) for
complicated operations
● For storing data indefinitely, storage is used.
● Reading from storage is free, but writing to storage is extremely
expensive.
55
56
Solidity
● Solidity is the most popular programming language for
Ethereum Smart Contracts
● It is similar to Javascript and C++
● Other experimental languages like Vyper and Bamboo are not
much in use
● Solidity Compiler (solc) converts the source code to EVM
bytecode
57
Image Source - https://en.wikipedia.org/wiki/Solidity
Ether and Gas
● Ether is the native cryptocurrency of the Ethereum Network
● Gas is a unit to measure the computational work done.
○ Introduced as it would have been unfair to base the
transaction fees on just the transaction length or keep it
constant
○ Each operation has a gas cost
○ Every transaction mentions the gas price
○ The two together give the transaction fees in Ether
○ Two new scenarios -
■ Transaction running out of gas
■ Gas price too low/high
58
Collection of On-Chain Smart Contracts
59
Collection of Smart Contracts - The Challenges
● How to get the smart contract data?
○ The most direct way is to connect to the Ethereum Network using a
client like geth and run a full node that is usually run by miners.
○ However, the Ethereum Blockchain data had crossed 1TB in May, 2018.
○ Syncing a full Ethereum node takes a lot of time
○ Therefore, running a full node was infeasible on the IITK network
60
Collection of Smart Contracts - Our Approach
● We leveraged the INFURA API (by Consensys) and leveraged its ‘geth-like’
methods (getCode()) and Web3 to get the smart contract data.
● However, the search space was huge and the network became a bottleneck.
Therefore, we distributed the workload accross GCP Compute Engine instances 61
Collection of Smart Contract Source Codes
● Etherscan gives an option to smart contract developers to publish their source
codes of the on-chain contracts.
● This allows for better transparency in the system as the readability and
auditability of the source codes is much easier.
● For all the collected smart contract addresses, we call the etherscan APIs
getsourcecode endpoint, and store the solidity code if available.
62
Collection of Smart Contracts - Summary
63
Analysis of On-Chain Smart Contracts
64
Analysis on the smart contracts - Parameters
DUPLICITY
ETHER BALANCE
NUMBER OF TRANSACTIONS
VALUE OF TRANSACTIONS
CONTRACT CREATION
65
* For all categories the results were aggregated for duplicate smart contracts
Duplicity
● It is observed that out of 1.9M smart contracts, 1.8M (94.6%) are duplicates
● The most duplicated contract is User Wallet contract with over 650K instances
● However, only 2 out of the top 10 have verified source codes available
● It is observed that the top hundred contracts (0.1%) amount to a total of 1.72M
(90.28%) occurrences in the dataset
● We call these High Occurrence Targets
66
Ether Balance
● The collected contracts contain a total of 10.88M ETH (worth US$1.66B1)
● The most valuable contract is Wrapped Ether (WETH9). It contains roughly 2.4M
ether (22%).
● It is observed that the top hundred contracts (0.1%) contain 10.7M (98.86%)
ETH. This is worth US$1.6B1
● We call these High Value Targets
68
Value of Transactions
● Smart Contracts in our dataset have been involved in transactions worth 484M
ETH (US$73B).
● 877K contracts (45.9%) have not been involved in any transaction involving ETH.
● The most ether has been moved by ReplaySafeSplit
○ this was used heavily post the Ethereum hard fork in 2016 to avoid replay attacks.
● It is observed that the top hundred contracts (0.1%) have moved 459.4M ETH
(94.89%).
● We call these contracts High Ether-Moving targets
69
Contract Creation Analysis
● Contracts can be created by
○ Normal Transactions - responsible for 39.4% (753K) contract deployments.
○ ‘Internal’ Transactions - not reflected on the blockchain. Amount to 60.6%
(1.16M) of all contract creations.
● The first contract was deployed on 7th August, 2015.
● Average gas used to deploy a contract is 318K gas.
● The trend of contract deployments over time closely resembles the price graph
of Bitcoin.
70
Contract Creation Analysis
● The 753K contracts deployed by normal transactions, have been deployed by
only 57,600 accounts.
71
Contract Creation Analysis
● For the 1.16M contracts deployed using internal transactions, it is observed that
these contracts have been deployed by only 9228 unique contract addresses.
This number reduces to 2420 contracts on considering duplicates.
● It is observed that the top 100 (0.1%) contracts have deployed 1.14M contracts
(98.93%)
● We call these High Origin Targets
72
Analysis of on-chain Contracts - Summary
● We observe that the smart contracts on the blockchain are not as
decentralised as expected.
● Across different categories, we observe that only a small fraction of smart
contracts are ‘important’.
● We call these 2900 (2715 unique) contracts - ‘Contracts of Importance’ and
use it for further studies.
73
Security of Ethereum
Security Issues
● DAO Attacks
● Ethereum is a public blockchain all the smart contracts are
available
● To study the security trends and patterns in the real world
smart contracts
● Analyse various smart contract verification tool on important
contracts
75
Smart Contract Security - Why it is needed?
● Smart Contracts once deployed on the blockchain become immutable - as
long as the blockchains integrity is not compromised.
● This attractive property becomes a unique challenge from a security and
software engineering viewpoint -
○ new features and functionalities cannot be added
○ bugs and other vulnerabilities discovered after deployment cannot be
patched
● It becomes imperative to thoroughly audit the smart contracts before
deploying it and also develop new software development methodologies to
cope up with these challenges
76
Impact of Smart Contract Insecurities
https://www.freecodecamp.org/news/a-hacker-stole-31m-of-ether-how-it-happened-and-what-it-means-for-ethereum-9e5dc29e33ce/
https://medium.com/@ogucluturk/the-dao-hack-explained-unfortunate-take-off-of-smart-contracts-2bd8c8db3562
https://www.theblockcrypto.com/linked/22366/tron-had-a-bug-that-could-have-made-the-entire-network-unusable
https://www.theregister.co.uk/2017/11/16/parity_flaw_not_fixed/ 77
Problems faced by Developers and Users
● Since smart contracts is a new area of research, and industry is leading most of
the efforts, not much information about smart contract vulnerabilities, tools and
practices is available in the organized domain.
● The biggest problems are -
○ Studies on smart contract vulnerabilities are often unorganized and
incomplete
○ Security tools do not have a corresponding academic paper
○ Most tools demonstrate their capabilities on different (sometimes random)
datasets.
○ Also, they call similar vulnerabilities by different names
● This makes it impossible for a smart contract developer, or the end-user to make
an informed decision about which tool to use and trust for their particular use-
case.
78
Problems faced by Security Researchers
● Studies on smart contract vulnerabilities are often outdated and incomplete
● Lack of a benchmark - no way to compare the tools/research
● No information on the trends and patterns followed by the real world smart
contracts - to guide security tool research and development
79
Insecurity Trends & Patterns
● According to the results of the tools on the contracts of importance the most common security
vulnerabilities and issues are -
○ Re-entrancy https://medium.com/coinmonks/protect-your-solidity-smart-contracts-from-reentrancy-attacks-9972c3af7c21
○ Bad Randomness https://medium.com/dedaub/bad-randomness-is-even-dicier-than-you-think-7fa2c6e0c2cd
80
Study of Security Vulnerabilities
81
Security Vulnerabilities - Re-entrancy
● A re-entrancy condition is when an actor can call your contract’s function and
potentially re-enter the contract before the previous call is completed - one or
multiple times.
○ This would be especially disastrous in the case of a payable function.
○ The fact that the call() function triggers code execution without setting a
gas limit makes in vulnerable to re-entrancy bugs.
○ The DAO Attack was a re-entrancy attack.
82
Security Vulnerabilities - Function Visibility
● Solidity has four visibility modifiers - public, private, external and internal.
● By default Solidity functions are set to public, therefore it is recommended to
always explicitly mention the visibility modifiers.
● It has been observed that these attacks are quite frequent (and dangerous)
because of improper constructor naming - either due to a typographical error or
improper copy-pasting of existing contracts.
● The Parity bug was a vulnerability of this category.
contract HashForEther {
function withdrawWinnings() {
// Winner if the last 8 hex characters of the address are 0.
require(uint32(msg.sender) == 0);
_sendWinnings();
}
function _sendWinnings() {
msg.sender.transfer(this.balance);
}
}
83
Security Vulnerabilities - Improper Access Control
● Use of tx.origin for authorization
○ A type of a phishing attack
○ If tx.origin is used for authorization, and the actual owner is conned to
call a malicious contract which in turn calls the victim contract, then the
authorization fails.
● Forced Ether Reception
○ If ether is forced using selfdestruct the receiving function’s fallback
function does not get executed.
○ Therefore, the contract’s balance should never be used as a guard
contract Phishable { import "Phishable.sol";
address public owner; contract AttackContract {
constructor (address _owner) { Phishable phishableContract;
owner = _owner; address attacker; // The attackers address to receive funds.
} constructor (Phishable _phishableContract, address
function () public payable { } // collect ether _attackerAddress) {
function phishableContract = _phishableContract;
attacker = _attackerAddress;
function withdrawAll(address _recipient) public { }
require(tx.origin == owner); _ function () payable {
recipient.transfer(this.balance); phishableContract.withdrawAll(attacker);
} } 84
} }
Security Vulnerabilities - Front Running
● Two transactions can be sent to the transaction pool and the order in which
they arrive is irrelevant.
● Gas sent is vital as it usually decides which transaction is mined first.
● An attacker can also be a miner and miners decide the order of transactions.
● Creates a problem for smart contracts that rely on state of storage variables.
contract TransactionOrdering {
uint256 price;
address owner;
contract OverflowUnderFlow {
uint public zero = 0;
uint public max = 2**256-1;
86
Security Vulnerabilities - Bad Randomness
● Many smart contracts, such as those made to create lotteries or online games,
use pseudo-random number generator where the initialization seed is chosen
uniquely for all miners.
● A common choice for the seed is the hash or timestamp of some block that will
appear on the blockchain in the future. This ensures that at run-time the value is
same for everyone and this is secure since content of future blocks is
unpredictable
● However, malicious miners can craft their attacks to bias the seed
87
A New Taxonomy for the Vulnerabilities
88
89
Vulnerability Benchmark
90
Vulnerability Benchmark Creation
● We collected contracts known to be vulnerable from various sources. This
included -
○ Smart Contract Weakness Classification (SWC) Registry
○ (Not So) Smart Contracts
○ EVM Analyzer Benchmark Suite
○ Research papers, theses and books
○ Various blog posts, articles, etc.
91
Vulnerability Benchmark Creation
● The Ponzi Scheme Menace
○ It has been observed that the Ethereum Smart Contracts have become a
breeding ground for ponzi schemes over the last few years.
○ Some of these Ponzi Schemes utilize the vulnerabilities explained earlier.
○ The others can be categorized into -
■ Does Not Refund, and
■ Allows owner to withdraw funds
92
The Vulnerability Benchmark - On-chain Contracts
93
The Vulnerability Benchmark
● The final benchmark contains 180 contracts (162 are unique). This also contains
40 on-chain vulnerable contracts.
94
Effectiveness of the Security Tools
95
Security Tools
RemixIDE
Slither
SECURITY TOOLS
Oyente
Securify
Symbolic Execution
Mythril
Zeus
Octopus
Formal Verification F* 96
Security Tools
97
The Experimental Setup
● All the experiments were carried out on a machine running Ubuntu 18.04.2 LTS
on an Intel® Core™ i7-4770 CPU with 16GB DDR3 RAM.
98
Security Tools - Claimed Vulnerability Coverage
99
Results on the Benchmark
100
Results on the Benchmark
101
Tool-wise Analysis
Remix IDE
● Manual Static Analysis & Incompleteness
● For solc<=0.3.1, the check-effects and the selfdestruct modules give an
error
102
Tool-wise Analysis
Slither
● Detected at least one from each category it claims to identify and was able to
analyze successfully
● Drawback - requires correct solc version installed and does not work prior to
0.4.0
103
Tool-wise Analysis
SmartCheck
● Performance not very good
● Can detect simpler vulnerabilities effectively
104
Tool-wise Analysis
Oyente
● Showing its age
● Average EVM code coverage for the entire benchmark set was found to be
75.98%.
● Not even a single case of integer overflow/underflow - bug in the tool
105
Tool-wise Analysis
Mythril
● It is able to detect the attacks with a fair accuracy, however it encounters a lot of
errors.
106
Tool-wise Analysis
Securify
● The only tool that reports a contract as ‘safe’ from a particular vulnerability.
● Lot of false negatives reported by the tool
107
Malicious Nodes in Ethereum
Motivation
● Permissionless blockchains mainly deal with crypto-currencies and are prone to cyber attacks,
scams and ransom payments.
○ They use graph properties such as inDegree, outDegree and clustering coefficient on top of blockchain
specific properties such as transaction amount.
A A A
D D D
B B
C E E C E
Motivation
● We find that each account behaves differently
○ Distribution of inDegree over time follows power law
○ Most malicious accounts interact with accounts that they have not
interacted in past (stability of neighbourhood is low).
Low stability
Our Approach
Unsupervised
Supervised
Features Extraction
● Based on previous attacks, scams and ransom payments
● Extended existing feature set to include temporal behaviour based features related to
○ Burstiness
■ In/out-Degree
■ Temporal
■ Transaction Amount
○ Attractiveness
Burstiness: Degree
● More than k events happening at the same time.
Incoming transactions
Outgoing transactions
t0 tn
Δt
Incoming transactions
Outgoing transactions
t0 tn
Δt
tx1 tx7
tn
Δt
t0
Attractiveness
● Measure of stability of neighbourhood.
○ Nit neighbourhood of account i at time t
○ Θa = duration of dataset
A A A B
A
Most Unstable
C E C Most Stable
B D Between Unstable and
B Stable
C B
E E
E
C3I Center
Acknowledgement
• IBM Hyperledger presentations/slides
• Slides of Praveen Jayachandran, IBM
Key Concepts and Benefits of Blockchain for Business
Censorship-resistant Privacy
Scale to large number of nodes Scale in transaction throughput
One global blockchain Many interacting blockchains
Figure source: “Distributed Ledger Technology: Beyond Blockchain”, A report by UK Govt Chief Scientific Adviser
4
The Linux Foundation Hyperledger Project
A collaborative effort created to advance blockchain technology by identifying and addressing important features for a cross-industry open
standard for distributed ledgers that can transform the way business transactions are conducted globally.
www.hyperledger.org
Premier
General
Associate
Trade Logistics Invoice discounting Trade finance Food Safety Channel Financing
The Participants in a Blockchain Network
R U
B2B transactions Blockchain
Regulator User
✓
performs
oversight Certificate
Authority
accesses
security
D certificate
Blockchain
Developer creates Blockchain s
applications
operates access to
data Traditional
Data Sources
O access to logic
Blockchain
Network
Operator Traditional
Processing
Platforms
7
Blockchain Components
Blockchain
8
Blockchain Applications and the Ledger
Blockchain
developer
develops
Application
D
emits
* Smart
Contract
event
‘get’ ‘put, ‘delete’
block
World/Ledger
state
txn txn txn txn …
Blockchain
Ledger * Smart Contract
implemented
using chain code
9
Hyperledger Fabric Model
Identity
Issuer
Ledger
Ledger
Transaction
(defining contracts) Peer Peer
Application fabric
Ledger
Ledger
AliceApp
Ledger
Client Validating Entities
Peer Peer
Transaction
(invoking contracts)
Ledger
Ledger
Peer Peer
fabric
Application
BobApp Client
15
Security & privacy features
Privacy of user- Each user has control over the degree to which its transaction activity will be
participation
shared with its environment
Contract Privacy Contract logic can be confidential, i.e., concealable to unauthorized entities
Accountability Users can be accounted for the transactions they create, cannot frame other
Non-repudiation
users for their transactions, or forge other users’ transactions.
Auditability
Auditors are able to access & verify any transaction they are legally
authorized to
16
A sample transaction (1/6)
Smart Contract
Client 1
App (PROPOSE)
E2 E3
A A
B D
E0
A
B
CC
CC
E1
A
B
Blockchain Network
E0
A
B
CC
CC
E1
A
B
Blockchain Network
E0
1 (PROPOSE, A
B
anchor)
CC
CC
E1
A
B
Blockchain Network
Client
App
E2 E3
A A
B D
3 (TRANSACTION-VALID)
E0
A
B
3 (TRANSACTION-
VALID) CC
CC
E1
A
B
Blockchain Network
Client
App
E2 E3
A A
B D
4 (BROADCAST)
E0
A
B
CC
CC
E1
A
B
Blockchain Network
Client
App
E2 E3
A A
B D
5 (DELIVER)
E0 5 (DELIVER)
A
B
5 (DELIVER) CC
CC 5 (DELIVER)
E1
A
B 5 (DELIVER)
Blockchain Network
6. The consensus service delivers the next block in the ledger with the
consented transaction. 2
2
Blockchain Technology And
Applications
Sandeep K. Shukla
IIT Kanpur
C3I Center
Acknowledgement
• Fred Schneider (Cornell Univ)
• Elli Androulaki et. al (Authors of Hyperledger Fabric paper)
https://arxiv.org/ct?url=https%3A%2F%2Fdx.doi.org%2F10.1145%2F3190508.3190538&v=92886ca2
Evolution of Blockchain Technology
▪ 1st generation: Store and transfer of value (e.g. Bitcoin, Ripple,
Dash)
▪ 2nd generation: Programmable via smart contracts (E.g. Ethereum)
▪ 3rd generation: Enterprise blockchains (E.g. Hyperledger, R3 Corda
& Ethereum Quorum)
▪ Next gen: Highly scalable with high concurrency
Server
10
X = 10
Client
get(x)
…No response
get(x)
Client
Motivation
Server
X = 10 X = 10
Client
X = 10 X = 10
Motivation
c X=Y
• c is a f(c)
Command
• f is a Transition
Function X=Z
State Machine Replication (SMR)
• The State
Machine
Approach
X=Y X=Y to a fault
c
tolerant
distributed
system
X=Y X=Y • Keep
around N
copies of
the state
machine
State Machine Replica
State Machine Replication (SMR)
• The State
f(c) f(c)
Machine
Approach
X=Z X=Z to a fault
tolerant
distributed
f(c) f(c) system
X=Z X=Z • Keep
around N
copies of
the state
machine
State Machine Replica
SMR Requirements
put(x,10)
X=3 X=3
X=3 X=3
SMR Requirements
X = 10 X = 10
Great!
X = 10 X = 10
SMR Requirements
put(x,10)
X=3 X=3
X=3 X=3
SMR Requirements
X = 10 X = 10
Great!
X = 10 X = 10
SMR Requirements
put(x,10)
X=3 X=3
X=3 X=3
SMR Requirements
get(x)
X = 10 X = 10
10
• Replicas get(x)
need to X = 10 X=3
agree on 3
the which
requests Problem!
have been
handled
SMR Requirements
put(x,10) put(x,30)
X=3 X=3
r0 r1
X=3 X=3
SMR Requirements
X = 10 X = 10 X=3 X=3
OR
X = 10 X = 10 X=3 X=3
SMR Requirements
put(x,10) put(x,30)
X=3 X=3
r0 r1
X=3 X=3
SMR Requirements
put(x,10) put(x,30)
r0 r1
r0 X=3 X=3 r1
r0 X=3 X=3 r1
SMR Requirements
put(x,10) put(x,30)
r0 r1
r0 X = 10 X = 30 r1
r0 X = 10 X = 30 r1
SMR Requirements
put(x,10) put(x,30)
r0 r1
r0 X = 10 X = 30
r1
r1 r0
r0 X = 10 X = 30 r1
r1 r0
SMR Requirements
r0 X = 30 X = 10
r1
r1 r0
r0 X = 30 X = 10 r1
r1 r0
• Replicas need to
handle requests in
the same order
SMR
• All non faulty servers need:
• Agreement
• Every replica needs to accept the same set of requests
• Order
• All replicas process requests in the same relative order
Implementation
• Agreement
• Someone proposes a request; if that person is nonfaulty all servers will accept
that request
• Strong and Dolev [1983] and Schneider [1984] for implementations
• Client or Server can propose the request
SMR Implementation
put(x,10)
X=3 X=3
X=3 X=3
SMR Implementation
X=3 X=3
X=3 X=3
put(x,10)
Non-faulty Transmitter
Implementation
• Order
• Assign unique ids to requests, process them in ascending order.
• How do we assign unique ids in a distributed system?
• How do we know when every replica has processed a given request?
SMR Requirements
put(x,30) put(x,10)
X=3 X=3
r0 r1
X=3 X=3
SMR Requirements
put(x,30) put(x,10)
X=3 X=3
r0 r1
X=3 X=3
Assign Total Ordering
Request ID
r0 1
r1 2
SMR Requirements
r0 X=3 X=3
r1
r1 r0
r0 r1
X=3 X=3
r1 r0
Request ID
r0 1
r1 2
SMR Requirements
r0 X=3 X=3
r0
r1 r1
r0 r0
X=3 X=3
r1 r1
Request ID
r0 1
r1 2
SMR Requirements
r0 X = 30 X = 30
r0
r1 r1
r0 r0
X = 30 X = 30
r1 r1
r0 1
r1 2
SMR Requirements
r0 X = 10 X = 10
r0
r1 r1
r0 r0
X = 10 X = 10
r1 r1
r0 1 r1 is now stable!
r1 2
Implementation Client Generated IDs
• Order via Clocks (Client timestamps represent IDs)
• Logical Clocks
• Synchronized Clocks
• Ideas from [Lamport 1978]
Implementation Replica Generated IDs
• 2 Phase ID generation
• Every Replica proposes a candidate
• One candidate is chosen and agreed upon by all replicas
Replica ID Generation
put(x,30) put(x,10)
X=3 X=3
r0
r1
X=3 X=3
Replica ID Generation
1) Propose Candidates
Replica ID Generation
2) Accept r0
Replica ID Generation
3) Accept r1
Replica ID Generation
r1 is now stable
Replica ID Generation
4) Apply r1
Replica ID Generation
5) Apply r0
Implementation Replica Generated IDs
• 2 Rules for Candidate Generation/Selection
• Any new candidate ID must be > the id of any accepted request.
• The ID selected from the candidate list must be >= each candidate
• In the paper these are written as:
• If a request r’ is seen by a replica smi after r has been accepted by smi
then uid(r) < cuid(smi,r’)
• cuid(smi,r) <= uid(r)
Fault Tolerance
• Fail-Stop
• A faulty server can be detected as faulty
• Byzantine
• Faulty servers can do arbitrary, perhaps malicious things
• Crash Failures
• Server can stop responding without notification
(subset of Byzantine)
Fault Tolerance
• Fail-Stop
• A faulty server can be detected as faulty
• Byzantine
• Faulty servers can do arbitrary, perhaps malicious things
• Crash Failures
• Server can stop responding without notification
(subset of Byzantine)
Fail-Stop Tolerance
put(x,30)
X=3 X=3
r0
X=3 X=3
Fail-Stop Tolerance
X=3 X=3
1) Propose Candidates….
Fail-Stop Tolerance
X=3 X=3
2) Accept r0
Fail-Stop Tolerance
X=3 X=3
2) Apply r0
Fail-Stop Tolerance
X = 30 X=3
GAME OVER!!!
X=3 X=3
2) Apply r0
Fail-Stop Tolerance
• To tolerate t failures, need t+1 servers.
• As long as 1 server remains, we’re OK!
• Only need to participate in protocols with other live servers
Byzantine Tolerance
get(x)
X=3 X=3
r0
X=3 X=3
Byzantine Tolerance
get(x)
X=3 X=3
r0
X=3 X=3
Byzantine Tolerance
X=3 X=3
3
X=3 X=3
Byzantine Tolerance
X=3 X=3
3
X=3 X=3
X=3 X=3
3
X=3 X=3
Who to trust?? 3 or 7?
Byzantine Tolerance
put(x,30)
X=3 X=3
r0
X=3 X=3
Byzantine Tolerance
r0 1.2 r0 1.4
1) Propose Candidates
Byzantine Tolerance : a) No response
r0 1.2 r0 1.4
a) Accept r0
Byzantine Tolerance: Small ID
r0 1.2 r0 1.4
1) Propose Candidates
Byzantine Tolerance: Small ID
uid = max(cuid(smi,r))
Ignore low candidates!
r0 1.2 r0 1.4
2) Accept r0
Byzantine Tolerance: Small ID
uid = max(cuid(smi,r))
Ignore low candidates!
2) Accept r0
Byzantine Tolerance: Large ID
r0 1.2 r0 1.4
1) Propose Candidates
Byzantine Tolerance: Large ID
Large numbers follow
protocol!
r0 1.2 r0 1.4
Byzantine Tolerance: Large ID
Large numbers follow
protocol!
r0 1.2 10 r0 1.4 10
2) Accept r0
Fault Tolerance
• Byzantine Failures
• To tolerate t failures, need 2t + 1 servers
• Protocols now involve votes
• Can only trust server response if the majority of servers say the same thing
• t + 1 servers need to participate in replication protocols
How Blockchains differ from SMRs
C3I Center
Acknowledgements
• IOTA while paper https://iota.org/IOTA_Whitepaper.pdf
• IOTA blog https://blog.iota.org/the-tangle-an-illustrated-introduction-
4d5eae6fe8d4
• https://public-rdsdavdrpd.now.sh/
Transactions, Confirmation And Consensus
4
Blockchain and IoT
5
IoT – Internet of Things
• Examples
• Smart City
• Smart Home
• Smart Grid
• Smart Transportation
• What is enabling information technology?
• IoT components must talk to each other M2M to share information
• Visibility of the State of the system or subsystem as a whole for autonomous decision
making
• Cloud based IoT ecosystem proposed by many companies
• All IoT devices communicate to the cloud and get global state info from the cloud
• Often communicate via cloud
22.10.2017 6
Cloud + IoT
7
Single Shared Truth for Everyone
8
What’s the problem with Cloud + IoT
• Single point of failure
• Data Integrity and confidentiality at stake
• Cyber attack on the cloud
• Cloud infrastructure provider gets enormous power and data
• Can we decentralized this?
• Blockchain anyone?
22.10.2017 9
IoT + Blockchain
• Existing Blockchain (Bitcoin, Ethereum etc)
• Scalability issues
• PoW computational requirement
• Centralization by powerful miners
• Cost of transactions
• All guarantees of integrity is probabilistic
• Privacy requires a bit more thought
• IoTA foundation claims to have a solution
• Replace Blockchain by Tangle
• It borrows a lot of ideas from Blockchain
• But not exactly a blockchain
22.10.2017 10
Requirements of IoT
• Low Resource Consumption
• Widespread Interoperability
• Billions of Nano-transactions
• Data Integrity
22.10.2017 11
The Tangle
22.10.2017 12
Tangle
• No block – individual transactions are tangled together
• What is Tangling
• Construct Directed Acyclic Graphs (DAGs) connecting transactions
• Self Regulating
• Very Scalable
• Still use PoW – but a long overhead PoW
• Prevent spamming
13
What we get out of Tangle in place of Blockchain?
• CAP
• Consistency
• Availability
• Partition-Tolerance
• No Fees
• Scalable
• Modular
• Lightweight
• Offline allowed
• Quantum Proof
14
Envisioned Use cases
• Complete M2M communication
• Anything which has computational resource (Chip) can be leased by another
machine autonomously
• Devices can share resources by coordinating – bandwidth sharing for example
• Supply Chain
• Smart Grid to coordinate production of energy without human dispatching
• On-demand API access
• Sensor Data Selling and Data Market Place
• ….
15
Towards Smart Decentralization
Tangle Initialization & Transaction Issuance
Issuing a Transaction
1.Bundling & Signing
2.Tip Selection
3.Validation
4.Proof-of-Work
(PoW)
5.Publishing
17
https://public-rdsdavdrpd.now.sh/
Simulations
• Simulation by varying λ (transaction arrival rate – Poisson process)
• https://public-rdsdavdrpd.now.sh/
• Simulation of unweighted random walk based tip selection
• https://public-xnmzdqumwy.now.sh/
• Simulation of weighted random walk based tip selection
• https://public-qnbiiqwyqj.now.sh/
• Simulation of Confirmation Confidence Computation
• https://public-krwdbaytsx.now.sh/
•
18
Initial Tangle State
Unconfirmed Conflicting
w
Fully Confirmed Validation path q
s
m x
j u
g p
b
z
c k n v
i
a
d f
y
o t
e l
h
r
α
Slide 19
Adding A Transaction
Unconfirmed Conflicting
w
Fully Confirmed Validation path q 1
s
m x
j u
g p
b
z
c k n v
i
a
d f
y
o t
e l
h
r
Slide 20
Another Transaction
Tip New tip
Unconfirmed Conflicting
w
Fully Confirmed Validation path q 1
s
m x
j u
g p
b
z
c k v
i n
a
d f 2
y
o t
e l
h
r
Slide 21
New Tangle State
Tip New tip
Unconfirmed Conflicting
w
Fully Confirmed Validation path q 1
s
m x
j u
g p
b
z
c k v
i n
a
d f 2
y
o t
e l
h
r
Slide 22
Confirmation Levels
Unconfirmed Conflicting
w
Fully Confirmed Validation path q 1
s
m x
j u 4
g p
b
z
c k v
i n
a
d f 2
y
o t
e l
h
r
3
Slide 23
Propagation Delay
w
Fully Confirmed Validation path q 1
s
m x
j u 4
g p
b
z
c k n v
i
a
d f 2
y
o t
e l
h
r
3 Slide 24
Double Spend
Unconfirmed Conflicting
w
Fully Confirmed Validation path q 1
s
m x
j u
p 4 5
g
b
z
c k v
i n
a
d f 2
y
o t
e l
h
r
3 Slide 25
Double Spend Resolution
Unconfirmed Conflicting
w 6
Fully Confirmed Validation path q 1
s 8
m x
j u 4
p 5
g
b
z
c k v
i n
a
d f 2
y
o t
e l 7
h
r
3
Slide 26
Offline Tangle
Unconfirmed Conflicting
s
m x
j u
g p
b
z
c i k n v
a
d f
y 8
o t
e l
3 7
h 2 5
r
1
4
6
C3I Center
Acknowledgements
• Richard Brown, R3
• Razi Rais, Microsoft
• Corda Whitepaper: https://docs.corda.net/_static/corda-
introductory-whitepaper.pdf
• Corda Technical Whitepaper: https://docs.corda.net/_static/corda-
technical-whitepaper.pdf
What is Corda? Is it a Blockchain?
• Corda has no unnecessary global sharing of data: only those parties with a legitimate
need to know can see the data within an agreement
• Corda choreographs workflow between firms without a central controller
• Corda achieves consensus between firms at the level of individual deals, not the level of
the system
• Corda’s design directly enables regulatory and supervisory observer nodes
• Corda transactions are validated by parties to the transaction rather than a broader pool
of unrelated validators
• Corda supports a variety of consensus mechanisms
• Corda records an explicit link between human-language legal prose documents and
smart contract code
• Corda is built on industry-standard tools
• Corda has no native cryptocurrency
Blockchains are basically 5 interlocking services
• Consensus
• Validity
• Uniqueness (anti-double-spend)
• Immutability
• Authentication
2008 Bitcoin
Bitcoin blockchain:
• Permission-less Blockchain
• Wastage of energy
• Pseudo-anonymous
Algorand: The Solution
• Proven security bounds, about % of malicious users who may disrupt majority of network for
certain amount of time.
• Very low CPU load, can potentially run on modern mobile phones
Algorand features
• No Forking (safety)
• Transaction Efficiency
Broad Ideas
• Security
• Latency: confirm transaction in order of minutes (no need to wait after block
accepted)
• Energy wastage
• Collusion: users may pool >50% mining power and steal currency
• Flexibility
• No mining
Asset
Consensu Ledger
s
Hyperledge
r
Membe
Chain-
r-ship
code
Services
Channel
Peers and Ledger
Blockchain
Channels
Organization
Endorsement policy
• A transaction can only be considered valid if it has been endorsed according to its policy
Examples of policies
• AND(‘org1.member’,’Org2.member’,’Org3.member’)
• Or(‘Org1.member’,’Org2.member’)
• Or(‘Org1.member’,AND(‘Org2.member’,’Org3.member’))
Proposal
Packaging
Validation
Pros
• Enterprise backing
• Modular architecture
• Private channels
• Smart contracts
• Permissioned
IOTA
No
Transaction Scalable
fee
No Mining
IOTA Blockchain
• Public Blockchain
Hashing
Aggregation Publication
KSI: Pros
• Privacy
• Quantum immune
• Private/permissioned
• Patented by Guardtime
• Loss of token
Summary
BFT
Cryptographic
Zk-Snarks
sorition
National
Blockchain
Permissioned
Hard printing
blockchain
Nash
Equilibrium
Credits images
https://arstechnica.com/tech-policy/2017/11/bitcoin-rival-doubles-in-price-in-four-days-as-bitcoin-price-slumps/
https://kryptomoney.com/ethereum-explores-higher-levels-heads-800/
https://image.slidesharecdn.com/smart-contracts-150925125324-lva1-app6892/95/smart-contracts-5-
638.jpg?cb=1443185644
https://image.slidesharecdn.com/smart-contracts-150925125324-lva1-app6892/95/smart-contracts-4-
638.jpg?cb=1443185644
https://bitcoinexchangeguide.com/algorand/
https://www.pinterest.co.uk/pin/5066618308753012/
https://chrispacia.wordpress.com/2013/09/02/bitcoin-mining-explained-like-youre-five-part-2-mechanics/
https://medium.com/@lhartikk/a-blockchain-in-200-lines-of-code-963cc1cc0e54
https://medium.com/hashtaagco/blockchain-say-what-8e16ed29e543
https://patents.google.com/patent/US20170033932
https://medium.com/iota-et-tangle/presentation-iota-tangle-2d6e63e3a70
https://www.bitcoinbeginner.com/blog/what-is-iota/
https://medium.com/@philippsandner/comparison-of-ethereum-hyperledger-fabric-and-corda-21c1bb9442f6
https://www.cryptocompare.com/mining/guides/how-to-mine-zcash/
https://www.criptonoticias.com/aplicaciones/zcash-celebra-primer-aniversario-impulsando-privacidad-intercambios-atomicos/
https://slack.com/apps/A0P9ZU35Z-crypto-currency-coin-market-cap
https://www.wired.com/story/how-to-set-up-twitter-lists/
https://www.vectorstock.com/royalty-free-vector/crypto-currency-zcash-silver-symbol-vector-19123605
https://atozforex.com/news/zcash-price-long-term-forecast-2025/
https://www.dreamstime.com/stock-illustration-thank-you-text-illustration-social-icons-tablet-computer-mobile-cellphones-cyan-digital-
world-map-background-image48170847
Hyperledger Documentation
Blockchain Technology And
Applications
Sandeep K. Shukla
IIT Kanpur
C3I Center
Land
Records on
Hyperledger
Fabric
Smart Contract
Hyperledger Ledger
Fabric Basics:
Peers
• Endorsing peers
• Committing peers
• Orderer
World State, Ledger and
Blockchain
Hyperledger
Fabric Basics:
Channels
Hyperledger
Fabric Basics:
Organization
Hyperledger
Fabric Basics:
Orderers
Fabric
Architecture
with 2
organizations
Land Registration
Example of multiple channel architecture
Problem Statement
Receives New
Land Records
Copy
P1 L2 P2
L1 L2 L3
Citizen Registration
Office
L1 L3
Channel 2
P1 L2 P2
L1 L2 L3
CC3
CC1
Channel 1 Channel 3
P3
L1 L3
Querying
chaincode of
other channels
CC1 CC2 is allowed CC2 CC3
Channel 2
P1 L2 P2
L1 L2 L3
CC3
CC1
Channel 1 Channel 3
P3
L1 L3
Land Records Registry Update Application
• Buyer
• Seller • Registration
• Land Id
• Sell Value number
• Owner
• Stamp Duty • Buyer
• Land Area
Assets • Circle Rate
• Date of • Seller
Transaction • Land ID
• Percentage land
• Witness • Date of
Holding
• Registration Transaction
• Registry
number
1. applyRegistration
2. validateRegistration
3. applyUpdate
4. approveChanges
Transactions 5. updateLandRecord
(some)
6. fetchLandRecords
7. getLandOwner
Process View
Citizen Registration Org.
• Orderer • Orderer
• Peer • Peer
• CA • CA
• Fabric Rest API • Fabric Rest API
Deployment
• Orderer
• Peer
• CA
• Fabric Rest API
Land Record Transfer using
Corda Blockchain
State in Corda
● A state is an immutable object representing a fact known by one or
more Corda nodes at a specific point in time. States can contain arbitrary
data, allowing them to represent facts of any kind (e.g. stocks, bonds,
loans, KYC data, identity information…)
● A Land Record title can thus be treated as a state object in Corda and the
transfer of this title can be portrayed by the state sequence which
represents the lifecycle of a shared fact(in the present case a land
ownership document) over time
System Design
● We will have the following participants as Corda nodes:
○ Buyer
○ Seller
○ Government
● Government can create a new land record document with the specified
owner
● Buyer can request to buy a specific land record document
● Seller can sell(transfer ownership) of the land record document
System Design - Assets
● Land Record
○ Land ID (number)
○ Owner
■ name (string)
■ ID (number)
○ Previous owners (list of owner)
○ Buying requests (list of potential buyers)
System Design - Workflows
● Flows automate the process of agreeing ledger updates
● We will have the following flows:
○ Create Land Record Flow
■ Participants: Buyer, Government
■ Can be initiated by Government only
○ Request Ownership Transfer Flow
■ Participants: Seller, Buyer, Government
■ Can be initiated by Buyer only
○ Transfer Ownership Flow
■ Participants: Seller, Buyer, Government
■ Can be initiated by Seller only
System Design - Contracts
● A contract takes a transaction as input, and states whether the transaction is considered valid
based on the contract’s rules. In our application the contract should check for the following
● Create Land Record Contract
○ Zero input state & One output state
○ Initiated by Government
○ Two signers namely, buyer and government
● Request Ownership Transfer Contract
○ One input state & One output state
○ Initiated by any buyer
○ Three signers namely, buyer, seller and government
● Transfer Ownership Contract
○ One input state & One output state
○ Initiated by current owner
○ Three signers namely, buyer, seller and government
System Design - Consensus & Notary
● Determining whether a proposed transaction is a valid ledger update
involves reaching two types of consensus:
● Validity consensus - this is checked by each required signer before they
sign the transaction
○ In present application the signers would be buyer, seller and the government
nodes
● Uniqueness consensus - this is only checked by a notary service
○ Notary clusters can have several nodes that can be owned by government and
NGOs(acting on behalf of citizens) which can act as a neutral third parties
Electronic Health Records (EHR)
application using Hyperledger
Fabric
Problem Statement
Preserving Patients privacy: Sensitive data like prescription dosage and Bill amounts must be
encrypted with patient's public key only
Ownership of Data: Patient should decide who could access his data
C3I Center
Prevailing misconceptions about Blockchain #1
• Blockchain is like the Internet – you need to build a network
infrastructure around the country or in a state – so that everyone can
use that infrastructure to do their e-governance and other
applications.
Prevailing misconceptions #2
• Blockchain is secure
Prevailing misconceptions #3
• Cryptography guarantees Blockchain data integrity
Prevailing misconceptions #4
• Government must design a blockchain on its own and force every
government organization to use its implementation of blockchain
Prevailing misconceptions #5
• One has to have a government vetted closed source blockchain
platform on which to develop e-governance solutions
Prevailing misconceptions #6
• Blockchain cannot have data-privacy
Prevailing misconceptions #7
• “Right to forget” in the data privacy law (being tabled in the
parliament) is incompatible with blockchain usage
Prevailing misconceptions #
• Data localization is not guaranteed if we use off the shelf blockchain
Prevailing misconceptions #9
• Government must regulate blockchain technology
Prevailing misconceptions #10
• Blockchain is all about crypto-currency