100% нашли этот документ полезным (4 голоса)
27 просмотров59 страниц

Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript Lee Download

Документ представляет собой руководство по программированию смарт-контрактов на Ethereum с примерами на Python, Solidity и JavaScript. Он охватывает основы блокчейна, создание собственных блокчейнов, работу с Ethereum, разработку и тестирование смарт-контрактов, а также использование различных инструментов, таких как MetaMask и web3.js. Книга включает практические проекты и примеры кода, доступные на GitHub.

Загружено:

icxgchcnd8650
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
100% нашли этот документ полезным (4 голоса)
27 просмотров59 страниц

Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript Lee Download

Документ представляет собой руководство по программированию смарт-контрактов на Ethereum с примерами на Python, Solidity и JavaScript. Он охватывает основы блокчейна, создание собственных блокчейнов, работу с Ethereum, разработку и тестирование смарт-контрактов, а также использование различных инструментов, таких как MetaMask и web3.js. Книга включает практические проекты и примеры кода, доступные на GitHub.

Загружено:

icxgchcnd8650
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 59

Beginning Ethereum Smart Contracts Programming:

With Examples in Python, Solidity, and


JavaScript Lee pdf download

https://textbookfull.com/product/beginning-ethereum-smart-
contracts-programming-with-examples-in-python-solidity-and-
javascript-lee/

Download more ebook instantly today - get yours now at textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/

Introducing Ethereum and Solidity: Foundations of


Cryptocurrency and Blockchain Programming for Beginners
Chris Dannen

https://textbookfull.com/product/introducing-ethereum-and-
solidity-foundations-of-cryptocurrency-and-blockchain-
programming-for-beginners-chris-dannen/

Ethereum for Architects and Developers With Case


Studies and Code Samples in Solidity Springerlink
(Online Service)

https://textbookfull.com/product/ethereum-for-architects-and-
developers-with-case-studies-and-code-samples-in-solidity-
springerlink-online-service/

Beginning Functional JavaScript. Functional Programming


with JavaScript using EcmaScript 6 1st Edition Anto
Aravinth

https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth/
Beginning Functional JavaScript: Functional Programming
with JavaScript Using EcmaScript 6 1st Edition Anto
Aravinth

https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth-2/

Ethereum for Architects and Developers: With Case


Studies and Code Samples in Solidity 1st Edition
Debajani Mohanty

https://textbookfull.com/product/ethereum-for-architects-and-
developers-with-case-studies-and-code-samples-in-solidity-1st-
edition-debajani-mohanty/

Good Habits for Great Coding: Improving Programming


Skills with Examples in Python Michael Stueben

https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-michael-
stueben/

Beginning Programming with Python For Dummies 2nd


Edition John Paul Mueller

https://textbookfull.com/product/beginning-programming-with-
python-for-dummies-2nd-edition-john-paul-mueller/

Blockchain The Ultimate Guide to the World of


Blockchain Technology Bitcoin Ethereum Cryptocurrency
Smart Contracts 1st Edition Takashima

https://textbookfull.com/product/blockchain-the-ultimate-guide-
to-the-world-of-blockchain-technology-bitcoin-ethereum-
cryptocurrency-smart-contracts-1st-edition-takashima/
Beginning Ethereum
Smart Contracts
Programming
With Examples in Python,
Solidity and JavaScript

Wei-Meng Lee
Beginning Ethereum Smart Contracts Programming:
With Examples in Python, Solidity and JavaScript
Wei-Meng Lee
Ang Mo Kio, Singapore

ISBN-13 (pbk): 978-1-4842-5085-3    ISBN-13 (electronic): 978-1-4842-5086-0


https://doi.org/10.1007/978-1-4842-5086-0

© 2019 by Wei-Meng Lee

Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484250853. For more
detailed information, please visit http://www.apress.com/source-code.
Contents

Introduction�����������������������������������������������������������������������������������������������������������xvii

Chapter 1: Understanding Blockchain���������������������������������������������������������������������� 1


Motivations Behind Blockchain����������������������������������������������������������������������������������������������������� 2
Placement of Trusts����������������������������������������������������������������������������������������������������������������� 2
Trust Issues����������������������������������������������������������������������������������������������������������������������������� 3
Solving Trust Issues Using Decentralization���������������������������������������������������������������������������� 4
Example of Decentralization���������������������������������������������������������������������������������������������������� 4
Blockchain As a Distributed Ledger����������������������������������������������������������������������������������������� 8
How Blockchain Works����������������������������������������������������������������������������������������������������������������� 9
Chaining the Blocks��������������������������������������������������������������������������������������������������������������� 10
Mining������������������������������������������������������������������������������������������������������������������������������������ 12
Broadcasting Transactions���������������������������������������������������������������������������������������������������� 12
The Mining Process��������������������������������������������������������������������������������������������������������������� 13
Proof of Work������������������������������������������������������������������������������������������������������������������������� 16
Immutability of Blockchains�������������������������������������������������������������������������������������������������� 16
Blockchain in More Detail����������������������������������������������������������������������������������������������������������� 17
Types of Nodes���������������������������������������������������������������������������������������������������������������������� 19
Merkle Tree and Merkle Root������������������������������������������������������������������������������������������������� 21
Uses of Merkle Tree and the Merkle Root������������������������������������������������������������������������������ 22
Summary������������������������������������������������������������������������������������������������������������������������������������ 23
Chapter 2: Implementing Your Own Blockchain Using Python������������������������������� 25
Our Conceptual Blockchain Implementation������������������������������������������������������������������������������� 25
Obtaining the Nonce�������������������������������������������������������������������������������������������������������������� 27
Installing Flask���������������������������������������������������������������������������������������������������������������������� 28
Importing the Various Modules and Libraries������������������������������������������������������������������������ 29
Declaring the Class in Python������������������������������������������������������������������������������������������������ 29
Finding the Nonce����������������������������������������������������������������������������������������������������������������� 31
Appending the Block to the Blockchain��������������������������������������������������������������������������������� 32
Adding Transactions�������������������������������������������������������������������������������������������������������������� 32
Exposing the Blockchain Class as a REST API����������������������������������������������������������������������� 33
Obtaining the Full Blockchain������������������������������������������������������������������������������������������������ 33
Performing Mining����������������������������������������������������������������������������������������������������������������� 34
Adding Transactions�������������������������������������������������������������������������������������������������������������� 35
Testing Our Blockchain��������������������������������������������������������������������������������������������������������������� 36
Synchronizing Blockchains��������������������������������������������������������������������������������������������������������� 41
Testing the Blockchain with Multiple Nodes�������������������������������������������������������������������������� 45
Full Listing for the Python Blockchain Implementation��������������������������������������������������������������� 51
Summary������������������������������������������������������������������������������������������������������������������������������������ 59

Chapter 3: Connecting to the Ethereum Blockchain����������������������������������������������� 61


Downloading and Installing Geth������������������������������������������������������������������������������������������������ 62
Installing Geth for macOS������������������������������������������������������������������������������������������������������ 62
Installing Geth for Windows��������������������������������������������������������������������������������������������������� 63
Installing Geth for Linux��������������������������������������������������������������������������������������������������������� 64
Getting Started with Geth������������������������������������������������������������������������������������������������������������ 64
Examining the Data Downloaded������������������������������������������������������������������������������������������� 65
Geth JavaScript Console�������������������������������������������������������������������������������������������������������� 66
Sync Modes��������������������������������������������������������������������������������������������������������������������������� 68
Summary������������������������������������������������������������������������������������������������������������������������������� 69
Chapter 4: Creating Your Own Private Ethereum Test Network������������������������������ 71
Creating the Private Ethereum Test Network������������������������������������������������������������������������������ 71
Creating the Genesis Block��������������������������������������������������������������������������������������������������� 72
Creating a Folder for Storing Node Data�������������������������������������������������������������������������������� 73
Initiating a Blockchain Node�������������������������������������������������������������������������������������������������� 74
Starting Up the Nodes����������������������������������������������������������������������������������������������������������� 76
Managing Accounts��������������������������������������������������������������������������������������������������������������������� 88
Removing Accounts��������������������������������������������������������������������������������������������������������������� 90
Setting the Coinbase������������������������������������������������������������������������������������������������������������� 90
Summary������������������������������������������������������������������������������������������������������������������������������� 91

Chapter 5: Using the MetaMask Chrome Extension������������������������������������������������ 93


What Is MetaMask?�������������������������������������������������������������������������������������������������������������������� 93
How MetaMask Works Behind the Scene������������������������������������������������������������������������������ 94
Installing MetaMask�������������������������������������������������������������������������������������������������������������� 95
Signing in to MetaMask��������������������������������������������������������������������������������������������������������� 97
Selecting Ethereum Networks�������������������������������������������������������������������������������������������������� 103
Getting Ethers���������������������������������������������������������������������������������������������������������������������� 104
Creating Additional Accounts����������������������������������������������������������������������������������������������� 111
Transferring Ethers�������������������������������������������������������������������������������������������������������������� 113
Recovering Accounts����������������������������������������������������������������������������������������������������������� 117
Importing and Exporting Accounts�������������������������������������������������������������������������������������������� 120
Exporting Accounts�������������������������������������������������������������������������������������������������������������� 120
Importing Accounts������������������������������������������������������������������������������������������������������������� 124
Summary���������������������������������������������������������������������������������������������������������������������������������� 126

Chapter 6: Getting Started with Smart Contract��������������������������������������������������� 127


Your First Smart Contract���������������������������������������������������������������������������������������������������������� 127
Using the Remix IDE������������������������������������������������������������������������������������������������������������ 128
Compiling the Contract�������������������������������������������������������������������������������������������������������� 131
Testing the Smart Contract Using the JavaScript VM���������������������������������������������������������� 133
Getting the ABI and Bytecode of the Contract��������������������������������������������������������������������� 136
Loading the Smart Contract onto Geth�������������������������������������������������������������������������������������� 139
Testing the Contract������������������������������������������������������������������������������������������������������������ 142
Calling the Contract from Another Node������������������������������������������������������������������������������ 144
Summary���������������������������������������������������������������������������������������������������������������������������������� 146

Chapter 7: Testing Smart Contracts Using Ganache��������������������������������������������� 147


Downloading and Installing Ganache���������������������������������������������������������������������������������������� 147
Command-Line Interface����������������������������������������������������������������������������������������������������� 148
Graphical User Interface������������������������������������������������������������������������������������������������������ 150
Creating a Smart Contract�������������������������������������������������������������������������������������������������������� 153
Deploying the Contract to Ganache������������������������������������������������������������������������������������� 154
Examining Ganache������������������������������������������������������������������������������������������������������������� 156
Testing the Contract������������������������������������������������������������������������������������������������������������ 159
Connecting MetaMask to Ganache������������������������������������������������������������������������������������������� 161
Summary���������������������������������������������������������������������������������������������������������������������������������� 167

Chapter 8: Using the web3.js APIs����������������������������������������������������������������������� 169


What Is web3.js?����������������������������������������������������������������������������������������������������������������������� 169
Installing web3.js���������������������������������������������������������������������������������������������������������������� 170
Testing the web3.js Using MetaMask���������������������������������������������������������������������������������� 171
Testing the web3.js Without MetaMask������������������������������������������������������������������������������� 175
Deploying Contracts Using web3.js������������������������������������������������������������������������������������������ 178
Interacting with a Contract Using web3.js�������������������������������������������������������������������������� 184
Sending Ethers to Smart Contracts������������������������������������������������������������������������������������� 191
Summary���������������������������������������������������������������������������������������������������������������������������������� 198

Chapter 9: Smart Contract Events������������������������������������������������������������������������ 199


What Are Events in Solidity?����������������������������������������������������������������������������������������������������� 199
Adding Events to the ProofOfExistence Contract����������������������������������������������������������������� 200
Deploying the Contract�������������������������������������������������������������������������������������������������������� 203
Handling Events Using web3.js������������������������������������������������������������������������������������������������� 204
Testing the Front End����������������������������������������������������������������������������������������������������������� 208
Notarizing the Same Document Twice��������������������������������������������������������������������������������� 213
Sending Incorrect Amount of Ether������������������������������������������������������������������������������������� 215
Summary���������������������������������������������������������������������������������������������������������������������������������� 219

Chapter 10: Project – Online Lottery�������������������������������������������������������������������� 221


How the Lottery Game Works���������������������������������������������������������������������������������������������������� 221
Defining the Smart Contract������������������������������������������������������������������������������������������������ 223
Constructor�������������������������������������������������������������������������������������������������������������������������� 224
Betting a Number���������������������������������������������������������������������������������������������������������������� 225
Drawing the Winning Number and Announcing the Winners����������������������������������������������� 227
Getting the Winning Number����������������������������������������������������������������������������������������������� 229
Killing the Contract�������������������������������������������������������������������������������������������������������������� 230
Testing the Contract������������������������������������������������������������������������������������������������������������������ 230
Betting on a Number����������������������������������������������������������������������������������������������������������� 231
Viewing the Winning Number���������������������������������������������������������������������������������������������� 236
Examining the Contract on Etherscan��������������������������������������������������������������������������������� 237
Killing the Contract�������������������������������������������������������������������������������������������������������������� 239
Adding Events to the Contract��������������������������������������������������������������������������������������������� 243
Creating the Web Front End������������������������������������������������������������������������������������������������������ 247
Returning Ethers Back to the Owner at the End of the Game���������������������������������������������� 253
Making the Game Run Indefinitely�������������������������������������������������������������������������������������� 255
Summary���������������������������������������������������������������������������������������������������������������������������������� 256

Chapter 11: Creating Your Tokens������������������������������������������������������������������������ 257


What Are Tokens?���������������������������������������������������������������������������������������������������������������������� 257
How Tokens Are Implemented?������������������������������������������������������������������������������������������� 259
Minting New Tokens������������������������������������������������������������������������������������������������������������ 259
Burning Tokens�������������������������������������������������������������������������������������������������������������������� 259
Units Used Internally in Token Contracts����������������������������������������������������������������������������� 260
ERC20 Token Standard�������������������������������������������������������������������������������������������������������� 261
Creating Token Contracts���������������������������������������������������������������������������������������������������������� 263
Deploying the Token Contract���������������������������������������������������������������������������������������������� 272
Adding Tokens to MetaMask������������������������������������������������������������������������������������������������ 275
Buying Tokens��������������������������������������������������������������������������������������������������������������������� 279
Creating an ICO Page����������������������������������������������������������������������������������������������������������� 284
Summary���������������������������������������������������������������������������������������������������������������������������������� 287

Index��������������������������������������������������������������������������������������������������������������������� 289
Introduction
Welcome to Beginning Ethereum Smart Contracts Programming!
This book is a quick guide to getting started with Ethereum Smart Contracts
programming. It first starts off with a discussion on blockchain and the motivations
behind it. You will learn what is a blockchain, how blocks in a blockchain are chained
together, and how blocks get added to a blockchain. You will also understand how
mining works and discover the various types of nodes in a blockchain network.
Once that is out of the way, we will dive into the Ethereum blockchain. You will
learn how to use an Ethereum client (Geth) to connect to the Ethereum blockchain and
perform transactions such as sending ethers to another account. You will also learn how
to create private blockchain networks so that you can test them internally within your
own network.
The next part of this book will discuss Smart Contracts programming, a unique
feature of the Ethereum blockchain. Readers will be able to get jumpstarted on Smart
Contracts programming without needing to wade through tons of documentation. The
learn-by-doing approach of this book makes you productive in the shortest amount
of time. By the end of this book, you would be able to write smart contracts, test them,
deploy them, and create web applications to interact with them.
The last part of this book will touch on tokens, something that has taken the
cryptocurrency market by storm. You would be able to create your own tokens and
launch your own ICO and would be able to write token contracts that allow buyers to buy
tokens using Ethers.
This book is for those who want to get started quickly with Ethereum Smart
Contracts programming. Basic programming knowledge and an understanding of
Python or JavaScript are recommended.
I hope you will enjoy working on the sample projects as much as I have enjoyed
working on them!
CHAPTER 1

Understanding Blockchain
One of the hottest technologies of late is Blockchain. But what exactly is a blockchain?
And how does it actually work? In this chapter, we will explore the concept of blockchain,
how the concept was conceived, and what problems it aimed to solve. By the end of this
chapter, the idea and motivation behind blockchain would be crystal clear.

Tip For the clearly impatient – A blockchain is a digital transaction of records


that’s arranged in chunks of data called blocks. These blocks link with one another
through a cryptographic validation known as a hashing function. Linked together,
these blocks form an unbroken chain – a blockchain. A blockchain is programmed
to record not only financial transactions but virtually everything of value. Another
name for blockchain is distributed ledger.

Hold on tight, as I’m going to discuss a lot of concepts in this chapter. But if you
follow along closely, you’ll understand the concepts of blockchain and be on your way to
creating some really creative applications on the Ethereum blockchain in the upcoming
chapters!

Tip Ethereum is an open-source public blockchain that is similar to the Bitcoin


network. Besides offering a cryptocurrency known as Ether (which is similar
to Bitcoin), the main difference between Bitcoin and itself is that it offers a
programming platform on top of the blockchain, called Smart Contract. This book
focuses on the Ethereum blockchain and Smart Contract.
Chapter 1 Understanding Blockchain

Motivations Behind Blockchain


Most people have heard of cryptocurrencies, or at least, Bitcoin.

Note The technology behind cryptocurrencies is blockchain.

To understand why we need cryptocurrencies, you have to first start with


understanding a fundamental concept – trust. Today, any asset of value or transaction is
recorded by a third party, such as bank, government, or company. We trust banks won’t
steal our money, and they are regulated by the government. And even If the banks fail,
it is backed by the government. We also trust our credit card companies – sellers trust
credit card companies to pay them the money, and buyers trust credit card companies to
settle any disputes with the sellers.

Placement of Trusts
All these boil down to one key concept – placement of trust. And that is, we place our
trust on a central body. Think about it, in our everyday life, we place our trusts on banks,
and we place our trusts on our governments.
Even for simple mundane day-to-day activities, we place our trusts in central bodies.
For example, when you go to the library to borrow a book, you trust that the library
would maintain a proper record of the books that you have borrowed and returned.
The key theme is that we trust institutions but don’t trust each other. We trust our
government, banks, even our library, but we just don’t trust each other. As an example,
consider the following scenario. Imagine you work at a cafe, and someone walks up
to you and offers you a US ten-dollar bill for two cups of coffee. And another person
who offers to pay you for the two cups of coffee using a handwritten note saying he
owes you ten dollars. Which one would you trust? The answer is pretty obvious, isn’t it?
Naturally you would trust the US ten-dollar bill, as opposed to the handwritten note.
This is because you understand that using the ten-dollar bill, you can use it elsewhere
to exchange for other goods or services, and that it is backed by the US government. In
contract, the handwritten note is not backed by anyone else (except perhaps the person
who wrote it), and hence it has literally no value.

2
Chapter 1 Understanding Blockchain

Now let’s take the discussion a bit further. Again, imagine you are trying to sell
something. Someone comes up to you and suggests paying for your goods using the
currencies as shown in Figure 1-1.

Figure 1-1. Currencies from two countries

Would you accept the currencies as shown in the figure? Here, you have two different
currencies – one from Venezuela and one from Zimbabwe. In this case, the first thing
you consider is whether these currencies are widely accepted and also your trust in these
governments. You might have read from the news about the hyperinflation in these two
countries, and that these currencies might not retain its value over time.
And so, would you accept these currencies as payment?

T rust Issues
Earlier on, I mentioned that people trust institutions and don’t trust each other. But even
established economies can fail, such as in the case of the financial crisis of the United
States in 2007–2008. Investment bank Lehman Brothers collapsed in September 2008
because of the subprime mortgage market. So, if banks from established economies can

3
Chapter 1 Understanding Blockchain

collapse, how can people in less developed countries trust their banks and governments?
Even if the banks are trusted, your deposits may be monitored by the government, and
they could arrest you based on your transactions.
As we have seen in the example in the previous section, there are times when people
don’t trust institutions, especially if the political situation in that country is not stable.
All these discussions bring us to the next key issue – even though people trust
institutions, institutions can still fail. And when people lose trust in institutions, people
turn to cryptocurrencies. In the next section, we will discuss how we can solve the trust
issues using decentralization, a fundamental concept behind cryptocurrency.

Solving Trust Issues Using Decentralization


Now that you have seen the challenges of trust – who to trust and who not to trust, it
is now time to consider a way to solve the trust issues. In particular, blockchain uses
decentralization to solve the trust issue.
In order to understand decentralization, let’s use a very simple example that is based
on our daily lives.

E xample of Decentralization
To understand how decentralization solves the trust issue, let’s consider a real-life example.
Imagine a situation where you have three persons with DVDs that they want to share
with one another (see Figure 1-2).

4
Chapter 1 Understanding Blockchain

Figure 1-2. Sharing DVDs among a group of people

The first thing they need to do is to have someone keep track of the whereabouts
of each DVD. Of course, the easiest is for each person to keep track of what they have
borrowed and what they have lent, but since people inherently do not trust each other,
this approach is not very popular among the three persons.
To solve this issue, they decided to appoint one person, say B, to keep a ledger, to
hold a record of the whereabouts of each DVD (see Figure 1-3).

5
Chapter 1 Understanding Blockchain

Figure 1-3. Appointing a particular person to keep the records

This way, there is a central body to keep track of the whereabouts of each DVD. But
wait, isn’t this the problem with centralization? What happens if B is not trustworthy?
Turns out that B has the habit of stealing DVDs, and he in fact could easily modify the
ledger to erase the record of DVDs that he has borrowed. So, there must be a better way.
And then, someone has an idea! Why not let everyone keep a copy of the ledger
(see Figure 1-4)? Whenever someone borrows or lent a DVD, the record is broadcast to
everyone, and everyone records the transaction.

6
Chapter 1 Understanding Blockchain

Figure 1-4. Getting everyone to keep the records

We say that the record keeping is now decentralized! We now have three persons
holding the same ledger. But wait a minute. What if A and C conspire to change the
records together so that they can steal the DVDs from B? Since majority wins, as long
as there is more than 50% of the people with the same records, the others would have
to listen to the majority. And because there are only three persons in this scenario, it is
extremely easy to get more than 50% of the people to conspire.
The solution is to have a lot more people to hold the ledger, especially people who
are not related to the DVDs sharing business (see Figure 1-5).

7
Chapter 1 Understanding Blockchain

Figure 1-5. Getting a group of unrelated people to help keep the records

This way, it makes it more difficult for one party to alter the records on the ledger,
and that in order to alter a record, it would need to involve a number of people altering
the record all at the same time, which is a time-consuming affair. And this is the key idea
behind distributed ledger, or commonly known as blockchain.

Blockchain As a Distributed Ledger


Now that we have a better idea of a distributed ledger, we can now associate it with
the term – blockchain. Using the DVD rental example, each time a DVD is borrowed
or returned, a transaction is created. A number of transactions are then grouped
into a block. As more transactions are performed, the blocks are linked together
cryptographically, forming what we now call a blockchain (see Figure 1-6).

8
Chapter 1 Understanding Blockchain

Figure 1-6. Transactions form a block, and then blocks are then chained

Based on what we have discussed, we can now summarize a few important points:

• Centralized databases and institutions work when there is trust in the


system of law, governments, regulatory bodies, and people.

• A decentralized database built on the blockchain removes the need


for the trust in a central body.

• A blockchain can be used for anything of value, not just currencies.

How Blockchain Works


At a very high level, a blockchain consists of a number of blocks. Each block contains a
list of transactions, as well as a timestamp (see Figure 1-7).

9
Chapter 1 Understanding Blockchain

Figure 1-7. Every blockchain has a beginning block known as the genesis block

The blocks are connected to each other cryptographically, the details in which we
will discuss in the sections ahead. The first block in a blockchain is known as the genesis
block.

Note Every blockchain has a genesis block.

So, the next important questions is – how do you chain the blocks together?

Chaining the Blocks


Before we discuss how blocks in a blockchain are chained together, we have to discuss
a key concept in blockchain – hashing. A hash function is a function that maps data of
arbitrary size to data of fixed size. By altering a single character in the original string, the
resultant hash value is totally different from the previous one. Most importantly, observe
that a single change in the original message results in a completely different hash,
making it difficult to know that the two original messages are similar.
10
Chapter 1 Understanding Blockchain

A hash function has the following characteristics:

• It is deterministic – the same message always results in the same


hash.

• It is a one-way process – when you hash a string, it is computationally


hard to reverse a hash to its original message.

• It is collision resistant – it is hard to find two different input messages


that hash to the same hash.

We are now ready to discuss how blocks in a blockchain are chained together. To
chain the blocks together, the content of each block is hashed and then stored in the next
block (see Figure 1-8). That way, if any transactions in a block is altered, that is going to
invalidate the hash of the current block, which is stored in the next block, which in turn
is going to invalidate the hash of the next block, and so on.

Figure 1-8. Chaining the blocks with hashes

11
Chapter 1 Understanding Blockchain

Observe that when hashing the content of a block, the hash of the previous block is
hashed together with the transactions. However, do take note that this is a simplification
of what is in a block. Later on, we will dive into the details of a block and see exactly how
transactions are represented in a block.
Storing the hash of the previous block in the current block assures the integrity of the
transactions in the previous block. Any modifications to the transaction(s) within a block
causes the hash in the next block to be invalidated, and it also affects the subsequent
blocks in the blockchain. If a hacker wants to modify a transaction, not only must he
modify the transaction in a block but all other subsequent blocks in the blockchain. In
addition, he needs to synchronize the changes to all other computers on the network,
which is a computationally expensive task to do. Hence, data stored in the blockchain
is immutable, for they are hard to change once the block they are in is added to the
blockchain.
Up to this point, you have a high-level overview of what constitutes a blockchain and
how the blocks are chained together. In the next section, you will understand the next
important topic in blockchain – mining.

M
 ining
Whenever you talk about blockchain or cryptocurrencies, there is always one term that
comes up – mining. In this section, you will learn what is mining, and what goes on
behind the scene.
Mining is the process of adding blocks to a blockchain. In a blockchain network,
such as the Bitcoin or Ethereum network, there are different types of computers known
as nodes. Computers on a blockchain that add blocks to the blockchain are known as
miner nodes (or mining nodes, or more simply miners).
We will talk about the different types of nodes later on in this course, but for now, we
want to talk about a particular type of node, known as the miner node. The role of the
miner node is to add blocks to the blockchain.
But how are blocks added?

B
 roadcasting Transactions
When a transaction is performed, the transaction is broadcasted to the network (see
Figure 1-9).

12
Chapter 1 Understanding Blockchain

Figure 1-9. Transactions are broadcasted to mining nodes, which then assemble
them into blocks to be mined

Each mining node may receive them at different times. As a node receives
transactions, it will try to include them in a block. Observe that each node is free to
include whatever transactions they want in a block. In practice, which transactions get
included in a block depends on a number of factors, such as transaction fees, transaction
size, order of arrival, and so on.
At this point, transactions that are included in a block but which are not yet added
to the blockchain are known as unconfirmed transactions. Once a block is filled with
transactions, a node will attempt to add the block to the blockchain.
Now here comes the problem – with so many miners out there, who gets to add the
block to the blockchain first?

The Mining Process


In order to slow down the rate of adding blocks to the blockchain, the blockchain
consensus protocol dictates a network difficulty target (see Figure 1-10).

13
Chapter 1 Understanding Blockchain

Figure 1-10. Hashing the block to meet the network difficulty target

In order to successfully add a block to the blockchain, a miner would hash the
content of a block and check that the hash meets the criteria set by the difficulty target.
For example, the resultant hash must start with five zeros and so on.
As more miners join the network, the difficultly level increases, for example, the
hash must now start with six zeros and so on. This allows the blocks to be added to the
blockchain at a consistent rate.
But, wait a minute, the content of a block is fixed, and so no matter how you hash it,
the resultant hash is always the same. So how do you ensure that the resultant hash can
meet the difficulty target? To do that, miners add a nonce to the block, which stands for
number used once (see Figure 1-11).

14
Chapter 1 Understanding Blockchain

Figure 1-11. Adding a nonce to change the content of the block in order to meet
the network difficulty target

The first miner who meets the target gets to claim the rewards and adds the block to
the blockchain. It will broadcast the block to other nodes so that they can verify the claim
and stop working on their current work of mining their own blocks. The miners would
drop their current work, and the process of mining a new block starts all over again.
The transactions that were not included in the block that was successfully mined will be
added to the next block to be mined.

REWARDS FOR MINERS

In the case of Bitcoin, the block reward initially was 50 BTC and will halve every 210,000
blocks. At the time of writing, the block reward is currently at 12.5 BTC, and it will eventually
be reduced to 0 after 64 halving events. For Ethereum, the reward for mining a block is
currently 2 ETH (Ether).

15
Chapter 1 Understanding Blockchain

BLOCKS ADDING RATES

For Bitcoin, the network adjusts the difficulty of the puzzles so that a new block is being mined
roughly every 10 minutes. For Ethereum, a block is mined approximately every 14 seconds.

Proof of Work
The process in which blocks are mined and added to the blockchain is known as the
Proof of Work (PoW). It is difficult to produce the proof but very easy to validate. A good
example of Proof of Work is cracking a combination lock – it takes a lot of time to find the
right combination, but it is easy to verify once the combination is found.
Proof of Work uses tremendous computing resources – GPUs are required, while
CPU speed is not important. It also uses a lot of electricity, because miners are doing the
same work repeatedly – find the nonce to meet the network difficulty for the block.
A common question is why you need to use a powerful GPU instead of CPU for
mining? Well, as a simple comparison, a CPU core can execute 4 32-bit instructions per
clock, whereas a GPU like the Radeon HD 5970 can execute 3200 32-bit instructions per
clock. In short, the CPU excels at doing complex manipulations to a small set of data,
whereas the GPU excels at doing simple manipulations to a large set of data. And since
mining is all about performing hashing and finding the nonce, it is a highly repetitive
task, something that GPU excels in.

Tip When a miner has successfully mined a block, he earns mining fees as well
as transaction fees. That’s what keeps miners motivated to invest in mining rigs
and keep them running 24/7, thereby incurring substantial electricity bills.

Immutability of Blockchains
In a blockchain, each block is chained to its previous block through the use of a
cryptographic hash. A block’s identity changes if the parent’s identity changes. This in
turn causes the current block’s children to change, which affects the grandchildren, and
so on. A change to a block forces a recalculation of all subsequent blocks, which requires
enormous computation power. This makes the blockchain immutable, a key feature of
cryptocurrencies like Bitcoin and Ethereum.

16
Chapter 1 Understanding Blockchain

As a new block is added to the blockchain, the block of transactions is said to be


confirmed by the blockchain. When a block is newly added, it’s deemed to have one
confirmation. As another block is added to it, its number of confirmation increases.
Figure 1-12 shows the number of confirmations that the blocks in a blockchain have. The
more confirmations a block has, the more difficult it is to remove it from the blockchain.

Tip In general, once a block has six or more confirmations, it’s deemed infeasible
for it to be reversed. Therefore, the data stored in the blockchain is immutable.

Figure 1-12. Confirmations of blocks in a blockchain

Blockchain in More Detail


In the previous section, you learned that a block contains a nonce, timestamp, and the
list of transactions. That was a simplification. In real implementation, a block consists of

• A block header

• The list of transactions

17
Chapter 1 Understanding Blockchain

The block header in turn consists of the following:

• The hash of the previous block

• Timestamp

• Merkle root

• Nonce

• Network difficulty target


Note that the block header contains the Merkle root, and not the transactions (see
Figure 1-13). The transactions are collectively represented as a merkle root, details of
which will be discussed in the next few sections.

Figure 1-13. A block contains the block header, which in turns contains the
Merkle root of the transactions

18
Chapter 1 Understanding Blockchain

T ypes of Nodes
Before we address the rationale for storing the Merkle root in the block header, we need
to talk about the types of nodes in a blockchain network. Figure 1-14 shows the different
types of nodes in a blockchain network.

Figure 1-14. Different types of nodes in a blockchain network

As we mentioned in our earlier sections, computers connected to the blockchain


network are known as nodes. We have discussed the role of mining nodes, whose key
responsibility is to gather transactions into blocks and then try to add the block to the
blockchain by finding the nonce that satisfies the network difficulty. Mining nodes are
also known as full nodes.

Tip Note that full nodes are not necessarily mining nodes. However, mining
nodes need to be a full node.

The purpose of a full node is to ensure the integrity of the blockchain and people
running full nodes do not get rewards. On the other hand, mining nodes are rewarded
when they add a block to the blockchain.
19
Chapter 1 Understanding Blockchain

An example of a full node is a desktop wallet, which allows users to perform


transaction using the cryptocurrency.
Each full node has a copy of the entire blockchain. Full nodes also validate every
block and transactions presented to it.
Besides full nodes, there are also light nodes. Light nodes help to verify transactions
using a method called simplified payment verification (SPV). SPV allows a node to verify
if a transaction has been included in a block, without needing to download the entire
blockchain. Using SPV, light nodes connect to full nodes and transmit transactions to the
full nodes for verifications.
Light nodes only need to store the block headers of all the blocks in the blockchain. An
example of a light node is a mobile wallet, such as the Coinbase mobile app for iOS and
Android. Using a mobile wallet, a user can perform transactions on the mobile device.

Note Desktop wallets can be full node or light node.

And so, we can summarize the types of nodes that we have discussed thus far:

• Full node

• Maintains a complete copy of the blockchain

• Able to verify all transactions since the beginning

• Verifies a newly created block and add it to the blockchain

• Visit the following sites to see the current number of full nodes for
the following blockchains:
• Bitcoin – https://bitnodes.earn.com

• Ethereum – www.ethernodes.org/network/1

• Mining node (must be a full node)

• Works on a problem (finding the nonce)

• Light node (e.g., wallets)

• Maintains the headers of the blockchain

• Uses SPV to verify if a transaction is present and valid in a block

20
Discovering Diverse Content Through
Random Scribd Documents
FOUNDATION OF BRITISH RULE IN INDIA. 211 a letter
from the Directors informing him that it was their determination to
take the collection of the revenue out of the hands of the native
revenue collectors, and to trust to their European servants " the
entire care and management of the revenues of Bengal.'' Reform of
the revenue system. — The reform of the revenue system therefore
was the first matter which engrossed his attention. A fresh
assessment of the land was set on foot, the treasury was removed
from Murshidabad to Calcutta, and European officers called
collectors were appointed to supervise the collection of the land-tax,
and to preside in the revenue courts of the districts into w-hich the
country was divided. Still further, to guard against irregularities
Commissioners were appointed over groups of districts to supervise
the work of the collectors, and courts of appeal were established in
Calcutta for both civil and criminal cases. In consideration of the
abolition of the dual system of government and the consequent
relief of the Nawab of Bengal from the responsibility of maintaining
order the Nawab's pension was cut down to one half. His next and
hardest task was the improvement of the Company's trade ; for the
corrupt practices and irregularities which he had to put a stop to
were in many cases committed by men in high places who were
friends and relatives of Directors. He did not, like Clive, raise a storm
of protest, for the wrongdoers had no shadow of excuse for their
conduct and dared not openly protest ; but he made for Jiimself
many private enemies, whose influence hereafter was used against
him on every possible occasion. The result of these measures was
that the Company once more received a profit from Bengal. Shah
Alam forfeits the Company's tribute.— ^ Meanwhile the state of
Upper India was giving cause for serious alarm. As soon as the
Mahrattas had got the feeble Emperor Shah Alam 11. into their
hands they began to put pressure on him. One of their first acts was
to force him to make over to them the districts of Allahabad and
Kora, which Lord Clive had given him in 1765 for the support of his
dignity. The occupation of this territory by the aggressive and
predatory Mahrattas was a direct menace to the Company's
possessions in Bengal, and to permit it would have been to
acquiesce in a state of things which the
212 HISTORY OF INDIA FOR HIGH SCHOOLS. grant to
Shah Alam had been intended to prevent. Warren Hastings therefore
declined to acknowledge the cession to the Mahrattas, promptly
occupied Allahabad, and declared a protectorate OA^er the ceded
districts. Furthermore, the yearly tribute of 25 lakhs paid by the
Company to Shah Alam was regarded as forfeited, since he had
voluntarily left British protection. The King of Oudh enters into a
subsidiary alliance. — It had been the object of successive
Governors in Bengal to maintain and support one or more friendly
powers an their northern border to serve as a barrier against
invasion. The Nawab Vizier of Oudh by the turn of affairs was now
alone able to play this part. To detach him from his northern
neighbours became a matter of the first importance. Accordingly, in
1773 Hastings went to Benares and concluded a treaty with him, by
the terms of which the Company sold to him the districts of
Allahabad and Kora, and agreed, on the payment of a subsidy by
him, to assist him with ^ the Company's troops in the event of his
being -attacked by the Mahrattas. The Rohilla War, 1774. — Within a
few months of this agreement the Nawab Vizier of Oudh wrote to
Hastings, proposing that the Company should assist him in driving
out the Rohillas from Rohilkhand, and annexing their country to his
own dominions. He pointed out that the Rohillas had dealt
treacherously with him ; that the year before, at their earnest
request, and on a promise made by them of a payment to him of 40
lakhs of rupees, he had assisted then in repelling a Mahratta
invasion of their country ; that they had since refused performance
of their promise ; and that they were now actually intriguing with
the Mahrattas against him. The Vizier offered to pay all expenses of
the expedition, and in the event of success, to give the 40 lakhs in
dispute to the English. Although the Company had never been
troubled by the Eohillas in any way, Hastings did not think it safe to
stand by while a formidable coalition of Mahrattas and Rohillas was
formed against the ally of the British. He therefore agreed to send a
brigade. No act of Hastings has been so severely condemned as this
participation in the ruin of a power which had done nothing directly
to incur the Company's hostility.
FOUNDATION OF BRITISH RULE IN INDIA. 213 But in his
defence it must be said that honour and political expediency alike
required that he should intervene ; for the fear of the Mahrattas was
very real and to abstain from interference in the coming struggle
between the Nawab Vizier and their friends the Rohillas would have
been to desert an ally and to play directly into their hands. The
Kohillas were not deserving of the sympathy they have received, for
they were merely Afghan adventurers, who had but lately imposed
their harsh rule upon the Hindu population of Eohilkhand. The Vizier
having got what he wanted, lost no time in attacking the Rohillas.
They fought bravely, and but for the staunchness of the Bengal
brigade would have routed the Vizier's undisciplined hordes ; but
they had no real chance of success, and were obliged shortly to
submit. Eohilkhand was annexed to Oudh, and the Rohillas, to the
number of some twenty thousand, were banished from the country.
CHAPTER n. THE GOVERNOR GENERALS OF BRITISH INDIA. The
Regulating Act. — The constant wars with the " Country Powers "
and the misgovernment and corruption which had marked the
Company's administration since its conversion by the exploits of Clive
from a mere commercial undertaking into a territorial sovereignty,
had been viewed with some alarm in England, and the Government
had been for some time anxiously looking for an opportunity of
interfering in its affairs. The opportunity had now arrived ; for the
Company which had for years been drifting further and further into
debt was forced in the year 1773 to apply to Government for
financial assistance. The Government, having the Company at its
mercy, informed it that it would be prepared to help it pecuniarily
only on conditions. These conditions were that the Government
should be kept informed of all political transactions of the Company;
that the Crown should have the right to veto or cancel any rules or
orders of the Company; that a Supreme Court of Judicature,
appointed by the Crown and independent of local authority, should
be estab 
214 HISTORY OF INDIA FOR HIGH SCHOOLS. lished in
Calcutta ; and that the Governor of Bengal, Behar, and Orissa should
be raised to the position of GovernorGeneral of the British
possessions in India, should be assisted by a Council of four, and
should exercise authority over the Governors of Madras and Bombay.
The Company was in no position to refuse these terms, and they
were accordingly embodied with others of minor importance in an
Act of Parliament known as the Kegulating Act. Meddlesomeness of
the new Council. — The Act did not come into force till October,
1774, when three of the members of the new Council arrived in
Calcutta from England. They were General Clavering, Colonel
Monson, and Philip Francis. The fourth member was a servant of the
Company named Barwell, residing at Calcutta. Warren Hastings
assumed the office of Governor-General from the date of their arrival
; but if he thought that his new dignity was to bring him increased
power he was doomed to bitter disappointment. Under the new Act
he was but the president of a committee, with a casting vote in case
his Council disagreed. He was therefore liable to be outvoted and
could do nothing withouttheconsentof themajority. The three
councillors from England came out with a violent prejudice against
him, having been well primed in England with stories — more or less
mendacious — to his discredit by his enemies, of whom in the
course of his administration he had been forced to make not a few ;
and they proceeded at once to make things uncomfortable for him
by enquiring into matters which had occurred before their arrival,
and by reversing or annulling several of his most important acts.
They seemed, in fact, bent upon his ruin, and prepared to
encompass it at all costs. They eagerly listened to every charge of
maladministration and corruption which the malice of his enemies
could invent, and in the investigation of abuses acted rather as the
agents of a prosecution than as impartial enquirers. Hastings
withstood them with firmness and spirit, but as he was supported by
Barwell alone he was completely at their mercy. Interference in the
affairs of Oudh. — In 1775 the Vizier of Oudh died, and the factious
members of the Council, in spite of the remonstrances of Hastings
and Barwell, cancelled the existing treaties, insisted on his heir
GOVERNOR-GENERALS OF BRITISH INDIA. 215 paying an
increased subsidy for the Company's troops stationed at Oudb, and
compelled him to make over the districts of Ghazipur and Benares to
the Company. Chet Singh, the local landowner, who had hitherto
been a tributary of the Vizier of Oudh, was by them raised to the
rank of Rajah, on consideration of his paying over to the Company
the annual tribute of 22 lakhs which he had been accustomed to
collect for the Nawab. This was bad enough ; but what followed was
still worse. The Begums, the widows of the late Vizier, had
appropriated two crores of rupees of treasure lying in the palace at
the time of his death, and had laid claim to the revenues of certain
rich districts in Oudh. The new Vizier, who was heavily in debt to the
Bengal Government, whose treasury was empty, and whose troops
were in a state of mutiny for arrears of pay, declined to acknowledge
their claims ; for, in truth, to have done so meant practically ruin to
him. The Begums appealed to the Council, and the intractable
majority decided in their favour out of sheer perverseness. The
affairs of Oudh at once fell into hopeless confusion, and the state
was soon in no position to perform its part oftheTreaty of 1773.
Execution of Nund Kumar. — Not satisfied with the public mischief
they had wrought, Clavering, Monson, and Francis proceeded to
collect privately against Hastings evidence of corruption and
embezzlement ; and to such a pass did things at length come that
they recorded a minute in Council in March, 1775, that there was no
species of peculation from which the Governor-General had thought
it reasonable to abstain. The chief of his accusers was a Bengali,
named Raja Nund Kumar. He was known to have been a bitter
enemy of Hastings for many years, and moreover he bore an
infkmous reputation ; but the three members of Council, ignoring all
this, proceeded to treat him as a trustworthy Avitncss, and eagerly
listened to the monstrous charges which he brought against the
Governor General. Hastings, whose ruin seemed imminent,
resolutely faced his refractory Council ; and while declining to be
arraigned as a criminal in the council chamber, offered to submit his
conduct to the investigation of a special committee. To this the
Council unreasonably declined to agree, and a deadlock /
216 HISTORY OF INDIA FOR HIGH SCHOOLS. ensued.
Suddenly, in the midst of the confusion, the chief accuser, Nund
Kumar, was arrested on a charge of forgery brought against him by a
native merchant. .The enemies of Hastings asserte'd then and
subsequently that he had instigated the prosecution, but Hastings
solemnly denied on oath having done so, and no evidence has ever
been found to support their allegation. It is significant that during
the course of Nund Kumar's trial no such suggestion was made, and
that the enemies of Hastings in the Council, though ai)pealed to,
declined to interfere on the prisoner's behalf Nund Kumar was tried*
in the Supreme Court, found guilty by the jury, and sentenced,
according to the then existing law, to be hanged as a forger. Even
then his patrons in the Council, who might still have intervened on
his behalf, refused an application to suspend the sentence, and he
was accordingly hanged in spite of his age, his caste, and his rank.
This dramatic incident, though it checked for a w^hile, did not put a
stop to the attacks upon Hastings' reputation. His implacable
enemies in the Council still continued to assail him, and in order to
destroy his influence systematically reversed all his decisions.
Dispute over the succession to the Peshwaship. — While through the
action of the Council affairs in Bengal were getting into a desperate
state of confusion and the kingdom of Oudh was drifting into ruin
and anarchy, matters in Bombay and Madras were almost equally
unsatisfactory. In the year 1772, a few months after his signal defeat
of Haidar, Madho Rao, the Peshwa died, a victim to consumption. He
was succeeded by his younger brother, Narayan Rao, who, being
only a boy, was placed under the guardianship of his uncle Raghaba.
But Narayan Rao had scarcely held office for six months when he
was assassinated in circumstances of peculiar atrocity. Raghaba as
next-of-kin thereupon assumed the office ; but as he was unpopular,
and was moreover strongly suspected of having contrived the
murder of his nephew, a conspiracy was formed againsjb him,
headed by Nana Furnavis, one of the greatest of Mahratta
statesmen. The conspirators produced a posthumous son of Narayan
Rao, and succeeded in getting his claims recognised by most of the
Mahratta chiefs. Raghaba, finding himself almost deserted, appealed
for help to the Bombay
GOVERNOR-GENERALS OF BRITISH INDIA. 217
Government, promising in return for it to give them the islands of
Salsette and Bassien. First Mahratta War, 1775-1782. — The Bombay
Government had already taken possession of the former, and they
were anxious to retain it, for fear that it might fall again into the
hands of its original owners, the Portuguese. Without troubling
themselves much about the merits of his case they readily agreed to
help Eaghaba, and in 1775 despatched a force under Colonel Keating
into the Mahratta country to support his claims. The whole ,
Mahratta country rose in arms to resist this unprovoked invasion,
and Colonel Keating found himself confronted with a force which
outnumbered his own by ten to one. Nevertheless, on the plains of
Arras, the Mahrattas, after a desperate struggle, were defeated.
Interference of the Supreme Council. — The Bombay Government,
by the terms of the Eegulating Act, were not empowered to make
war without the previous sanction of the Governor-General in
Council. As soon as the Supreme Council of Calcutta heard of what
was going on it denounced the war as * impolitic, dangerous,
unauthorised and unjust,' ordered tlie Bombay Government to cease
hostilities, and sent a representative to make peace with the
Mahrattas. Hastings, though strongly disapproving of the conduct of
the Bombay Government, disagreed with his Council's summary
method of dealing with the affair. Moreover, he thought it impolitic
for the Supreme Government openly to disavow the action of the
Western Presidency, and he feared that the Mahrattas might
misunderstand the motives of the English in thus abruptly treating
for peace. The Bombay Govermr.ent having meanwhile received the
approval of the Court of Directors to their 'agreement with Eaghaba,
continued, in spite of the Supreme Government, to support his
cause. The result showed that they were wise in not abandoning him
; for it was soon after discovered that Nana Furnavis was intriguing
with the French, with a view to recovering Salsette from the English
with their co-operation. Goddard's march across India. — Hastings
was not now hampered at every turn by a factious majority in his
Council ; for of his antagonists Monson had died in
218 HISTORY OF INDIA FOR HIGH SCHOOLS. 1776 and
Clavering in 1777, and Francis in a minority of one, though as
bitterly hostile as ever, was now powerless to organise a systematic
opposition to his plans. He was at last free to follow his own
judgment, and the greatness of his character never showed to better
advantage than in the eventful years which followed the outbreak of
the first Mahratta war. Eealising that a crisis was impending on the
western side, he promptly despatched Colonel Goddard with a force
from Bengal to assist the Bombay Government. Goddard's rapid
march across the peninsula through a wild and hostile country is one
of the most daring and brilliant exploits in history. He reached Surat
on 6th February, 1779, having marched the last 300 miles in twenty
days. The convention of Wargaom, — But meanwhile disaster had
overtaken an expedition sent by the Bombay Government against
Poona. After getting within eighteen miles of the place, the officer in
command came to the conclusion that the task was too great for his
small force, and decided to retreat. The Mahrattas at once took
heart* and gathered round hini like a swarm of bees. The force,
harassed in front and rear, and unable to obtain supplies, struggled
on as far as a place called Wargaom, and there, utterly exhausted,
allowed itself to be surrounded. To save his troops from annihilation,
the commander was obliged to enter into a disgraceful convention
with the two Mahratta Jleaders, Nana Furnavis and Sindhia. British
successes. — When the news of the disaster reached Bombay, the
Government, though in sore straits, refused to ratify the convention,
and Goddard, with whom was the fugitive Eaghaba, opened fresh
negotiations with Nana Furnavis. But as the Mahratta haughtily
declined to treat till Eaghaba had been given up and Salsette handed
over, Goddard recommenced hostilities in January, 1780. The
Mahrattas had soon cause to regret their uncompromising attitude,
for Goddard captured Ahmadabad, overran Guzerat, and reduced the
strong fort of Bassein; while Captain Popham, with another force
sent from Bengal, stormed and took the rock fortress of Gwalior,
hitherto regarded by the natives as impregnable. The second Mysore
war, 1780-1784. — In the midst of these successes alarming news
arrived from Southern India.
GOVERNOR-GENERALS OF BR|TISH INDIA, 219 The
Madras Government, with characteristic incapacity and
meddlesomeness, had so provoked Haidar AH and the Nizam of
Hyderabad that, setting aside their differences, they had agreed to
make common cause with the Mahrattas ao:ainst the Eno^lish. The
Nizam from the first does not seem to have been in earnest, and not
much difficulty was found in detaching him from the alliance. But
Haidar, who cherished an implacable hatred against the English for
their abandonment of him in 1772, was burning for revenge ; and as
he had taken advantage of the war between the English and the
Mahrattas in Western India to consolidate his power and to extend
the boundaries of his kingdom, he was now a still more formidable
antagonist than in the first Mysore war. In 1780, having completed
his preparations for attack, he made a sudden descent upon the
Carnatic, and laid waste the country with fire and sword -up to
within fifty miles of Madras. The Government, with its wonted short-
sightedness, had made no preparation for such a contingency, and
though all available troops were at once ordered out, only a
wretchedly inadequate force could be got together. When all
arrangements were complete. Sir Hector Munro with 5000 men took
the field against Haidar, while Colonel Baillie marched with 2800 men
to occupy Guntur. A fatal mistake was made in dividing up so small a
force ; for Haidar, getting between the two intercepted Baillie,
overwhelmed him, and took him prisoner. Munro, now old and
feeble, and but a shadow of his former self, on learning of the
disaster and fearing that a similar fate would overtake him, at once
retreated to Madras, and left Haidar unchecked, to spread ruin and
desolation far and wide over the fertile country of the Carnatic. Sir
Eyre Coote despatched to Madras. — When Hastings received the
news of this serious reverse he began at once with his accustomed
calmness and energy to devise means of retrieving it. It was a
difficult task, for the war in the Western Presidency had almost
drained his resources. But he was as usual equal to the occasion,
and within three weeks the veteran Sir Eyre Coote was despatched
to Madras with all available men and money, and with orders to
suspend the incompetent governor who had so recklessly involved
his presidency in ruin. Haidar in the meantime
220 HISTORY OF^ INDIA FOR HIGH SCHOOLS. had laid
siege to and captured Arcot, and was causing untold loss and
suffering in all directions by his raids ; while his son Tippu was
vigorously assaulting Wandewash, and its reduction appeared
imminent. Defeat of Haidar. — For four months Coote was obliged to
remain inactive for want of provisions, while Haidar ravaged the
country to his heart's content. Then he struck a sudden and decisive
blow, catching Haidar with the bulk of his forces at a place called
Porto Novo. The battle raged for six hours, and Haidar, after losing
10,000 men upon the field, was forced to fly. The news of the
victory caused Tippu to relinquish the siege of WandcAvash, and
completely changed the aspect of affairs. But Haidar was not yet
vanquished ; for, quickly gathering together a large force he attacked
Coote at Pollilor. Again he suffered a crushing defeat ; but, rallying
once more, he threw himself a third time upon Coote at Solinghar.
After a stubDornly contested fight, he was there finally overcome
and forced to retreat to the south, September, 1781. But his son
Tippu still kept the field, and soon after succeeded in cutting off and
overwhelming a force under Colonel Braithwaite operating on the
western side. Capture of Negapatam. — The English, though
successful both against the Mahrattas and Haidar, were not yet by
any means secure. Haidar was hardly in worse plight than
themselves ; for they were nearly ruined by the cost of their wars,
and the Mahrattas, though worsted, were still dangerous. To make
matters worse, in the ^atter half of 1781, the French and the Dutch,
who were at war with England, came forward with offers of
assistance to the enemies of the English in India. But far from being
overwhelmed by misfortunes, the greater the dangers and
difficulties, the greater grew Hastings's spirit and the stronger his
determination. The Dutch, who had been encouraging Haidar to
continue the war, had soon good cause to rue their interference ; for
they were attacked by land and sea in their settlement of
Negapatam, and after a short resistance, forced to yield up the place
with all the stores and ammunition they had been accumulating
there. Critical situation of the British. — Early in the next year a
French fleet under a distinguished naval commander.
GOVERNOR-GENERALS OF BRITISH INDIA. 221 Admiral
SufFren, appeared off the Coromandel coast, bringing help to Haidar
in the shape of men and guns. Indecisive engagements between the
French and English fleets followed ; but the French managed to land
3000 men at Porto Novo, while the English, under Admiral Hughes,
although getting slightly the best of the encounters, suffered so
much from the effects of a storm that they were obliged to put into
Madras to refit. Affairs on shore were no better ; for Sir Eyre Coote
quarrelled with Lord Macartney, the new governor, and resigning his
command returned to Bengal. The outlook was indeed gloomy
towards the end of 1782. Haidar was recovering from his defeats
and had with him now a large contingent of French soldiers ; and
the Mahrattas, on the western side, though they had been worsted
in every engagement, still kept the field, and had lately mustered in
such overwhelming numbers in front of Goddard that they had
compelled him to retire. Madras was famine stricken, partly from
natural causes and partly owing to Haidar 's devastating raids.
Bengal alone was free from trouble; but its revenues were well nigh
exhausted by the calls which the 'other Presidencies had made upon
it to carry on their wars. Death of Haidar and treaty of Salbai— But
just when things were at their worst, news arrived that Haidar who
was now more than 80 years of age, had died at his capital on the
7th December, 1782, from the effects of a carbuncle. His death
coming so unexpectedly caused a profound impression. Some idea
of the influence which he had exercised on Indian politics may be
gathered from the fact that Nana Furnavis and the Poona party,
upon receipt of the news, at once agreed to sign the treaty which
Sindhia, tired of the war, was trying to negotiate with the English.
On the 20th of December, at Salbai, near Sindhia's capital, a treaty
of peace was made between the English and the Mahrattas, under
the terms of which Eaghunath Rao, in consideration of foregoing his
claims to the Peshwaship, received a handsome pension ; the
English retained Salsette ; and the Mahrattas bound themselves not
to admit the French or the Dutch within their dominions. Haidar's
death at such a time was a great stroke of luck for the English. He
was their most implacable enemy, and
222 HISTORY OF INDIA FOR HIGH SCHOOLS. with his
military genius, his large and well equipped army, and the support of
the French, he might have wrested from them the whole of the
Carnatic, had he lived a little longer. He had been a savage and a
ruthless tyrant, ignorant and bigoted, and his subjects, more
especially the Hindus, had groaned under his cruel yoke. But he
must have possessed uncommon powers of organisation ; for h*e
had found Mysore a petty and insignificant principality, and had left
it the most powerful kingdom in the peninsula. Tippu resumes the
war. — Tippu was away on the Malabar coast when the news of his
father's death reached him, and he hurried at once to Seringapatam
to take possession of the vacant throne. He had good reason to
congratulate himself upon his father's thrift ; for, in addition to a
territory which stretched as far north as the Krishna, he came into
possession of three crores of rupees in cash and vast hoards of
treasure in jewels and gold. Tippu, though a man pf energy, had not
his father's abilities ; but he was equally ambitious and
unscrupulous, and had an even blinder hatred of the English. Finding
himself possessed of such vast wealth, with an army of more than
100,000 men at his command, and supported by the French, he was
not inclined to make peace with the English. He therefore hastened
back to the Malabar coast to resume hostilities. General Matthews,
who was . in command of the forces operating on the western side
and had been meeting with continuous siiccess, soon found the
tables turned upon him. Tippu, as Sultan of Mysore, was a very
diiferent person to be reckoned with than as heir-apparent.
Matthews was forced to give up all he had taken, and within a year,
being shut up at Mangalore with no hope of escape, was obliged to
capitulate after a gallant resistance. French support withdrawn from
Tippu. — While Tippu was engaged upon the Malabar coast, the
French under their veteran leader Bussy had managed to land a
large force at Cuddalore to aid him. Things were becoming so
serious that Hastings despatched Sir Eyre Coote again, to Madras to
take up the supreme command. But, two days after landing, the fine
old soldier died. His military career, which throughout had been
almost uniformly brilliant, reached back to the days of Plassey. His
loss at
GOVERNOR-GENERALS OF BRITISH INDIA. 223 such a time
was a great misfortune, for he was dreaded by the enemies of the
English more than any other commander. Stuart, who succeeded
him, was quarrelsome and irresolute, and wasted precious time in
dilatory operations. A crisis again seemed imminent, when the
English were once more saved by their good fortune. News arrived
at this juncture that peace had been made between the English and
the French in Europe. Bussy at once withdrew his troops and
recalled the French officers and men lent to Tippu. Tippu, finding
himself unsupported, and learning that a force under Colonel
FuUerton had entered Mysore and was marching on his capital after
reducing the forts along the way, surlily and with much reluctance
consented to receive envoys of peace from the English. The treaty of
Mangalore. — It was by this time characteristic of the Madras
Government to throw away its advantages, and it need not therefore
be a matter of surprise that, in the midst of Fullerton's victorious
progress, it sent an embassy to Tippu and sued for peace. By the
treaty of Mangalore, 1784, which resulted from these negotiations,
each side agreed to give up all that it had gained by the war, and
Tippu restored to liberty such of his English prisoners as had
survived the misery of their captivity, or had not, like the unfortunate
Baillie and Matthews, actually been murdered in prison. Peace on
such terms with a proud, revengeful and inveterate enemy, who now
despised the English as much as he hated them, could not be
lasting, and Lord Macartney who concluded it must bear the blame
for what followed ; but at any rate it put an end for a time to
hostilities in India, and gave the British time to recover from the
exhaustion resulting from their recent struggles. The untamable
spirit of Hastings. — The Governments of Madras and Bombay had
shown recklessness and incapacity in the conduct of their wars. That
disaster was averted was due to the energy and judgment of
Hastings alone. He had kept them constantly supplied with money
and troops, and, when their own generals proved incompetent, had
even supplied them with able commanders to replace them. He had
never failed them in their hour of need, althougli himself at his wits'
end to find means to
224 HISTORY OF INDIA FOR HIGH SCHOOLS. meet their
calls upon him; all the while, too, he had his own difficulties to
contend with. Francis had never ceased to harass him with his
opposition, and with unflagging malice to misrepresent his motives.
The Court of Directors, which should have supported him with its
confidence, treated him, as he himself says, "with every mark of
indignity and reproach." But no amount of opposition or mortification
could break his indomitable spirit ; instead, his determination to
overcome his difficulties seemed to grow with their accumulation.
His methods of raising money. — Hastings's methods of meeting his
financial embarrassments have been severely blamed ; and as it was
in the main on this account that he was subsequently impeached by
Parliament, we must therefore briefly glance at the more important
of them. The insurrection at Benares. — In 1778, with his council's
approval, he had called upon Chet Singh, the Rajah of Benares, for a
war subsidy of five lakhs of rupees. This was provided without
demur ; but when Hastings the next year made a similar demand,
the Rajah did not comply. It will be remembered that Chet Singh had
been made a tributary of the British by the Council, when the Vizier
of Oudh was made to cede the districts of Ghazipur and Benares to
the Company. As a feudatory he was, by immemorial custom, liable
to aid his sovereign in time of war both with men and money, if
called upon to do so. The contribution was not excessive, and the
Rajah was moreover immensely rich ; but he had heard exaggerated
accounts of the disasters which had overtaken the British in Madras,
and had begun to wonder whether the end of their rule might not be
at hand. He was, therefore, hesitating w hether or not to comply
with their further demands. Hastings determined to teach him a
lesson ; and, as he was on his way to visit the Nawab Vizier of Oudh,
he halted at Benares and demanded from the Rajah fifty lakhs of
rupees as a fine for his dilatoriness, and, further, called upon him to
answer a charge of treasonable correspondence with the enemies of
the British. As the Rajah's reply was unsatisfactory, Hastings, though
Avith but a small escort, ordered his arrest. The Rajah submitted
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

Вам также может понравиться