Blockchain Technologies - SITA3011 PDF
Document Details
Uploaded by GuiltlessMoon
Rajalakshmi Engineering College
SITA3011
Tags
Summary
These documents appear to be notes on blockchain technology, specifically focused on the introduction.
Full Transcript
UNIT - I Blockchain Technologies – SITA3011 I INTRODUCTION TO BLOCKCHAIN Unit 1 Introduction to blockchain. Basics of blockchain-Public Ledgers-Block Chain as Public Ledgers-Types of Block chains- Pillars of Block chain- Government Initiatives of Block Chain...
UNIT - I Blockchain Technologies – SITA3011 I INTRODUCTION TO BLOCKCHAIN Unit 1 Introduction to blockchain. Basics of blockchain-Public Ledgers-Block Chain as Public Ledgers-Types of Block chains- Pillars of Block chain- Government Initiatives of Block Chain – Bitcoin – Smart Contracts. 1.1 Basics of Blockchain “A blockchain is a continuously growing list of records, called blocks, which are linked and secured using cryptography.” The concept is introduced by Satoshi Nakamoto 2009 Block Block 1.Data :“hello everyone” 2.Prev Hash:23432FRT123 3.Hash :123FFRE342 Blockchain Figure 1.1.All blocks are cryptographically link together 1 Figure 1.2 blockchain Features Blockchain Blockchain is simply a data structure where each block is linked to another block in a time- stamped chronological order It is a distributed digital ledger of an immutable public record of digital transactions. Every new record is validated across the distributed network before it is stored in a block. All information once stored on the ledger is verifiable and auditable but not editable. Each block is identified by its cryptographic signature. The first block of the blockchain is known as Genesis block “To access data of the first ever created block ,you have to traverse from the last created block to the first block” How trading happens Using Current System Figure 1.3 Traditional transactions Ledger 2 A ledger is a record-keeping book that stores all the transactions of an organization. Figure 1.4 Ledger Problems with the current system Banks and other third parties take fees for transferring money Mediating costs increases transaction costs Minimum practical transaction size is limited; Financial exchanges are slow. Checking and low cost wire services take days to complete System is opaque and lacks transparency and fairness Also, central authority in control can overuse the power and can create money as per their own will Figure 1.5 Traditional payments 3 We need a system which: Eliminates the need of middlemen or Third parties thereby making transaction costs nil or negligible. Enhance transaction execution speeds and can facilitate instant reconciliation. Is transparent and tamper resistant in order to avoid manipulation or misuse. Currency creation is not in control of any central authority. Is regulated to maintain the value of the currency. Distributed system attempt to solve the problem Figure 1.6 Different network of systems Distributed system enables a network of computers to maintain a collective bookkeeping via internet this is open and is not in control of one party. it is available in one ledger which is fully distributed across the network. Figure 1.7 Centralized Vs Decentralized 4 Most of the Internet applications we use every day are centralized, they are owned by a particular company or person that provision and maintain the source code to execute on a computer, server or maybe even a cluster. Decentralized Applications Figure 1.8 Decentralized network Decentralized means no node is instructing any other node as to what to do. The code runs on a peer-to-peer network of nodes and no single node has control over the dApp. Depending on the functionality of the dApp, different data structures can be used to store the application data. Bitcoin uses a blockchain decentralized ledger of transactions. Distributed Applications 5 Figure 1.9 Distributed applications Applications in which computation is distributed across components, communicate and coordinate their actions by passing messages. The components interact with each other in order to achieve a common goal. Some distributed applications examples are: CDN AWS Cloud Instances Google, Facebook, Netflix, etc Distributed system Figure 1.10 Distributed system 6 A System where two or more nodes work with each other in a coordinated fashion in order to achieve a common outcome It’s modeled in such a way that end users see it as a single logical platform. What is a node ? A node can be defined as an individual processing unit in a distributed system All nodes are capable of sending and receiving messages to and from each other. Introduction – Blockchain Blockchain technology is a distributed ledger technology originally proposed for the crypto-currency Bitcoin. FEATURES – Immutable and tamper-proof data store – Sequential Chain with Cryptographic hashing – Trust-free Consensus-based transactions – Decentralized peer-to-peer network – Distributed shared ledger What is Blockchain? A blockchain is a decentralized, distributed public ledger where all transactions are verified and recorded. Blockchain is a system comprised of.. Transactions Immutable ledgers Decentralized peers Encryption processes Consensus mechanisms Optional Smart Contracts Transactions As with enterprise transactions today, Blockchain is a historical archive of decisions and actions taken Proof of history, provides provenance 7 Immutable As with existing databases, Blockchain retains data via transactions. The difference is that once written to the chain, the blocks can be changed, but it is extremely difficult to do so. Requiring rework on all subsequent blocks and consensus of each. The transaction is, immutable, or indelible In DBA terms, Blockchains are Write and Read only Like a ledger written in ink, an error would be resolved with another entry. Decentralized Peers Rather than the centralized “Hub and Spoke” type of network, Blockchain is a decentralized peer to peer network. Where each NODE has a copy of the ledger. Legacy Network Blockchain Network Centralized DB Distributed Ledgers Figure 1.11 Legacy network Vs blockchain network Encryption Standard encryption practices. Some Blockchains allow for “BYOE” (Bring Your Own Encryption) All blocks are encrypted Some Blockchains are public, some are private Public Blockchains are still encrypted, but are viewable to the public, e.g. https://www.blocktrail.com/BTC 8 Private Blockchains employ user rights for visibility, e.g. Customer – Writes and views all data Auditors – View all transactions Supplier A – Writes and views Partner A data Supplier B – Writes and views Partner B data Consensus Ensures that the next block in a blockchain is the one and only version of the truth. Keeps powerful adversaries from derailing the system and successfully forking the chain consensus algorithm is a process in computer science used to achieve agreement on some information among the distributed systems. The consensus algorithm was designed for the blockchain technology to achieve reliability in a blockchain network having multiple nodes. Figure 1.12 Consensus mechanism Smart Contracts Computer code Provides business logic layer prior to block submission. Table 1.1 Example blockchain netwoks Blockchain Smart Contracts? Language Bitcoin No Ethereum Yes Solidity Hyperledger Yes Various GoLang, C++, etc, depends Others Depends Depends 9 How Blockchain Works? Figure 1.13 Blockchain working model Figure 1.14 Blockchain Flow diagram Elements of blockchain blockchain has five elements: Distribution, encryption, immutability, tokenization and decentralization. 10 Figure 1.15 Features of blockchain Distribution: Blockchain participants are located physically apart from each other and each node copy of a ledger that updates with new transactions as they occur. Encryption: Blockchain uses technologies such as public and private keys to record the data in the blocks securely. Immutability: Completed transactions are cryptographically signed, time-stamped and sequentially added to the ledger. Tokenization: Transactions and other interactions in a blockchain involve the secure exchange of value. Decentralization:Both network information and the rules for how the network operates are maintained by nodes due to consensus mechanism. Benefits of Blockchains Benefits of Blockchains Over Traditional Finance 11 Figure 1.16 Benefits of blockchain Trustless: The blockchain is immutable and automates trusted transactions between counterparties who do not need to know each other. Transactions are only executed when programmed conditions are met by both parties. Unstoppable: Once the conditions programmed into a blockchain protocol are met, an initiated transaction cannot be undone, changed, or stopped. It’s going to execute and nothing – no bank, government, or third party – can stop it. Immutable: Records on a blockchain cannot be changed or tampered. A new block of transactions is only added after a complex mathematical problem is solved and verified by a consensus mechanism. Each new block has a unique cryptographic key resulting from the previous block’s information and key being added into a formula. Decentralized: No single entity maintains the network. Unlike centralized banks, decisions on the blockchain are made via consensus. Decentralization is essential because it ensures people can easily access and build on the platform. Lower Cost: In the traditional finance system, you pay third parties like banks to process transactions. The blockchain eliminates these intermediaries and reduces fees, with some systems returning fees to miners and stakers. Peer-to-Peer: Cryptocurrencies like Bitcoin, let you send money directly to anyone, anywhere in the world, without an intermediary like a bank charging transaction or handling fees. 12 Transparent: Public blockchains are open-source software, so anyone can access them to view transactions and their source code. They can even use the code to build new applications and suggest improvements to the code. Suggestions are accepted or rejected via consensus. Universal Banking: anyone can access the blockchain to store money, it’s a great way to protect against theft that can happen due to holding cash in physical locations. Use cases Dubai has been able to integrate blockchain into eight industry sectors Real estate Tourism Security Transportation Finance Health Education. The end result is to become the world’s first blockchain city. Cryaptocurrency Cryptocurrency is a form of currency that exists solely in digital form. Cryptocurrency can be used to pay for purchases online without going through an intermediary, such as a bank, or it can be held as an investment. Example : Bitcoin, Etherium etc How Do You Buy Crypto? You can buy cryptocurrencies through crypto exchanges, such as Coinbase, Kraken or Gemini. In addition, some brokerages, such as WeBull and Robinhood, also allow consumers to buy cryptocurrencies. Example Cryptocurrencies 13 14 Figure 1.17 Example Cryptocurrencies Blockchain Evolution 15 Figure 1.18 Evolution of blockchain 1.2 Public Ledger Shared Ledger Figure 1.19 Ledger Records all transactions across business network Shared between participants Participants have own copy through replication Permissioned, so participants see only appropriate transactions It is the shared system of record. 16 Figure 1.20 Features of Distributed Ledger 1.2 Blockchain as public ledger How Distributed Ledgers Work Figure 1.21 illustration of distributed ledger Distributed ledgers are held, reorganized, and controlled by individuals called nodes. The database is constructed independently by each node. Every transaction occurring on the network is processed, and a conclusion on the development of the database is created by each node. 17 Based on the transaction, voting is carried out on the changes completed on the database. All nodes participate in the voting, and if at least 51% of them agree, the new transaction is accepted on the database. Afterward, the nodes update the versions of the database so that all the devices or nodes will be of the same version. The new transaction is written onto a block on the blockchain. Nodes in Proof-of-Work blockchain are also called miners. When a miner successfully puts a new transaction into a block, they receive a reward. It requires a dedicated 24×7 computer power. It is the responsibility of miners to compute the cryptographic hash for new blocks. Whoever, among the miners, successfully finds the hash first, gets the reward. Miners dedicating more computational power to find the hash will be more successful. However, as blocks keep generating, it becomes more difficult to find subsequent hash scales. The goal is to keep a constant speed of generating the blocks. Benefits of Distributed Ledgers Highly transparent, secure, tamper-proof, and immutable. After records are written into distributed ledgers, they cannot be altered by any other party. The need for a third party is eliminated Inherently decentralized Highly transparent Advantages of Distributed Ledgers It is secure because there is no third-party intervention. It is immutable once recorded cannot be intervened. The data is distributed so it is tamper-proof. 18 Disadvantages of Distributed ledger: The distributed ledger is spread along with the nodes so making it vulnerable to attack. The transaction cost is high because of a larger network. The transaction speed is low because of the operation of a large number of nodes. 1.4 Types of blockchain 1. Public Blockchains 2. Private Blockchains 3. Consortiums Blockchains 4. Hybrid Blockchains Public Blockchains Public blockchains are open, decentralized networks of computers accessible to anyone wanting to request or validate a transaction (check for accuracy). Those (miners) who validate transactions receive rewards. Public blockchains use proof-of-work or proof-of-stake consensus. permission-less distributed ledger system. Anyone who has access to the internet can sign in on a blockchain platform to become an authorized node and be a part of the blockchain network. Example : Bitcoin and Ethereum (ETH) blockchains. Figure 1.22 public blockchain A public blockchain has some characteristic features: Write-only, immutable, transparent data storage. 19 It brings trust among the whole community of users Decentralized, no need for intermediaries. Consistent state across all participants. Resistant against malicious participants. Anyone can join the public blockchain. Disadvantages They suffer from a lack of transaction speed. Private Blockchains A Private Blockchain is just like a relational database i.e. fully centralized and owned by a single organization. Private blockchains are not open, they have access restrictions. People who want to join require permission from the system administrator. They are typically governed by one entity, meaning they’re centralized. For example, Hyperledger is a private, permissioned blockchain. Figure 1.23 private blockchain Consortiums blockchain 20 Figure 1.24 Consortium blockchain Validation is conducted by known and identified members of the limited network of nodes greater privacy since the information from verified blocks is not exposed to the public. There are no transaction fees consensus is reached by a relatively small number of nodes in accordance to the governance scheme. Increased scalability - Bitcoin’s block transmits only up to 1 Mb* (from 1500 to 2700 transactions) per 10 minutes, when a consortium blockchain can optimize it to 1000 and more transactions per second. A consortium platform is more flexible. voting-based system, it ensures low latency and superb speed. Hybrid Blockchain like a consortium blockchain, but it is not. Hybrid blockchain is best defined as a combination of a private and public 21 blockchain. It has use-cases in an organization that neither wants to deploy a private blockchain nor public blockchain and simply wants to deploy both worlds’ best. Example of Hybrid Blockchain: Dragonchain, XinFin’s Hybrid blockchain Advantages Works in a closed ecosystem without the need to make everything public. Rules can be changed according to the needs. Hybrid networks are also immune to 51% attacks. It offers privacy while still connected with a public network. It offers good scalability compared to the public network. Disadvantages Not completely transparent. Upgrading to the hybrid blockchain can be a challenge. There is no incentive for participating and contributing to the network. Table 1.2 Types of blockchain Public Private Hybrid The hybrid blockchain is The public a combination of the Private blockchain is blockchain is open public and private controlled by owners Definition to everyone where blockchain. This means and access is limited anyone can that some process is kept to certain users. participate. private and others public. The public The private blockchain Hybrid blockchain blockchain is is only transparent to transparency depends on Transparency completely the users who are how the owners set the transparent. granted access. rules. Public blockchain The private blockchain incentivizes is limited and hence Hybrid blockchain can Incentive participants for have no similar opt to incentivize users growing the incentive as that of a if they want to. network. public blockchain. 22 Can be used in Hybrid is best suited for Private blockchain is almost every projects that can neither great for organization industry. Good for go private or public blockchain public projects. It is and have a lack of trust. Use-case implementation as also good for The supply chain is a they require complete creating great example. It is also control over their cryptocurrency for effective in banking, workflow. commercial use. finance, IoT, and others. Bitcoin, Litecoin, Example Ripple, Corda Hyperledger Ethereum KYC needed No Yes Yes Transactional Costly Not so costly Not so costly Cost Carries basic property of Yes Yes Yes blockchain 1.5 Pillars of Blockchain Figure 1.25 Pillars of blockchain Every Blockchain can be rated on the basis of 3 components: Decentralization, Scalability, and Security. It is a challenge to keep all of these three components in balance. Usually, one of them is partly sacrificed to get the other two. Scalability Decentralization (censorship resistance) Security 23 security, scalability, and decentralization. These are among the most prominent driving factors in ongoing development (privacy/anonymity is another contender). Security: The network is secure from both internal and external flaws. Security is the most crucial concept, and without it, the technology would be unusable. Security is the most important of them all, as no one would use banks or Bitcoin without it. For example, we could say the lack of security in has stopped us in adopting that scalability solution. Scalability: The technology must be able to grow to and handle a commercially viable scale. Scalability is required for the technology to gain broad adoption Decentralization: The network must not, in practice, be vulnerable to control by a few entities. Decentralization is necessary to cut costs (middlemen) and to build trust. 1.6 Government Initiatives of Block Chain 24 Figure 1.26 Government Initiatives of Block Chain Why Use Blockchain in Government Processes? 25 Figure 1.27 Benefits of Blockchain Government Initiatives Blockchain Government Use Cases e-Estonia digital ID, e-tax, i-voting Georgia – Land Registry The project supplements the traditional land registry protocol with Blockchain. Malta – Academic Record Using the Blockcerts app, the citizen enlists their academic institution as an issuer of certificates. Switzerland – Decentralized Identity limited to residential proof in its first phase Blockchain for Government – The Obstacles Scalability Risk of private-key theft and the consequent data breach Lack of Blockchain awareness The ideal case blockchain implementation - India 26 Figure 1.28 blockchain initiatives 1.7 Bitcoin Released in 2008 by Satoshi Nakamoto. Focus on crypto-currencies and micro-payments Proof of Work Consensus Bitcoin vs. bitcoins Bitcoin is the system bitcoins are the units What is Bitcoin? A peer-to-peer internet currency that allows decentralized transfers of value between individuals and businesses. Before Bitcoin DigiCash (1989): The 1st Electronic Cash System 27 - David Chaum’s company, featuring ecash (1983) - Ecash notes backed by fiat from bank - Relied on blind signatures The idea was published in 2009 by an pseudonymous person/group of people, named Satoshi Nakamoto. Goal with Bitcoin was: - To create a trustless system, using cryptography - Solve double-spending problem of previous digital currencies - Create digital assets that can be owned, with proof of ownership Creating a currency from scratch Motivation Distrust of financial institutions Transaction costs Primary concerns Transaction security Double spends Distrust of financial institutions Any noncash transaction requires a trusted third-party administrator—commonly a bank or financial service provider. The system forces participants to trust financial institutions that are not always trustworthy. Transaction security Two levels of verification Source is legitimate Coins are legitimate Public/private key verification ensures the legitimacy 28 Double spends If the money is just digital codes, why not copy and paste to make more money? Timestamps Hashes Block chain Timestamp Each transaction is packaged and publically recorded in the order it was carried out. Hash The time-stamped group of transactions are given a unique algorithmically derived number Bitcoin Bitcoin is the official first cryptocurrency that had been released in 2009. It is basically a digital currency and only exists electronically. Bitcoin is the first successful electronic cash system and coincidentally, the first instance of a successful Blockchain. Secure, trustless, borderless No bank needed to authorize/process transactions Transactions are stored on a distributed ledger Bitcoin introduced the concept of cryptocurrency; decentralized digital money secured by cryptography, and used to create valuable digital assets that cannot be counterfeited. Bitcoin transactions are authorized in a peer-to-peer network. Each node stores the history of the chain of blocks, containing validated transactions Counterfeiting is impossible because if one node’s history is corrupted the others stay the same, and no central authority (i.e. bank) needs to confirm; this is called decentralization Unlike previous P2P network models, members of the Bitcoin network are 29 incentivized to participate through cryptocurrency. Specifically, the incentive is for the people who mint (create) Bitcoin, called miners. Figure 1.28 before and after bitcoin Bitcoin Properties Bitcoins can be possessed. Bitcoins can be transferred. Bitcoins are impossible to copy. Mining bitcoins Miners solve complicated algorithms to find a solution called a hash. Finding a hash creates a block that is used to process transactions. Each new block is added to the block chain. Until there are 21 million bitcoins, miners are paid for finding a hash in new coin. After 21 million, miners will charge transaction fees for creating a new block. The amount paid per hash goes down by half about every 4 years. Owning bitcoins 30 Users create accounts called wallets. Wallets are secured using passwords and contain the private keys used for transferring bitcoins. Spending bitcoins Buyer signs the Buyer enters the transaction with a seller’s address and Buyer broadcasts Seller provides an private key and the amount of the the transaction to all address to the buyer announces the payment to a the Bitcoin network public key for transaction message verification Figure 1.29 bitcoin transaction Wallets A wallet is a combination of public address and private key. 31 Figure 1.30 botcoin wallets Hardware wallets Most popular hardware wallets are Ledger Nano S and Trezor. Figure 1.31 Hardware Walet Hardware wallets are hardware devices that individually handle public addresses and keys. It looks like a USB with OLED screen and side buttons. when you open a wallet (in the hardware wallet or software wallet) you are provided with 2 pair of keys (sometimes more). Public key and the private key. public key is used to generate the public cryptocurrency address you can use to 32 receive the cryptocurrency, the private key is used to sign the transactions confirming your ownership over it. This is a reason why private key must be kept secret Paper Wallets It is a physically printed QR coded form wallet. Some wallets allow downloading the code to generate new addresses offline. Figure 1.32 Paper Wallet Desktop Wallet Desktop wallets are programs that store and manage the private key for your Bitcoins on your computer’s hard drive. Figure 1.33Desktop Wallet 33 Mobile wallets A mobile wallet is a virtual wallet that stores payment card information on a mobile device. They are quite convenient as it uses QR codes for transactions Some mobile wallets are Coinomi and Mycelium Figure 1.34 Mobile Wallet Web Wallets These wallets are accessed by internet browsers. They are the least secure wallets. They are not the same as hot wallets. They are ideal for small investments and allow quick transactions. Some of these are MetaMask and Coinbase. 34 Figure 1.35 Web Wallet Bitcoin Transactions Figure 1.36 Bitcoin Transactions A full node is basically an electronic bookkeeper, and anybody in the world can set up and run one. Each node has a complete copy of the public ledger – that’s a record of every Bitcoin transaction 35 Sample Transaction Figure 1.37 Transactions with Hash values Every transaction has a set of inputs and a set of outputs. The inputs identify which bitcoins are being spent, and the outputs assign those bitcoins to their new owners. Each input is just a digitally signed reference to some output from a previous transaction. Once an output is spent by a subsequent input, no other transaction can spend that output again. Each unspent output represents some amount of bitcoin that is currently in someone’s possession. Note that nobody’s real name appears anywhere within a transaction. That’s why Bitcoin 36 is often said to be pseudonymous. Instead of real names, bitcoins are assigned to addresses such as 1PreshX6QrHmsWbSs8pHpz6kLRcj9kdPy6. Where Do Addresses Come From? Obviously, if you want to receive bitcoins, you need to have a Bitcoin address. Your wallet can generate addresses for you. In order to generate an address, your wallet first generates a private key. A private key is nothing but a large number roughly between 1 and 2256. To make such numbers shorter to write, it’s customary to encode them as sequence of numbers and letters. Bitcoin Address Next, your wallet converts that private key to a Bitcoin address using a well-known function. This function is very straightforward for a computer to perform. it uses elliptic curve cryptography to generate Bitcoin addresses If anyone knows your private key, they could easily convert it to a Bitcoin address, too. If someone knows only your Bitcoin address, it’s virtually impossible to figure out what the private key was. How Are Transactions Authorized In Bitcoin, a valid digital signature serves as proof that the transaction was authorized by the address’s owner. Just as a private key was required to generate that address, the same private key is required, once again, to generate a valid digital signature. 37 A digital signature is only valid if a specific equation is satisfied by the address, the previous output and the signature. The Bitcoin lifecycle Sender wants to send 1 Bitcoin to Receiver. This is what is going to happen: Figure 1.38 Bitcoin Life cycle 1. Sender creates a transaction. 38 2. Sender's bitcoin wallet validates the transaction. 3. The transaction is sent to Mempool. 4. Miners get the transaction from Mempool and start mining the block using a consensus algorithm. 5. After the block is fully mined, it is added to the network. 6. The chain validates the new block and every peer in the network will get the blockchain with the new block added. 7. Finally, the Receiver get your BTCs Mempool The Mempool (Shortcut for Memory Pool) is where the transactions stay until the miner is ready to get them. In the bitcoin's blockchain, the miner prioritize the biggest transactions over the smallest ones. This happens because here is where the miner makes money. Miner "mine" the block through the consensus algorithm. Bitcoin Flow of Transaction Figure 1.38 Bitcoin Flow diagram 39 Let us say that there are two parties Alice and Bob who want to communicate with each other for funds transfer over an insecure channel, Internet. Then following sequence of activities are performed between two parties. If Alice wants to send some coins from her walletX to Bob’s wallet Y, then a request of transactional data “t” is sent to Bob. This request is broadcasted in the entire network. The distributed nodes accept the request and update their ledgers with the transactional information of Alice–Bob. After updating ledgers, Alice computes digital signature (DS) and broadcasts it in the network. A miner node is selected to verify and validate the transaction. It computes proof-of- work (PoW) to match the DS received. If PoW is successfully matched with DS, then the result is broadcast to all the nodes for verification and validation. The other miner nodes also verify the PoW with DS. If the verification is successful, then the miner node is (financially) rewarded for computing the PoW. The validated block is added in the validated chain and the transaction is broadcasted to the entire blockchain. Using the validated transaction “t,” the bitcoins are added to walletY of Bob. Bob decrypts the content using the paired public key (PUK) of Alice and sends the acknowledgment (ACK) to Alice. The transaction is finished once Alice receives the transaction acknowledgment. Consensus Algorithm The consensus algorithm is probably the most important part of any implementation of blockchain. The Bitcoin uses one consensus algorithm called Proof Of Work. Try to get the right nonce number by checking the hash created for the block until the result hash have the same number of zero's in it's prefix. This execution to try to get the right nonce number takes a lot of energy cost and 40 computational work, and that's why the miners get the fees from the transaction. Proof of Work consensus algorithm Proof of Work” because it requires some type of work - usually computer processing. consensus algorithm is a set of rules that governs a blockchain network. It is an agreement on the rules of a specific blockchain and how users can participate in the network Miners who carry out the validation of transactions in the blockchain. Miners have downloaded the full Bitcoin blockchain and chosen to run it on powerful computers. These users (nodes) in the Bitcoin network are called “miners” because they check and prove the accuracy of a transaction in a process called mining - similar to the computation of a complex mathematical problem. Once a request to record and complete a transaction is disseminated into the blockchain, usually the transactions with the highest fee offered are selected to go into the next block on the blockchain. In order to reach consensus on a valid block in the blockchain, the Bitcoin algorithm provides a difficulty as a parameter that needs to be met for a block to be valid. This “difficulty” is regularly modified by the Bitcoin network depending on the computational power of the miners. Difficulty may be decreased or increased to maintain a constant speed at which new blocks are added. An arbitrary number called a nonce (the abbreviation for “number only used once”) is added to the block for purposes of cryptography. Miners alter the nonce until a value is found that gives the block's hash the required difficulty level Once this requirement is met the block cannot be changed without redoing the work. During hashing, an algorithm called a hash function is used to convert one value (the selected set of data) into a fixed-size as the output - the hash value, thus masking the 41 original value. A hash function cannot be reverse-engineered, meaning that the hash value cannot be used to find out the original data. Thus, the hash value is a “fingerprint” providing thorough authentication and ensuring that no tampering took place with the transmitted content. Each hash value contains information on all previous network transactions. The newly generated hash is checked against the current difficulty. A hash value always has to contain a specific number of zero-bits. If the hash meets the criteria of difficulty, it is broadcast to the other miners in the network. If it does not, another nonce is selected and hashed. Miners generate many hashes with different nonces until they find one that meets the needed criteria. This repetitive process is known as “mining” and now you know why it requires so much energy. Therefore, the first miner who finds a valid hash validates the block into a new block and gets a block reward in Bitcoin. Disadvantages of Proof of Work Bitcoin transactions per second has been seven transactions, VISA network’s estimated 1,700 vast amounts of energy are required for the mining process in the Bitcoin blockchain. larger mining pools have more computational power at their access and thus greater chances of mining valid blocks, putting individual miners at disadvantage. Source : https://www.bitpanda.com/academy/en/lessons/consensus-algorithms-proof- of-work/ Proof of Work Vs Proof of Stake Proof of Work Proof of Stake Participating nodes are called validators or Participating nodes are called miners forgers 42 Mining capacity depends on Validating capacity depends on the stake in computational power the network Mining produces new coins No new coins are formed Miners receive block rewards Validators receive transaction fees Massive energy consumption Low to moderate energy consumption Significantly prone to 51% attacks 51% attacks are virtually impossible Proof of work and mining To create new digital currencies by rewarding miners for performing the previous task. When you want to set a transaction this is what happens behind the scenes: Transactions are bundled together into what we call a block; Miners verify that transactions within each block are legitimate; To do so, miners should solve a mathematical puzzle known as proof-of-work problem; A reward is given to the first miner who solves each blocks problem; Verified transactions are stored in the public blockchain. 43 Figure 1.39 Proof of Work Vs Proof of stake Mining Process From a technical point of view, the mining process is an operation of inverse hashing: it determines a number (nonce), so the cryptographic hash algorithm of block data results in less than a given threshold. This threshold, called difficulty, is what determines the competitive nature of mining: more computing power is added to the network, the higher this parameter increases, increasing also the average number of calculations needed to create a new block. Bitcoin Address Example Bitcoin addresses are 26-35 characters long, consist of alphabetic and numeric characters, and either begin with “1”, “3”, or “bc1”. Currently, there are three Bitcoin address formats in use: 1. P2PKH (address starts with the number “1”) The P2PKH concept stands for “Pay to Public Key Hash”. 44 P2PKH means “pay to this Bitcoin address”. It serves as an instruction on the blockchain for users wanting to transfer Bitcoin to one another. Behind every transaction, there are underlying codes working behind the scene. This scripting language is known as the Bitcoin Scripting Language. Example: 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2 P2PKH Figure 1.40 GUI of Pay to Public Key Hash 2. P2SH (address starts with the number “3”) Pay to script hash (P2SH) is an advanced type of transaction used in Bitcoin and other similar cryptocurrencies. P2SH or Pay-to-Script-Hash was a patch to Bitcoin added in 2012 which altered the way it validated transactions. It is most commonly identifiable as the addresses in Bitcoin that start with a “3” instead of a “1”. Unlike P2PKH, it allows sender to commit funds to a hash of an arbitrary valid script. Example: 45 3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy 3. Bech32 (address starts with “bc1”) Example: bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq How to Get a Bitcoin Address To get a Bitcoin address, you first need to download a Bitcoin wallet, which is software that allows you to securely send, receive, and store Bitcoin funds in the Bitcoin network. Bitcoin wallets also store your private key, which is essentially your Bitcoin password. The software will generate a brand new Bitcoin address for you every time you create an invoice or receive a payment request for Bitcoins too. There are four types of Bitcoin wallets that you can use: mobile, web, desktop, and hardware. Source: https://blog.hubspot.com/marketing/bitcoin-address 1.8 Smart Contract A smart contract is a self-executing contract with the terms of the agreement between buyer and seller being directly written into lines of code. The code and the agreements contained therein exist across a distributed, decentralized blockchain network. The code controls the execution, and transactions are trackable and irreversible. 46 Figure 1.41 illustration of Smart contract Smart contracts work by following simple “if/when…then…” statements that are written into code on a blockchain. A network of computers executes the actions when predetermined conditions have been met and verified. These actions could include releasing funds to the appropriate parties, registering a vehicle, sending notifications, or issuing a ticket. The blockchain is then updated when the transaction is completed. That means the transaction cannot be changed, and only parties who have been granted permission can see the results. Within a smart contract, there can be as many stipulations as needed to satisfy the participants that the task will be completed satisfactorily. Participants must determine how transactions and their data are represented on the blockchain. Participants agree on the “if/when...then…” rules that govern those transactions, explore all possible exceptions, and define a framework for resolving disputes. 47 The smart contract can be programmed by a developer. organizations that use blockchain for business provide templates, web interfaces, and other online tools to simplify structuring smart contracts. Benefits of smart contracts Speed, efficiency and accuracy Once a condition is met, the contract is executed immediately. Because smart contracts are digital and automated, there’s no paperwork to process. No time spent reconciling errors that often result from manually filling in documents. Trust and transparency Because there’s no third party involved, and because encrypted records of transactions are shared across participants, there’s no need to question whether information has been altered for personal benefit. Security Blockchain transaction records are encrypted, which makes them very hard to hack. Moreover, because each record is connected to the previous and subsequent records on a distributed ledger, hackers would have to alter the entire chain to change a single record. Savings Smart contracts remove the need for intermediaries to handle transactions and, by extension, their associated time delays and fees. Applications of smart contracts Smart contracts can be used across industries to streamline and automate doing business around the world. Government - voting system Management single ledger as a source of trust, accuracy, transparency, and automated system Supply chain automates tasks and payment 48 Automobile with the help of smart contract insurance company can be connected for claim Real Estate No need of Brokers, real estate agents Healthcare 49 UNIT - I BLOCKCHAIN TECHNOLOGIES-SITA3011 UNIT II Architecture and Conceptualization of Block Chain, Crypto Currencies Block in a Block chain-find Transactions-Distributed Consensus-Proof of work, Stake, Space-Attacks on POW-Ethereum-Pos/POW Hybrids-Crypto currency to block chain 2.0, Model of Blockchain- Algorand. 2.1 BLOCK IN A BLOCK CHAIN Definition of Blockchain A block chain is an open, distributed ledger that can record transactions between two parties efficiently and in a verifiable and permanent way without the need for a central authority. Key Characteristics to be remembered: Open: Anyone can access blockchain. Distributed or Decentralised: Not under the control of any single authority. Efficient: Fast and Scalable. Verifiable: Everyone can check the validity of information because each node maintains a copy of the transactions. Permanent: Once a transaction is done, it is persistent and can’t be altered. Contents of a Block Blockchain starts with a block called genesis block. Each block stores the following information in it: Index: Position of the block in blockchain. Index of genesis block is 0. Time stamp: The time when that particular block was created. Hash: Numeric value that uniquely identifies data just like our fingerprints. Previous hash: Hash value of the previous block. For genesis block, this value is 0. Data: Data stored on the node. For example, transactions. 50 Nonce: It is a number used to find a valid hash. To generate this number, the processing power is used. Fig.2.1 Genesis block Mechanism of Blockchain Fig 2.2 Blocks connected in backward direction Blockchain works like a public ledger. Any small change in the data value can affect the hash value. Hence, affecting the whole block chain. Every peer in a Blockchain network maintains a local copy of the Blockchain. All the replicas need to be updated with the last mined block. All the replicas need to be consistent — the copies of the Blockchain at different peers need to be exactly similar. Structure of a Block (Reference: Bitcoin) The blockchain is a chain of data blocks. Each block can be thought of as a page in a ledger. The individual blocks are composed of several components. Roughly these can be differentiated into the head of the block (block header) and the body (block body). 51 Block header The head of the block is divided into six components: 1. the version number of the software 2. the hash of the previous block 3. the root hash of the Merkle tree 4. the time in seconds since 1970–01–01 T00: 00 UTC 5. the goal of the current difficulty 6. the nonce The version number of the software: The software version number does not matter in most cases. However, a miner with a particular version number can signal which protocol decisions he supports. The hash of the previous block :The hash of the previous block is, so to speak, the chain of blockchains. Because the hash of the previous block is contained in the hash of the new block, the blocks of the blockchain all build on each other. Without this component, there would be no connection and chronology between each block. The root hash of the Merkle tree :All transactions contained in a block can be aggregated in a hash. This is the root hash of the Merkle tree. The time in seconds since 1970–01–01 T00: 00 UTC: A timestamp in the block itself. The time is given in seconds since 1.1.1970. The goal of the current difficulty :The goal indicates how small the new hash must be to claim validity. In other words, every hash has a size in bits. The lower the goal in bits is, the harder it is to find a matching hash. A hash with many zeros at the beginning is smaller than a hash without zeros. Find out more about the difficulty of the proof of work. The Nonce:The nonce is the variable incremented by the proof of work. In this way, the miner guesses a valid hash, a hash that is smaller than the target. The six components form the block header. The block header plays a fundamental role in Bitcoin because it connects all blocks together. You can imagine it like the cockpit of a truck. Here are the important papers with which the truck comes through the controls of the network. 52 Block Body The block body is conceivable as the loading space of a truck. It contains all transactions that are confirmed with the block. When a miner constructs a block, it validates the transactions. That is, he checks that the sender actually has enough money to spend. He can easily read this information from the blockchain. The miner looks in the past blocks to see if the sender has even gotten ten Bitcoins if he wants to send ten Bitcoins. The transactions in a block are not just in a list, but in a so- called Merkle Tree. Merkle Tree The Merkle Tree takes its name from the mathematician Ralph Merkle. The discovery was that much information can be represented in a single hash. For this, the data itself is first hashed. Then the hashes are hashed again and merged. Finally, the Merkle Tree is merged into a single hash. This last hash is also called the root hash, the root of the tree. It represents all the information of its “leaves” (individual transactions) and “branches” (hashes of the leaves) in a relatively short string. Creating the root hash is quick and easy, as long as all branches and leaves are known. We remember the function of a hash function: it works clearly and quickly in one direction and is impossible to break down in the other direction. If the root hash is known, but the transactions are unknown, it is impossible to guess the transactions. A root hash alone is therefore not enough, and the rest of the block must be saved. Thus, the miner can validate the root hash at any time by hashing the information contained in the block again. As long as the hash function is the same, the miners always get the same hash for a given input of data. This is very handy because they can only check if they are on the same level as the hash. Mining: The search for a special hash 53 In this context, it is easier to understand the mining of the proof of work. When mining, the block header of the block is incrementally changed to get a special hash. The header consists of five constants and one variable. The constants are the version number of the software, the hash of the previous block, the root hash of the Merkle tree, the timestamp, and the target size of the searched hash in bytes. The variable is the nonce. A nonce is a number raised by one. Then the miner hashes the data and checks if the data results in a hash that is below the searched target value. If the hash value is greater than the target, the miner repeats the process; So it increases the nonce by one, hashes and checks again. It repeats this until it finds a hash below the target, or it gets another block from another networker whose hash is below the target. Then takes this new block and uses it as the basis for the next block (using the new hash as the “hash of the previous block”). Mining is a hyper-repetitive process whose goal is to find a special hash. Once the hash is found, the game starts again. The probability of finding a special hash depends on the difficulty. On average Bitcoin finds a new block every ten minutes. The difficulty keeps adapting, so this average stays the same. The special feature of this process is that the special hash can only be found by guessing. This rate costs computing power and therefore energy. A look at the special hash is enough to see that it is special because it begins with zeros. Here is an example of such a hash from the Bitcoin blockchain: 000000000000000000094bfa4edb1245c347e42452e4418e9fe5a1d24e335b16 Hashes: The matryoshka of the blockchain A block can be simplified as a matryoshka image. The smallest doll is the unhashed transaction. The next envelope is the hashed form of this transaction. Thereafter, two hashed transactions are hashed together. So the hashes are merged more and more. In the end, there is only one hash remaining, the root hash, or the biggest matryoshka. 54 2.2 DISTRIBUTED CONSENSUS Consensus is the process by which peers agree to the addition of next block in the block chain. Distributed Consensus ensures that different nodes in the network see the same data at nearly the same point of time. Hence in case of any failure, the system can still provide a service as the data is decentralised. To maintain anonymity in this large network, the permission less protocol is used where you don’t need to record your identity while participating in the consensus. Consensus Algorithms We know that Blockchain is a distributed decentralized network that provides immutability, privacy, security, and transparency. There is no central authority present to validate and verify the transactions, yet every transaction in the Blockchain is considered to be completely secured and verified. This is possible only because of the presence of the consensus protocol which is a core part of any Blockchain network. A consensus algorithm is a procedure through which all the peers of the Blockchain network reach a common agreement about the present state of the distributed ledger. In this way, consensus algorithms achieve reliability in the Blockchain network and establish trust between unknown peers in a distributed computing environment. Essentially, the consensus protocol makes sure that every new block that is added to the Blockchain is the one and only version of the truth that is agreed upon by all the nodes in the Blockchain. The Blockchain consensus protocol consists of some specific objectives such as coming to an agreement, collaboration, co-operation, equal rights to every node, and mandatory participation of each node in the consensus process. Thus, a consensus algorithm aims at finding a common agreement that is a win for the entire network. Now, we will discuss various consensus algorithms and how they work. 2.2.1 Proof of Work (PoW): The idea for Proof of Work(PoW) was first published in 1993 by Cynthia Dwork and Moni Naor and was later applied by Satoshi Nakamoto in the Bitcoin paper in 2008. Proof of Work consensus is the mechanism of choice for the majority of cryptocurrencies currently in circulation. The term “proof of work” was first used by Markus Jakobsson and Ari Juels in a publication in 1999. 55 Principle: A solution that is difficult to find but is easy to verify. The purpose of a consensus mechanism is to bring all the nodes in agreement, that is, trust one another, in an environment where the nodes don’t trust each other. All the transactions in the new block are then validated and the new block is then added to the blockchain. Note that, the block will get added to the chain which has the longest block height(see blockchain forks to understand how multiple chains can exist at a point of time). Miners(special computers on the network) perform computation work in solving a complex mathematical problem to add the block to the network, hence named, Proof-of-Work. With time, the mathematical problem becomes more complex. Working of POW(Proof of Work) “The Proof of Work consensus algorithm involves solving a computational challenging puzzle in order to create new blocks in the Bitcoin blockchain. Colloquially, the process is known as ‘mining’, and the nodes in the network that engage in mining are known as ‘miners’. The incentive for mining transactions lies in economic payoffs, where competing miners are rewarded with 12.5 bitcoins(at the time of writing this article; this reward will get reduced by half its current value with time) and a small transaction fee.” The process of verifying the transactions in the block to be added, organizing these transactions in a chronological order in the block and announcing the newly mined block to the entire network does not take much energy and time. The energy consuming part is solving the ‘hard mathematical problem’ to link the new block to the last block in the valid blockchain. When a miner finally finds the right solution, the node broadcasts it to the whole network at the same time, receiving a cryptocurrency prize (the reward) provided by the PoW protocol. At the time of writing this article, mining a block in the bitcoin network gives the winning miner 12.5 bitcoins. The amount of bitcoins won halves every four years or so(thats how the bitcoin network is designed). So, the next deduction in the amount of bitcoin is due at around 2020-21(with the current rate and growth). With more miners comes the inevitability of the time it takes to mine the new block getting shorter. This means that the new blocks are found faster. In order to consistently find 1 block every 10 minutes (That is the amount of time that the bitcoin developers think 56 is necessary for a steady and diminishing flow of new coins until the maximum number of 21 million is reached (expected some time with the current rate in around 2140)), the Bitcoin network regularly changes the difficulty level of mining a new block. Fig 2.3 Proof of Work The fact that Block GFG1 is connected to Block GFG2 through its hash number is important. The significance lies in the fact that this ‘hash number’ connects new block to the last block in the valid blockchain. If, on the other hand, the Block GFG1 Hash number on Block GFG2 had a different hash number than Block GFG1 they would not match up, and Block GFG2 would not be verified. First block in the blockchain is called the Genesis Block and has no Prev Block Hash value. Changing a block (which can only be done by making a new block containing the same predecessor) requires regenerating all successors and redoing the work they contain (amounting to calculating the entire chain of ‘hard mathematical problems’) which is practically impossible. This protects the blockchain from tampering. Bitcoin’s Proof-of-Work system: Bitcoin uses the Hashcash Proof of Work system as the mining basis. The ‘hard mathematical problem’ can be written in an abstract way like below : Given data A, find a number x such as that the hash of x appended to A results is a number less than B. The miners bundle up a group of transactions into a block and try to mine. To mine it, a hard mathematical problem has to be solved. This problem is called the proof of work problem which has to be solved to show that the miner has done some work in finding out the solution to the problem and hence the mined block must be valid. The answer to the 57 problem needs to be a lower number than the hash of the block for it to be accepted, known as the ‘target hash’.A target hash is a number that the header of a hashed block must be equal to or less than for a new block, along with the reward, to be awarded to a miner. The lower a target is, the more difficult it is to generate a block. A miner continues testing different unique values (known as nonce(s)) until a suitable one is produced. The miner who manages to solve the problem gets the bitcoin reward and adds the block into the blockchain by broadcasting that the block has been mined. The target hash adjusts once every 2016 blocks or approximately once every 2 weeks. All the miners immediately stop work on the said block and start mining the next block. Common cryptographic protocols used in Proof of Work systems: The most widely used proof-of-work consensus is based on SHA-256 and was introduced as a part of Bitcoin. Others include Scrypt, SHA-3, scrypt-jane, scrypt-n, etc. Features of Proof of Work system: There are mainly two features that have contributed to the wide popularity of this consensus protocol and they are: It is hard to find a solution for the mathematical problem It is easy to verify the correctness of that solution Main issues with the Proof-of-Work consensus: \The Proof-of-Work consensus mechanism has some issues which are as follows: The 51% risk: If a controlling entity owns 51% or more than 51% of nodes in the network, the entity can corrupt the blockchain by gaining the majority of the network. Time consuming: Miners have to check over many nonce values to find the right solution to the puzzle that must be solved to mine the block, which is a time consuming process. Resource consumption: Miners consume high amounts of computing power in order to find the solution to the hard mathematical puzzle. It leads to a waste of precious resources(money, energy, space, hardware). It is expected that the 0.3% of the world’s electricity will be spent to verify transactions by the end of 2018. 58 Transaction confirmation takes about 10–60 minutes. So, it is not an instantaneous transaction; because it takes some time to mine the transaction and add it to the blockchain thus committing the transaction. Cryptocurrencies using PoW: Litecoin Ethereum Monero coin Dogecoin 2.2.2 Proof of Stake (PoS): Proof of Stake (PoS) is a type of algorithm which aims to achieve distributed consensus in a Blockchain. This way to achieve consensus was first suggested by Quantum Mechanic here and later Sunny King and his peer wrote a paper on it. This led to Proof-of- Stake (PoS) based Peercoin. A stake is value/money we bet on a certain outcome. The process is called staking. A more particular meaning of stake will be defined later on. Need of Proof-of-Stake: Before proof of stake, the most popular way to achieve distributed consensus was through Proof-of-Work (implemented in Bitcoin). But Proof-of-Work is quite energy(electrical energy in mining a bitcoin) intensive. So, a proof-of-work based consensus mechanism increases an entity’s chances of mining a new block if it has more computation resources. Apart from the upper two points, there are other weaknesses of a PoW based consensus mechanism which we will discuss later on. In such a scenario, a Proof-of-Stake based mechanism holds merit. Proof-of-Stake: As understandable from the name, nodes on a network stake an amount of cryptocurrency to become candidates to validate the new block and earn the fee from it. Then, an algorithm chooses from the pool of candidates the node which will validate the new block. This selection algorithm combines the quantity of stake (amount of cryptocurrency) with other factors (like coin-age based selection, randomization process) to make the selection fair to everyone on the network. 59 Coin-age based selection: The algorithm tracks the time every validator candidate node stays a validator. The older the node becomes, the higher the chances of it becoming the new validator. Random Block selection: The validator is chosen with a combination of ‘lowest hash value’ and ‘highest stake’. The node having the best weighted-combination of these becomes the new validator. A typical PoS based mechanism workflow: 1. Nodes make transactions. The PoS algorithm puts all these transactions in a pool. 2. All the nodes contending to become validator for the next block raise a stake. This stake is combined with other factors like ‘coin-age’ or ‘randomized block selection’ to select the validator. 3. The validator verifies all the transactions and publishes the block. His stake still remains locked and the forging reward is also not granted yet. This is so that the nodes on the network can ‘OK’ the new block. 4. If the block is ‘OK’-ed, the validator gets the stake back and the reward too. If the algorithm is using a coin-age based mechanism to select validators, the validator for the current block’s has its coin-age reset to 0. This puts him in a low-priority for the next validator election. 5. If the block is not verified by other nodes on the network, the validator loses its stake and is marked as ‘bad’ by the algorithm. The process again starts from step 1 to forge the new block. Features: Fixed coins in existence: There is only a finite number of coins that always circulate in the network. There is no existence of bringing new coins into existence(as in by mining in case of bitcoin and other PoW based systems). Note that the network starts with a finite number of coins or ‘initially starts with PoW, then shifts to PoS’ in some cases. This initiation with PoW is meant to bring coins/cryptocurrency in the network. Transaction fee as reward to minters/forgers: 60 Every transaction is charged some amount of fee. This is accumulated and given to the entity who forges the new block. Note that if the forged block is found fraudulent, the transaction fee is not rewarded. Moreover, the stake of the validator is also lost(which is also known as slashing). Impracticality of the 51% attack: To conduct a 51% attack, the attacker will have to own 51% of the total cryptocurrency in the network which is quite expensive. This deems doing the attack too tedious, expensive and not so profitable. There will occur problems when amassing such a share of total cryptocurrency as there might not be so much currency to buy, also that buying more and more coins/value will become more expensive. Also validating wrong transactions will cause the validator to lose its stake, thereby being reward-negative. Advantages of PoS: Energy-efficient: As all the nodes are not competing against each other to attach a new block to the blockchain, energy is saved. Also, no problem has to be solved( as in case of Proof-of-Work system) thus saving the energy. Decentralization: In blockchains like Bitcoin(Proof of Work system to achieve distributed consensus), an extra incentive of exponential rewards are in place to join a mining pool leading to a more centralized nature of blockchain. In the case of a Proof-of-Stake based system(like Peercoin), rewards are proportional(linear) to the amount of stake. So, it provides absolutely no extra edge to join a mining pool; thus promoting decentralization. Security: A person attempting to attack a network will have to own 51% of the stakes(pretty expensive). This leads to a secure network. Weakness of a PoS mechanism: Large stake validators: If a group of validator candidates combine and own a significant share of total cryptocurrency, they will have more chances of becoming validators. Increased chances lead to increased selections, which lead to more and more forging reward earning, which lead to owning a huge currency share. This can cause the network to become centralized over time. New technology: PoS is still relatively new. Research is ongoing to find flaws, fix them and making it viable for a live network with actual currency transactions. 61 The ‘Nothing at Stake’ problem: This problem describes the little to no disadvantage to the nodes in case they support multiple blockchains in the event of a blockchain split(blockchain forking). In the worst-case scenario, every fork will lead to multiple blockchains and validators will work and the nodes in the network will never achieve consensus. Blockchains using Proof-of-Stake: Ethereum(Casper update) Peercoin Nxt Variants of Proof-of-Stake: Regular Proof-of-Stake Delegated Proof-of-Stake Leased Proof-of-Stake Masternode Proof-of-Stake 2.2.3 Proof of Space/ proof of capacity Proof of space is a type of consensus algorithm achieved by demonstrating one's legitimate interest in a service (such as sending an email) by allocating a non-trivial amount of memory or disk space to solve a challenge presented by the service provider. Proofs of space are very similar to proofs of work (PoW), except that instead of computation, storage is used to earn cryptocurrency. Proof-of-space is different from memory-hard functions in that the bottleneck is not in the number of memory access events, but in the amount of memory required. the release of Bitcoin, alternatives to its PoW mining mechanism were researched and PoS was studied in the context of cryptocurrencies. Proofs of space are seen as a fairer and greener alternative by blockchain enthusiasts due to the general-purpose nature of storage and the lower energy cost required by storage, but have been criticized for increasing demand for storage. Several theoretical and practical implementations of PoS have been released and discussed, such as SpaceMint, Burstcoin, and Chia. Concept Description 62 A proof-of-space is a piece of data that a prover sends to a verifier to prove that the prover has reserved a certain amount of space. For practicality, the verification process needs to be efficient, namely, consume a small amount of space and time. For security, it should be hard for the prover to pass the verification if it does not actually reserve the claimed amount of space. One way of implementing PoS is by using hard-to-pebble graphs.The verifier asks the prover to build a labeling of a hard-to-pebble graph. The prover commits to the labeling. The verifier then asks the prover to open several random locations in the commitment. 2.3 Types of Attacks on PoW (Proof of Work) based systems As we know, the idea of Proof of Work was by Cynthia Dwork and Moni Naor. This permissionless consensus uses double SHA 256 which makes it secure from hackers. With proof of work, miners compete with each other to complete the transaction and get the bounty. Even it has many advantages like solving the double-spending problem and very difficult to tamper it, but it is not impossible to tamper if the hacker has high computational power. There are two major attacks by which PoW based systems can crash.They are : 1. Sybil Attacks 2. Denial of Service(DOS) Attacks These are explained as following below with their solutions. Sybil Attacks : In Sybil attacks, the attacker attempts to fill the network with the clients under its control. When this thing happens the attacker can actually control or get a monopoly over the network and these clients can do different kinds of actions based on the instruction from the attacker. They can refuse to relay the valid blocks or they can only relay the blocks which are generated by the attackers and those blocks can lead to double-spending. In Simple language, The attacker can include multiple nodes in the network who can collectively compromise the Proof of Work mechanism. Solution – To prevent Sybil attacks we have to diversify the connections i.e allowing outbound connection to one IP per / 16 IP address. So by diversifying the network it is expected that if 63 the attacker generates multiple false miners the attacker will generate them within the same clustered network or subnet. Denial of Service (DOS) Attacks : In this attack, the attacker sends a lot of data to a particular node so that node will not able to process normal Bitcoin transactions. As a result, the metabolism of the mining procedure will get delayed which wastes the power for computation and in that meantime, the attacker can also send new nodes to the network resulting in a monopoly which is nothing but a Sybil attack. Solution – To prevent DOS attacks there are several rules bitcoin have which are: No forwarding of orphaned blocks. No forwarding of double-spend transactions. No forwarding of same block or transactions Disconnect a peer that sends too many messages Restrict the block size to 1 MB (1mb according to Satoshi Nakamoto) Limit the size of the bitcoin script up to 10000 bytes. 1.4 Ethereum Ethereum is a blockchain platform with its own cryptocurrency, called Ether (ETH) or Ethereum, and its own programming language, called Solidity. As a blockchain network, Ethereum is a decentralized public ledger for verifying and recording transactions. The network's users can create, publish, monetize, and use applications on the platform, and use its Ether cryptocurrency as payment. Insiders call the decentralized applications on the network "dapps.". The Enterprise Ethereum Alliance (EEA) has some big-name founding members too, including Microsoft, Intel, and JPMorgan Chase, according to The Motley Fool. “The adoption of Ethereum by the corporate world,” says CNBC, “means it could eventually be bigger than its early stage rival.” That means it’s time to get to know the Ethereum platform, including its features and applications, and what makes Ethereum different from Bitcoin. Our “Ethereum Explained” Ethereum tutorial video lays it all out for you, and here we’ll cover what’s discussed in the video. 64 Ethereum Ethereum is a blockchain-based computing platform that enables developers to build and deploy decentralized applications—meaning not run by a centralized authority. You can create a decentralized application for which the participants of that particular application are the decision-making authority. Ethereum Features Ether: This is Ethereum’s cryptocurrency. Smart contracts: Ethereum allows the development and deployment of these. Ethereum Virtual Machine: Ethereum provides the underlying technology—the architecture and the software—that understands smart contracts and allows you to interact with it. Decentralized applications (Dapps): Ethereum allows you to create consolidated applications, called decentralized applications. A decentralized application is called a Dapp (also spelled DAPP, App, or DApp) for short. Decentralized autonomous organizations (DAOs): Ethereum allows you to create these for democratic decision-making. These are the essential features of Ethereum and before going deep into the Ethereum tutorial, let’s discuss each of these features in more detail. Ether Ether (ETH) is Ethereum’s cryptocurrency. It is the fuel that runs the network. It is used to pay for the computational resources and the transaction fees for any transaction executed on the Ethereum network. Like Bitcoins, ether is a peer-to-peer currency. Apart from being used to pay for transactions, ether is also used to buy gas, which is used to pay for the computation of any transaction made on the Ethereum network. Also, if you want to deploy a contract on Ethereum, you will need gas, and you would have to pay for that gas in ether. So gas is the execution fee paid by a user for running a 65 transaction in Ethereum. Ether can be utilized for building decentralized applications, building smart contracts, and making regular peer-to-peer payments. Smart Contracts Smart contracts are revolutionizing the way how traditional contracts worked, which is why you need to know about them in this Ethereum tutorial. A smart contract is a simple computer program that facilitates the exchange of any valuable asset between two parties. It could be money, shares, property, or any other digital asset that you want to exchange. Anyone on the Ethereum network can create these contracts. The contract consists primarily of the terms and conditions mutually agreed on between the parties (peers). The primary feature of a smart contract is that once it is executed, it cannot be altered, and any transaction done on top of a smart contract is registered permanently—it is immutable. So even if you modify the smart contract in the future, the transactions correlated with the original contract will not get altered; you cannot edit them. The verification process for the smart contracts is carried out by anonymous parties of the network without the need for a centralized authority, and that’s what makes any smart contract execution on Ethereum a decentralized execution. The transfer of any asset or currency is done in a transparent and trustworthy manner, and the identities of the two entities are secure on the Ethereum network. Once the transaction is successfully done, the accounts of the sender and receiver are updated accordingly, and in this way, it generates trust between the parties. a) Smart Contracts Vs. Traditional Contract Systems In conventional contract systems, you sign an agreement, then you trust and hire a third party for its execution. The problem is that in this type of process, data tampering is possible. With smart contracts, the agreement is coded in a program. A centralized authority does not verify the result; it is confirmed by the participants on the Ethereum blockchain- based network. Once a contract is executed, the transaction is registered and cannot be altered or tampered, so it removes the risk of any data manipulation or alteration. Let’s take an example in which someone named Zack has given a contract of $500 to someone named Elsa for developing his company’s website. The developers code the agreement of the smart contract using Ethereum’s programming language. The smart contract 66 has all the conditions (requirements) for building the website. Once the code is written, it is uploaded and deployed on the Ethereum Virtual Machine (EVM). EVM is a runtime compiler to execute a smart contract. Once the code is deployed on the EVM, every participant on the network has a copy of the contract. When Elsa submits the work on Ethereum for evaluation, each node on the Ethereum network will evaluate and confirm whether the result given by Elsa has been done as per the coding requirements, and once the result is approved and verified, the contract worth $500 will be self-executed, and the payment will be paid to Elsa in ether. Zack’s account will be automatically debited, and Elsa will be credited with $500 in ether. Fig 2.4 Smart contract Ethereum Virtual Machine EVM, as mentioned above in this Ethereum tutorial, is designed to operate as a runtime environment for compiling and deploying Ethereum-based smart contracts. EVM is the engine that understands the language of smart contracts, which are written in the Solidity language for Ethereum. EVM is operated in a sandbox environment—basically, you can deploy your stand-alone environment, which can act as a testing and development environment, and you can test your smart contract (use it) “n” number of times, verify it, and then once you are satisfied with the performance and the functionality of the smart contract, you can deploy it on the Ethereum main network. 67 Any programming language in the smart contract is compiled into the bytecode, which the EVM understands. This bytecode can be read and executed using the EVM. One of the most popular languages for writing a smart contract in Solidity. Once you write your smart contract in Solidity, that contract gets converted into the bytecode and gets deployed on the EVM. And thereby EVM guarantees security from cyberattacks. a)Working of EVM Suppose person A wants to pay person B 10 ethers. The transaction will be sent to the EVM using a smart contract for a fund transfer from A to B. To validate the transaction; the Ethereum network will perform the proof-of-work consensus algorithm. The miner nodes on Ethereum will validate this transaction—whether the identity of A exists or not, and if A has the requested amount to transfer. Once the transaction is confirmed, the ether will be debited from A’s wallet and will be credited to B’s wallet, and during this process, the miners will charge a fee to validate this transaction and will earn a reward.All the nodes on the Ethereum network execute smart contracts using their respective EVMs. b) Proof of Work Every node in the Ethereum network has: The entire history of all the transactions—the entire chain The history of the smart contract, which is the address at which the smart contract is deployed, along with the transactions associated with the smart contract The handle to the current state of the smart contract The goal of the miners on the Ethereum network is to validate the blocks. For each block of a transaction, miners use their computational power and resources to get the appropriate hash value by varying the nonce. The miners will vary the nonce and pass it through a hashing algorithm—in Ethereum, it is the Ethash algorithm. 68 This produces a hash value that should be less than the predefined target as per the proof-of-work consensus. If the hash value generated is less than the target value, then the block is considered to be verified, and the miner gets rewarded. When the proof of work is solved, the result is broadcast and shared with all the other nodes to update their ledger. If other nodes accept the hashed block as valid, then the block gets added to the Ethereum main blockchain, and as a result, the miner receives a reward, which as of today stands at three ethers. Plus the miner gets the transaction fees that have been generated for verifying the block. All the transactions that are aggregated in the block— the cumulative transaction fees associated with all the transactions are also given as a reward to the miner. c) Proof of Stake In Ethereum, a process called proof of stake is also under development. It is an alternative to proof of work and is meant to be a solution to minimize the use of expensive resources spent on mining using proof of work. In proof of stake, the miner—who is the validator—can validate the transactions based on the number of crypto coins he or she holds before actually starting the mining. So based on the accumulation of crypto coins the miner has beforehand, he or she has a higher probability of mining the block. However, proof of stake is not widely used as of now compared to proof of work. d) Gas Just like we need fuel to run a car, we need gas to run applications on the Ethereum network. To perform any transaction within the Ethereum network, a user has to make a payment—shell out ethers—to get a transaction done, and the intermediary monetary value is called gas. On the Ethereum network, gas is a unit that measures the computational power required to run a smart contract or a transaction. So if you have to do a transaction that updates the blockchain, you would have to shell outgas, and that gas costs ethers. In Ethereum, the transaction fees are calculated using a formula (see screenshot below). For every transaction, there is gas and its correlated gas price. The amount of gas required to execute a transaction multiplied by the gas price equals the transaction fees. “Gas 69 limit” refers to the amount of gas used for the computation and the amount of ether a user is required to pay for the gas. Fig 2.5 Gas value Below is a screenshot from the Ethereum network showing the transaction cost. You can see for this particular transaction, the gas limit was 21,000, the gas used by the transaction was 21,000, and the gas price was 21 Gwei, which is the lowest denomination of ether. So 21 Gwei * 21,000 gave the actual transaction fees: 0.000441 ethers, or about 21 cents as of today. As mentioned, the transaction fee goes to the miner, who has validated the transaction. Fig 2.6 Transaction fees in ethereum To understand the gas limit and the gas price, let’s consider an example using a car. Suppose your vehicle has a mileage of 10 kilometers per liter and the amount of petrol is $1 per liter. Then driving a car for 50 kilometers would cost you five liters of petrol, which is 70 worth $5. Similarly, to perform an operation or to run code on Ethereum, you need to obtain a certain amount of gas, like petrol, and the gas has a per-unit price, called gas price. If the user provides less than the amount of gas to run a particular operation, then the process will fail, and the user will be given the message “out of gas.” And Gwei, as noted above, is the lowest denomination of ether used for measuring a unit of a gas price. e) Ethereum Mining Vs. Bitcoin Mining The hashing algorithm is the primary difference between Ethereum mining and Bitcoin mining. Bitcoin uses SHA-256, and Ethereum uses Ethash. The average time taken on Bitcoin for mining a block is 10 minutes, whereas on Ethereum it is 12 to 15 seconds. As of today, the mining reward for Bitcoin is 12.5 bitcoins; for Ethereum it’s three ethers plus the transaction fee—the cumulative transaction fees of all the transactions of a block. As of April 10, 2019, the value of 1 bitcoin is $5249.03, whereas one ether is $180.89. f) Ethereum Mining VS Bitcoin Mining Table 1 comparison of Bitcoin and Ethereum Bitcoin Ethereum Hashing Algorithm SHA-256 Ethash Time is taken to An average of 10 An average of 12-15 mine a block minutes seconds Reward 12.5 BTC 3 ETH USD - 04/10/2019 1 Bitcoin = 5249.03 1 Ether = 180.89 Below is a screenshot of an Ethereum reward that has been given to the miner of the block. As you can see, the reward is three ethers plus the total accumulated transaction fees of all the underlying transactions in this block, which are 0.0666 ethers. 71 Fig 2.7 Reward calculation in ethereum Decentralized Applications (Dapps) Let’s compare decentralized applications with traditional applications. When you log in to Twitter, for example, a web application gets displayed that is rendered using HTML. The page will call an API to access your data (your information), which is centrally hosted. It’s a simple process: your front end executes the backend API, and the API goes and fetches your data from a centralized database. Fig 2.8 Dapps If we transform this application into a decentralized application when you log in, the same web application gets rendered, but it calls a smart contract-based API to fetch the information from the blockchain network. So the API is replaced by a smart contract 72 interface, and the smart contract will bring the data from the blockchain network, which is its backend. That blockchain network is not a centralized database; it’s a decentralized network in which the participants of the network (the miners) validate (verify) all the transactions that are happening using the smart contract on the blockchain network. So any transaction or action happening on a Twitter-type application that has now been transformed will be a decentralized transaction. A Dapp consists of a backing code that runs on a distributed peer-to-peer network. It is a software designed to work in the Ethereum network without being controlled by a centralized system, as mentioned, and that is the primary difference: it provides direct interaction between the end-users and the decentralized application providers. An application qualifies as a Dapp when it is open-source (its code is on Github), and it uses a public blockchain-based token to run its applications. A token acts as fuel for the decentralized application to run. Dapp allows the backend code and data to be decentralized, and that is the primary architecture of any Dapp. Decentralized Autonomous Organizations (DAOs) A DAO is a digital organization that operates without hierarchical management; it works in a decentralized and democratic fashion. So basically a DAO is an organization in which the decision-making is not in the hands of a centralized authority but preferably in the hands of certain designated authorities or a group or designated people as a part of an authority. It exists on a blockchain network, where it is governed by the protocols embedded in a smart contract, and thereby, DAOs rely on smart contracts for decision-making—or, we can say, decentralized voting systems—within the organization. So before any organizational decision can be made, it has to go through the voting system, which runs on a decentralized application. Here’s how it works. People add funds through the DAO because the DAO requires funding in order to execute and make decisions. Based on that, each member is given a token that represents that person’s percentage of shares in the DAO. Those tokens are used to vote in the DAO, and the proposal status is decided based on the maximum votes. Every decision within the organization has to go through this voting process. 73 Real-World Applications of Ethereum Voting Systems As we’ve seen with DAO, voting systems are adopting Ethereum. The results of polls are publicly available, ensuring a transparent and fair democratic process by eliminating voting malpractices. Banking Systems Ethereum is getting adopted widely in banking systems because with Ethereum’s decentralized system; it is challenging for hackers to gain unauthorized access. It also allows payments on an Ethereum-based network, so banks are also using Ethereum as a channel to make remittances and payments. Shipping Deploying Ethereum in shipping helps with the tracking of cargo and prevents goods from being misplaced or counterfeited. Ethereum provides the provenance and tracking framework for any asset required in a typical supply chain. Agreements With Ethereum smart contracts, agreements can be maintained and executed without any alteration. So in an industry that has fragmented participants, is subject to disputes, and requires digital contracts to be present, Ethereum can be used as a technology for developing smart contracts and for digitally recording the agreements and the transactions based on them. 2.3 POS/POW HYBRID Understanding POW In the blockchain network, there are various ways to validate transactions in a decentralized manner, one is Proof of Work (PoW), and the other is Proof of Stake(PoS). Now, as we have understood the concept of consensus mechanism, let’s start discussing with Proof-of-Work (PoW) consensus. The central principle behind this consensus is to solve