Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript, 2nd Edition Wei-Meng Lee download
Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript, 2nd Edition Wei-Meng Lee download
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/fresh-produce-shipping-damages-and-
compensation-1st-edition-rex-c-tester/
Emergency War Surgery Fifth Edition Borden Institute
https://ebookmeta.com/product/emergency-war-surgery-fifth-
edition-borden-institute/
https://ebookmeta.com/product/private-associations-in-the-pontic-
greek-cities-6th-century-bc-3rd-century-ad-volume-35-colloquia-
antiqua-1st-edition-a-i-pazsint/
https://ebookmeta.com/product/wilkins-clinical-practice-of-the-
dental-hygienist-14th-edition-linda-d-boyd-lisa-f-mallonee/
https://ebookmeta.com/product/flexible-electronics-volume-2-thin-
film-transistors-1st-edition-vinod-kumar-khanna/
https://ebookmeta.com/product/hot-dog-summer-hot-h-e-a-
summer-1st-edition-lola-west/
Machine Hallucinations Architecture and Artificial
Intelligence Architectural Design 1st Edition Neil
Leach (Editor)
https://ebookmeta.com/product/machine-hallucinations-
architecture-and-artificial-intelligence-architectural-
design-1st-edition-neil-leach-editor/
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
Another Random Scribd Document
with Unrelated Content
when the glass is merely stored in a damp place, it is often mistaken
for “devitrification.” This latter action, however, is not known to occur
at the ordinary temperature, although glass when heated in a flame
frequently shows the phenomenon; it is, however, entirely distinct
from the surface “corrosion” just described. Water containing
alkaline substances in solution acts upon all glasses in a relatively
rapid manner; it acts by first abstracting silica from the glass, the
alkali and lime being dissolved or mechanically removed at a later
stage. Water containing acid bodies in solution—i.e., dilute acid—on
the other hand acts upon most varieties of glass decidedly less
energetically than even pure water, and much less vigorously than
alkaline solutions; this peculiar behaviour probably depends upon
the tendency of acids to prevent the hydration of silica, this
substance being thereby enabled to act as a barrier to the solvent
action of the water upon the alkaline constituents of the glass. The
better varieties of glass are also practically impervious to the action
of strong acids, although certain of these, such as phosphoric and
hydrofluoric, exert a rapid action on all kinds of glass. Only certain
special glasses, containing an excessive proportion of basic
constituents and of such substances as boric or phosphoric acid, are
capable of being completely decomposed by the action of strong
acids, such as hydrochloric or nitric, the bases entering into
combination with the acids, while the silicic and other acids are
liberated.
In connection with the action of acids upon glass, mention
should be made of certain special actions that are of practical
importance. The dissolving action of hydrofluoric acid upon glass is,
of course, well known. It is used in practice both in the liquid and
gaseous form, and also in that of compounds from which it is readily
liberated (such as ammonium or sodium fluoride), for the purpose of
“etching” glass, and also in decomposing glass for purposes of
chemical analysis. Next in importance ranks the action of carbonic
acid gas upon glass, especially in the presence of moisture. The
action in question is probably indirect in character; the moisture of
the air, condensing upon the surface of the glass, first exerts its
dissolving action, and thus draws from the glass a certain quantity of
alkali, which almost certainly at first goes into solution as alkali
hydrate (potassium or sodium hydroxide); this alkaline solution,
however, rapidly absorbs carbonic acid from the air, and the
carbonate of the alkali is formed. If the glass dries, this carbonate
forms a coating of minute crystals on the surface of the glass, giving
it a dull, dimmed appearance; this, however, only occurs ordinarily
with soda glasses, since the carbonate of potassium is too
hygroscopic to remain in the dry solid state in any ordinary
atmosphere. Potash glasses are, as such, no more stable chemically
than soda glasses, but they are for the reason just given less liable
to exhibit a dim surface. If the dimming process, in the case of a
soda glass, has not gone too far, the brightness of the surface of the
glass may be practically restored by washing it with water, in which
the minute crystals of carbonate of soda readily dissolve, while
separated silica is removed mechanically. An attempt made to clean
the same dimmed surface by dry wiping would only result in finally
ruining the surface, since the small sharp crystals of carbonate of
soda would be rubbed about over the surface, scratching it in all
directions.
The dimming process in the case of the less resistant glasses is
not only confined to the formation of alkaline carbonates; the films
of alkaline solution which are formed on the surface of glass form a
ready breeding-ground for certain forms of bacteria and fungi,
whose growth occurs partly at the expense of the glass itself; the
precise nature of these actions has not been fully studied, but there
can be little doubt that silicate minerals—and glass is to be reckoned
among these—are subject to bacterial decomposition, a well-known
example in another direction being the “maturing” of clays by
storage in the dark, the change in the clay being accompanied by an
evolution of ammonia gas. In the case of glass it has been shown
that specks of organic dust falling upon a surface give rise to local
decomposition. In this connection it is interesting to note the effect
of the presence of a small proportion of boric acid in some glasses.
The presence of this ingredient in small proportions is known to
render the glass more resistant to atmospheric agencies, and more
especially to render it less sensitive to the effects of organic dust
particles lying upon the surface. It has been suggested—probably
rightly—that the boric acid, entering into solution in the film of
surface moisture, exerts its well-known antiseptic properties, thus
protecting the glass from bacterial and fungoid activity.
The durability of glass under the action of atmospheric agents is
a matter of such importance that numerous efforts have been made
to establish a satisfactory test whereby this property of a given glass
may be ascertained without actually awaiting the results of
experience obtained by actual use under unfavourable conditions.
One of the earliest of the tests proposed consisted in exposing
surfaces of the glass to the vapour of hydrochloric acid. For this
purpose some strong hydrochloric acid is placed in a glass or
porcelain basin, and strips of the glass to be tested are placed across
the top of the basin, the whole being covered with a bell-jar. After
several days the glass is examined, and as a rule the less stable
glasses show a dull, dimmed surface as compared with the more
stable ones. A more satisfactory form of test depends upon the fact
that aqueous ether solutions react readily with the less stable kinds
of glass; if a suitable dye, such as iod-eosin, be dissolved in the
water-ether solution, then the effect upon the less stable glasses
when immersed in the solution is the formation of a strongly
adherent pink film. The density or depth of colour of this film may be
regarded as measuring the stability of the glass; the best kinds of
glass remain practically free from coloured film even on prolonged
exposure. A test of a somewhat different kind is one devised in its
original form by Dr. Zschimmer, of the Jena glass works; this
depends upon the fact that the disintegrating action of moist air can
be very much accelerated if both the moisture and the temperature
of the air surrounding the glass be considerably increased. For this
purpose the samples of glass are exposed to a current of air
saturated with moisture at a temperature of about 80° C. in a
specially arranged incubator for one or more days, means being
provided for securing a constant stream of moist air during the
whole time. On examining the glass surfaces after this exposure—
any wiping or other cleaning of the surfaces being avoided—various
qualities of glass are found to show widely varying appearances. The
best and most stable glasses remain entirely unaffected; less stable
kinds show small specks, which merge into a generally dulled
surface in unstable kinds. There is no doubt that this test gives a
sharp classification of glasses, but it yet remains to be proved that
this classification agrees with their true relative durability in practice;
the writer is inclined to doubt whether this is really the case, since
certain glasses that have proved very satisfactory in this respect in
practical use all over the world were classed among the less stable
kinds by this test.
Before leaving the subject of the chemical behaviour of glass, a
reference should be made to the changes which glass undergoes
when acted upon by light and other radiations. Under the influence
of prolonged exposure to strong light, particularly to sunlight, and
still more so to ultra-violet light, or the light of the sun at high
altitudes, practically all kinds of glass undergo changes which
generally take the form of changes of colour. Glasses containing
manganese especially are apt to assume a purple or brown tinge
under such circumstances, although the powerful action of radium
radiations is capable of producing similar discoloration in glasses free
from manganese. Apart from these latter effects, of which very little
is known as yet, there can be no doubt that the action of light brings
about chemical changes within the glass, but it is by no means easy
to ascertain the true nature of these changes, although they most
probably consist in a transfer of oxygen from one to another of the
oxides present in the glass. Although it has not been definitely
proved, it seems very unlikely that the glass either loses or gains in
any constituent during these changes. Good examples of the
changes undergone by glass under the action of sunlight are
frequently found in skylights, where the oldest panes sometimes
show a decided purple tint which they did not possess when first put
in place. The glass spheres of the instruments used for obtaining
records of the duration of sunshine at meteorological stations also
show signs of the changes due to light—the glass of these spheres
when new has a light greenish tint, but after prolonged use the
colour changes to a decided yellow. The coloured glass in stained-
glass windows also shows signs of having undergone changes of tint
in consequence of prolonged exposure to light; glass removed from
ancient windows usually shows a deeper tint in those portions which
have been protected from the direct action of light by the leading in
which the glass was set, and it is at least an open question whether
the beauty of ancient glass may not be, in part, due to the
mellowing effect of light upon some of the tints of the design. This
photo-sensitiveness of glass is also of some importance in
connection with the manufacture of photographic plates. It has been
found that if the glass plate of a strongly-developed negative be
cleaned, a decided trace of the former image is retained by the
glass, and this image is apt to re-appear as a “ghost” if the same
glass be again coated with sensitive emulsion and again exposed
and developed. The best makers of plates recognise this fact and do
not re-coat glass that has once been used for the production of a
negative.
CHAPTER II.
Tensile
strength:
1 to tons per (Trautwine).
From
4 sq. in.
1
/3 to (Henrivaux).
” ” ” ”
1¼
2 to (Winkelmann and
” ” ” ”
5½ Schott).
5 to (Kowalski).
” ” ” ”
6
Crushing
strength:
9 to tons per (Trautwine).
From
16 sq. in.
3 to (Winkelmann and
” ” ” ”
8 Schott).
20 to (Kowalski).
” ” ” ”
27