SlideShare a Scribd company logo
1 of 37
Download to read offline
Let’s build a blockchain... in 40 minutes!
@MichelSchudel
michel@craftsmen.nl
Amsterdam | April 2-3, 2019
Let's build a blockchain.... in 40 minutes!
Let's build a blockchain.... in 40 minutes!
Let's build a blockchain.... in 40 minutes!
Let's build a blockchain.... in 40 minutes!
transactiontransaction
Central
authority
Ledger
transactiontransaction
transaction
transation
Distributed
ledger
Distributed
ledger
Distributed
ledger
Distributed
ledger
@MichelSchudel
1. A Blockchain is an implementation of a distributed ledger
t1t2t3
t1t2t3
t1t2t3
t1t2t3
t1t2t3
t1t2t4
@MichelSchudel
2. A Blockchain is an sequential, immutable chain of records
called Blocks
Block
transactiontransactiontransaction
Block
transactiontransactiontransaction
Block
transactiontransactiontransaction
@MichelSchudel
index : 2
previous hash
payload
transaction
transaction
transaction
3. Immutability is implemented by hashing
index : 1
previous hash: 0
Genesis block
transaction
index : 3
previous hash
payload
transaction
transaction
transaction
@MichelSchudel
Let’s build a Blockchain, then!
@MichelSchudel
Let’s build a Blockchain, then!
BlockchainRestController
Blockchain TransactionPool
BlockBlockBlockBlock
TransactionTransactionTransactionTransaction
Manages Manages
Has Has
API
GET /api/blockchain
POST /api/createtransaction
GET /api/pendingtransactions
POST /api/mine
Network
Interacts
with
@MichelSchudel
Step 1: Create the initial blockchain
index : 1
previous hash: 0
Genesis block
@MichelSchudel
Kudo’s (from, to, kudos)
Pool of transactions
Out of scope:
• Transaction integrity (signing)
• Transaction inputs and outputs
Transaction pool
transaction
transaction
transaction
Step 2: Create something to store in
the blocks
@MichelSchudel
• New block should contain hash of
previous block (immutability, trust)
• Creating a block requires proof-of-
work / stake (supports consensus)
• Creating a block should give a reward
(incentive, generation transaction)
index : 2
previous hash
payload
transaction
transaction
transaction
index : 1
previous hash: 0
Genesis block
Step 3: making (mining) a new block
@MichelSchudel
Proof-of-work
• It should be hard to create a new
block
• Makes cheating unattractive
• It should be easy to verify a new
block
@MichelSchudel
Remember this Nonce thingy?
“(new block)” “00005c3d2d...”SHA256 hash
“(new block with nonce x)” “00005c3df8...”SHA256 hash
X = 100
Creating a proof-of-work (hard)
Verifying proof-of-work (easy)
@MichelSchudel
• The longest blockchain that is valid “wins”
• A blockchain is valid when
• Previous hash field of each block matches hash of previous block
• Proof-of-work (nonce) is verified and correct for each block
Step 4: consensus with other nodes
@MichelSchudel
Step 5: Implementing decentralization
• Transactions are propagated
• Everybody should have the chance to mine
• Blocks are propagated
• Validation is performed before accepting
• This could prevent downloading all chains
@MichelSchudel
Summary
We created a blockchain in 40 minutes with:
• Blocks
• Transactions
• Mining
• Reaching consensus
• Propagation
Now go and build one yourself!
https://gitlab.com/craftsmen/workshop-blockchain
@MichelSchudel
https://gitlab.com/craftsmen/workshop-blockchain
@MichelSchudel
michel@craftsmen.nl
Code slides
(in case you didn’t see the demo)
Create the block structure
public class Block {
private long index;
private Set<Transaction> transactions = new HashSet<>();
private String previousHash;
private long nonce;
…getters, setters, toString etc.
}
Making the initial chain
public class Blockchain {
private LinkedList<Block> blocks = new LinkedList<>();
static Blockchain create() {
Blockchain blockchain = new Blockchain();
Block block = new Block();
block.setIndex(1);
block.setPreviousHash("0");
block.setNonce(0);
blockchain.blocks.add(block);
return blockchain;
}
}
Creating a transaction
public class Transaction {
private String id;
private String from;
private String to;
private int kudos;
..getters, setters…
… equals and hashcode based on id only!
}
Creating a transaction pool
public class TransactionPool {
private Set<Transaction> transactions = new HashSet<>();
public void addTransaction(Transaction transaction) {
transactions.add(transaction);
}
public void clearTransactions() {
transactions.clear();
}
public Set<Transaction> getAllTransactions() {
return new HashSet<>(transactions);
}
}
Creating a transaction
@PostMapping("/api/createtransaction")
public long createTransaction(@RequestBody Transaction transaction) {
//give the transaction an id
transaction.setId(UUID.randomUUID().toString());
//add the transaction to the pool
transactionPool.addTransaction(transaction);
//return the height of the next block
return blockchain.height() + 1;
}
Mining a new block
@PostMapping("/api/mine")
public Block mine() {
Block block = getBlockchain().mine(transactionPool.getAllTransactions());
transactionPool.clearTransactions();
return block;
}
Mining a new block
public class Blockchain {
...
public Block mine(Set<Transaction> allTransactions) {
Block block = new Block();
block.setIndex(this.blocks.size() + 1);
block.setPreviousHash(DigestUtils.sha256Hex(blocks.getLast().toString()));
block.setTransactions(allTransactions);
//create reward
Transaction reward = new Transaction();
reward.setId(UUID.randomUUID().toString());
reward.setFrom("");
reward.setTo(“Michel for creating this block");
reward.setKudos(3);
allTransactions.add(reward);
block.calculateProofOfWork();
blocks.add(block);
return block;
}
}
Proof of work
public class Block {
…
public void calculateProofOfWork() {
this.nonce = 0;
while (!DigestUtils.sha256Hex(this.toString()).startsWith("0000")) {
this.nonce++;
}
}
}
Comparing with other blockchains
In your service…
public void init() {
this.blockchain = Blockchain.create();
this.blockchain = network.retrieveBlockchainsFromPeers()
.stream()
.filter(b -> b.isValid())
.filter(b -> b.height() > this.blockchain.height())
.max(Comparator.comparing(Blockchain::height))
.orElse(this.blockchain);
}
Comparing with other blockchains
public boolean isValid() {
for (int i = blocks.size() - 1; i > 0; i--) {
Block currentBlock = blocks.get(i);
Block previousBlock = blocks.get(i - 1);
if (!previousHashMatches(previousBlock, currentBlock)) {
System.out.println("previous hash doesn't match!");
return false;
}
if (!currentBlock.isValid()) {
System.out.println("proof of work is invalid");
return false;
}
}
return true;
}
private boolean previousHashMatches(Block previousBlock, Block currentBlock) {
return currentBlock.getPreviousHash()
.equals(DigestUtils.sha256Hex(previousBlock.toString()));
}
Comparing with other blockchains
public class Block {
…
boolean isValid() {
return DigestUtils.sha256Hex(this.toString()).startsWith("0000");
}
…
}
Propagating transactions
@PostMapping("/api/createtransaction")
public long createTransaction(@RequestBody Transaction transaction) {
…create transaction…
network.notifyPeersOfNewTransaction(transaction);
}
Receiving transactions from the network
@PostMapping("/api/addtransaction")
public void newTransactionReceived(@RequestBody Transaction transaction) {
if (!transactionPool.getAllTransactions().contains(transaction)) {
transactionPool.addTransaction(transaction);
network.notifyPeersOfNewTransaction(transaction);
}
}
Propagating blocks
@PostMapping("/api/mine")
public Block mine() {
Block block = getBlockchain().mine(transactionPool.getAllTransactions());
transactionPool.clearTransactions();
//propgate transaction
network.notifyPeersOfNewBlock(block);
return block;
}
Receiving blocks from the network
@PostMapping("/api/addblock")
public void newBlockReceived(@RequestBody Block block) {
//only add block if it is valid
if (blockchain.isValid(block)) {
blockchain.addBlock(block);
//clear all transactions that are already in the block
transactionPool.clearTransactions(block.getTransactions());
//propagate block through the network
network.notifyPeersOfNewBlock(block);
}
}
Receiving blocks from the network
public class Blockchain {
...
private boolean previousHashMatches(Block previousBlock, Block currentBlock) {
return currentBlock.getPreviousHash()
.equals(DigestUtils.sha256Hex(previousBlock.toString()));
}
public boolean isValid(Block block) {
return block.isValid() && previousHashMatches(blocks.getLast(), block);
}
public void addBlock(Block block) {
blocks.add(block);
}
}

More Related Content

What's hot

Introduction to blockchain and cryptocurrency technologies
Introduction to blockchain and cryptocurrency technologiesIntroduction to blockchain and cryptocurrency technologies
Introduction to blockchain and cryptocurrency technologiesPaweł Wacławczyk
 
CBGTBT - Part 5 - Blockchains 102
CBGTBT - Part 5 - Blockchains 102CBGTBT - Part 5 - Blockchains 102
CBGTBT - Part 5 - Blockchains 102Blockstrap.com
 
Bitcoin, Banking and the Blockchain
Bitcoin, Banking and the BlockchainBitcoin, Banking and the Blockchain
Bitcoin, Banking and the Blockchainseancarmody
 
CBGTBT - Part 4 - Mining
CBGTBT - Part 4 - MiningCBGTBT - Part 4 - Mining
CBGTBT - Part 4 - MiningBlockstrap.com
 
Introduction to blockchain
Introduction to blockchainIntroduction to blockchain
Introduction to blockchainPriyab Satoshi
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirTDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirWix Engineering
 
CBGTBT - Part 6 - Transactions 102
CBGTBT - Part 6 - Transactions 102CBGTBT - Part 6 - Transactions 102
CBGTBT - Part 6 - Transactions 102Blockstrap.com
 
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)Nicholas Lin
 
How to Create AltCoin(Alternative Cryptocurrency)?
How to Create AltCoin(Alternative Cryptocurrency)?How to Create AltCoin(Alternative Cryptocurrency)?
How to Create AltCoin(Alternative Cryptocurrency)?Abdullah Khan Zehady
 
Intro to Blockchain - And, by the way, what the heck is proof-of-work?
Intro to Blockchain - And, by the way, what the heck is proof-of-work?Intro to Blockchain - And, by the way, what the heck is proof-of-work?
Intro to Blockchain - And, by the way, what the heck is proof-of-work?Jim Flynn
 
Advanced n service bus deployment - NSBConnyc 2014 by Kijana Woodard
Advanced n service bus deployment - NSBConnyc 2014 by Kijana WoodardAdvanced n service bus deployment - NSBConnyc 2014 by Kijana Woodard
Advanced n service bus deployment - NSBConnyc 2014 by Kijana WoodardParticular Software
 
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...WithTheBest
 

What's hot (20)

Introduction to blockchain and cryptocurrency technologies
Introduction to blockchain and cryptocurrency technologiesIntroduction to blockchain and cryptocurrency technologies
Introduction to blockchain and cryptocurrency technologies
 
Blockchain Technology
Blockchain TechnologyBlockchain Technology
Blockchain Technology
 
Di and Dagger
Di and DaggerDi and Dagger
Di and Dagger
 
CBGTBT - Part 5 - Blockchains 102
CBGTBT - Part 5 - Blockchains 102CBGTBT - Part 5 - Blockchains 102
CBGTBT - Part 5 - Blockchains 102
 
Bitcoin, Banking and the Blockchain
Bitcoin, Banking and the BlockchainBitcoin, Banking and the Blockchain
Bitcoin, Banking and the Blockchain
 
Pi network
Pi networkPi network
Pi network
 
CBGTBT - Part 4 - Mining
CBGTBT - Part 4 - MiningCBGTBT - Part 4 - Mining
CBGTBT - Part 4 - Mining
 
Introduction to blockchain
Introduction to blockchainIntroduction to blockchain
Introduction to blockchain
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirTDD With Typescript - Noam Katzir
TDD With Typescript - Noam Katzir
 
CBGTBT - Part 6 - Transactions 102
CBGTBT - Part 6 - Transactions 102CBGTBT - Part 6 - Transactions 102
CBGTBT - Part 6 - Transactions 102
 
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
 
Blockchain bootcamp for boards
Blockchain bootcamp for boardsBlockchain bootcamp for boards
Blockchain bootcamp for boards
 
Blockchain technology
Blockchain technologyBlockchain technology
Blockchain technology
 
How to Create AltCoin(Alternative Cryptocurrency)?
How to Create AltCoin(Alternative Cryptocurrency)?How to Create AltCoin(Alternative Cryptocurrency)?
How to Create AltCoin(Alternative Cryptocurrency)?
 
Blockchain
Blockchain Blockchain
Blockchain
 
Intro to Blockchain - And, by the way, what the heck is proof-of-work?
Intro to Blockchain - And, by the way, what the heck is proof-of-work?Intro to Blockchain - And, by the way, what the heck is proof-of-work?
Intro to Blockchain - And, by the way, what the heck is proof-of-work?
 
Advanced n service bus deployment - NSBConnyc 2014 by Kijana Woodard
Advanced n service bus deployment - NSBConnyc 2014 by Kijana WoodardAdvanced n service bus deployment - NSBConnyc 2014 by Kijana Woodard
Advanced n service bus deployment - NSBConnyc 2014 by Kijana Woodard
 
Blockchain
BlockchainBlockchain
Blockchain
 
Ecom2
Ecom2Ecom2
Ecom2
 
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...
 

Similar to Let's build a blockchain.... in 40 minutes!

The Blockchain - The Technology behind Bitcoin
The Blockchain - The Technology behind Bitcoin The Blockchain - The Technology behind Bitcoin
The Blockchain - The Technology behind Bitcoin Jérôme Kehrli
 
BLOCKCHAIN PPT.pptx
BLOCKCHAIN PPT.pptxBLOCKCHAIN PPT.pptx
BLOCKCHAIN PPT.pptxSohanaAmreen
 
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad SarangNinad Sarang
 
How does blockchain work
How does blockchain workHow does blockchain work
How does blockchain workShishir Aryal
 
Blockchain 101 - public, tokenized blockchains
Blockchain 101 - public, tokenized blockchainsBlockchain 101 - public, tokenized blockchains
Blockchain 101 - public, tokenized blockchainsBrett Colbert
 
Node.js Blockchain Implementation
Node.js Blockchain ImplementationNode.js Blockchain Implementation
Node.js Blockchain ImplementationGlobalLogic Ukraine
 
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...Mariya James
 
BlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshopBlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshopPad Kankipati
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to BlockchainArunimShukla
 
De Blockchain: Een reis door de mist
De Blockchain: Een reis door de mist De Blockchain: Een reis door de mist
De Blockchain: Een reis door de mist Martijn Zoet
 
Python packages for blockchain
Python packages for blockchainPython packages for blockchain
Python packages for blockchainCeline George
 
20190606 blockchain101
20190606 blockchain10120190606 blockchain101
20190606 blockchain101Hu Kenneth
 
9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...
9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...
9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...abdallah76803
 
Ethereum Mining How To
Ethereum Mining How ToEthereum Mining How To
Ethereum Mining How ToNugroho Gito
 
A Quick Start To Blockchain by Seval Capraz
A Quick Start To Blockchain by Seval CaprazA Quick Start To Blockchain by Seval Capraz
A Quick Start To Blockchain by Seval CaprazSeval Çapraz
 

Similar to Let's build a blockchain.... in 40 minutes! (20)

Basics of Block Chain
Basics of Block ChainBasics of Block Chain
Basics of Block Chain
 
Blockchain - a simple implementation
Blockchain - a simple implementationBlockchain - a simple implementation
Blockchain - a simple implementation
 
The Blockchain - The Technology behind Bitcoin
The Blockchain - The Technology behind Bitcoin The Blockchain - The Technology behind Bitcoin
The Blockchain - The Technology behind Bitcoin
 
BLOCKCHAIN PPT.pptx
BLOCKCHAIN PPT.pptxBLOCKCHAIN PPT.pptx
BLOCKCHAIN PPT.pptx
 
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang
 
How does blockchain work
How does blockchain workHow does blockchain work
How does blockchain work
 
Blockchain 101 - public, tokenized blockchains
Blockchain 101 - public, tokenized blockchainsBlockchain 101 - public, tokenized blockchains
Blockchain 101 - public, tokenized blockchains
 
Flowchain: A case study on building a Blockchain for the IoT
Flowchain: A case study on building a Blockchain for the IoTFlowchain: A case study on building a Blockchain for the IoT
Flowchain: A case study on building a Blockchain for the IoT
 
Node.js Blockchain Implementation
Node.js Blockchain ImplementationNode.js Blockchain Implementation
Node.js Blockchain Implementation
 
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
 
BlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshopBlockchainConf.tech - Build a private blockchain workshop
BlockchainConf.tech - Build a private blockchain workshop
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to Blockchain
 
De Blockchain: Een reis door de mist
De Blockchain: Een reis door de mist De Blockchain: Een reis door de mist
De Blockchain: Een reis door de mist
 
Python packages for blockchain
Python packages for blockchainPython packages for blockchain
Python packages for blockchain
 
Blockchain
BlockchainBlockchain
Blockchain
 
20190606 blockchain101
20190606 blockchain10120190606 blockchain101
20190606 blockchain101
 
Blockchain Fundamentals
Blockchain FundamentalsBlockchain Fundamentals
Blockchain Fundamentals
 
9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...
9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...
9hfuleqnrlml5uhh9ilx-signature-f880bde3edecbc4113a9071227f39f1fbf3aec3f859381...
 
Ethereum Mining How To
Ethereum Mining How ToEthereum Mining How To
Ethereum Mining How To
 
A Quick Start To Blockchain by Seval Capraz
A Quick Start To Blockchain by Seval CaprazA Quick Start To Blockchain by Seval Capraz
A Quick Start To Blockchain by Seval Capraz
 

More from Michel Schudel

Testing an onion architecture - done right
Testing an onion architecture - done rightTesting an onion architecture - done right
Testing an onion architecture - done rightMichel Schudel
 
What makes a high performance team tick?
What makes a high performance team tick?What makes a high performance team tick?
What makes a high performance team tick?Michel Schudel
 
Atonomy of-a-tls-handshake-mini-conferentie
Atonomy of-a-tls-handshake-mini-conferentieAtonomy of-a-tls-handshake-mini-conferentie
Atonomy of-a-tls-handshake-mini-conferentieMichel Schudel
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da HoodMichel Schudel
 
Cryptography 101 for Java Developers - Devoxx 2019
Cryptography 101 for Java Developers - Devoxx 2019Cryptography 101 for Java Developers - Devoxx 2019
Cryptography 101 for Java Developers - Devoxx 2019Michel Schudel
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Michel Schudel
 
Cryptography 101 for_java_developers, Fall 2019
Cryptography 101 for_java_developers, Fall 2019Cryptography 101 for_java_developers, Fall 2019
Cryptography 101 for_java_developers, Fall 2019Michel Schudel
 
Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019Michel Schudel
 
Java n-plus-1-incl-demo-slides
Java n-plus-1-incl-demo-slidesJava n-plus-1-incl-demo-slides
Java n-plus-1-incl-demo-slidesMichel Schudel
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developersMichel Schudel
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developersMichel Schudel
 
Test your microservices with REST-Assured
Test your microservices with REST-AssuredTest your microservices with REST-Assured
Test your microservices with REST-AssuredMichel Schudel
 

More from Michel Schudel (15)

Testing an onion architecture - done right
Testing an onion architecture - done rightTesting an onion architecture - done right
Testing an onion architecture - done right
 
What makes a high performance team tick?
What makes a high performance team tick?What makes a high performance team tick?
What makes a high performance team tick?
 
Atonomy of-a-tls-handshake-mini-conferentie
Atonomy of-a-tls-handshake-mini-conferentieAtonomy of-a-tls-handshake-mini-conferentie
Atonomy of-a-tls-handshake-mini-conferentie
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da Hood
 
Cryptography 101 for Java Developers - Devoxx 2019
Cryptography 101 for Java Developers - Devoxx 2019Cryptography 101 for Java Developers - Devoxx 2019
Cryptography 101 for Java Developers - Devoxx 2019
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
 
Cryptography 101 for_java_developers, Fall 2019
Cryptography 101 for_java_developers, Fall 2019Cryptography 101 for_java_developers, Fall 2019
Cryptography 101 for_java_developers, Fall 2019
 
Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019
 
Micronaut brainbit
Micronaut brainbitMicronaut brainbit
Micronaut brainbit
 
Java n-plus-1-incl-demo-slides
Java n-plus-1-incl-demo-slidesJava n-plus-1-incl-demo-slides
Java n-plus-1-incl-demo-slides
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developers
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developers
 
What's new in Java 11
What's new in Java 11What's new in Java 11
What's new in Java 11
 
Java 9 overview
Java 9 overviewJava 9 overview
Java 9 overview
 
Test your microservices with REST-Assured
Test your microservices with REST-AssuredTest your microservices with REST-Assured
Test your microservices with REST-Assured
 

Recently uploaded

OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorShane Coughlan
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?AmeliaSmith90
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptkinjal48
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageDista
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampVICTOR MAESTRE RAMIREZ
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfBrain Inventory
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdfMeon Technology
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxJoão Esperancinha
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfTobias Schneck
 
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine HarmonyLeveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmonyelliciumsolutionspun
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyRaymond Okyere-Forson
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 

Recently uploaded (20)

OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS Calculator
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?
 
Salesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptxSalesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptx
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.ppt
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - Datacamp
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdf
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdf
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptx
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
 
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine HarmonyLeveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human Beauty
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 

Let's build a blockchain.... in 40 minutes!

  • 1. Let’s build a blockchain... in 40 minutes! @MichelSchudel michel@craftsmen.nl Amsterdam | April 2-3, 2019
  • 7. 1. A Blockchain is an implementation of a distributed ledger t1t2t3 t1t2t3 t1t2t3 t1t2t3 t1t2t3 t1t2t4 @MichelSchudel
  • 8. 2. A Blockchain is an sequential, immutable chain of records called Blocks Block transactiontransactiontransaction Block transactiontransactiontransaction Block transactiontransactiontransaction @MichelSchudel
  • 9. index : 2 previous hash payload transaction transaction transaction 3. Immutability is implemented by hashing index : 1 previous hash: 0 Genesis block transaction index : 3 previous hash payload transaction transaction transaction @MichelSchudel
  • 10. Let’s build a Blockchain, then! @MichelSchudel
  • 11. Let’s build a Blockchain, then! BlockchainRestController Blockchain TransactionPool BlockBlockBlockBlock TransactionTransactionTransactionTransaction Manages Manages Has Has API GET /api/blockchain POST /api/createtransaction GET /api/pendingtransactions POST /api/mine Network Interacts with @MichelSchudel
  • 12. Step 1: Create the initial blockchain index : 1 previous hash: 0 Genesis block @MichelSchudel
  • 13. Kudo’s (from, to, kudos) Pool of transactions Out of scope: • Transaction integrity (signing) • Transaction inputs and outputs Transaction pool transaction transaction transaction Step 2: Create something to store in the blocks @MichelSchudel
  • 14. • New block should contain hash of previous block (immutability, trust) • Creating a block requires proof-of- work / stake (supports consensus) • Creating a block should give a reward (incentive, generation transaction) index : 2 previous hash payload transaction transaction transaction index : 1 previous hash: 0 Genesis block Step 3: making (mining) a new block @MichelSchudel
  • 15. Proof-of-work • It should be hard to create a new block • Makes cheating unattractive • It should be easy to verify a new block @MichelSchudel
  • 16. Remember this Nonce thingy? “(new block)” “00005c3d2d...”SHA256 hash “(new block with nonce x)” “00005c3df8...”SHA256 hash X = 100 Creating a proof-of-work (hard) Verifying proof-of-work (easy) @MichelSchudel
  • 17. • The longest blockchain that is valid “wins” • A blockchain is valid when • Previous hash field of each block matches hash of previous block • Proof-of-work (nonce) is verified and correct for each block Step 4: consensus with other nodes @MichelSchudel
  • 18. Step 5: Implementing decentralization • Transactions are propagated • Everybody should have the chance to mine • Blocks are propagated • Validation is performed before accepting • This could prevent downloading all chains @MichelSchudel
  • 19. Summary We created a blockchain in 40 minutes with: • Blocks • Transactions • Mining • Reaching consensus • Propagation Now go and build one yourself! https://gitlab.com/craftsmen/workshop-blockchain @MichelSchudel
  • 21. Code slides (in case you didn’t see the demo)
  • 22. Create the block structure public class Block { private long index; private Set<Transaction> transactions = new HashSet<>(); private String previousHash; private long nonce; …getters, setters, toString etc. }
  • 23. Making the initial chain public class Blockchain { private LinkedList<Block> blocks = new LinkedList<>(); static Blockchain create() { Blockchain blockchain = new Blockchain(); Block block = new Block(); block.setIndex(1); block.setPreviousHash("0"); block.setNonce(0); blockchain.blocks.add(block); return blockchain; } }
  • 24. Creating a transaction public class Transaction { private String id; private String from; private String to; private int kudos; ..getters, setters… … equals and hashcode based on id only! }
  • 25. Creating a transaction pool public class TransactionPool { private Set<Transaction> transactions = new HashSet<>(); public void addTransaction(Transaction transaction) { transactions.add(transaction); } public void clearTransactions() { transactions.clear(); } public Set<Transaction> getAllTransactions() { return new HashSet<>(transactions); } }
  • 26. Creating a transaction @PostMapping("/api/createtransaction") public long createTransaction(@RequestBody Transaction transaction) { //give the transaction an id transaction.setId(UUID.randomUUID().toString()); //add the transaction to the pool transactionPool.addTransaction(transaction); //return the height of the next block return blockchain.height() + 1; }
  • 27. Mining a new block @PostMapping("/api/mine") public Block mine() { Block block = getBlockchain().mine(transactionPool.getAllTransactions()); transactionPool.clearTransactions(); return block; }
  • 28. Mining a new block public class Blockchain { ... public Block mine(Set<Transaction> allTransactions) { Block block = new Block(); block.setIndex(this.blocks.size() + 1); block.setPreviousHash(DigestUtils.sha256Hex(blocks.getLast().toString())); block.setTransactions(allTransactions); //create reward Transaction reward = new Transaction(); reward.setId(UUID.randomUUID().toString()); reward.setFrom(""); reward.setTo(“Michel for creating this block"); reward.setKudos(3); allTransactions.add(reward); block.calculateProofOfWork(); blocks.add(block); return block; } }
  • 29. Proof of work public class Block { … public void calculateProofOfWork() { this.nonce = 0; while (!DigestUtils.sha256Hex(this.toString()).startsWith("0000")) { this.nonce++; } } }
  • 30. Comparing with other blockchains In your service… public void init() { this.blockchain = Blockchain.create(); this.blockchain = network.retrieveBlockchainsFromPeers() .stream() .filter(b -> b.isValid()) .filter(b -> b.height() > this.blockchain.height()) .max(Comparator.comparing(Blockchain::height)) .orElse(this.blockchain); }
  • 31. Comparing with other blockchains public boolean isValid() { for (int i = blocks.size() - 1; i > 0; i--) { Block currentBlock = blocks.get(i); Block previousBlock = blocks.get(i - 1); if (!previousHashMatches(previousBlock, currentBlock)) { System.out.println("previous hash doesn't match!"); return false; } if (!currentBlock.isValid()) { System.out.println("proof of work is invalid"); return false; } } return true; } private boolean previousHashMatches(Block previousBlock, Block currentBlock) { return currentBlock.getPreviousHash() .equals(DigestUtils.sha256Hex(previousBlock.toString())); }
  • 32. Comparing with other blockchains public class Block { … boolean isValid() { return DigestUtils.sha256Hex(this.toString()).startsWith("0000"); } … }
  • 33. Propagating transactions @PostMapping("/api/createtransaction") public long createTransaction(@RequestBody Transaction transaction) { …create transaction… network.notifyPeersOfNewTransaction(transaction); }
  • 34. Receiving transactions from the network @PostMapping("/api/addtransaction") public void newTransactionReceived(@RequestBody Transaction transaction) { if (!transactionPool.getAllTransactions().contains(transaction)) { transactionPool.addTransaction(transaction); network.notifyPeersOfNewTransaction(transaction); } }
  • 35. Propagating blocks @PostMapping("/api/mine") public Block mine() { Block block = getBlockchain().mine(transactionPool.getAllTransactions()); transactionPool.clearTransactions(); //propgate transaction network.notifyPeersOfNewBlock(block); return block; }
  • 36. Receiving blocks from the network @PostMapping("/api/addblock") public void newBlockReceived(@RequestBody Block block) { //only add block if it is valid if (blockchain.isValid(block)) { blockchain.addBlock(block); //clear all transactions that are already in the block transactionPool.clearTransactions(block.getTransactions()); //propagate block through the network network.notifyPeersOfNewBlock(block); } }
  • 37. Receiving blocks from the network public class Blockchain { ... private boolean previousHashMatches(Block previousBlock, Block currentBlock) { return currentBlock.getPreviousHash() .equals(DigestUtils.sha256Hex(previousBlock.toString())); } public boolean isValid(Block block) { return block.isValid() && previousHashMatches(blocks.getLast(), block); } public void addBlock(Block block) { blocks.add(block); } }

Editor's Notes

  1. So why this session? I’ll explain. Does anyone have any cryptocurrency? How’s it going so far? Well, I started to get really exited about all these crypto currencies and the technology behind them. So I started looking for articles. Problem was, the articles were either like this:
  2. …or this, way too complex examples that also pulled in signing, double spending etc.
  3. In essence, a blockchain is…. Each block contains one or more transactions, and each block has some kind of backreference to the previous block. This will give the blockchain its immutability. Furthermore, a blockchain is distributed. So each participant in the network has the same copy of the blockchain. So if you’re the odd one out, you won’t be accepted as having a valid blockchain.
  4. Important point to discuss is that immutabilty is implemented by hashing. Each block contains a hash of the previous block. You can imagine that if you change a transaction in block 2, all subsequent block’s hashes will change as well. So you’ll have to recalculate all these hashes as well. Apart from convincing everyone your blockchain is the correct one, making new blocks or changing existing blocks is not easy. It requires something called proof-of-work, which we will see when we’re going to build the blockchain.
  5. So, let’s get started with an initial block! Not to worry about this hashing thingy, let’s just set up the model, right?