SlideShare a Scribd company logo
1 of 37
Let’s build a blockchain... in 40 minutes!
@MichelSchudel
michel@craftsmen.nl
Amsterdam | April 2-3, 2019
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
 
Introduction to Blockchain Web3 Session
Introduction to Blockchain Web3 SessionIntroduction to Blockchain Web3 Session
Introduction to Blockchain Web3 SessionDSCIITPatna
 
Python packages for blockchain
Python packages for blockchainPython packages for blockchain
Python packages for blockchainCeline George
 
20190606 blockchain101
20190606 blockchain10120190606 blockchain101
20190606 blockchain101Hu Kenneth
 
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
 
Introduction to Blockchain Web3 Session
Introduction to Blockchain Web3 SessionIntroduction to Blockchain Web3 Session
Introduction to Blockchain Web3 Session
 
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
 
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

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 

Recently uploaded (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 

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
  • 2.
  • 3.
  • 4.
  • 5.
  • 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?