Securing Blockchain Networks like Ethereum and Hyperledger Fabric - Alessandro Parisi - E-Book

Securing Blockchain Networks like Ethereum and Hyperledger Fabric E-Book

Alessandro Parisi

0,0
36,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Build secure private blockchain networks to handle mission-critical security challenges such as denial-of-service attacks, user wallets, and pool mining attacks




Key Features



  • Explore blockchain concepts such as cryptography, consensus algorithms, and security assumptions


  • Architect network security for mission-critical decentralized apps (Dapps) using design security considerations


  • Consider various deployment and operational aspects while building a blockchain network



Book Description



Blockchain adoption has extended from niche research to everyday usage. However, despite the blockchain revolution, one of the key challenges faced in blockchain development is maintaining security, and this book will demonstrate the techniques for doing this.







You'll start with blockchain basics and explore various blockchain attacks on user wallets, and denial of service and pool mining attacks. Next, you'll learn cryptography concepts, consensus algorithms in blockchain security, and design principles while understanding and deploying security implementation guidelines. You'll not only cover architectural considerations, but also work on system and network security and operational configurations for your Ethereum and Hyperledger Fabric network. You'll later implement security at each level of blockchain app development, understanding how to secure various phases of a blockchain app using an example-based approach. You'll gradually learn to securely implement and develop decentralized apps, and follow deployment best practices. Finally, you'll explore the architectural components of Hyperledger Fabric, and how they can be configured to build secure private blockchain networks.







By the end of this book, you'll have learned blockchain security concepts and techniques that you can implement in real blockchain production environments.




What you will learn



  • Understand blockchain consensus algorithms and security assumptions


  • Design secure distributed applications and smart contracts


  • Understand how blockchains manage transactions and help to protect wallets and private keys


  • Prevent potential security threats that can affect distributed ledger technologies (DLTs) and blockchains


  • Use pentesting tools for assessing potential flaws in Dapps and smart contracts


  • Assess privacy compliance issues and manage sensitive data with blockchain



Who this book is for



This book is for blockchain developers, security professionals, and Ethereum and Hyperledger developers who are looking to implement security in blockchain platforms and ensure secure data management using an example-driven approach. Basic knowledge of blockchain concepts will be beneficial.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 308

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Securing Blockchain Networks like Ethereum and Hyperledger Fabric

 

 

 

 

Learn advanced security configurations and design principles to safeguard Blockchain networks

 

 

 

 

 

 

 

Alessandro Parisi

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Securing Blockchain Networks like Ethereum and Hyperledger Fabric

Copyright © 2020 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

Commissioning Editor: Sunith ShettyAcquisition Editor:Srikanth VaranasiContent Development Editor:Nathanya DiasSenior Editor: Ayaan HodaTechnical Editor: Utkarsha S. KadamCopy Editor: Safis EditingProject Coordinator:Aishwarya MohanProofreader: Safis EditingIndexer:Manju ArasanProduction Designer:Joshua Misquitta

First published: April 2020

Production reference: 1100420

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-83864-648-6

www.packt.com

 

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Fully searchable for easy access to vital information

Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

About the author

Alessandro Parisi has been an IT professional for over 20 years, acquiring significant experience as a security data scientist and as an artificial intelligence cybersecurity and blockchain specialist. He has experience of operating within organizational and decisional contexts characterized by high complexity. Over the years, he has helped companies to adopt artificial intelligence and blockchain DLT technologies as strategic tools in protecting sensitive corporate assets. He holds a master's degree in economics and statistics.

To my wife Ilaria, for all her love and patience!

About the reviewers

Samanyu Chopra is a developer, entrepreneur, and blockchain supporter with broad experience in conceptualizing, developing, and producing computer and mobile software. He has been programming since the age of 11. He is proficient in programming languages such as JavaScript, Scala, C#, C++,and Swift. He has a wide range of experience in developing for desktop and mobile. He has been a supporter of Bitcoin and blockchain since their early days and has been part of wide-ranging decentralized projects for a long time. You can connect with him via LinkedIn.

 

Narendranath Reddy is an experienced full-stack blockchain engineer and Hyperledger Fabric expert with a proven track record of helping enterprises to build production-ready, blockchain-backed applications. He is an experienced innovator and creative thinker. He has won four hackathons on blockchain and is a keynote speaker, regularly speaking about blockchain and distributed ledgers. He is currently working as a blockchain software engineer at ConsenSys, in Dubai, and previously worked as a blockchain developer at Blockgemini in Dubai and as a software developer at UST Global, Trivandrum, and in Spain, Madrid.

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Securing Blockchain Networks like Ethereum and Hyperledger Fabric

About Packt

Why subscribe?

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Code in Action

Download the color images

Conventions used

Get in touch

Reviews

Section 1: Blockchain Security Core Concepts

Introducing Blockchain Security and Attack Vectors

An introduction to blockchain

Blockchain as the Internet of Value

Understanding the emergence of Bitcoin

Blockchain use cases beyond Bitcoin

The role played by the distributed ledger

The building blocks of blockchain

Unique addresses and transactions

Nodes and consensus

How Blockchain works

Guaranteeing traceability and block synchronization

The Blockchain process

Blockchain network topology

Network discovery and block synchronization

Different types of blockchain

Public blockchains

Private blockchains

Permissioned blockchains

Distributed ledger technology

Blockchain use cases

Establishing trust through consensus algorithms

Blockchain consensus layer

Reaching consensus in the blockchain

Understanding the consensus mechanisms

Byzantine Generals Problem

Proof of Work 

Proof of Stake

Proof of Authority

Potential threats that affect trust

Threats to the distributed architecture

51% attack

Eclipse attacks

Threats to the application layer

Cryptojacking

Attacking smart contracts

Threats to the security model

Summary

Cryptography Essentials

Technical requirements

A glimpse into cryptography

The role played by cryptography

Cryptography and the blockchain

Simple encryption example

Symmetric versus asymmetric cryptography

Stream and block ciphers

Symmetric cryptography limitations

Asymmetric cryptography

Asymmetric key management with PKI

Understanding RSA from scratch

Modular arithmetic

The extended Euclidean algorithm

RSA algorithm implementation

Generating RSA keys

Encrypting and decrypting with RSA keys

Elliptic cryptography in blockchain

The discrete logarithm problem

RSA versus ECC keys

Elliptic curves math properties

Abelian groups

Abelian groups for elliptic curves

Generating public keys with ECC

SHA hashing and digital signatures in practice

Cryptographic hash function characteristics

Hash functions in blockchain

Hashing algorithms

SHA algorithms

Hashing examples

Digital signatures and DSA

Blockchain Merkle trees

A Merkle tree audit proof

Merkle tree consistency proof

Implementing a Merkle tree

Summary

Blockchain Security Assumptions

Centralized models versus decentralized models

The centralized application model

The decentralized application model

Advantages and disadvantages of blockchain

Advantages of blockchain

Disadvantages of blockchain

Blockchain versus DLT

Understanding transaction security

Securing private keys

Blockchain transaction weaknesses

Attacking a blockchain

The Sybil attack

The majority attack

Estimating the chances of a 51% attack

Double-spending attacks

Eclipse attacks

Eclipse attack on Bitcoin's blockchain

Mining pool security threats

Selfish mining attacks

Forking attacks

Understanding the quantum computing threat

Quantum computing in a nutshell

Cryptography at stake

Quantum versus traditional computability

Dealing with computability and decidability

Computational complexity

Quantum computability and complexity

Quantum computing attack resistance

Summary

Further Reading

Section 2: Architecting Blockchain Security

Trustless Blockchain Networks

Technical requirements

Network discovery with P2P

Implementing a P2P network over the public internet

Implementing P2P network discovery

Network discovery in Bitcoin's blockchain

DNS seeds

Bitcoin hardcoded IP list

Peer discovery in Bitcoin

Bitcoin addresses

Bitcoin addresses and cryptographic keys

Analyzing blockchain network attacks

DNS attacks

Denial of Service attacks

Possible countermeasures to network attacks

Block synchronization

Synching blocks at node startup

Block data structure

Achieving consensus in a trustless network

Exploring blockchain

Exploring Bitcoin addresses

Exploring a blockchain's blocks

Block vulnerabilities and attacks

Transaction management

Transactions in a nutshell

Transaction verification

Transaction scripts

P2PKH scripts

P2SH scripts

Adding transactions to blocks

Exploring transactions

Wallet key secure management

Introducing wallets

Types of wallets

Deterministic wallets

Non-deterministic wallets

Paper wallets

Brain wallet

Wallet vulnerabilities

Securing Bitcoin wallets

Securing online wallets

Securing paper wallets

Summary

Securing Hyperledger Fabric

Permissioned blockchains and DLTs

Public versus private blockchains

Permissioned blockchains access rights

DLTs as permissioned blockchains

Consensus in permissioned blockchains

Assessing availability and consistency with the CAP theorem

Getting to know Hyperledger Fabric

Hyperledger Fabric architecture

Hyperledger Fabric application model

Hyperledger Fabric versus other blockchains

Hyperledger transaction flow

Execution phase

Ordering phase

Validation phase

Hyperledger strong identities

Designing a Hyperledger Fabric network

Hyperledger Fabric network governance

MSP

Fabric CA configuration

Registration operation

Enrollment operation

Revoking digital identities

Hyperledger chaincode security

Installing and deploying chaincodes

Chaincode security

Chaincode trusted execution

Trusted execution with Intel SGX

Preventing common threats with Hyperledger

The Hyperledger Fabric ecosystem

Running Hyperledger on Docker

Hyperledger transaction privacy

Channels

Private data

Summary

Section 3: Securing Decentralized Apps and Smart Contracts

Decentralized Apps and Smart Contracts

Technical requirements

Introducing DApps

Types of DApps

Smart contracts

Decentralized organizations

Decentralized autonomous organizations

Characteristics of DApps

Introducing Ethereum

Creating Ethereum accounts

Ethereum transactions

Ethereum consensus mechanism

The Ethereum Virtual Machine

Ethereum gas

Ethereum communication and storage protocols

Ethereum security threats

Stale blocks

Blockchain forks

Catastrophic bugs – the DAO bug

Introducing smart contract fundamentals

Smart contract requirements

Automating execution and enforcement

Secure and unstoppable

Bridging the gap between computers and people

Feeding data to smart contracts through Oracles

Deploying smart contracts on a blockchain

Creating secure smart contracts

Developing smart contracts with Turing-complete languages

Bitcoin Script

Example of Bitcoin Script

Bug inevitability and the risks of Turing-complete programs

Developing smart contracts with Remix IDE

A simple smart contract

Executing secure smart contracts

Best practices for smart contract security

Dealing with bugs in smart contracts

Summary

Preventing Threats for DApps and Smart Contracts

Technical requirements

Hacking smart contracts

Introducing MAIAN

Analyzing smart contracts with MAIAN

Types of buggy smart contracts

Suicidal contracts

Prodigal contracts

Greedy contracts

Checking buggy contract types with MAIAN

Analyzing smart contract threats

Integer overflow and underflow

Remediation of integer overflow and underflow

Overflow example code

DoS using loops and overflow

A buggy smart contract

Fixing the buggy smart contract

Re-entrancy attack

Smart contract attack examples

Analyzing the DAO attack

The Parity attack

Preventing smart contract attacks

Analyzing smart contracts for security

Analyzing smart contracts with Mythril

Analyzing smart contracts with Securify

Summary

Section 4: Preserving Data Integrity and Privacy

Exploiting Blockchain as an Attack Vector

Storing illicit data in the blockchain

Storing illicit data on Bitcoin's blockchain

Storing illicit data on the blockchain through transactions

Erasing illicit data from the blockchain

Erasing data from Bitcoin's blockchain with Bitcoind Erase

Preserving anonymity in the blockchain

Bitcoin's anonymity myth

Public keys as identities

One-time public keys and stealth addresses

Transaction anonymity

Privacy coins

Dealing with identity theft

Stealing users identities

Managing and protecting identity with blockchain

How effective is blockchain at preventing identity theft?

Ensuring real and unique identities

Verifying the attribution of identities to legitimate owners

Spreading malware with blockchain

Malware versus antivirus software

Getting to know K-ary malware

Blockchain as the vector of choice for k-ary malware spreading

Summary

Analyzing Privacy and GDPR Compliance Issues

Preserving sensitive data in a blockchain

What data should be stored on a blockchain

Storing sensitive data off-chain

Leveraging blockchain for healthcare

Protecting healthcare data with blockchain

Managing healthcare data with smart contracts

Improving IoT security with blockchain

IoT security threats

Solving IoT security issues with blockchain

Reconciling blockchain with the GDPR

Blockchain versus GDPR

Personal data in the GDPR

Public keys as personal data

Assessing the data controller role in a blockchain

Complying with the right to be forgotten

Possible alternatives to data erasure on blockchains

Assessing blockchain compatibility with the GDPR

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Blockchain adoption has extended from niche research to everyday usage. However, despite the blockchain revolution, one of the key challenges faced in blockchain development is maintaining security, and this book will demonstrate the techniques for doing this.

You'll start with blockchain basics and explore various blockchain attacks on user wallets, and denial of service and pool mining attacks. Next, you'll learn cryptography concepts, consensus algorithms in blockchain security, and design principles while understanding and deploying security implementation guidelines. You'll not only cover architectural considerations, but also work on system and network security and operational configurations for your Ethereum and Hyperledger Fabric network. You'll later implement security at each level of blockchain app development, understanding how to secure various phases of a blockchain app using an example-based approach. You'll gradually learn to securely implement and develop decentralized apps, and follow deployment best practices. Finally, you'll explore the architectural components of Hyperledger Fabric, and how they can be configured to build secure private blockchain networks.

By the end of this book, you'll have learned blockchain security concepts and techniques that you can implement in real blockchain production environments.

Who this book is for

This book is for blockchain developers, security professionals, and Ethereum and Hyperledger developers who are looking to implement security in blockchain platforms and ensure secure data management using an example-driven approach. Basic knowledge of blockchain concepts will be beneficial.

What this book covers

Chapter 1, Introducing Blockchain Security and Attack Vectors, illustrates the core concepts and fundamental elements of blockchain technology, such as distributed ledgers, peer-to-peer network topology, and consensus protocols.

Chapter 2,Cryptography Essentials, introduces cryptography primitives and their use in blockchain, looking at the differences between cryptography algorithms and hashing algorithms and how cryptography primitives fit into blockchain architecture.

Chapter 3,Blockchain Security Assumptions, focuses on the assumptions made about blockchain security and potential threats related to centralized and decentralized models. We will analyze different types of blockchains and distributed ledger technologies, such as permissioned and permissionless architectures.

Chapter 4,Trustless Blockchain Networks, looks at trustless blockchain networks, analyzing how blockchains achieve decentralization by leveraging peer-to-peer networking. We will also see how blockchains manage transactions and show how to protect wallets and private keys.

Chapter 5,Securing Hyperledger Fabric, is where we analyze the security aspects relating to Hyperledger Fabric, showing how Hyperledger provides protection against the most common security threats.

Chapter 6,Decentralized Apps and Smart Contracts, explores decentralized applications and the core concepts of smart contracts, dealing with central aspects such as developing, creating, and executing decentralized apps and smart contracts in the Ethereum environment.

Chapter 7,Preventing Threats for DApps and Smart Contracts, goes into the security aspects of decentralized applications and smart contracts, showing security best practices to prevent potential threats and attacks. We will also learn how to leverage pentesting tools to assess decentralized applications and potential flaws in smart contracts.

Chapter 8,Exploiting Blockchain as an Attack Vector, looks into how a blockchain can become an attack vector for data integrity compromises, identity theft, and malware.

Chapter 9,Analyzing Privacy and GDPR Compliance Issues, analyzes potential privacy issues for blockchain technology, particularly in terms of EU privacy law (GDPR) compliance.

To get the most out of this book

No particular software or operating system is required to follow the book's content, apart from an up-to-date version of a web browser and an internet connection to download source code examples and the tools suggested in the book. A good understanding of the plaforms such as Hyperledger, Fabric, and Ethereum can be an added advantage. Previous knowledge of blockchain technology would be beneficial, but is not strictly necessary. To get the most out of the book, you are expected to be fluent in networking security core concepts and to have some exposure to a general-purpose programming language.

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

Support

tab.

Click on

Code Downloads

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/-Securing-Blockchain-Networks-like-Ethereum-and-Hyperledger-Fabric. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Code in Action

Code in Action videos for this book can be viewed at https://bit.ly/2xZyAoE.

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838646486_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "An example of a Bitcoin address follows: mwog86wxZsWf6KGufzwA69xbvzE9TGZ5vA."

A block of code is set as follows:

>>> import math>>> print math.gcd (5, 72)>>> 1

Any command-line input or output is written as follows:

bitcoin

-

cli

getnewaddress

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: Blockchain Security Core Concepts

In this section, you will be introduced to the fundamental primitives of cryptography, along with blockchain's core concepts. With this information under your belt, you will be able to understand the specific design features the blockchains and distributed ledger technology.

This section comprises the following chapters:

Chapter 1

,

Introducing Blockchain Security and Attack Vectors

Chapter 2

,

Cryptography Essentials

Chapter 3

Blockchain Security Assumptions

Introducing Blockchain Security and Attack Vectors

In this chapter, we will introduce the fundamental constitutive elements of blockchain technology, such as distributed ledger, peer-to-peer network topology, and consensus algorithms, all of which will be further explored in depth in the chapters that follow.

These notions are essential to fully understand the aspects of cyber security associated with blockchain technology, especially with regard to identifying possible attack vectors.

In particular, we will cover the following topics in this chapter:

An introduction to blockchain

The building blocks of blockchain 

Blockchain network topology

 

Establishing trust through consensus algorithms

Potential threats that affect trust

An introduction to blockchain

The blockchain is often compared to the internet in terms of innovation potential. Just as the network of networks has allowed information and ideas to circulate globally, allowing for the reduction of gaps in terms of space and time, in the same way, the blockchain proposes to become the Internet of Value.

Another aspect that unites the internet and blockchain is their ability to disintermediate the productive sectors (starting from the financial one) to reduce the areas of inefficiency and allow the emergence of innovative solutions, thereby overcoming the rigidity derived from the status quo preserved by incumbent operators.

Blockchain as the Internet of Value

Blockchain is commonly defined as the Internet of Value in comparison to the traditional internet. To understand the definition of the Internet of Value, let's briefly introduce the limitations of the traditional internet.

Since the first e-commerce experiments that were conducted on the traditional internet, a series of problems have emerged that have to do with the guarantee of authenticity. This involves various factors in the field, such as the following:

Identity of counterparties in transactions

Ownership of the rights of the transactions

Guaranteeing the financial solvency of counterparties

Intermediaries that traditionally guaranteed such factors (typically, banks) have proven to be ineffective in a dematerialized environment such as digital commerce on the internet. The need has, therefore, emerged not only to guarantee users immunity from identity theft, or the holders of copyright from infringement, but also to guarantee the reliability of the means of payment themselves.

By fulfilling this need, the blockchain has become the Internet of Value.

Understanding the emergence of Bitcoin

In coincidence with the financial crisis of 2007-2008, a digital currency, Bitcoin, was introduced for the first time. First and foremost, it was intended to ensure that its value was protected from inflation, without being conditioned by the monetary policies of central banks.

The protection that was provided regarding the value of the currency against erosion caused by inflation, together with its independence from the central monetary authorities, testifies to the aim of introducing a democratic means of payment, which can also act as an alternative (and in competition) currency to the traditional national currencies.

It is no coincidence that many citizens of politically unstable countries have decided to use Bitcoin as a reserve currency, precisely because of the guarantees that this digital instrument provides with respect to the fragility of national currencies.

Like any self-respecting coin, even Bitcoin is based on an essential element that is constituted by trust.

The concept of currency trust translates into practice as follows:

Conservation of currency value over time

Protection against possible counterfeiting attempts

A general acceptance of money as a means of payment

To this end, given the dematerialized nature of Bitcoin, it was necessary to set up a technological infrastructure that would guarantee these prerequisites and be responsible for preserving the trust in transactions between operators.

This technological infrastructure, which is the basis of Bitcoin, is the blockchain.

Blockchain use cases beyond Bitcoin

The blockchain is a technological infrastructure through which it is possible to certify value transactions (which are not limited to the exchange of currencies but can include any type of asset) between trusted counterparties, without the need for the intervention of a central authority (be it banks, government regulators, brokers, and so on).

To perform these tasks, the blockchain is organized into a sequence of blocks (hence the name, block and chain) that contain the references of the transactions that took place over time. For each transaction that's entered into the blocks, a reference is associated with the previous and subsequent transactions. Finally, the blocks are stored in a shared register (blockchain ledger).

The main feature of the blockchain ledger is that it is append-only; that is, each registration is appended to the pre-existing ones, and the integrity of the ledger is guaranteed by the use of the cryptographic primitives offered by the Public Key Infrastructure (PKI), which we will cover in more depth in Chapter 2, Cryptography Essentials.

The other element that characterizes the blockchain is its network topology, which follows the peer-to-peer protocol. This is used to realize the decentralization of the infrastructure, thereby eliminating the need for a central authority that guarantees the reliability and integrity of transactions.

In practice, a copy of the ledger is saved at each node of the peer-to-peer network; in this way, users taking part in the blockchain can always obtain a copy of the ledger by contacting any of the peer-to-peer network nodes without needing to contact a predefined central node.

Whenever a new transaction is added to the blockchain, all copies of the ledger that are saved within the nodes of the peer to peer network are updated accordingly.

To summarize, the blockchain is characterized by the following elements:

The presence of a shared ledger within a peer-to-peer network.

Value transactions are recorded in append-only mode within the ledger.

The reliability and integrity of the transactions recorded within the ledger is guaranteed by the use of cryptography.

Each new transaction that's entered into the blockchain determines the corresponding update for the ledger and the copies of it present in each node of the peer-to-peer network. In this way, it is possible to do without a central authority that guarantees the reliability and integrity of the transactions that are carried out within the network.

The role played by the distributed ledger

One of the revolutionary ideas of the Bitcoin blockchain was to introduce the distributed ledger mechanism. Satoshi (the pseudonym that the creator of Bitcoin is hidden behind) had, in fact, realized that the main reason for the intervention of intermediaries (in particular, banks) in transactions between private individuals was linked to the management of such transactions. These were recorded in a centralized ledger book. Satoshi's intuition was to replace the centralized ledger, which was managed by the corresponding central authorities, with a shared public ledger that's updated by the same subjects participating in value transactions.

However, with this, a series of problems remained to be solved:

How to ensure that this shared ledger is tamper-proof and that it is robust with respect to arbitrary changes

How to guarantee an adequate degree of confidentiality to the subjects who carry out value transactions

How to properly manage the size of the ledger, since each transaction must be registered in it

To solve these problems, the blockchain was created. Now, let's take a look at the building blocks of blockchain.

The building blocks of blockchain

Now, we're going to analyze the constituent elements of the blockchain and start with the blocks. As we mentioned earlier, transactions are stored within the blockchain blocks, so each block is composed of two parts:

A block

header

, in which the link to the previous block is stored in the form of a 

hashing

checksum digest. This is done to prevent the possibility of altering the transactions stored in the previous block.

A block

body

, containing the list of

transactions

, complete with relevant information (including the amount transferred, the addresses of peers, and so on).

The following diagram shows the structure of Bitcoin blocks and their mutual relationships within the blockchain:

You can check out the image in the following link,https://commons.m.wikimedia.org/wiki/File:Bitcoin_Block_Data.png. As a consequence of how the blocks of the blockchain are structured, and by virtue of the reciprocal relationships that connect them, it is clear that both the transactions and the data that refer to them are immutable. This, however, does not mean that updates cannot be made to previous transactions; any changes will result in new transactions, which will, in turn, be validated and recorded within the blockchain in appending mode, thereby allowing the evolution of individual transactions to be reconstructed over time.

Unique addresses and transactions

We have already mentioned that, among the relevant information that's recorded within the blocks, there are the addresses of the counterparties of the transactions. These addresses are the unique identifiers that are needed to identify and distinguish between the counterparties involved in the transactions.

A transaction is, in fact, nothing but the transfer of an asset (monetary amount, right of use, or any other value) that is made between two addresses. To define these unique identifiers, cryptography is used – in particular, PKI – so the addresses are nothing but the public keys associated with the individual counterparts.

We often wonder if this addressing mechanism guarantees the anonymity of the counterparties of a transaction; in particular, we wonder whether the use of Bitcoins guarantees the anonymity of the users who use them.

To answer this question, it is necessary to distinguish between the functions that are performed by the addresses. This is done to uniquely identify the single counterpart of the transaction in terms of identifying the real physical subject that this unique identifier is associated with.

There is no doubt that the individual public keys are unique, but this does not exclude the possibility that the same user can generate a different public key for each individual transaction. Similarly, the end users are not directly identifiable from the public keys associated with them. To verify their real identity in a reliable way, they must be identified (verifying, for example, identity documents, and other biometric evidence), before allowing them to take part in transactions.

Nodes and consensus

Another important concept is that of a node.

Each node within the blockchain contributes to establishing or validating a transaction while making use of a predefined consensus protocol that's been specifically selected to guarantee the security and integrity of the blockchain (we will deal with the consensus mechanism in the final part of this chapter).

Now that we've introduced its building blocks, let's see how the blockchain actually works.

How Blockchain works

To realize the objectives that it was designed for, the blockchain must implement a series of mechanisms that involve not only computer science and cryptography, but also some concepts that come from other branches of scientific research (such as the use of theorems regarding game theory).

We have already mentioned that the main objective of the blockchain is to create a decentralized network, in which the individual nodes can carry out the functions that are traditionally in charge of a central authority. To achieve this result, we must ensure that the system is reliable in itself, without depending on the reliability of the single operators taking part in the network.

To this end, cryptography and game theory come together, united by the peer-to-peer network topology.

Guaranteeing traceability and block synchronization

Through the use of cryptography, it is possible to guarantee the traceability (non-repudiation) of a transaction to a specific counterparty. In the same way, it is possible to guarantee the integrity of the transaction by applying hashing algorithms.

The use of game theory performs another task. It ensures that all the nodes always have the updated synchronized copy of the ledger containing all the transactions.

One of the main problems that the Bitcoin blockchain has faced has been, for example, to prevent the possibility of double-spending; that is to say, that the same Bitcoin is not used simultaneously in two different transactions by the same counterparty.

To avoid this phenomenon, it is necessary that all the operators (nodes) are on the same page. This means that they all need to have the updated copy of the transaction database that all the operators must agree on. Therefore, the consensus on the history of transactions is achieved after the nodes agree on the status of the transaction database.

This requirement can be achieved by referring to a well-known theorem of game theory known as the Nash equilibrium (we will deal with consensus protocols later in this chapter).

Once the reliability and integrity of the transactions has been guaranteed, it is possible to share information within a decentralized and open network, thereby exploiting the typical characteristics of peer-to-peer networks.

The Blockchain process

Let's have a look at the process that characterizes the blockchain (in the description that follows, we will mostly refer to the Bitcoin blockchain).

The following diagram depicts the overall blockchain process:

You can check out the image in the following link, https://commons.m.wikimedia.org/wiki/File:Blockchain-Process.png.

Let's take a look at the steps involved in this process:

The first step of the process consists of a node starting a transaction. This transaction is digitally signed with the private key associated with the same node that created the transaction.

At this point, the transaction is submitted for validation to other peers of the network (in Bitcoin, the peer nodes, called

miners

,

are remunerated by assigning Bitcoins for this notarization task they perform).

Once validated, the transaction can be inserted into a block, which can be appended to the blockchain (the decision as to which block of which node must be inserted into the blockchain is determined by the consensus protocol).

Only after entering the block in the blockchain can the transaction be considered confirmed and become part of the shared ledger. The same block will receive a confirmation message from the subsequent block that will refer to it leveraging the

previous link

present in the block header. Transactions that haven't been confirmed yet are stored locally in a transaction pool, which, in the case of Bitcoins, is called

mempool

.

In this way, all the transactions that were undertaken beforehand are continuously reconfirmed by the new transactions that are inserted as successive blocks within the blockchain, thus realizing the immutability of the entire transaction chain.

Blockchain network topology

Now, let's look at the networking features of the blockchain.

The following diagram is a typical example of the centralized network topology, in which there is a central node that acts as a hub for sharing information with the other nodes:

You can check out the image in the following link, https://commons.m.wikimedia.org/wiki/File:NetworkCentral.svg. The advantages of the centralized network can be summarized by the fact that there is only one central authority (server) that acts as an arbitrator. This manages the requests coming from the remaining nodes of the network (clients).