Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and Javascript, 2Nd Edition Wei-Meng Lee
Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and Javascript, 2Nd Edition Wei-Meng Lee
Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and Javascript, 2Nd Edition Wei-Meng Lee
com
https://ebookmeta.com/product/beginning-ethereum-smart-
contracts-programming-with-examples-in-python-solidity-and-
javascript-2nd-edition-wei-meng-lee/
OR CLICK BUTTON
DOWLOAD NOW
https://ebookmeta.com/product/beginning-swift-programming-1st-
edition-wei-meng-lee/
https://ebookmeta.com/product/building-games-with-ethereum-smart-
contracts-intermediate-projects-for-solidity-developers-kedar-
iyer/
https://ebookmeta.com/product/blockchain-and-ethereum-smart-
contract-solution-development-dapp-programming-with-solidity-1st-
edition-weijia-zhang/
https://ebookmeta.com/product/cambridge-igcse-and-o-level-
history-workbook-2c-depth-study-the-united-states-1919-41-2nd-
edition-benjamin-harrison/
Solidity Programming Essentials: A guide to building
smart contracts and tokens using the widely used
Solidity language 2nd Edition Ritesh Modi
https://ebookmeta.com/product/solidity-programming-essentials-a-
guide-to-building-smart-contracts-and-tokens-using-the-widely-
used-solidity-language-2nd-edition-ritesh-modi/
https://ebookmeta.com/product/hands-on-smart-contract-
development-with-solidity-and-ethereum-from-fundamentals-to-
deployment-1st-edition-kevin-solorio/
https://ebookmeta.com/product/beginning-programming-with-python-
for-dummies-2nd-edition-john-paul-mueller/
https://ebookmeta.com/product/beginning-programming-with-python-
for-dummies-2nd-edition-john-paul-mueller-2/
https://ebookmeta.com/product/beginning-programming-with-python-
for-dummies-3rd-edition-john-paul-mueller/
Beginning Ethereum
Smart Contracts
Programming
With Examples in Python, Solidity,
and JavaScript
Second Edition
Wei-Meng Lee
Beginning Ethereum Smart Contracts Programming: With Examples in Python,
Solidity, and JavaScript
Wei-Meng Lee
Ang Mo Kio, Singapore
Introduction�����������������������������������������������������������������������������������������������������������xvii
iii
Table of Contents
iv
Table of Contents
v
Table of Contents
vi
Table of Contents
viii
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 361
ix
About the Author
Wei-Meng Lee is the founder of Developer Learning
Solutions, a technology company specializing in hands-on
training of blockchain and other emerging technologies.
He has many years of training expertise and his courses
emphasize a learn-by-doing approach. He is a master at
making learning a new programming language or technology
less intimidating and more fun. He can be found speaking
at conferences worldwide such as NDC, and he regularly
contributes to online and print publications such as Medium
(https://weimenglee.medium.com) and CoDe Magazine.
He is active on social media, on his blog calendar.learn2develop.net, on Facebook
(www.facebook.com/DeveloperLearningSolutions), on Twitter as @weimenglee, and
on LinkedIn (linkedin.com/leeweimeng).
xi
About the Technical Reviewer
Prasanth Sahoo is a Blockchain Certified Professional,
Professional Scrum Master, and Microsoft Certified
Trainer who is passionate about helping others
learn how to use and gain benefits from the latest
technologies. He is a thought leader and practitioner
in blockchain, cloud, and Scrum. He also handles the
Agile methodology, cloud, and blockchain technology
community initiatives within TransUnion through
coaching, mentoring, and grooming techniques.
Prasanth is an adjunct professor and a technical speaker. He was selected as a speaker
at the China International Industry Big Data Expo 2018 by the Chinese government and
also to the International Blockchain Council by the governments of Telangana and Goa.
He also received accolades for his presentation at China International Industry Big Data
Expo 2018 by the Chinese government. Prasanth has published a patent titled "Digital
Educational Certificate Management System using IPFS Based Blockchain."
To date, Prasanth has reached over 50,000 students, mostly within the technical
domain. He is a working group member of the CryptoCurrency Certification
Consortium, Scrum Alliance, Scrum Organization, and International Institute of
Business Analysis.
xiii
Acknowledgments
Writing a book is immensely exciting, but along with it comes long hours of hard work
and responsibility, straining to get things done accurately and correctly. To make a book
possible, a lot of unsung heroes work tirelessly behind the scenes.
For this, I would like to take this opportunity to thank a number of special people
who made this book possible. First, I want to thank my acquisitions editor, Joan Murray,
for giving me this opportunity. Thanks for suggesting that I update this book with the
latest happenings in the crypto world!
Next, a huge thanks to Jill Balzano, my associate editor, who was always very patient
with me, even though I missed several of my deadlines for the revision of this book.
Thanks, Jill, for your guidance. I could not finish the book without your encouragement
and help!
Equally important is my project coordinator, Shobana Srinivasan. Shobana has been
very patient with me during the whole project while I struggle between work and writing.
Thanks, Shobana, for the assistance rendered during the project!
Last, but not least, I want to thank my parents and my wife, Sze Wa, for all
the support they have given me. They have selflessly adjusted their schedules to
accommodate my busy schedule when I was working on this book. I love you all!
xv
Introduction
Welcome to Beginning Ethereum Smart Contracts Programming, Second Edition!
This book is a quick guide to getting started with Ethereum smart contracts
programming. It starts off with a discussion of blockchain and the motivations behind it.
You will learn what a blockchain is, 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. Since the publication of the
first edition of this book, a lot of things have changed. In particular, Ethereum has been
updated to use Proof of Stake (PoS) (instead of Proof of Work) as its consensus algorithm.
This book has been updated to include a discussion of how PoS works.
Once that is out of the way, you dive into the Ethereum blockchain. You will learn
how to use an Ethereum client (Geth) to create a private Ethereum blockchain and
perform simple transactions such as sending Ethers to another account.
The next part of this book discusses smart contract programming, a unique feature of
the Ethereum blockchain. You will jumpstart 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 should be able to write smart contracts, test them, deploy them, and create web
applications to interact with them. In this second edition, I have added more examples
to make it easy for you to explore more complex smart contracts.
The last part of this book touches on tokens and DeFi (decentralized finance),
something that has taken the cryptocurrency market by storm. You will be able to create
your own tokens, launch your own ICO, and write token contracts that allow buyers
to buy tokens using Ethers. As a bonus, I show you how to write a DEX (decentralized
exchange) smart contract to exchange two different tokens!
This book is designed 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 enjoy working on the sample projects as much as I enjoyed creating them!
xvii
CHAPTER 1
Understanding the
Science Behind
Blockchain: Cryptography
The reason you are reading this book is because you want to understand what a
blockchain is, how it works, and how you can write smart contracts on it to do cool
things. And while I perfectly understand that you are excited to get started in this first
chapter, we need to take a step back and look at one fundamental technology that makes
blockchain possible: cryptography.
In this chapter, I will explain what cryptography is, the different types of
cryptographic algorithms, how they work, and how they play a vital role in the world
of blockchain. I will also show you how to experiment with the various cryptographic
algorithms using the Python programming language. Even if you are familiar with
cryptography, I suggest scanning through this chapter so that you have a firm foundation
for the subsequent chapters.
What Is Cryptography?
Whether you are trying to build a web application to store users’ credentials or writing
a network application to securely transmit encrypted messages, or even trying to
understand how blockchain works, you need to understand one important topic:
cryptography.
So, what exactly is cryptography? Put simply, cryptography (or cryptology) is the
practice and study of hiding information. It is the science of keeping information secret
and safe.
1
© Wei-Meng Lee 2023
W.-M. Lee, Beginning Ethereum Smart Contracts Programming, https://doi.org/10.1007/978-1-4842-9271-6_1
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
One of the simplest and most widely known cryptographic algorithms is the Caesar
Cipher. It is a very simple algorithm in which each letter in the plaintext is replaced by a letter
a fixed number of positions down the alphabet. Consider the example shown in Figure 1-1.
As you can observe, each character in the alphabet is shifted down three positions.
A becomes D, B becomes E, and so on. If you want to send a sentence (known as the
plaintext), say ATTACK, to your recipient, you map each of the characters in the sentence
using the above algorithm and derive the encrypted sentence (known as the ciphertext):
DWWDFN. When the recipient receives the ciphertext, they reverse the process to obtain
the plaintext. While this algorithm may seem impressive (especially in the early days
of cryptography), it no longer works as intended as soon as someone knows how the
messages are encrypted. Nevertheless, this is a good illustration of the attempt by early
inventors of cryptography to hide information. Today, the cryptographic algorithms we
use are much more sophisticated and secure.
In the following sections, I will explain the main types of cryptographic functions
and how they are used.
Types of Cryptography
There are three main types of cryptography:
• Hash functions
• Symmetric cryptography
• Asymmetric cryptography
In the following sections, I will go through each of the above types in more detail.
2
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Hash Functions
Hashing is the process in which you convert a block of data of arbitrary size to a
fixed-size value. The function that performs this process is known as a hash function .
Figure 1-2 shows the hashing process.
Tip A commonly-used hash function is SHA256. SHA stands for Secure Hash
Algorithms.
For example, the SHA256 hash function converts a block of text into a 256-bit
hash output. The resultant hash is usually written in hexadecimal, and since each
hexadecimal takes up 4 bits, a 256-bit hash will have 64 characters. To experience how
hashing works, go to https://emn178.github.io/online-tools/sha256.html, type in a
sentence, and observe the result (see Figure 1-3).
3
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
• Deterministic: The same block of text will always produce the same
hash output.
Another important feature of hashing is that a single change in the original text will
cause a totally different hash to be generated. This is also known as the avalanche effect.
For example, a change in a single character in the input shown in Figure 1-4 will have a
totally different output.
4
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Figure 1-4. A single change in the input will cause a totally different output hash
Uses of Hashing
Hashing fulfils some very important roles in computing. For one, websites use hashing
to store your password, instead of storing it in plaintext. Storing your password as hashes
prevents hackers from reversing the hashes and obtaining your original password (which
may very likely be used on other websites as well).
Hashing also plays a very crucial role in blockchain, where each block is “chained”
to the previous block using the hash of the previous block. Any modifications to a block
will invalidate the hash stored in the next block, and the rest of the blocks will hence be
invalid.
Tip Some commonly used hashing algorithms are MD5, SHA256, SHA512, and
Keccak-256.
5
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Note To install Python on your computer, the easiest way is to download the
Anaconda package (www.anaconda.com/products/distribution). If you do
not want to install Python on your computer, you can use Google Colab
(https://colab.research.google.com).
In Python, you can use the hashlib module to perform hashing. The following code
snippet uses the sha256() function to perform hashing on a string:
import hashlib
result = hashlib.sha256(
bytes("The quick brown fox jumps over the lazy dog",'utf-8'))
Note that the string to be hashed must be passed to the sha256() function as a
byte array. And so you use the bytes() function to convert the string into a byte array.
Alternatively, in Python, you can prefix the string with a b to denote a bytes string literal:
result = hashlib.sha256(
b'The quick brown fox jumps over the lazy dog')
The sha256() function returns a sha256 hash object. To get the resultant hash in
hexadecimal, you can call the hexdigest() function of the sha256 hash object:
print(result.hexdigest())
d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
If you make a small change to the original string, the output is drastically different
from the previous hash:
result = hashlib.sha256(
b'The quick brown fox jumps over the lazy dag')
print(result.hexdigest())
# output:
# 559cc2cb0e1998182b4b6343e38611b3757e8a6279d43e9914d74dfb7e7089e6
6
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Symmetric Cryptography
In symmetric cryptography, you use the same cryptographic key (commonly referred to
as the shared key) for both the encryption of plaintext and the decryption of ciphertext.
Figure 1-5 shows the use of the shared key for both encryption and decryption.
Symmetric cryptography is fast and simple, but the main problem is how to ensure
that the key is kept secret. For example, if Tom wants to send a secret message to Susan,
Tom can encrypt the message using the shared key and Susan can decrypt the encrypted
message using the same shared key. The problem here is how can Tom securely send
Susan the shared key? Can Tom email Susan? Send it through SMS or WhatsApp? How
about through the traditional post office? All these methods are not absolutely safe and
are subject to eavesdropping. Moreover, there is this popular saying, “Three may keep a
secret if two of them are dead.” This means, if more than one person knows the secret, it
is no longer a secret.
Having said that, symmetric cryptography has its uses and applications. It is useful
when you want to protect your private data. For example, say you have some confidential
data on your computer that you want to prevent others from seeing. Using symmetric
cryptography, you can encrypt and decrypt the data using the same key, which is only
known to you and no one else.
7
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Let’s generate a shared key in Python. To do so, use the Fernet class:
The generate_key() function returns a shared key in binary format and it is base64
encoded.
8
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
You can then use the encrypt() function to encrypt your data:
Then, create an instance of the Fernet class using the shared key and call the
decrypt() function to decode the ciphertext:
9
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Asymmetric Cryptography
Unlike symmetric cryptography, which uses a single shared key, asymmetric
cryptography uses a key-pair, one public and one private.
A public key algorithm generates two keys that are mathematically linked:
• One public and one private: The public key, as the name implies,
should be made public. The private key, on the other hand,
absolutely must be kept a secret.
• You can encrypt data with a public key and decrypt with the private
key. For example, if Tom wants to send a secret message to Susan,
Tom could encrypt the message using Susan’s public key and only
Susan can decrypt the secret message with her private key.
• You can encrypt data with a private key and decrypt with the public
key. At first, this sounds counterintuitive. If one could decrypt using
the public key (which is supposed to be public), what’s the point of
this? Actually, this is useful. Suppose Tom encrypts a message using
his own private key and sends it to Susan. When Susan receives
the message, she can try to decrypt it using Tom’s public key. If the
message can be decrypted, this means that the message has not been
tampered with and that it indeed comes from Tom. On the other
hand, if the message has been tampered with, Susan would not be
able to decrypt the message using Tom’s public key. This technique is
used in creating a digital signature.
10
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Figure 1-6 shows the first approach, that of encrypting the data using the public key
and then decrypting it using the private key.
Figure 1-6. Encrypting data using the public key and then decrypting the
ciphertext using the private key
Figure 1-7 shows the second approach of encrypting the data using the private key
and then decrypting it using the public key.
11
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Figure 1-7. Encrypting data using the private key and then decrypting the
ciphertext using the public key
12
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
In this code snippet, you are using the RSA algorithm to first generate a private key.
Using the private key, you can then derive its corresponding public key. Once the keys
are generated, it’s useful to serialize (flatten) them to files:
13
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
14
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
15
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
• The hash is then encrypted using the private key and turned into a
digital signature (this also includes the information on the hashing
algorithm used).
• The original text, together with the digital signature, are then sent to
the recipient. This is known as the signed message.
Figure 1-9 shows what happens when the signed message is received by the
recipient.
• When the signed message is received, the receiver uses the sender’s
public key to decrypt the hash from the digital signature.
• The receiver also hashes the received text and compares it with the
hash that was decrypted in the previous step.
• If the two hashes match, this means the text has not been
tampered with.
16
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
private_key.encrypt(...) # ERROR
# AttributeError: '_RSAPrivateKey' object has no attribute 'encrypt'
import base64
Here you use the private key to sign the message. The sign() function returns the
digital signature of the string. It returns the digital signature as a byte array, and in the
above code snippet you encode it using base64 encoding and then converted it to string.
The output looks like this:
aNUZixxLUiRRpDjm+nqkcaZo5URklvIA/hiSECR+DoLmS+oVb650Ic5/vg6ADmCvi91CSwiXRY
kknDBEr2qTWaK+Fe9UPqukDFx8WwyW7K2NacjS8TiKqAfPPSH4t2l9ohexwTqfih9oZXli57zf
Z4LKaY63iQxXlWKE9S5OZ0hWyGUfygEInY8OZerGKWFnmxuXHjWNCpDmzSngP04MYBBnfoPVps
Dg7vgKL0gpaz1dn2Qg+Ra2GFLmznqjYKq2qP43zLrdYSmzH3MmPAkO0AIh8XaRnHc+q0XYyUGhT
Bm9iIa7rS8eYaB7MD9G18j0HA7lWWVQjqujnFCQNm8Npg==
When you transmit the message (plaintext), you also send the digital signature
along with it.
17
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
try:
public_key.verify(
signed,
plaintext, # from the previous section
padding.PSS(
mgf = padding.MGF1(hashes.SHA256()),
salt_length = padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
print('Signature is valid!')
except InvalidSignature:
print('Signature is invalid!')
Note that you have to catch the exception raised by the verify() function. If there is
no exception, the signature is deemed to be correct; otherwise, it is invalid.
18
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
The following sections discuss how the various cryptographic algorithms are used in
blockchain. If you are new to blockchain, feel free to skip the following sections and read
the next chapter. Come back to the next few sections after you have read the following
chapters:
• Chapter 2: Hashing is used to “chain” the blocks in a blockchain.
H
ashing
As mentioned briefly, hashing is used to “chain” the blocks in a blockchain. Each block
in a blockchain contains the hash of the previous block. Doing so allows you to ensure
that data recorded on the blockchain are immutable and thus prevent tampering.
Another good use case of hashing is when storing data on the blockchain. Since all
data on public blockchains are open to scrutiny, you should not store private data on the
public blockchain. If you need to store private data on a public blockchain for proofing
purposes, you should instead store the hash of the data, since it is not reversible.
Chapter 7 provides a good example of this.
19
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Using this private key, a public key is generated using ECDSA (Elliptic Curve Digital
Signature Algorithm). This public key is then used to generate the account address using
the Keccak256 hashing algorithm. The last 20 bytes of this output is used as the address
of the account.
At the same time, remember that when you create an account you must supply
a password. This password is used to encrypt your private key using symmetric
cryptography.
D
igital Signature
In blockchain, a digital signature is used when creating transactions. In Chapter 4, you
will learn how to create a simple transaction by sending some Ethers from one account
to another.
When you create a transaction, the transaction is signed using your account’s private
key to derive the digital signature. The digital signature, together with the details of the
transaction, are then broadcasted to the various miners/validators in the blockchain
network (see Figure 1-11).
20
Chapter 1 Understanding the Science Behind Blockchain: Cryptography
Figure 1-11. A digital signature is created for a transaction to prove the identity of
the creator
S
ummary
In this chapter, you learned about the main science behind blockchain: cryptography.
You learned about hashing, symmetric cryptography, and asymmetric cryptography. If
you are familiar with Python, I strongly suggest you try out the code samples so that you
get first-hand experience with the various cryptographic algorithms. With that, you are
now ready to dive into the world of blockchain. See you in Chapter 2!
21
CHAPTER 2
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, you will explore the concept of
blockchain, how the concept was conceived, and what problems it aims to solve. By the
end of this chapter, the idea and motivation behind blockchain will be crystal clear.
Tip For the clearly impatient, a blockchain is a digital transaction of records that
is arranged in chunks of data called blocks. These blocks link with each other
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
common 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!
23
© Wei-Meng Lee 2023
W.-M. Lee, Beginning Ethereum Smart Contracts Programming, https://doi.org/10.1007/978-1-4842-9271-6_2
Chapter 2 Understanding Blockchain
Placement of Trust
All of this boils down to one key concept: the placement of trust. And that is, we place
our trust in a central body. Think about it. In our everyday life, we place our trust in
banks and we place our trust in our governments.
Even for simple mundane day-to-day activities, we place our trust in central bodies.
For example, when you go to the library to borrow a book, you trust that the library will
maintain a proper record of the books 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 $10 bill for two cups of coffee. Another person offers to pay you
for the two cups of coffee using a handwritten note saying he owes you $10. Which one
would you trust? The answer is pretty obvious, isn’t it? Naturally you would trust the
$10 bill as opposed to the handwritten note. This is because you understand that you
can use the $10 bill elsewhere for other goods or services and that it is backed by the US
government. In contrast, the handwritten note is not backed by anyone, except perhaps
the person who wrote it, and hence it has literally no value.
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 shown in Figure 2-1.
24
Chapter 2 Understanding Blockchain
Would you accept the currencies 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. Then you consider your trust
in these governments. You might have read in the news about the hyperinflation in these
two countries, and that these currencies might not retain their value over time. So, would
you accept these currencies as payment?
Trust Issues
Earlier, 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 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 you saw 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.
25
Chapter 2 Understanding Blockchain
This brings us to the next key issue: even though people trust institutions,
institutions can fail. And when people lose trust in institutions, people turn to
cryptocurrencies. In the next section, I will discuss how to solve the trust issues using
decentralization, a fundamental concept behind cryptocurrency.
Example 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 2-2).
26
Chapter 2 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 people.
To solve this issue, they decided to appoint one person, say B, to keep a ledger of the
whereabouts of each DVD (see Figure 2-3).
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 can easily modify the ledger to
erase the record of DVDs that he has borrowed. So, there must be a better way.
Then someone has an idea! Why not let everyone keep a copy of the ledger?
Whenever someone borrows or lends a DVD, the record is broadcast to everyone, and
everyone records the transaction. See Figure 2-4.
27
Chapter 2 Understanding Blockchain
So now the record keeping is decentralized. Three people now hold the same ledger.
But wait a minute. What if A and C conspire to change the ledger 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 people 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 DVD-sharing business (see Figure 2-5).
28
Chapter 2 Understanding Blockchain
Figure 2-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 in the ledger. In
order to alter a record, it would need to involve a number of people to do so all at the
same time, which is a time-consuming affair. And this is the key idea behind a distributed
ledger, commonly known as blockchain.
29
Chapter 2 Understanding Blockchain
Figure 2-6. Transactions form a block, and blocks are then chained
30
Chapter 2 Understanding Blockchain
Figure 2-7. Every blockchain has a beginning block known as the genesis block
The blocks are connected to each other cryptographically, the details of which
I 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?
Tip Chapter 1 discussed hashing in more detail. Be sure to read it first before
continuing with this section.
31
Chapter 2 Understanding Blockchain
Recall that 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.
A hash function has the following characteristics:
You are now ready to learn 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 2-8). This way, if any transaction in a block is altered, this will invalidate the
hash of the current block, which is stored in the next block, which in turn invalidates the
hash of the next block, and so on.
32
Random documents with unrelated
content Scribd suggests to you:
kuitenkin lietsoo halua? Hupsu, hupsu, kun sysäät luotasi onnen
mahdollisuuden!»
Petersille menevä kirje oli valmis, mutta vielä oli jälellä vaikeampi
kirje, joka hänen oli lähetettävä vaimolleen — jonka kirjoittaminen
häntä peloitti, mutta jonka hän silti kiihkeästi halusi lähettää. Se
saapuisi perille vasta hänen kuolemansa jälkeen, jonka hän varmasti
uskoi hänet saavuttavan ja jota hän hartaasti rukoili, ja paljastaisi
Gillianille koko hänen entisyytensä salaisuuden ja hänen
intohimoisen rakkautensa, joka oli karkoittanut hänet, arvottoman,
kauaksi vaimostaan. Sillä kaksi vuotta kestäneiden seikkailujen ja
vaarojen aikana ei kuolema ollut koskaan näyttänyt niin uhkaavan
läheiseltä kuin nyt, ja ennen kuolemaansa hän tahtoisi saada tämän
ainoan tyydytyksen — hän rikkoisi vaitiolon, joka oli syövän tavoin
jäytänyt hänen sieluaan. Vihdoinkin saisi Gillian tietää kaikki, mistä
hän ei ollut milloinkaan rohjennut puhua, hänen toivottoman
rakkautensa, hänen katumuksensa ja häpeänsä, hänen kiihkeän
halunsa tehdä vaimonsa onnelliseksi.
Hän oli kahdesti ennen käynyt heimon parissa sheikki Mukair Ibn
Zarrarahin nuoremman pojan, Pariisissa kohtaamansa
spahiupseerin vieraana, ja hänelle osoitettu lämmin vierasystävyys
oli tehnyt häneen syvän vaikutuksen. Äkillinen, selittämätön halu oli
vetänyt hänet uudelleen tänne, missä hän oli viettänyt muutamia
elämänsä onnellisimpia kuukausia. Hänessä oli herännyt voimakas
ihailu vanhaa, juroa arabialaispäällikköä ja hänen kahta perinpohjin
erilaista poikaansa kohtaan; vanhempi heistä oli totinen, tavallisesti
harvapuheinen mies, noudatti vanhoja perinnäistapoja
oikeauskoisen muhamettilaisen jäykän sitkeään tapaan, vihasi
ranskalaista oikeudenkäyttöä, jonka alaisena hänen oli pakko elää,
ja uhrasi kaiken aikansa heimon asioihin ja kauniille, palvotulle
vaimolleen, joka oli yksin hänen haareminsa valtiattarena, vaikka ei
ollutkaan lahjoittanut hänelle lasta; nuorempi oli ihan päinvastoin
kuin veljensä komea-asuinen, perin nykyaikainen nuori arabialainen
ja yhtä innokas ranskalaisten pyrkimysten kannattaja kuin Omar oli
niiden vastustaja. Varakas ja mahtava sheikki, jonka ystävyyteen
ranskalaiset hallintoviranomaiset olivat uutterasti pyrkineet
taatakseen itselleen hänen heimonsa tuen, sillä sen vaikutusvalta
ulottui laajalle ja se olisi saattanut osoittautua vaaralliseksi tekijäksi
levottomassa piirissä, kannatti sydämessään esikoisensa tunteita,
mutta viisaampana, laajanäköisempänä ja harkitsevampana oivalsi,
kuinka suotavaa oli, että ainakin yksi hänen sukunsa jäsenistä oli
läheisessä yhteydessä hallituksen kanssa, joka hänen oli pakko
tunnustaa, vaikka hän tekikin sen nurkuen ja puolittain halveksivasti.
Kauan hän oli ollut kahdella päällä ennakkoluulojen ja poliittisen
viisauden taistellessa vallasta hänen mielessään, ennenkuin oli
vastahakoisesti suostunut siihen, että Said merkittiin spahirykmentin
luetteloihin. Ja veljesten välinen harvinaisen voimakas rakkaus oli
kestänyt kokeen, joka olisi saattanut olla liian ankara sen
jatkumiselle; Omar oli alistunut itsevaltaisen päällikkövanhuksen
päätökseen eikä ollut edes huomauttanut asiasta mitään, ja Said
taas oli innostaan huolimatta huolellisesti varonut lietsomasta
ilmiliekkiin veljensä syvälle juurtunutta vihaa sitä kansaa kohtaan,
jota palvellessaan hän itse ylpeili. Hänen suruton luontonsa
mukautui keveästi elämään kahta toisistaan jyrkästi eroavaa elämää,
ja vaikka hän salaisesti pitikin parempina rykmentissään vietettyjä
kuukausia, osasi hän mahdollisimman paljon nauttia loma-ajoistaan,
joiksi hän aina palasi heimon pariin, riisui siellä komean
upseeripukunsa, josta hänen kiihkeä mielensä nautti, salasi
huolellisesti kaikki ranskalaisystävällisten taipumustensa merkit ja
näytteli erittäin tahdikkaasti jonkun verran vastenmielistä osaansa
sheikin nuorempana poikana.
Mutta jos asia olisi ollut toisin — jos hän olisi ollut vapaa
tavoittelemaan Gilliania, koettamaan voittaa hänet omakseen! Hänen
rangaistuksensa lievin puoli ei ollut se, että hän sisimmässään
varmasti uskoi rakkauden uinuvana piilevän Gillianin sydämessä
kaikista hänen päinvastaisista vakuutuksistaan huolimatta. Ja se
rakkaus olisi saattanut kohdistua häneen, olisi kohdistunut häneen,
sillä hänen oma voimakas ja hellä tunteensa olisi vetänyt sitä
puoleensa. Gillianin olisi viimein täytynyt kääntyä hänen puoleensa,
ja hänen rakkautensa olisi luonut Gillianin onnen. Ja hänelle olisi
Gillianin rakkaus ollut elämän kruunu — elämä, täynnä sanomatonta
riemua ja kauneutta, täydellistä, eheää myötätuntoa huokuva liitto.
Yhdessä he olisivat tehneet Towersista maallisen paratiisin; yhdessä
he olisivat voineet murtaa Cravenien kirouksen voiman; yhdessä he
olisivat voineet kylvää onnea monien ihmisten elämään.
Ja hänen haaveillessaan, miten olisi saattanut olla, heräsi
hänessä ensimmäisen kerran isyyden kaipaus; hän kaipasi lasta,
jonka hänen jumaloimansa nainen olisi synnyttänyt, jonka pienessä
olemuksessa yhtyisivät molempien olennaiset piirteet ja joka siten
olisi heidän keskinäisen rakkautensa kouraantuntuva todistus, joka
jatkaisi hänen juurenaan ollutta sukua. Uusi, järkyttävä tunne pani
Cravenin huohottamaan kiivaasti. Hirvittävän äkillisenä kuin salama
välähti sitten muisto, pistävä muisto, joka paiskasi hänen unelmansa
sirpaleiksi hänen jalkojensa juureen. Taaskin hän kuuli hiljaisen,
vienon, nyyhkivän äänen sanovan: »Etkö ole iloinen?» Taaskin hän
näki O Hara Sanin vetoavat, kyyneleiset silmät, tunsi hänen hennon,
surun puistattaman vartalonsa vapisevan sylissään, ja hän painoi
päänsä käsiensä varaan huumaavan kauhun valtaamana.