Download full Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript Lee ebook all chapters
Download full Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript Lee ebook all chapters
com
https://textbookfull.com/product/beginning-ethereum-smart-
contracts-programming-with-examples-in-python-solidity-and-
javascript-lee/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/
textboxfull.com
https://textbookfull.com/product/ethereum-for-architects-and-
developers-with-case-studies-and-code-samples-in-solidity-
springerlink-online-service/
textboxfull.com
https://textbookfull.com/product/ethereum-for-architects-and-
developers-with-case-studies-and-code-samples-in-solidity-1st-edition-
debajani-mohanty/
textboxfull.com
https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-michael-stueben/
textboxfull.com
https://textbookfull.com/product/beginning-programming-with-python-
for-dummies-2nd-edition-john-paul-mueller/
textboxfull.com
Wei-Meng Lee
Beginning Ethereum Smart Contracts Programming:
With Examples in Python, Solidity and JavaScript
Wei-Meng Lee
Ang Mo Kio, Singapore
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
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.
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!
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.
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.
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
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
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
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.
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:
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.
So, the next important questions is – how do you chain the blocks together?
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.
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?
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.
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
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
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.
• A block header
17
Chapter 1 Understanding Blockchain
• Timestamp
• Merkle root
• Nonce
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.
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
And so, we can summarize the types of nodes that we have discussed thus far:
• Full node
• 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
20
Exploring the Variety of Random
Documents with Different Content
"Where is my father, Dorothy?" she asked, feeling as if she
must say something.
"Your father has gone out with the old priest who was here
last night, Mistress Anne," was the short reply.
"How do you know that these saints can hear you? They
were, and are, but finite beings like yourself, and cannot
possibly be present in all places and at all times at once."
And was all this to be given up? Was she to abandon all her
cherished ambitions and be content with the life of a
daughter at home or a mere commonplace mother of a
family? Or, still worse, was she to run the risk of open
shame and disgrace and punishment, of being despised and
held up as a warning, instead of an example, by those over
whom she had hoped and expected to rule? Was she to
confess that all her righteousness, her prayers and
penances and sufferings, were worse than worthless in
God's sight, and receive the gift of salvation as a free,
wholly undeserved alms? Was her only title to heaven to
consist in the fact, not that she was a saint, but a sinner? It
could not be true—it should not be true! It was a work of
the devil tempting her to abandon her vocation and all the
great things she had planned.
And then came the thought—was it not her own fault after
all? Had she not by weakly yielding to family affection—
those fleshly ties from which she had been told again and
again she must tear herself loose—had she not given the
Tempter a handle against her? Ought she not to do all in
her power to prevent the spread of heresy, and had she not,
by yielding to her regard for her only brother, and
concealing his fault, made herself a partaker therein? Would
not her peace of mind return, if she were once to make the
sacrifice? Would not that sacrifice be an additional and most
precious jewel in the crown of martyrdom she coveted?
Father William had set out only the day before his return,
on a visit to London, and there was too much reason to fear
that by the connivance of friends, he might escape to
Germany. But here was a notable prey to be taken at once,
and he was not the man to let the grass grow under his
feet. He commended Anne for her faithfulness, though he
gave her less praise and paid less attention to the rest of
her confession than she thought she deserved. However, he
told her she had taken the best means to get rid of her
trouble of mind, and confirmed her in the idea that it had all
been owing to her having wickedly concealed her brother's
errors. A watch was at once set upon Jack's movements,
and he was apprehended, as we have seen.
Lo! Her enemy was there awaiting her, armed with tenfold
power.
She had done the deed. She had betrayed her brother to
shame and death, she had incurred her father's hatred and
curse, which was withheld only for the sake of his son; and
all for what? Was she any nearer to the quiet of mind she
had so ardently desired? She did not find it so. Instead
thereof, her doubts returned with tenfold power. They were
no longer doubts, they were certainties—demonstrated
truths. She did not reason upon them; she could not.
She felt, rather than knew, that it was Jack who was the
martyr for the truth, and she was the Judas who had
betrayed him. She had denied her Lord, belied her own
conscience, and sacrificed her family to a monstrous lie.
What would she not have given to recall the events of the
last few hours? But it was too late—forever too late; and
the thought filled her with inexpressible anguish and
despair.
Anne rose at last from the floor, where she had thrown
herself at the foot of the crucifix, and in the sheer
restlessness of misery wandered into Jack's room. There
were all his treasures; his strings of birds' eggs, his shells
and other foreign curiosities derived from traders and
sailors, his Latin books and exercises. The blackbird and
squirrel he had brought from the country were hopping
about their cages, and seemed to wonder why they were
neglected. Anne took down the cages and ministered to the
wants of the occupants. The action, simple as it was,
seemed to bring her some relief, and as the blackbird tuned
up its mellow whistle, she leaned her head beside the cage,
and wept long and bitterly.
CHAPTER XXII.
THE TRIAL.
Jack was hurried into the jail and the doors shut upon him,
so he heard no more, but he noted even then the look of
furious wrath mingled with confusion on Father Barnaby's
face. He had no time for further observations before he
found himself pushed into the cell of which the jailer had
spoken, and the door locked upon him.
"My son, my son!" cried the old man. "Is it indeed my son?
I feared this, but hoped you might have timely warning.
And is it to this I have brought thy youth?"
"Alas! Poor maid, was she so far left to herself?" said the
shepherd, when he heard of Anne's part in the transaction.
"We must put up many prayers for her. And how is your
father disposed?"
"He gave me his blessing ere I left him, and do not think he
is angry with me. I left him with old Father John, who rode
all the way from Holford to give me warning, but he was too
late. But how were you taken, dear uncle?"
"But surely Sir John Brydges will take your part?" said Jack.
"But here comes the jailer with our bread and water."
"Don't cry out before you are hurt, young sir," said the
jailer, depositing a jug of broth on the table. "I have so far
stretched my orders as to bring you the same breakfast as
the other prisoners who are only confined for highway
robbery, murder, and the like."
"I would you were at liberty to do it," said the jailer bluntly.
"This turning the key on old friends and neighbors is no
pleasure to me, I can tell you. What then? A man must do
his duty, be he jailer or mayor; but he need not have a
heart as hard as the nether millstone. I judged you and the
old man would like to be together, so I clapped you in here;
but do not you tell yonder monk so."
"Never fear," said Jack. "I do not love him so well as all
that. Again I thank you, Master Davis, and so will my father.
Be assured you shall be no loser. Come, we are better than
we might be," said he after the man had closed the door. "I
am heartily glad we have fallen into such good hands. Shall
we awaken our companion? He sleeps soundly."
"He has not slept all night," said Thomas Sprat. "I fear
much he will not stand the trial. The goods and ties of this
world are over-near his heart, poor man. What, brother!
Will you awake and break your fast?"
"Where am I?" said Master Dennett, sitting up and gazing
round him with a bewildered expression. "What has
happened? Alas, I know too well!" he added, sinking back
again. "That I should ever live to find myself here in
Bridgewater jail! And who is this new companion in misery?
Surely, it is Master Lucas's son. Alas, young man, what has
brought you hither?"
"The fear of God and the love of His Word," said Jack. "But
come, sir, arise and eat, that you may be strengthened for
the day's trial."
Master Dennett lay on his pallet and wept over his hard
fate.
"The good, kind, old man!" said Thomas Sprat. "I know not
what he can do, and yet I thank him with all my heart. I
would not have believed anything would lead him to make
such an exertion. For myself, I hope nothing in this world
save a speedy passage out of it, and that my age gives me
warrant to expect: but I would gladly have you, my son,
saved from the fiery trial, if it might be done without your
denying the faith."
"Ay, but those words were not spoken to men like us," said
Master Dennett. "They were spoken to apostles and saints."
"And what were the apostles and saints but common simple
men like to us?" asked Thomas Sprat. "Are not all God's
children called to be saints, and does He not promise the
same grace freely to all if we are but faithful?"
"It is indeed hard for flesh and blood," said the old man.
"The spirit is willing, but the flesh is weak. We will pray for
and with you, brother, that you may have strength in the
evil day."
"Nobody led me into it, good Master Davis," said Jack. "I
thank you heartily for bringing me these things. Have you
heard whether we are to be brought to trial this day?"
"I cannot but hope so," replied Jack, "if only for her own
sake. I have all the time thought she was fighting against
her inward convictions. Poor maiden! I forgive her with all
my heart. I suppose I had better destroy this writing,
though I should love to keep it."
"Destroy it by all means," said the shepherd hastily, "lest it
bring the poor girl into trouble."
The whole of that day Jack was left alone. It was the
longest day of his life. The little book which Anne had so
strangely sent him was his greatest comfort, and he read till
his eyes ached with the dim light, striving to impress on his
memory the words of the sacred text, lest the book should
be found and taken from him.
"And will you not let me see my uncle again?" Jack asked.
"The old man is not here, but confined in the room in the
church tower yonder. Fare you well."
When Jack was left alone, he sat down on his bedside like
one stunned. Burned! That good, innocent old man! That
one whom he loved like a father—who had been truly, and
not in mere name, a spiritual father to him. Burned alive!
And he was to see it! There was no escape. He was in hands
which knew not how to show mercy, and which would never
spare him one pang.
The priest put down the lantern he carried, and sat himself
down on the pallet opposite to Jack, as if prepared to enter
into conversation. Jack quietly waited for him to begin.
Jack assented.
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.
textbookfull.com