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 Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 2019

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 Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amsterdam 2019 (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 Codemotion

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

More from Codemotion (20)

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

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

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

  • 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?