Let’s build a Blockchain!

Slides:



Advertisements
Similar presentations
Secure Multiparty Computations on Bitcoin
Advertisements

COMS 486 Iowa State University Introduction to Bitcoin A P2P Electronic Cash System.
The world’s first decentralized digital currency Meni Rosenfeld Bitcoil 29/11/2012Written by Meni Rosenfeld1.
Bitcoins and the Digital Economy Presented By: Matt Blackman.
1 Bitcoin A Digital Currency. Functions of Money.
Bitcoin Bitcoin is a cryptocurrency. The platform that hosts Bitcoin is a p2p system. Bitcoin can be abstracted as a digital file that records the account.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
Block Chain 101 May 2017.
Motivation ✓ ✘ ? Bitcoin/Ideal Credit Card Works on Internet
Kermit Lowry, John Whatley, Wesley Cooper, and Matthew Eith
Blockchains . or . How to avoid paying $40,000,000 for two pizzas
Virtual currency? Crypto-currency? Internet Money? Property?
Bitcoin - a distributed virtual currency system
Testing and Debugging.
Distributed Systems for Information Systems Management
Cryptocurrencies By Rui Sakurai and Shane Spears
Introduction to Blockchain & Ethereum
Bitcoin Created By: CoinSecure.in.
Blockchain beyond cryptocurrencies
So what is Blockchain anyway?
Deanonymization of Clients in Bitcoin P2P Network

{ BLOCKCHAIN Technology. BSEtecBSEtec is a digital solution provider company which offers the best service with the implement of the latest technologies.
Technical Overview of Bitcoin
Advanced Cryptography Protocols
Data Structures and Analysis (COMP 410)
Breaking through with Blockchain
EECS 498 Introduction to Distributed Systems Fall 2017
Focus Group 3: Blockchain and digitalisation
Getting Started with Ethereum Private Blockchain
NEECOM – May 16, 2018 Todd L. Gould, CEO
Advanced Programming Giuseppe Attardi Università di Pisa
Introduction to Blockchains
slides created by Ethan Apter
Setting the Stage for a Community Blockchain Incubator
Blockchains slides have been taken from:
Proof-of-Personhood: Redemocratizing Permissionless Cryptocurrencies
Good afternoon, everyone. I’m Haobin Ni from Cornell University
Blockchain Alexander Prenta 9/27/2018.
Bitcoin: Data flow.
Nonce Making Sense of Nonces.
slides created by Ethan Apter
Generic Classes and Methods
Introduction to Blockchain
Blockchain Concepts RISK FORUM 2017 Hash function (e.g. SHA-256)
刘振 上海交通大学 计算机科学与工程系 电信群楼3-509
CSE 143 Lecture 25 Set ADT implementation; hashing read 11.2
OurSQL = MySQL + Blockchain
Data Structures and Analysis (COMP 410)
Kai Bu 04 Blockchain Kai Bu
CSCE 190 Computing in the Modern World Blockchain: the Basics
Blockchains and Auditing
Modified from Bob Vachon
Introduction to blockchain
Wokshop SAIS 2018 Dr. Meg Murray Kennesaw state university
slides created by Ethan Apter and Marty Stepp
Faculty Seminar Series Blockchain Technology
CMPE212 – Reminders Assignment 2 due next Friday.
Blockchain Technology: A New Approach to Provenance
Distributed Computers and Web Technologies (3-0-6)
CSE 552 preparation for reading
Campbell R. Harvey Duke University and NBER
Blockchain Tech Big Picture
Block Chain Technology in Agriculture
Blockchain Tech Big Picture
Bitcoin and Blockchain
Explore Txs, block, blockchain in Bitcoin
Not about digital currencies
BUILDING A BLOCKCHAIN USING PYTHON
Cryptocurrency and Blockchain Technology
Presentation transcript:

Let’s build a Blockchain! (In 40 minutes) So good afternoon! Still got some every left? Thank you for coming to this session. My name is Michel Schudel. I’m a software developer from a Dutch IT company called Craftsmen, I’m currently working for Dutch Railways, buidling systems for traffic control, very interesting stuff. So today, let’s build a blockchain from scratch and hopefully have it working in 40 minutes! @MichelSchudel michel@craftsmen.nl #technation

So why this session. I’ll explain. Does anyone have any cryptocurrency 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:

…or this, way too complex examples that also pulled in signing, double spending etc.

Central authority Ledger transaction transaction transation Distributed ledger transaction Central authority Ledger

A Blockchain is an implementation of a distributed ledger B1B2B3 B1B2B4 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.

A Blockchain is an sequential, immutable chain of records called Blocks transaction Block transaction Block transaction

Immmutability is implemented by hashing index : 1 previous hash: 0 Genesis block index : 2 previous hash payload transaction index : 3 previous hash payload transaction 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. transaction

Let’s build a Blockchain, then! Kudo’s

Let’s build a Blockchain, then! GET /api/blockchain POST /api/createtransaction GET /api/pendingtransactions POST /api/mine API Interacts with BlockchainRestController Network Manages Manages Blockchain TransactionPool Has Has Block Transaction Block Transaction Block Transaction Block Transaction

Step 1: Create the initial blockchain index : 1 previous hash: 0 Genesis block So, let’s get started with an initial block! Not to worry about this hashing thingy, let’s just set up the model, right?

Step 2: Create something to store in the blocks Kudo’s (from, to, kudos) Pool of transactions Out of scope: Transaction integrity (signing) Transaction inputs and outputs Transaction pool transaction transaction transaction

Step 3: making (mining) a new block Block should contain hash of previous block (immutability, trust) Creating a block should give a reward (incentive, generation transaction) Creating a block requires proof-of-work (supports consensus) index : 1 previous hash: 0 Genesis block index : 2 previous hash payload transaction

Proof-of-work It should be hard to create a new block Makes cheating unattractive It should be easy to verify a new block

Remember this Nonce thingy? Creating a proof-of-work (hard) “(new block with nonce x)” “00005c3df8...” SHA256 hash X = 100 Verifying proof-of-work (easy) “(new block)” “00005c3d2d...” SHA256 hash

Step 4: consensus with other nodes 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 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

https://gitlab.com/craftsmen/workshop-blockchain 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

https://gitlab.com/craftsmen/workshop-blockchain @MichelSchudel michel@craftsmen.nl

(in case you didn’t see the demo) 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("Me!"); 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); } }