Ethereum Smart Contract Development - Mayukh Mukhopadhyay - E-Book

Ethereum Smart Contract Development E-Book

Mayukh Mukhopadhyay

0,0
27,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

Ethereum is a public, blockchain-based distributed computing platform featuring smart contract functionality. This book is your one-stop guide to blockchain and Ethereum smart contract development.

We start by introducing you to the basics of blockchain. You'll learn about hash functions, Merkle trees, forking, mining, and much more. Then you'll learn about Ethereum and smart contracts, and we'll cover Ethereum virtual machine (EVM) in detail. Next, you'll get acquainted with DApps and DAOs and see how they work. We'll also delve into the mechanisms of advanced smart contracts, taking a practical approach.

You'll also learn how to develop your own cryptocurrency from scratch in order to understand the business behind ICO. Further on, you'll get to know the key concepts of the Solidity programming language, enabling you to build decentralized blockchain-based applications. We'll also look at enterprise use cases, where you'll build a decentralized microblogging site.

At the end of this book, we discuss blockchain-as-a-service, the dark web marketplace, and various advanced topics so you can get well versed with the blockchain principles and ecosystem.

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

EPUB
MOBI

Seitenzahl: 277

Veröffentlichungsjahr: 2018

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.



Ethereum Smart Contract Development

 

 

 

 

 

Build blockchain-based decentralized applications using solidity

 

 

 

 

 

 

 

 

 

Mayukh Mukhopadhyay

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Ethereum Smart Contract Development

Copyright © 2018 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:Chandan KumarContent Development Editor:Amrita NoronhaTechnical Editor:Sayali ThanekarCopy Editor: Safis Editing, Vikrant PhadkeProject Coordinator:Shweta H BirwatkarProofreader: Safis EditingIndexer:Pratik ShirodkarGraphics:Jisha ChirayilProduction Coordinator:Aparna Bhagat

First published: February 2018

Production reference: 1210218

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

ISBN 978-1-78847-304-0

www.packtpub.com

 

Dedicated to my wife, Mrittika, for loaning me her ACER laptop to complete this book.
And my daughter, Abriti, for keeping her mom super busy while I was crashing it by mining ethers.
mapt.io

Mapt is an online digital library that gives you full access to over 5,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

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

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.PacktPub.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.PacktPub.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.

Contributors

About the author

Mayukh Mukhopadhyay started his career as a BI developer. After the 2008-09 financial crisis, he was at Tata Consultancy Services for one of their Fortune 500 clients in the telecom sector. Holding a master's in software engineering from Jadavpur University, he is presently working as a data insight developer, where he focuses on applying data science and machine learning to raw telecom equipment logs to generate business insights. He has a varied list of academic interests, ranging from audio signal processing, structural bioinformatics, and bio-inspired algorithms to consciousness engineering. Apart from being an Oracle Certified Specialist, he is a Certified Bitcoin Professional, recognized by C4 (Crypto Currency Certification Consortium). He tries to apply blockchain as a technology to different business domains.

To my guide @JUDr Parama Bhaumik —your lectures on distributed systems were my main inspiration while writing this book.

To my professional network connections Ivan Liljeqvist, Dug Campbell, Mahesh Murthy, Kaushik Sathupadi, Ravinder Deol, Narayan Prusty, and Thomas Wiesner—thanks for your blogs and vlogs. This book is as much your creation as it is mine.

 

 

About the reviewer

Daniel Kraft studied applied mathematics and theoretical physics in Graz, Austria, where he obtained his PhD from the University of Graz in 2015. After that, he started as a software engineer in Zurich, Switzerland. He has been very interested in Bitcoin and cryptocurrencies since 2011 and involved in Bitcoin development since 2013. Since 2014, he has been the main developer for Namecoin and Huntercoin, and has successfully reimplemented both on top of the modern Bitcoin Core code base. Wherever possible, Daniel also contributed improvements to the upstream Bitcoin Core. He has published multiple research articles in peer-reviewed journals, two of them directly related to cryptocurrency.

 

 

 

 

 

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

Ethereum Smart Contract Development

Dedication

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewer

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

Download the color images

Conventions used

Get in touch

Reviews

Blockchain Basics

Understanding distributed systems

The Byzantine Generals' Problem

Losing strategy

Winning strategy

The CAP theorem

Consensus in distributed systems

Understanding the hash function and the Merkle tree

Understanding a blockchain–a developer and trader's perspective

Inside a block

Blockchain mining and forking

Blockchains – evolution, generations, and hype

Summary

Grokking Ethereum

Understanding Ethereum

The notion of decentralization

The Ethereum ecosystem

Mist

Decentralized applications

Middleware

Swarm

Whisper

EVM

Hardware clients and internet

Turing completeness and the magic sauce

Ethereum block, mining, and forking

The Ethereum wallet and client interface

Summary

Hello World of Smart Contracts

A smart contract in seven lines of code

Remix in a nutshell

Increment and decrement operations using Solidity

Coding a loop

Raising an issue on GitHub

Smart contract on a private blockchain

Writing the genesis block

Building a private blockchain

Connecting MIST browser using geth

Mining ethers in a private blockchain

Deploying smart contracts on our private chain

Summary

A Noob's Guide to DApps and DAO

Understanding DApps

Steps to develop a DApp

Architecture of a DApp

What is ethercast?

btcrelay.org

oraclize.it

the-pitts-circus.com

Understanding the design of DAO

The rise and fall of DAO

Summary

Deep-Diving into Smart Contracts

What makes a contract "smart"?

Definition and design

Role of code in a smart contract

Basic anatomy of a smart contract design

Smart contract optimization

Smart contract auditing and compliance

Designing a voting DApp

Summary

Solidity in Depth

Need for solidity

Nuances, syntax, and features of solidity

Pragma, import, and comments

Class properties of a contract

Functions

Events

Inheritance

Libraries

Expression and control structures

Units and variables

Optimizer and debugging options

Parity hack demystified

Summary

Primer on Web3.js

Web3.js in the Ethereum ecosystem

Running a smart contract using Web3.js

API structure of Web3.js

Designing an ownership contract

Summary

Developing a Cryptocurrency from Scratch

Token versus coin

ERC20 token development using Truffle

Arbitrage trading for cryptocurrencies

The ICO story

Fiat2Crypto and Crypto2Crypto exchange

Parity hack returns

Summary

Enterprise Use Cases

Banking and payments

Insurance

Supply chain management

Forecasting and prediction market

Charity

Public benefits

Energy management

Art and music

Retail

Real estate

Cyber security

Crowdfunding

Networking and the Internet of Things

Voting

Government

Private transport and ride sharing

Cloud storage

Healthcare

Smart contract use cases

Insurance

Trade finance

Derivatives

Securities

Accounts

Digital identity

Record-keeping

Loans and mortgages

Legal

Supply chain

Clinical trials

Terminal disease research

Decentralized microblogging

Administrative and security constraints

TwtAccount.sol

TwtRegistry.sol

Service setup on the private blockchain

Reading tweets

Summary

BaaS and the Dark Web Market

Playful privacy

Types of blockchain

Private blockchains

Public blockchains

Consortium blockchains

Blockchain-as-a-service

Enterprise platforms for BaaS

IBM Hyperledger

Microsoft Azure EBaaS

Amazon Eris

Dark web marketplace

Project smartCV

Summary

Advanced Topics and the Road Ahead

Common design patterns

Restricting access

Token systems

Factory pattern

Registries

Voting systems

DACs and DAS

Ethereum improvement proposal

Rational behind EIPs

Types of EIP

EIP life cycle

EIP template

Consortium blockchains

Case study on R3 Corda

Tangle beyond blockchain

Shortcomings of a blockchain

Tangle demystified

Iota GitHub analysis

Purchase and storage of Iota

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

If you are reading this line, I want to congratulate you because you have already overcome the most difficult hurdle in the pursuit of the understanding blockchain, and specifically, Ethereum smart contracts. This hurdle is the overwhelming hype surrounding this promising yet premature technology and trying to know what is really going on under the hood.

I am a software developer, and through my book, which you are viewing in your electronic device or physically holding in your hand, we will together embark on a fascinating journey through this enigmatic and revolutionary technology.

The chapters in this book have been arranged in an incremental fashion. We start with a gentle introduction to blockchain using the familiar bitcoin, and quickly dive into the world of Ethereum and the major players in its ecosystem.

Then we proceed to do some hands-on coding of a typical "Hello World" smart contract. We then take on the subject of decentralized autonomous organizations, decentralized applications, and smart contract optimization. We also analyze two famous multi-million-dollar hacks that recently occurred in the Ethereum community, along with the preventive measures employed to avoid them in future.

We then move on to the intricacies of the solidity programming language and web3.js library.

The final chapters mainly deal with the development of standardized tokens, the concept of initial coin offering, potential enterprise use cases of smart contracts, designing a decentralized micro-blogging platform, and surfing the dark web marketplace.

We conclude the book by providing primers on advanced topics with promising future prospects such as graph-based DLTs and quantum secured blockchains.

At the onset, I want to have a clear understanding between us. Even though I am the author of this book and it is my sole responsibility to present the facts as accurately as possible in this book, in no possible way do I consider myself as the sole authority on this subject.

As my reader, I want you to realize that I am just another overenthusiastic fellow learner who will try to assist you with your pursuit of knowledge by introducing the optimal amount of information required to kick-start your journey. And I will make you aware of the hurdles and pitfalls I faced along the way so that you can learn from my mistakes.

Enough said. Let's start our journey to blockchain and get our hands dirty with Ethereum Smart Contract Development.

Happy reading!

Who this book is for

This book is dedicated to novice programmers, solution architects, and blockchain enthusiasts who want to build powerful, robust, and optimized smart contracts using solidity from scratch and in combination with other open source JavaScript libraries. If you want to build your own extensive, decentralized applications that can smartly execute on a blockchain, then this book is what you need! An open and inquisitive mind is a necessary and sufficient prerequisite. Some preliminary knowledge of data structures, object-oriented programming, networking concepts, and cryptography is a plus and will help  the reader to understand the concepts presented in this book.

What this book covers

Chapter 1, Blockchain Basics, will serve as a warm-up session about blockchain before we deep dive into Ethereum and smart contract development. To really appreciate blockchain, we must understand the two founding pillars on which blockchain as a technology is firmly grounded: distributed systems and cryptography. Once we have covered these two core concepts, we try to understand a blockchain from two different perspectives: as a software developer and as a trader of financial instruments. Then we probe into the internal logical architecture of a block in the blockchain, focusing the bitcoin block structure, and get a gentle introduction to the mining and forking process. We conclude the chapter by discussing how blockchain has evolved in recent years and clearly marking out its current position in the technological hype cycle.

Chapter 2, Grokking Ethereum, will help us to understand the meaning of decentralization and whether Ethereum is truly decentralized. We will also cover its core technological stack and get familiarized with various jargon, such as Mist, EVM, Swarm, Whisper, Ether, and Gas. We will briefly discuss the notion of a Turing-complete language. We'll then revisit forking, mining, and block architecture from the perspective of Ethereum. We'll end this chapter by getting a notion of Ethereum wallets and client interfaces, which will serve as a firm base for smart contract development.

Chapter 3, The Hello World of Ethereum Smart Contract, provides a hands-on guide to developing our first smart contract. As an unspoken tradition of a software developer, we start with a "Hello World" program. Then we try some basic arithmetic increment and decrement operations using a contract. We then learn how to code a loop inside a smart contract and how to raise an issue in GitHub. We end this chapter by creating our own private blockchain right from the genesis block, attach it with Geth, and use the Mist browser to deploy one of the smart contracts we studied in this chapter, after mining some ethers.

Chapter 4, A Noob's Guide to DApps and DAOs, develops our understanding towards decentralized applications from a developer's perspective. We introduce the high-level steps to develop a decentralized application. Then we explore a unique marketplace called ethercast, which serves as an aggregator of several DApps. We then move on to design a decentralized autonomous organization. We conclude this chapter with a retrospection of the infamous DAO hack, which led to the ETH/ETC split, from a purely technical perspective.

Chapter 5, Deep-Diving into Smart Contracts, digs deeper into smart contract designs. We start by understanding the textbook definition of a smart contract. Then we move on to understand different smart contract models and the role of code in a smart contract. We go through the basic anatomy of a smart contract and see how a smart contract works. Then we shift our focus to advanced topics such as smart contract optimization, auditing, and ERC20 compliance. We conclude the chapter with a hands-on drill of building a voting DApp.

Chapter 6, Solidity in Depth, is all about the Turing complete solidity language on the Ethereum blockchain. We will start by probing into the design decision of why we really need a new language like solidity. The next sections will cover the nuances of the solidity language and the basic syntax used in it. Specifically, we'll cover contract-oriented features, functions and events, inheritance, libraries, expressions, control structures, units, and variables. Then we'll look at the optimizer and debugging options. We will conclude this chapter by analyzing the code flaw that led to the recent parity wallet hack in the Ethereum blockchain, which stole around $30 million worth of ethers.

Chapter 7, Primer on Web3.js, introduces a special application programming interface library written in JavaScript. This interface connects our web browser with the Ethereum blockchain node. We will begin this chapter by understanding the difference between Geth, Web3.js, and Mist. Then we will learn how to import this API library and get connected with Geth. We will then explore the API structure inside the web3.js library. We'll conclude the chapter by studying the design of an ownership contract.

Chapter 8, Developing Cryptocurrency from Scratch, provides a hands-on tutorial to develop an ERC20 standardized token using the Truffle framework. We then dive in to the concepts of initial coin offering (ICO) and how to identify genuine ICOs among fake and Ponzi schemes. The chapter concludes by discussing various token conversion process and pair-trading concepts.

Chapter 9, Enterprise Use Cases, provides some exciting and promising use cases of Ethereum smart contracts. We also discuss the design of a decentralized micro-blogging platform using solidity.

Chapter 10, BaaS and the Dark Web Market, introduce us to the blockchain framework of Microsoft and IBM. We conclude this chapter by discussing the difference between the Conventional Web and the Dark Web (.onion website and TOR) and how to safely browse the Dark Web to find use cases of cryptocurrencies.

Chapter 11, Advanced Topics and the Road Ahead, deals with exciting topics such as graph-based DLTS with a focus on Tangle, quantum secured blockchain, Ethereum improvement protocols, consortium blockchains, distributed autonomous societies, and common design patterns for solidity.

To get the most out of this book

Inform the reader of the things that they need to know before they start, and spell out what knowledge you are assuming

Some preliminary knowledge of data structures, object-oriented programming, networking concepts, and cryptography is a plus but not mandatory

Download the example code files

You can download the example code files for this book from your account at www.packtpub.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.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

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 athttps://github.com/PacktPublishing/Ethereum-Smart-Contract-Development. 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 athttps://github.com/PacktPublishing/. Check them out!

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: http://www.packtpub.com/sites/default/files/downloads/EthereumSmartContractDevelopment_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: "Open your Google Chrome browser and type remix solidity in Google, as shown in Figure 3.1."

A block of code is set as follows:

{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id": 67}

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

$ geth --datadir=./chaindata/ init genesis.json

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Click on the Create button as highlighted in Figure 3.7. Voila! You just created your smart contract."

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: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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/submit-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 packtpub.com.

Blockchain Basics

This chapter will serve as a warm-up session about blockchain before we dive into Ethereum and smart contract development. To really appreciate blockchain, we must understand the two pillars on which blockchain, as a technology, is firmly grounded: distributed systems and cryptography. Once we have tackled these two core concepts, we will try to understand blockchain from two different perspectives: one as a software developer and another as a trader of financial instruments. Then, we'll probe into the internal logical architecture of a block in blockchain, focusing on the bitcoin block structure and get a gentle introduction to the mining and forking process.

We conclude the chapter by discussing the evolution of blockchain as a technology in recent years, three generations of blockchain technology, and the current position of blockchain on the gartner hype cycle.

After studying this chapter, you will be able to:

Understand the foundation of

blockchain

technology

Appreciate 

blockchain

as a developer and a trader

Discuss the basic structure of a bitcoin block

Know about

blockchain

mining and forking and understand the evolution, generations, and hype surrounding 

blockchain

Understanding distributed systems

To understand a distributed system, we need to first distinguish it from traditional centralized systems. Traditional centralized systems consist of two main components: the client and the server. In the simplest setup, the client is the one who makes a request for getting a job done, and a server is the one who gets it done. This was how web 1.0 operated; the one we started calling the World Wide Web. For example, you placed a search request on Google search engine, and it gave you back a set of web links and summarized results.

Now, if two clients want to communicate between each other, they have to place request via the server, which serves as the middleman. A second example might be, for instance, if I send you a message from the client app of my mobile, this message is pushed to the WhatsApp server, which then notifies your client app about my message. Once you see my message, your client app sends back an acknowledgement signal in terms of a blue double tick to my client app, again using the WhatsApp server. This is how the present internet operates and we call it web 2.0, the advent of the social network. In both of these examples, we can see the centralized system works just fine. In Figure 1.1, this centralized setup is represented by the left-side lego block setup. The aggregated middle blocks represent the server, whereas the circumferential isolated blocks represent the clients. However, these centralized servers are generally owned by business organizations and can be influenced by a criminal entity or central authority to leak private data while the clients communicate. To overcome this fundamental flaw, peer-to-peer networking (web 3.0) came into practice (for example, BitTorrent). These were distributed systems, as depicted in the right of Figure 1.1, where each node can be a client or server or both and are not distinguishable from other nodes. Even though these systems were good at privacy, they faced challenges like the Byzantine Generals' Problem and the CAP theorem, which we will discuss in the subsequent sections.

Figure 1.1: Lego block representation of centralized system (left) and distributed system (right)

The Byzantine Generals' Problem

Imagine a time during the dark ages, where a pirate ship is under attack. There are 200 pirates aboard the pirate ship surrounded by six army ships of 50 warriors each, who've anchored, surrounding the pirate ship. Each army ship is commanded by a captain. The 300 warriors can easily overpower the 200 pirates aboard the pirate ship. However, if they don't all attack simultaneously, there is a very real risk that the warriors will be outnumbered by the pirates and they'll go on to lose the battle.

Figure 1.2: Pirate ship (200) surrounded by arm ship (50)

So, how can the captains all agree on the same time to attack the pirate ship? These days, we'd simply need a quick group video-conference call, and the captains would have to agree to attack at 22:00 hours (10 PM).

However, back in the dark ages, things were a little more complicated:

The 22:00 attack message could only be passed on by a sailor on a small boat. He has to sail around each army ship, visiting each captain in turn to confirm.

Any captain may be a traitor and in league with the pirates in the pirate ship.

Losing strategy

Captain 1 decides to attack at 22:00. He sends his sailor out with the message (22:00 attack) to deliver to Captain 2. Upon arrival, Captain 2 reads the message, notes the time of the attack, and sends a message that also says 22:00 attack. He sends the sailor on to share the message with Captain 3. However, we have a problem. Captain 3 is a traitor. He wants the attack to fail. So, when he gets the message, he rips it up and replaces it with a new message that says 21:00 attack (9 PM). The sailor continues unaware. Captain 4 now receives a message saying 21:00 attack. He notes the time, signs the message saying 21:00 attack and sends this on to Captain 5, who then sends the same message to Captain 6. Now, the message has gone around everyone, but we have a problem. The dishonest captain has disrupted the result. We now have three captains (4, 5, and 6) with 150 warriors attacking the pirate ship at 21:00. Expecting others to join them, they instead get outnumbered and overpowered by the 200 pirates. The victorious pirates now stream out of the pirate ship and join forces with the treacherous Captain 3. Suddenly, the two remaining captains (1 and 2) have only 100 warriors and find themselves fighting 200 pirates plus 50 traitors. Unfortunately, the pirates and traitors win.

Winning strategy

Captain 1 wants to send the same message (attack at 22:00). However, this time, there are two new rules he must obey:

He must spend 10 minutes preparing any new message for it to be valid

He must include the history of every previous message in every new message

So, let's see what happens this time. As before, Captain 1 sends the message (22:00 attack) with the sailor on the boat. This time, however, it is different for Captain 2, because he knows two things for certain:

The message must have taken 10 minutes to prepare

There are no previous messages, so it must be the truth (even if Captain 1 is a traitor and put in the wrong time, it doesn't matter; if the majority of captains followed this suggestion and went with a 22:00 attack time, they would still outnumber those in the pirate ship and win the battle)

So, now it is time for Captain 2 to send a message. As required, he spends 10 minutes preparing the new message and he embeds Captain 1's message into his own. The sailor then sets off with this message (now in fact, it is two messages chained together as the second has the first embedded within it). Now it gets to Captain 3.

Remember, he's the traitor. So, what does he do? Last time, he changed the message to 21:00 attack so that captains 4, 5, and 6 would attack early and get overpowered. Now, however, he can't because, under the new rules, he has only 10 minutes to prepare a message for Captain 4. He has two options:

Cheat by changing the message to 21:00 attack. To do this, he needs to (a) spend 10 minutes creating his message and then (b) spend an extra 2 x 10 minutes working to create replacement 21:00 attack messages from Captains 1 and 2 to embed these into his message and carry out this 30 minutes of work within the next 10 minutes to avoid the other captains knowing that he's a traitor.

Admit defeat and prepare the 22:00 attack message during those 10 minutes.

In other words, every captain has got no more than 10 minutes to provide the next captain with something that would take more than 10 minutes to fake if they were trying to be dishonest. If they can't deliver it within 10 minutes, everyone knows they're dishonest and ignores them, rendering their attempts to mislead others useless.

The CAP theorem

Before stating the CAP theorem, let's try to understand consistency, availability, and partition tolerance using a real-world problem.

As a married person, I know how pathetic a person's life can become if they forget important dates like the birthday and anniversary of their spouse (in most cases, the husband is the culprit, but that is a separate discussion). One of my friends, let's call him Kaushik, saw an opportunity in this and opened up a start-up, HappySpouse.com, to address this issue. During a typical business day, Kaushik (K) and his customer (C) would have the following conversation:

K: Hello from HappySpouse.com. How may I help you?

C: Hey, I want you to remember my wife's birthday.

K: Sure! When is it?

C: September 3.

K: (Writing it down on a page exclusive for C.) Stored. Call me any time to remind you of your spouse's birthday again!

C: Thank you!

K: No problem! Your credit card has been charged with $0.05.

Kaushik's idea was so simple, needed nothing but a notebook and phone, yet so effective that it rolled off like an avalanche. VC firms started pouring in funds. He also started getting hundreds of calls every day. That's where the problem started. Now, more and more of his customers had to wait in the queue to speak to him. Most of them even hung up, tired of the waiting tone. Besides, when he was sick for a day and could not come to work, he lost a whole day of business. Not to mention all those unsatisfied customers who wanted information on that day. So, Kaushik decided to scale up and bring in his wife to help him.

He started with a simple plan to solve his availability to customers:

He and his wife both got an extension phone

Customers still dialed the same number

A PBX routed the customer calls to whoever was free at that moment

A few weeks went by smoothly. One fine morning, he got a call from one of his old customers, Joey (J):

J: Hello, am I speaking to Kaushik from HappySpouse.com?

K: Hi Joey, great you remembered us. What can I do for you?

J: Can you tell me when our anniversary was?

K: Sure. 1 sec, Joey (looking up in his notebook, there was no entry on Joey's page). Joey, I have only your spouse's birthday here.

J: Holy cow! I just called you guys yesterday! (Cuts the call!)

How did that happen? Was Joey lying? Kaushik thought about it for a second and the reason hit him! Yesterday, did Joey's call reach his wife? He goes to his wife's desk and checks her notebook. Sure enough, it's there. He tells this to his wife and she realizes the problem too. What a terrible flaw in this distributed setup! This setup was not consistent!