SlideShare a Scribd company logo
Let’s build a blockchain... in 40 minutes!
@MichelSchudel
michel@craftsmen.nl
Amsterdam | April 2-3, 2019
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 2019
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 2019
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 2019
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 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 (20)

PDF
Introduction to blockchain and cryptocurrency technologies
Paweł Wacławczyk
 
PDF
Blockchain Technology
Giuseppe Andreetti
 
PDF
Di and Dagger
K. Matthew Dupree
 
ODP
CBGTBT - Part 5 - Blockchains 102
Blockstrap.com
 
PDF
Bitcoin, Banking and the Blockchain
seancarmody
 
PDF
Pi network
VamsikrishnaVemavara
 
ODP
CBGTBT - Part 4 - Mining
Blockstrap.com
 
PPTX
Introduction to blockchain
Priyab Satoshi
 
PPTX
TDD With Typescript - Noam Katzir
Wix Engineering
 
ODP
CBGTBT - Part 6 - Transactions 102
Blockstrap.com
 
PPTX
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
Nicholas Lin
 
PDF
Blockchain bootcamp for boards
Jason Liew 廖颂成
 
PPTX
Blockchain technology
Rajlakshmi Maurya
 
PPTX
How to Create AltCoin(Alternative Cryptocurrency)?
Abdullah Khan Zehady
 
PPTX
Blockchain
Ranajeet Barik
 
ODP
Intro to Blockchain - And, by the way, what the heck is proof-of-work?
Jim Flynn
 
PDF
Advanced n service bus deployment - NSBConnyc 2014 by Kijana Woodard
Particular Software
 
PPTX
Blockchain
Abhinand Valasseri
 
PPT
Ecom2
Santosh Pandey
 
PPTX
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...
WithTheBest
 
Introduction to blockchain and cryptocurrency technologies
Paweł Wacławczyk
 
Blockchain Technology
Giuseppe Andreetti
 
Di and Dagger
K. Matthew Dupree
 
CBGTBT - Part 5 - Blockchains 102
Blockstrap.com
 
Bitcoin, Banking and the Blockchain
seancarmody
 
CBGTBT - Part 4 - Mining
Blockstrap.com
 
Introduction to blockchain
Priyab Satoshi
 
TDD With Typescript - Noam Katzir
Wix Engineering
 
CBGTBT - Part 6 - Transactions 102
Blockstrap.com
 
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
Nicholas Lin
 
Blockchain bootcamp for boards
Jason Liew 廖颂成
 
Blockchain technology
Rajlakshmi Maurya
 
How to Create AltCoin(Alternative Cryptocurrency)?
Abdullah Khan Zehady
 
Blockchain
Ranajeet Barik
 
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
Particular Software
 
Blockchain
Abhinand Valasseri
 
Bitcoin, Blockchains and APIs: The Decentralization Spectrum - Josh Cincinnat...
WithTheBest
 

Similar to Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 2019 (20)

PDF
Basics of Block Chain
Tharindu Weerasinghe
 
PPTX
Blockchain - a simple implementation
Commit Software Sh.p.k.
 
PPTX
The Blockchain - The Technology behind Bitcoin
Jérôme Kehrli
 
PPTX
BLOCKCHAIN PPT.pptx
SohanaAmreen
 
PDF
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang
Ninad Sarang
 
PDF
How does blockchain work
Shishir Aryal
 
PPTX
Blockchain 101 - public, tokenized blockchains
Brett Colbert
 
PDF
Flowchain: A case study on building a Blockchain for the IoT
LinuxCon ContainerCon CloudOpen China
 
PPTX
Node.js Blockchain Implementation
GlobalLogic Ukraine
 
PDF
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
Mariya James
 
PPTX
BlockchainConf.tech - Build a private blockchain workshop
Pad Kankipati
 
PPTX
Introduction to Blockchain
ArunimShukla
 
PDF
De Blockchain: Een reis door de mist
Martijn Zoet
 
PDF
Blockchain Facts_ What Is It, How It Works, and How It Can Be Used.pdf
MaryRozetteNuezca
 
PPTX
Introduction to Blockchain Web3 Session
DSCIITPatna
 
PPTX
Python packages for blockchain
Celine George
 
PPTX
Blockchain
Mohit Singh
 
PPTX
20190606 blockchain101
Hu Kenneth
 
PDF
Blockchain Fundamentals
Provide Technologies
 
PDF
Ethereum Mining How To
Nugroho Gito
 
Basics of Block Chain
Tharindu Weerasinghe
 
Blockchain - a simple implementation
Commit Software Sh.p.k.
 
The Blockchain - The Technology behind Bitcoin
Jérôme Kehrli
 
BLOCKCHAIN PPT.pptx
SohanaAmreen
 
14 Jan17- Nullmeets -Blockchain concept decoded by Ninad Sarang
Ninad Sarang
 
How does blockchain work
Shishir Aryal
 
Blockchain 101 - public, tokenized blockchains
Brett Colbert
 
Flowchain: A case study on building a Blockchain for the IoT
LinuxCon ContainerCon CloudOpen China
 
Node.js Blockchain Implementation
GlobalLogic Ukraine
 
A Comprehensive Guide To Create Blockchain In Python | Blockchain Development...
Mariya James
 
BlockchainConf.tech - Build a private blockchain workshop
Pad Kankipati
 
Introduction to Blockchain
ArunimShukla
 
De Blockchain: Een reis door de mist
Martijn Zoet
 
Blockchain Facts_ What Is It, How It Works, and How It Can Be Used.pdf
MaryRozetteNuezca
 
Introduction to Blockchain Web3 Session
DSCIITPatna
 
Python packages for blockchain
Celine George
 
Blockchain
Mohit Singh
 
20190606 blockchain101
Hu Kenneth
 
Blockchain Fundamentals
Provide Technologies
 
Ethereum Mining How To
Nugroho Gito
 
Ad

More from Codemotion (20)

PDF
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
PDF
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
PPTX
Pastore - Commodore 65 - La storia
Codemotion
 
PPTX
Pennisi - Essere Richard Altwasser
Codemotion
 
PPTX
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
PDF
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
PDF
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
PDF
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
PDF
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
PDF
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
PDF
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
PPTX
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
PDF
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
PDF
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
PDF
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
PDF
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 
PDF
Mike Kotsur - What can philosophy teach us about programming - Codemotion Ams...
Codemotion
 
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
Pastore - Commodore 65 - La storia
Codemotion
 
Pennisi - Essere Richard Altwasser
Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 
Mike Kotsur - What can philosophy teach us about programming - Codemotion Ams...
Codemotion
 
Ad

Recently uploaded (20)

PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Python basic programing language for automation
DanialHabibi2
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 

Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 2019

  • 1. Let’s build a blockchain... in 40 minutes! @MichelSchudel [email protected] 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

  • #3: 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:
  • #5: …or this, way too complex examples that also pulled in signing, double spending etc.
  • #8: 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.
  • #10: 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.
  • #13: So, let’s get started with an initial block! Not to worry about this hashing thingy, let’s just set up the model, right?