Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
15 views

Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript, 2nd Edition Wei-Meng Lee download

The document is an overview of the book 'Beginning Ethereum Smart Contracts Programming' by Wei-Meng Lee, which covers programming Ethereum smart contracts using Python, Solidity, and JavaScript. It includes various chapters on blockchain technology, cryptography, and practical implementations of smart contracts. Additionally, it provides links to other related books and resources available for download.

Uploaded by

bloutenloexw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
15 views

Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript, 2nd Edition Wei-Meng Lee download

The document is an overview of the book 'Beginning Ethereum Smart Contracts Programming' by Wei-Meng Lee, which covers programming Ethereum smart contracts using Python, Solidity, and JavaScript. It includes various chapters on blockchain technology, cryptography, and practical implementations of smart contracts. Additionally, it provides links to other related books and resources available for download.

Uploaded by

bloutenloexw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Beginning Ethereum Smart Contracts Programming:

With Examples in Python, Solidity, and


JavaScript, 2nd Edition Wei-Meng Lee install
download
https://ebookmeta.com/product/beginning-ethereum-smart-contracts-
programming-with-examples-in-python-solidity-and-javascript-2nd-
edition-wei-meng-lee/

Download more ebook from https://ebookmeta.com


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

Beginning Swift Programming 1st Edition Wei Meng Lee

https://ebookmeta.com/product/beginning-swift-programming-1st-
edition-wei-meng-lee/

Building Games with Ethereum Smart Contracts:


Intermediate Projects for Solidity Developers Kedar
Iyer

https://ebookmeta.com/product/building-games-with-ethereum-smart-
contracts-intermediate-projects-for-solidity-developers-kedar-
iyer/

Blockchain and Ethereum Smart Contract Solution


Development: Dapp Programming with Solidity 1st Edition
Weijia Zhang

https://ebookmeta.com/product/blockchain-and-ethereum-smart-
contract-solution-development-dapp-programming-with-solidity-1st-
edition-weijia-zhang/

Fresh Produce Shipping: Damages and Compensation 1st


Edition Rex C. Tester

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/

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/private-associations-in-the-pontic-
greek-cities-6th-century-bc-3rd-century-ad-volume-35-colloquia-
antiqua-1st-edition-a-i-pazsint/

Wilkins Clinical Practice of the Dental Hygienist 14th


Edition Linda D Boyd Lisa F Mallonee

https://ebookmeta.com/product/wilkins-clinical-practice-of-the-
dental-hygienist-14th-edition-linda-d-boyd-lisa-f-mallonee/

Flexible Electronics Volume 2 Thin film transistors 1st


Edition Vinod Kumar Khanna

https://ebookmeta.com/product/flexible-electronics-volume-2-thin-
film-transistors-1st-edition-vinod-kumar-khanna/

Hot Dog Summer Hot H E A Summer 1st Edition Lola West

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

ISBN-13 (pbk): 978-1-4842-9270-9 ISBN-13 (electronic): 978-1-4842-9271-6


https://doi.org/10.1007/978-1-4842-9271-6
Copyright © 2023 by Wei-Meng Lee
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Joan Murray
Development Editor: Laura Berendson
Editorial Assistant: Gryffin Winkler
Copy Editor: Mary Behr
Cover image designed by eStudioCalamar
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza,
Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@
springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole
member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc
is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for reprint,
paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub (github.com/apress). For more detailed information, please visit www.apress.com/
source-code.
Printed on acid-free paper
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� xi

About the Technical Reviewer������������������������������������������������������������������������������� xiii


Acknowledgments���������������������������������������������������������������������������������������������������xv

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

Chapter 1: Understanding the Science Behind Blockchain: Cryptography��������������� 1


What Is Cryptography?������������������������������������������������������������������������������������������������������������������ 1
Types of Cryptography������������������������������������������������������������������������������������������������������������� 2
Hash Functions����������������������������������������������������������������������������������������������������������������������������� 3
Uses of Hashing����������������������������������������������������������������������������������������������������������������������� 5
Implementing Hashing in Python��������������������������������������������������������������������������������������������� 6
Symmetric Cryptography�������������������������������������������������������������������������������������������������������������� 7
Generating the Shared Key in Python�������������������������������������������������������������������������������������� 8
Performing Symmetric Encryption������������������������������������������������������������������������������������������ 9
Performing Symmetric Decryption������������������������������������������������������������������������������������������ 9
Asymmetric Cryptography���������������������������������������������������������������������������������������������������������� 10
Generating and Saving the Public/Private Key Pairs������������������������������������������������������������� 12
Encrypting Using the Public Key�������������������������������������������������������������������������������������������� 14
Decrypting Using the Private Key������������������������������������������������������������������������������������������ 14
Digital Signature: Signing Using Private Key������������������������������������������������������������������������� 15
Verifying the Digital Signature Using a Public Key���������������������������������������������������������������� 18
How Cryptography Is Used in Blockchain����������������������������������������������������������������������������������� 18
Hashing��������������������������������������������������������������������������������������������������������������������������������� 19
Symmetric and Asymmetric Cryptography���������������������������������������������������������������������������� 19
Digital Signature�������������������������������������������������������������������������������������������������������������������� 20
Summary������������������������������������������������������������������������������������������������������������������������������������ 21

iii
Table of Contents

Chapter 2: Understanding Blockchain�������������������������������������������������������������������� 23


Motivations Behind Blockchain��������������������������������������������������������������������������������������������������� 24
Placement of Trust����������������������������������������������������������������������������������������������������������������� 24
Trust Issues��������������������������������������������������������������������������������������������������������������������������� 25
Solving Trust Issues Using Decentralization�������������������������������������������������������������������������� 26
Example of Decentralization�������������������������������������������������������������������������������������������������� 26
Blockchain As a Distributed Ledger��������������������������������������������������������������������������������������� 29
How a Blockchain Works������������������������������������������������������������������������������������������������������������� 30
Chaining the Blocks��������������������������������������������������������������������������������������������������������������� 31
Immutability of Blockchains�������������������������������������������������������������������������������������������������� 34
Consensus Protocols������������������������������������������������������������������������������������������������������������� 35
Proof of Work������������������������������������������������������������������������������������������������������������������������� 37
Proof of Stake (PoS)�������������������������������������������������������������������������������������������������������������� 41
Blockchain in More Detail����������������������������������������������������������������������������������������������������������� 43
Types of Nodes���������������������������������������������������������������������������������������������������������������������� 44
Merkle Tree and Merkle Root������������������������������������������������������������������������������������������������� 47
Uses of Merkle Tree and the Merkle Root������������������������������������������������������������������������������ 48
Summary������������������������������������������������������������������������������������������������������������������������������������ 49

Chapter 3: Implementing Your Own Blockchain Using Python������������������������������� 51


Your Conceptual Blockchain Implementation����������������������������������������������������������������������������� 51
Obtaining the Nonce�������������������������������������������������������������������������������������������������������������� 53
Installing Flask���������������������������������������������������������������������������������������������������������������������� 55
Importing the Various Modules and Libraries������������������������������������������������������������������������ 56
Declaring the Class in Python������������������������������������������������������������������������������������������������ 56
Finding the Nonce����������������������������������������������������������������������������������������������������������������� 57
Appending the Block to the Blockchain��������������������������������������������������������������������������������� 58
Adding Transactions�������������������������������������������������������������������������������������������������������������� 59
Exposing the Blockchain Class as a REST API����������������������������������������������������������������������� 60
Obtaining the Full Blockchain������������������������������������������������������������������������������������������������ 60
Performing Mining����������������������������������������������������������������������������������������������������������������� 60
Adding Transactions�������������������������������������������������������������������������������������������������������������� 61

iv
Table of Contents

Testing Your Blockchain�������������������������������������������������������������������������������������������������������������� 62


Synchronizing Blockchains��������������������������������������������������������������������������������������������������������� 67
Testing the Blockchain with Multiple Nodes�������������������������������������������������������������������������� 72
Full Listing for the Python Blockchain Implementation��������������������������������������������������������������� 78
Summary������������������������������������������������������������������������������������������������������������������������������������ 85

Chapter 4: Creating Your Own Private Ethereum Test Network������������������������������ 87


Downloading and Installing Geth, the Ethereum Client��������������������������������������������������������������� 87
Installing Geth for macOS������������������������������������������������������������������������������������������������������ 88
Installing Geth for Windows��������������������������������������������������������������������������������������������������� 89
Installing Geth for Linux��������������������������������������������������������������������������������������������������������� 89
Creating the Private Ethereum Test Network������������������������������������������������������������������������������ 90
Creating the Genesis Block��������������������������������������������������������������������������������������������������� 91
Creating a Folder for Storing Node Data�������������������������������������������������������������������������������� 92
Initiating a Blockchain Node�������������������������������������������������������������������������������������������������� 93
Starting Up the Nodes����������������������������������������������������������������������������������������������������������� 94
Managing Accounts������������������������������������������������������������������������������������������������������������������� 107
Removing Accounts������������������������������������������������������������������������������������������������������������� 109
Setting the Coinbase����������������������������������������������������������������������������������������������������������� 109
Summary���������������������������������������������������������������������������������������������������������������������������������� 110

Chapter 5: Using the MetaMask Crypto-Wallet����������������������������������������������������� 111


What Is MetaMask?������������������������������������������������������������������������������������������������������������������ 111
How MetaMask Works Behind the Scenes�������������������������������������������������������������������������� 112
Installing MetaMask������������������������������������������������������������������������������������������������������������ 113
Setting Up the Accounts������������������������������������������������������������������������������������������������������ 115
Using the MetaMask Extension������������������������������������������������������������������������������������������� 119
Selecting Ethereum Networks�������������������������������������������������������������������������������������������������� 121
Getting Test Ethers�������������������������������������������������������������������������������������������������������������� 122
Creating Additional Accounts����������������������������������������������������������������������������������������������� 126
Transferring Ethers�������������������������������������������������������������������������������������������������������������� 129
Recovering Accounts����������������������������������������������������������������������������������������������������������� 135

v
Table of Contents

Importing and Exporting Accounts�������������������������������������������������������������������������������������������� 138


Exporting Accounts�������������������������������������������������������������������������������������������������������������� 138
Importing Accounts������������������������������������������������������������������������������������������������������������� 142
Summary���������������������������������������������������������������������������������������������������������������������������������� 144

Chapter 6: Getting Started with Smart Contracts������������������������������������������������� 145


What Is a Smart Contract?�������������������������������������������������������������������������������������������������������� 145
How Smart Contracts Are Executed������������������������������������������������������������������������������������� 146
Your First Smart Contract���������������������������������������������������������������������������������������������������������� 148
Using the Remix IDE������������������������������������������������������������������������������������������������������������ 148
Compiling the Contract�������������������������������������������������������������������������������������������������������� 152
Testing the Smart Contract Using the JavaScript VM���������������������������������������������������������� 154
Getting the ABI and Bytecode of the Contract��������������������������������������������������������������������� 158
Testing the Smart Contract Using the Goerli Testnet����������������������������������������������������������� 162
Summary���������������������������������������������������������������������������������������������������������������������������������� 166

Chapter 7: Storing Proofs Using Smart Contracts������������������������������������������������ 167


A Smart Contract as a Store of Proofs�������������������������������������������������������������������������������������� 167
Creating the Smart Contract������������������������������������������������������������������������������������������������ 168
Compiling the Contract�������������������������������������������������������������������������������������������������������� 174
Deploying the Contract�������������������������������������������������������������������������������������������������������� 176
Testing the Contract������������������������������������������������������������������������������������������������������������ 177
Making Further Changes to the Smart Contract����������������������������������������������������������������������� 180
Restricting Access to Functions������������������������������������������������������������������������������������������ 181
Accepting Payments in Smart Contracts����������������������������������������������������������������������������� 182
Events in Smart Contracts��������������������������������������������������������������������������������������������������� 188
Cashing Out������������������������������������������������������������������������������������������������������������������������� 191
Destroying a Contract���������������������������������������������������������������������������������������������������������� 193
Summary���������������������������������������������������������������������������������������������������������������������������������� 194

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


What Is web3.js?����������������������������������������������������������������������������������������������������������������������� 195
Installing web3.js���������������������������������������������������������������������������������������������������������������� 196

vi
Table of Contents

Testing the web3.js Using MetaMask���������������������������������������������������������������������������������� 197


Interacting with a Contract Using web3.js�������������������������������������������������������������������������� 202
Summary���������������������������������������������������������������������������������������������������������������������������������� 214

Chapter 9: Developing Web3 dapps using Python������������������������������������������������ 215


Interacting with Ethereum Using Python���������������������������������������������������������������������������������� 216
Registering with Infura�������������������������������������������������������������������������������������������������������� 217
Connecting to Infura������������������������������������������������������������������������������������������������������������ 220
Fetching a Block������������������������������������������������������������������������������������������������������������������ 221
Setting Up the Accounts������������������������������������������������������������������������������������������������������ 223
Getting the Balance of an Account�������������������������������������������������������������������������������������� 225
Transferring Ethers Between Accounts������������������������������������������������������������������������������� 225
Creating a Dapp Using Python�������������������������������������������������������������������������������������������������� 227
Loading the Contract����������������������������������������������������������������������������������������������������������� 230
Base64 Encoding����������������������������������������������������������������������������������������������������������������� 231
Saving Credentials on the Blockchain��������������������������������������������������������������������������������� 231
Verifying the Result������������������������������������������������������������������������������������������������������������� 234
Summary���������������������������������������������������������������������������������������������������������������������������������� 239

Chapter 10: Project: Online Lottery���������������������������������������������������������������������� 241


How the Lottery Game Works���������������������������������������������������������������������������������������������������� 241
Defining the Smart Contract������������������������������������������������������������������������������������������������ 243
Betting a Number���������������������������������������������������������������������������������������������������������������� 246
Setting the Winning Number and Announcing the Winners������������������������������������������������� 249
Getting the Game Status and Winning Number������������������������������������������������������������������� 253
Cashing Out from the Contract�������������������������������������������������������������������������������������������� 253
Testing the Contract������������������������������������������������������������������������������������������������������������������ 254
Announcing the Winner������������������������������������������������������������������������������������������������������� 258
Saving the ABI of the Contract��������������������������������������������������������������������������������������������� 260
Deploying the Contract to the Testnet��������������������������������������������������������������������������������� 262
Creating the Web Front End������������������������������������������������������������������������������������������������������ 263
Announcing the Winning Number���������������������������������������������������������������������������������������� 269
Cashing Out������������������������������������������������������������������������������������������������������������������������� 271
vii
Table of Contents

The Complete Contract������������������������������������������������������������������������������������������������������������� 272


Summary���������������������������������������������������������������������������������������������������������������������������������� 277

Chapter 11: Creating Your Tokens������������������������������������������������������������������������ 279


What Are Tokens?���������������������������������������������������������������������������������������������������������������������� 279
How Tokens Are Implemented?������������������������������������������������������������������������������������������� 281
Minting New Tokens������������������������������������������������������������������������������������������������������������ 282
Burning Tokens�������������������������������������������������������������������������������������������������������������������� 282
Units Used Internally in Token Contracts����������������������������������������������������������������������������� 283
ERC-20 Token Standard������������������������������������������������������������������������������������������������������� 285
Creating Token Contracts���������������������������������������������������������������������������������������������������������� 287
Overriding the Number of Decimal Places of Precision������������������������������������������������������� 288
Deploying the Token Contract���������������������������������������������������������������������������������������������� 289
Adding the Token to MetaMask������������������������������������������������������������������������������������������� 291
What Can You Do with the Token?��������������������������������������������������������������������������������������� 291
Using Tokens for Smart Contract Payments������������������������������������������������������������������������ 292
Selling Tokens Programmatically���������������������������������������������������������������������������������������������� 300
Calculating the Amount of Tokens Bought��������������������������������������������������������������������������� 302
Deploying the Contract�������������������������������������������������������������������������������������������������������� 304
Summary���������������������������������������������������������������������������������������������������������������������������������� 310

Chapter 12: Creating Non-Fungible Tokens Using ERC-721���������������������������������� 311


What Is an NFT?������������������������������������������������������������������������������������������������������������������������ 311
Ownership vs. Copyright����������������������������������������������������������������������������������������������������� 313
Where Do You Buy or Sell NFTs?����������������������������������������������������������������������������������������� 313
Creating NFTs Using Token Contracts��������������������������������������������������������������������������������������� 314
Who Deploys the NFT Token Contract?�������������������������������������������������������������������������������� 315
Using ERC-721 for Creating NFTs���������������������������������������������������������������������������������������� 315
Deploying the NFT Token Contract��������������������������������������������������������������������������������������� 316
Testing the NFT Contract����������������������������������������������������������������������������������������������������� 318
Summary���������������������������������������������������������������������������������������������������������������������������������� 327

viii
Table of Contents

Chapter 13: Introduction to Decentralized Finance���������������������������������������������� 329


Limitations of Traditional Finance��������������������������������������������������������������������������������������������� 329
Decentralized Finance��������������������������������������������������������������������������������������������������������� 330
Components in DeFi������������������������������������������������������������������������������������������������������������ 331
Stablecoins������������������������������������������������������������������������������������������������������������������������������� 331
Fiat-Backed Stablecoins������������������������������������������������������������������������������������������������������ 333
Crypto-Backed Stablecoins������������������������������������������������������������������������������������������������� 334
Non-Collateralized Stablecoins������������������������������������������������������������������������������������������� 340
Crypto Exchanges��������������������������������������������������������������������������������������������������������������������� 340
Creating a Decentralized Exchange������������������������������������������������������������������������������������� 342
Creating the Token Contract������������������������������������������������������������������������������������������������ 343
Deploying the Token Contract���������������������������������������������������������������������������������������������� 343
Creating the DEX Contract��������������������������������������������������������������������������������������������������� 345
Funding the DEX������������������������������������������������������������������������������������������������������������������ 351
Swapping WML Tokens for LWM Tokens������������������������������������������������������������������������������ 354
Summary���������������������������������������������������������������������������������������������������������������������������������� 359

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.

Figure 1-1. Understanding how the Caesar Cipher works

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.

Figure 1-2. A hash function converts a block of data of variable length to


a fixed-­length output

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

Figure 1-3. Trying out the SHA256 hash function

Hashing has the following important properties:

• Preimage resistant: Based on the hash created, you cannot obtain


the original block of text.

• Deterministic: The same block of text will always produce the same
hash output.

• Collision resistant: It is hard to find two different blocks of text that


will produce the same hash.

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

Implementing Hashing in Python

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())

The hash for the above string is as follows:

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.

Figure 1-5. Using a shared key for 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

Tip Some examples of symmetric key algorithms are AES (Advanced Encryption


Standard, originally known as Rijndael), DES (Data Encryption Standard), and IDEA
(International Data Encryption Algorithm).

Generating the Shared Key in Python


In Python, you can use the cryptography module for symmetric and asymmetric
cryptography. To use the cryptography module, install it using pip:

$ pip install cryptography

Let’s generate a shared key in Python. To do so, use the Fernet class:

from cryptography.fernet import Fernet

# generate the shared key


shared_key = Fernet.generate_key()
print(shared_key)

# base64 encoded, binary format


# A new key is generated each time you run this block of code
# e.g. b'ixXEfrz2NTJlxy1OhxXlsCiFf0Ycg_GL0Cy0MlgTv4U='

Tip The Fernet class is an implementation of symmetric (also known as “secret


key”) authenticated cryptography. Fernet uses the AES algorithm in CBC mode with
a 128-bit key for encryption. For more details, refer to https://github.com/
fernet/spec/blob/master/Spec.md.

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

Performing Symmetric Encryption


To encrypt your data using the shared key, you first create an instance of the Fernet class
using the shared key:

# create an instance of the Fernet class


fernet = Fernet(shared_key)

You can then use the encrypt() function to encrypt your data:

# encrypt the message with the shared key


ciphertext = fernet.encrypt(
    bytes("Secret message!",'utf-8'))
# remember to pass in a byte array

You can save the encrypted data into a file:

# write the encrypted message to file


with open('message.encrypted', 'wb') as f:
    f.write(ciphertext)

And you can save the shared key to file:

# write the shared key to file


with open('symmetric_key.crypt', 'wb') as f:
    f.write(shared_key)

Performing Symmetric Decryption


Decryption is similar to encryption. First, load the shared key from the file (which you
saved previously):

with open('symmetric_key.crypt', 'rb') as f:


    shared_key = f.read()
print(shared_key)

Then, create an instance of the Fernet class using the shared key and call the
decrypt() function to decode the ciphertext:

# create an instance of the Fernet class


fernet = Fernet(shared_key)

9
Chapter 1 Understanding the Science Behind Blockchain: Cryptography

# decrypt the encrypted message read from file


with open('message.encrypted', 'rb') as f:
    print(fernet.decrypt(f.read()).decode("utf-8"))

Asymmetric Cryptography
Unlike symmetric cryptography, which uses a single shared key, asymmetric
cryptography uses a key-pair, one public and one private.

Tip Asymmetric cryptography is also known as public-key cryptography.

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.

Tip Some examples of public key algorithms are RSA (Rivest–Shamir–Adleman),


Elliptical Curve Cryptography (ECC), and TLS/SSL protocol.

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

Generating and Saving the Public/Private Key Pairs


Let’s generate the public/private key pair using the cryptography module with some
commonly used parameters:

from cryptography.hazmat.backends import default_backend


from cryptography.hazmat.primitives.asymmetric import rsa

# generate the private key


private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

# derive the public key from the private key


public_key = private_key.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:

from cryptography.hazmat.primitives import serialization

#---serialize the private key as bytes---


pem = private_key.private_bytes(
    encoding = serialization.Encoding.PEM,
    format = serialization.PrivateFormat.PKCS8,
    encryption_algorithm = serialization.NoEncryption()
)
with open('private_key.pem', 'wb') as f:
    f.write(pem)

#---serialize the public key as bytes---


pem = public_key.public_bytes(
    encoding = serialization.Encoding.PEM,
    format = serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_key.pem', 'wb') as f:
    f.write(pem)

You also need to be able to load them back from files:

with open('private_key.pem', 'rb') as f:


    private_key = serialization.load_pem_private_key(
        f.read(),
        password = None,
        backend = default_backend()
    )

with open('public_key.pem', 'rb') as f:


    public_key = serialization.load_pem_public_key(
        f.read(),
        backend = default_backend()
    )

13
Chapter 1 Understanding the Science Behind Blockchain: Cryptography

Encrypting Using the Public Key


You are now ready to perform encryption using the public key:

from cryptography.hazmat.primitives import hashes


from cryptography.hazmat.primitives.asymmetric import padding

plaintext = bytes("This message is secret.",'utf-8')

# encrypt the message using the public key


ciphertext = public_key.encrypt(
    plaintext,
    padding.OAEP(
        mgf = padding.MGF1(algorithm = hashes.SHA256()),
        algorithm = hashes.SHA256(),
        label = None
    )
)

Note The encrypted ciphertext is a byte array.

Decrypting Using the Private Key


With the ciphertext created, you can decrypt it using the private key:

# decrypt using the private key


plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf = padding.MGF1(algorithm = hashes.SHA256()),
        algorithm = hashes.SHA256(),
        label = None
    )
)

14
Chapter 1 Understanding the Science Behind Blockchain: Cryptography

# decode the plaintext as it is a byte array


print(plaintext.decode('utf-8'))
# This message is secret.

Note The decrypted plaintext is a byte array.

Digital Signature: Signing Using Private Key


Earlier I mentioned that in a digital signature you perform encryption using the private
key and then decrypt using the public key. How does this really work and how is it
useful? Let’s look at the flow of events shown in Figure 1-8.

Figure 1-8. Generating a digital signature using the private key

15
Chapter 1 Understanding the Science Behind Blockchain: Cryptography

• First, the text to be sent is hashed using a hash function.

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

Figure 1-9. Verifying a digital signature using the public key

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

Note A digital signature is a mathematical technique used to validate the


authenticity and integrity of a message, software, or digital document.

16
Chapter 1 Understanding the Science Behind Blockchain: Cryptography

Let’s create a digital signature using the private key.


Technically, you can’t call the encrypt() function on the private key:

private_key.encrypt(...)    # ERROR
# AttributeError: '_RSAPrivateKey' object has no attribute 'encrypt'

Rather, you call the sign() function:

import base64

plaintext = bytes("This message is public.",'utf-8')

# sign the message using the private key


signed = private_key.sign(
    plaintext,
    padding.PSS(
        mgf = padding.MGF1(algorithm=hashes.SHA256()),
        salt_length = padding.PSS.MAX_LENGTH
    ),
    hashes.SHA256()
)

# print out the digital signature using base64 encoding


signed_base64 = base64.b64encode(signed).decode('utf-8')
print(signed_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

Verifying the Digital Signature Using a Public Key


When the recipient receives the message along with the digital signature, they can
simply verify that the message has not been tampered by calling the verify() function
on the public key:

from cryptography.exceptions import InvalidSignature

# decode the digital signature from base64


signed = base64.b64decode(signed_base64)

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.

How Cryptography Is Used in Blockchain


If you have been following up to this point, you should now have a good idea of how
cryptography works. You might now be wondering how cryptography plays an important
role in blockchain.

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.

• Chapters 4 and 5: Asymmetric cryptography is used to generate your


accounts, and symmetric cryptography is used to secure the accounts
you have created in your crypto-wallets.
• Chapter 4 onwards: Asymmetric cryptography is used to create digital
signatures for all of your transactions on the 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.

Symmetric and Asymmetric Cryptography


Symmetric and asymmetric cryptography are used in generating and securing of
accounts in blockchain.
As shown in Figure 1-10, when you create an account in Ethereum, a private key
using asymmetric cryptography is first generated.

19
Chapter 1 Understanding the Science Behind Blockchain: Cryptography

Figure 1-10. Understanding how an account is generated and secured

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

The miners/validators, upon receiving your transaction, verify the authenticity of


your transaction using the transaction’s digital signature. Once the transaction is verified
to be authentic, the miners/validators proceed to verify the content of the transaction.

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!

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


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

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

Motivations Behind Blockchain


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

Note The technology behind cryptocurrencies is blockchain.

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


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

Placement of 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

Figure 2-1. Currencies from two countries

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.

Solving Trust Issues Using Decentralization


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

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

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

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

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

This way, there is a central body to keep track of the whereabouts of each DVD. But
wait, isn’t this the problem with centralization? What happens if B is not trustworthy?
Turns out that B has the habit of stealing DVDs, and he 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

Figure 2-4. Getting everyone to keep the records

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.

Blockchain As a Distributed Ledger


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

29
Chapter 2 Understanding Blockchain

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

Here’s a summary of a few important points:

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


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

• A decentralized database built on the blockchain removes the need


for the trust in a central body.

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

How a Blockchain Works


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

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.

Note Every blockchain has a genesis block.

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

Chaining the Blocks


To understand how blocks in a blockchain are chained together, you must understand
one key concept: hashing.

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:

• It is deterministic: The same message always results in the


same hash.

• It is a one-way process: When you hash a string, it is computationally


hard to reverse a hash to its original message.

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


that hash to the same hash.

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.

THE PHYSICAL PROPERTIES OF GLASS.

The Mechanical Properties of Glass are of considerable


importance in many directions. Although glass is rarely used in such
a manner that it is directly called upon to sustain serious mechanical
stresses, the ordinary uses of glass in the glazing of large windows
and skylights depend upon the strength of the material to a very
considerable extent. Thus in the handling of plate-glass in the
largest sheets, the mechanical strength of the plates must be relied
upon to a considerable extent, and it is this factor which really limits
the size of plate that can be safely handled and installed. The same
limitation applies to sheet-glass also, for, although its lighter weight
renders it less liable to break under its own weight, its thinner
section renders it much more liable to accidental fracture. In special
cases, also, the mechanical strength of glass must be relied upon to
a considerable extent. Gauge tubes of high-pressure boilers, port-
hole glasses in ships, the glass prisms inserted in pavement lights,
and the glass bricks which have found some use in France, as well
as champagne bottles and mineral water bottles and syphons, are all
examples of uses in which glass is exposed to direct stresses. It is,
therefore, a little surprising that while the mechanical properties of
metals, timbers, and all manner of other materials have been
studied in the fullest possible manner, those of glass have received
very little attention, at all events so far as published data go. One
reason for this state of affairs is probably to be found in the fact that
it is by no means easy to determine the strength of so brittle and
hard a body as glass. As a consequence even the scanty data
available can only be regarded as first approximations. The following
data are only intended to give an idea of the general order of
strength to be looked for in glass:—

Tensile
strength:
1 to tons per (Trautwine).
From
4 sq. in.
1
/3 to (Henrivaux).
” ” ” ”

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

Of the above figures the experiments of Winkelmann and Schott


are probably by far the most reliable, but these refer to a series of
special Jena glasses, selected with a view to determining the
influence of chemical composition on mechanical properties, and,
unfortunately, this series does not include glasses at all closely
resembling those ordinarily used for practical purposes. The attempt
to connect tensile and crushing strength with chemical composition
was also only very partially successful; but the results serve to show
that the chemical composition has a profound influence on the
mechanical strength of glass, so that by systematic research it would
probably be possible to produce glasses of considerably greater
mechanical strength than those at present known. It must be noted
in this connection that the mechanical properties of glass depend to
a very considerable extent upon the rate of cooling which the
specimen in question has undergone. It is well known that by rapid
cooling, or quenching, the hardness of glass can be considerably
increased; such treatment also increases the strength both as
against tension and compression, and numerous processes have
been put forward for the purpose of utilising these effects in
practice. Unfortunately the “hardened” glass thus obtained is
extremely sensitive to minute scratches, and flies to pieces as soon
as the surface is broken, and the great internal stress which always
exists in such glass is thereby relieved. All these peculiarities are, of
course, dependent as to their degree upon the rapidity with which
the glass has been cooled, and the aim of inventors in this field has
been to devise a rapid cooling process which should strike the happy
mean between the increased strength and the induced brittleness
resulting from quenching. Thus processes for “tempering” glass by
cooling it in a blast of steam or in a bath of hot oil or grease have
been brought forward; but, although some such glass is
manufactured, no very extensive practical application has resulted.
Elasticity and Ductility of Glass.—In a series of glasses
investigated by Winkelmann and Schott, the modulus of elasticity
(Young’s Modulus) varied from 3,500 to 5,100 tons per sq. in., the
value being largely dependent upon the chemical composition of the
glass. Measurable ductility has not been observed in glass under
ordinary conditions except in the case of champagne bottles under
test by internal hydraulic pressure; in these tests it was found that a
permanent increase of volume of a few tenths of a cubic centimetre
could be obtained by the application of an internal pressure just
short of that required to burst the bottle—pressure of the order of
18 to 30 atmospheres being involved. This small permanent set has
been ascribed to incipient fissuring of the glass, and this explanation
is probably correct. On the other hand, it is in the writer’s opinion
very probable that glass is capable of decided flow under the
prolonged action of relatively small forces; the behaviour of large
discs of worked optical glass suggests some such action, but the
view as yet lacks full experimental confirmation.
The Hardness of glass is a property of some importance in most
of the applications of glass. The durability of glass objects which are
exposed to handling or to periodical cleaning must largely depend
upon the power of the glass to resist scratching; this applies to such
objects as plate-glass windows and mirrors, spectacle and other
lenses, and in a minor degree to table-ware. On the other hand, the
exact definition and means of measuring hardness are not yet
satisfactorily settled. Experimenters have found it very difficult to
measure the direct resistance to scratching, since it is found, for
example, that two glasses of very different hardness are yet capable
of decidedly scratching each other under suitable conditions. Resort
has therefore been had to other methods of measuring hardness;
the method which, from the experimental point of view, is, perhaps,
the most satisfactory, depends upon principles laid down by Hertz
and elaborated experimentally by Auerbach. This depends upon
measuring the size of the circular area of contact produced when a
spherical lens is pressed against a flat plate of the same glass with a
known pressure. Auerbach himself found some difficulty in deciding
the exact connection between the “indentation modulus” thus
determined and the actual hardness of the glass. This method is,
therefore, of theoretical interest rather than of use in testing glasses
for hardness. A test of a more practical kind consists in exposing
specimens of the glasses to be tested to abrasion against a revolving
disc of cast-iron fed with emery or other abrasive, and to measure
the loss of weight which results from a given amount of abrading
action under a known contact pressure. If a number of specimens of
different glasses are exposed to this test at one time, a very good
comparison of their power of resisting abrasion can be obtained. It is
not quite certain that this test measures the actual “hardness” of the
glass, but it affords some information as to its power of resisting
abrasion, and for many purposes this power is the important factor.
Hardness being, as indicated above, a somewhat indefinite term,
it is not possible to give any precise statement as to the influence of
chemical composition upon the hardness of glass. In general terms it
may be said that glasses rich in silica and lime will be found to be
hard, while glasses rich in alkali, lead or barium, are likely to be soft.
It must, however, be borne in mind that rapid cooling, or even the
lack of careful annealing, will produce a very great increase of
hardness in even the softest glasses. The actual behaviour of a given
specimen of glass will, therefore, depend at least as much upon the
nature of the processes which it has undergone as upon its chemical
composition.
The Thermal Properties of Glass, although not of such general
importance as the mechanical properties, are yet of considerable
interest in a large number of the practical uses to which glass is
constantly applied. Perhaps the most important of these properties is
that known as thermal endurance, which measures the amount of
sudden heating or cooling to which glass may be exposed without
risk of fracture; the chimneys employed in connection with
incandescent gas burners, boiler gauge glasses, laboratory vessels,
and even table and domestic utensils are all exposed at times to
sudden changes of temperature, and in many cases the value of the
glass in question depends principally upon its power of undergoing
such treatment without breakage. The property of “thermal
endurance” itself depends upon a considerable number of more or
less independent factors, and their influence will be readily
understood if we follow the manner in which sudden change of
temperature produces stress and, sometimes, fracture in glass
objects. If we suppose a hot liquid to be poured into a cold vessel,
the first effect upon the material of the vessel will be to raise the
temperature of the inner surface. Under the influence of this rise of
temperature the material of this inner layer expands, or endeavours
to expand, being restrained by the resistance of the central and
outer layers of material which are still cold; the result of this contest
is, that while the inner layer is thrown into a state of compression,
the outer and central layers are thrown into a state of tension.
Accordingly, if the tension so produced is sufficiently great, the outer
layers fracture under tension and the whole vessel is shattered by
the propagation of the crack thus initiated. From this description of
the process it will be seen that a high coefficient of expansion and a
low modulus of elasticity will both favour fracture, while high tensile
strength will tend to prevent it. The thermal conductivity of the glass
will also affect the result, because the intensity of the tensile stress
set up in the colder layers of glass will depend upon the temperature
gradient which exists in the glass; thus if glass were a good
conductor of heat it would never be possible to set up a sufficient
difference of temperature between adjacent layers to produce
fracture; for the same reason, vessels of very thin glass are less apt
to break under temperature changes than those having thick walls,
since the greatest difference of temperature that can be set up
between the inner and outer layers of a thin-walled vessel can never
be very considerable. It also follows from these considerations, that
if a cold glass vessel be simultaneously heated or cooled from both
sides, it can be safely exposed to a much more sudden change of
temperature than it could withstand if heated from one side alone;
on the other hand, when very thick masses of glass have to be
heated, this must be done very gradually, as a considerable time will
necessarily elapse before an increment of temperature applied to the
outside will penetrate to the centre of the mass. It should also be
noted here, that in addition to the thermal conductivity of the glass,
its heat capacity or specific heat also enters into this question, since
heat will obviously penetrate more slowly through a glass whose
own rise of temperature absorbs a greater quantity of heat. It will
thus be seen that “thermal endurance” is a somewhat complicated
property, depending upon the factors named above, viz.: coefficient
of expansion, thermal conductivity, specific heat, Young’s modulus of
elasticity, and tensile strength.
The coefficient of thermal expansion varies considerably in
different glasses, and we can here only state the limiting values
between which these coefficients usually lie; these are 37 × 10-7 as
the lower, and 122 × 10-7 as the upper limit. These figures express
the cubical expansion of the glass per degree Centigrade, the
corresponding figures for steel and brass respectively being about
360 × 10-7 and 648 × 10-7 respectively. It should be noted that
vitreous bodies of extremely low expansibility are obtainable by the
suitable choice of ingredients, but in some cases these “glasses” are
white opaque bodies, and in all cases they present great difficulty in
manufacture, owing to the fact that alkalies and lime must be
avoided in their composition.
Quite apart from the question of thermal endurance, the
expansive properties of glass are of some importance. Thus when
several kinds of glass have to be united, as, for example, in the
process of producing “flashed” coloured glass, it is essential that
their coefficients of expansion should be as nearly as possible the
same; otherwise considerable stresses will be set up when the
glasses, which have been joined at a red heat, are allowed to cool.
On the other hand, this mutual stressing of two glasses owing to
differences in their thermal expansion has been utilised for the
production of tubes and other glass objects possessing special
strength. If a tube be drawn out of glass consisting of two layers,
one considerably more expansible than the other, and the cooling
process be rightly conducted, it is possible to produce a tube in
which both the inner and outer layers of glass are under a
considerable compressive stress. Not only is glass, as we have seen
above, enormously stronger as against compression than it is
against tension, but glass under compressive stress behaves as
though it were a much tougher material, being less liable to injury
by scratches or blows. Moreover, if a tube in this condition be heated
and then exposed to sudden cooling, the first effect of the
application of cold will be a contraction of the surface layers,
resulting in a relief of the initial condition of compression. These
tubes are, therefore, remarkably indifferent to sudden cooling,
although they are naturally more sensitive to sudden heating. In this
respect they differ entirely from ordinary glass, which is considerably
more sensitive to sudden cooling than to sudden heating,
particularly when the heat or cold is applied to all the surfaces of the
object at the same time. The special tubes made of two layers of
glass above referred to are manufactured by the Jena Glass Works
for special purposes, among which boiler gauge glasses are the most
important. It should be also mentioned here that the remarkable
thermal endurance of vitrified silica, which can be raised to a red
heat and then immersed in cold water without risk of breakage, is
chiefly due to its very low coefficient of expansion.
In another direction the expansive properties of glass are of
importance wherever glass is rigidly attached to metal. At the
present time this is done in several industrial products, such as
incandescent electric lamps and “wired” plate glass. In certain
varieties of incandescent lamps, metallic wires are sealed into the
glass bulbs, and the only metal available for this purpose, at all
events until recently, has been platinum, whose coefficient of
expansion is low as compared with most metals, and whose freedom
from oxidation when heated to the necessary temperature makes it
easy to produce a clean joint between glass and metal. More
recently the use of certain varieties of nickel steel has been patented
for this purpose, since it is possible to obtain nickel steel alloys of
almost any desired coefficient of expansion from that of the alloy
known as “invar,” having a negligibly small expansion compared with
that of ordinary steel. By choosing a suitable member of this series a
metal could be obtained whose coefficient of expansion corresponds
exactly with that of the glass to which it is to be united. The
oxidation of the nickel steel when heated to the temperature
necessary for effecting its union with the glass presented serious
difficulties to the production of a tight joint, and several devices for
avoiding this oxidation have been patented. In the incandescent
electric lamp, although the joint between glass and metal is required
to be perfectly air-tight, the two bodies are only attached to one
another over a very short length. In wired plate glass, however, an
entire layer of wire netting is interposed between two layers of glass,
the wire being inserted during the process of rolling. Here a certain
amount of oxidation of the wire is not of any serious importance, as
it only appears to give rise to a few bubbles, whose presence does
not interfere with the strength and usefulness of the glass; but any
considerable difference of coefficient of expansion will produce the
most serious results on account of the great lengths of glass and
metal that are attached to each other. This factor has been
neglected by some manufacturers, with the result that much of the
wired glass of commerce is liable to crack spontaneously some time
after it has left the manufacturer’s hands, while there is also much
loss by breakage during the process of manufacture.
Thermal expansion is a vital factor in yet another of the uses of
glass. Our ordinary instrument for measuring temperature—the
mercury thermometer—is very considerably affected by the
expansive behaviour of glass. When a mercury thermometer is
warmed the mercury column rises in the stem because the mercury
expands upon warming to a greater extent than the glass vessel,
bulb and stem, in which it is contained. The subject of the
graduations and corrections of the mercury glass thermometer is a
very large one and somewhat outside the scope of the present
volume; but attention should be drawn in this place to the
peculiarities of the behaviour of glass that have been discovered in
this connection. One of these is that when first blown the bulb of a
thermometer takes a very considerable time to acquire its final
volume, the result being, that if a freshly made thermometer is
graduated, after some time the zero of the instrument will be found
considerably changed, generally in a direction which indicates that
the volume of the bulb has slightly increased. By a special annealing
or “ageing” process this change can be completed in a comparatively
short time before the instrument is graduated. There is, however, a
further peculiarity which is prominent in some thermometers,
although very greatly reduced in the best modern glasses. This
becomes apparent in a decided change of zero whenever the
thermometer has been exposed for any length of time to a high
temperature, the zero gradually returning more or less to its original
position in the course of time. With thermometers made of glasses
liable to these aberrations, the reading for a given temperature
depended largely upon the immediate past history of the instrument;
but, thanks to the Jena Works, thermometer glasses are now
available which are almost entirely free from this defect. In this
connection the curious fact has been observed that glass containing
both the alkalies (potash and soda) shows these thermal effects
much more markedly than a glass containing one of the alkalies
only.
The thermal conductivity of glass, except in so far as it affects
the thermal endurance, is not a matter of any great direct practical
importance, although the fact that glass is always a comparatively
poor conductor of heat is utilised in many of its applications, as, for
example, the construction of conservatories and hot-houses,
although even in that case the opacity of glass to thermal radiations
of long wave-lengths is of more importance than its low thermal
conductivity. Similar statements apply, in a still more marked degree,
to the subject of the specific heat of glass.
The electrical properties of glass are of much greater practical
importance, glass being frequently used in electrical appliances as an
insulating medium. The insulating properties of glass, as well as the
property known as the specific inductive capacity, vary greatly
according to the chemical composition of the material. Generally
speaking, the harder glasses, i.e., those richest in silica and lime, are
the best insulators, while soft glasses, rich in lead or alkali, are much
poorer in this respect. In practice, particularly when the glass
insulator is exposed to even a moderately damp atmosphere, the
nature of the glass affects the resulting insulation or absence of
insulation, in another way. Almost all varieties of glass have the
property of condensing upon their surfaces a decided film or layer of
moisture from the atmosphere, and, as we have seen above, glasses
differ very considerably in the degree to which they display this
hygroscopic tendency. The softer glasses are much more
hygroscopic than the hard ones, and the resulting film of surface
moisture serves to lessen or even to break down the insulating
power of the glass, the electricity leaking away along the film of
moisture. In the case of appliances for static electricity, where very
high voltages have to be dealt with, an endeavour is sometimes
made to avoid this leakage by varnishing the surface of the glass
with shellac or other similar substance, and this proves a satisfactory
remedy up to a certain point. Quite recently a variety of glass has
been brought forward which is peculiar in having a comparatively
low electrical resistance, so that for certain purposes it can be used
as an electric conductor. Although interesting in itself, this glass is
not very likely to prove useful even for the limited number of
applications that could be found for an electrically conducting glass,
since it is very rich in alkali, and is, therefore, likely to be unstable
chemically, even under the action of atmospheric agencies alone.
The most valuable and in many ways the most interesting of the
properties of glass—its transparency—has not been dealt with as
yet, and all mention of this subject has been postponed to the end
of the present chapter, because the whole subject of the optical
properties of glass will be dealt with more fully in the chapter on
optical glass (Chap. XII.), so that a very brief reference only need be
made to the matter here.
There can be no doubt that, in most of its practical applications,
transparency is the fundamental and essential property which leads
to the employment of glass in the place of either stronger or cheaper
materials. By transparency, in this sense, we wish to include mere
translucence also, since very frequently it is as necessary to avoid
undisturbed visibility as it is to secure the admission of light. It is
indeed hard to find any use to which glass is extensively put into
which the function of transmitting light does not very largely enter.
Almost the only such example of use is the modern application of
opal glass to the covering of walls, and the use—not as yet widely
extended—of pressed glass blocks as bricks and paving stones; in
these cases it is the hardness and smoothness of surface that gives
to the vitreous body its superiority over other materials, but apart
from these special cases, the fact remains that well over 95 per cent.
of the glass used in the world is employed for purposes where
transmission of light is essential to the attainment of the desired
result, either from the point of view of utility or from that of beauty.
It is interesting to note that the power of transmitting light is not
shared by many solid bodies. Some colloidal organic bodies, such as
gelatine and celluloid, possess the property to a degree comparable
with glass, while certain mineral crystals, such as quartz and fluor-
spar, may even surpass the finest glass in this respect; while some of
the other optical properties of glass are greatly exceeded by such
natural substances as the diamond and the ruby. But the very
brevity of this list is in itself striking, because it must be borne in
mind that transparency by no means constitutes the only common
characteristic of vitreous bodies.
Although the transparency of glass is so valuable and indeed so
essential a property of that substance, it must be remembered that
no kind of glass is perfectly transparent. Quite apart from the fact
that of the light that falls upon a glass surface, however perfectly
polished, a considerable proportion is turned back by reflection at
the surface of entry and again by reflection at the surface of exit
from the glass, a certain proportion of light is absorbed during its
passage through the glass itself, and the transmitted beam is
correspondingly weakened. In the purest and best glasses this
absorption is so small that in any moderate thickness very delicate
instruments are required to show that there has been any loss of
light at all; but even the best glass, when examined through a
thickness of 20 in. or more, always shows the effects of the
absorption of light quite unmistakably. In fact, not only does all glass
absorb light, but it does this to a different degree according to the
colour of the light, so that in passing through the glass a beam of
white light becomes weakened in one of its constituent colours more
than in the others, with the result that the emergent light is slightly
coloured. Thus the purest and whitest of glasses, when examined in
very thick pieces, always show a decided blue or green tint, although
this tint is quite invisible on looking through a few inches of the
glass. The ordinary glass of commerce, however, is far removed from
even this approach to perfect transparency. The best plate glass
shows a slight greenish-blue tint, which is just perceptible to the
trained eye when a single sheet of moderate thickness is laid down
upon a piece of white paper. When a sheet of this glass is viewed
edgewise, in such a way that the light reaching the eye has
traversed a considerable thickness, the greenish-blue tint of the
glass becomes more apparent. By holding strips of various kinds of
glass, cut to an equal length, close together and comparing the
colour exhibited by their ends, a means of comparing the colours of
apparently “white” glasses is readily obtained. It will be found that
different specimens of glass differ most markedly in this respect.
Sheet glass is, as a rule, decidedly deeper in colour than polished
plate, but rolled plate is as a rule much greener—the colour of this
glass can, in fact, in most cases be seen quite plainly in looking
through or at the sheets in the ordinary way.
The question of how far the colour of glass affects the value of
the light which it transmits depends for its answer upon the purpose
to which the lighted space is to be put. Where delicate comparisons
of colour are to be made, or other delicate work involving the use of
the colour sense is to be carried on, it is essential that all colouration
of the entering daylight should be avoided, and the use of the most
colourless glass obtainable will be desirable. Again, in photographic
studios it is important to secure a glass which shall absorb as small a
proportion of the chemically active rays contained in daylight as
possible, and special glasses for this purpose are available. Although
for the present the price of these special glasses may prove
prohibitive for the glazing of studio lights, their use is found highly
advantageous where artificial light is to be used to the best
advantage. On the other hand, for every-day purposes, the slight
tinge of colour introduced into the light by the colour of ordinary
sheet and plate glass, or even of greenish rolled plate glass, has no
deleterious effect whatever, the majority of persons being entirely
unconscious of its presence. The transmission of light by glass, its
absorption, refraction, dispersion, etc., are, however, best grouped
together as the “optical” properties of glass, and under that heading
they will receive a fuller treatment in connection with the subject of
the manufacture of glass for optical purposes.
CHAPTER III.

THE RAW MATERIALS OF GLASS


MANUFACTURE.

The choice of raw materials for all branches of glass


manufacture is a matter of vital importance. As a rule all “fixed”
bodies that are once introduced into the glass-melting pot or furnace
appear in the finished glass, while volatile or combustible bodies are
more or less completely eliminated during the process of fusion.
Thus while the chemical manufacturer can purify his products by
filtration, crystallisation or some other process of separation, the
glass-maker must eliminate all undesirable ingredients before they
are permitted to enter the furnace, and the stringency of this
condition is increased by the fact that the transparency of glass
makes the detection of defects of colour or quality exceedingly easy.
For the production of the best varieties of glass, therefore, an
exacting standard of purity is applied to the substances used as raw
materials. As the quality of the product decreases, so also do the
demands upon the purity of raw materials, until finally for the
manufacture of common green bottles, even such very
heterogeneous substances as basaltic rock and the miscellaneous
residues of broken, defective and half-melted glass forming the
refuse of other glassworks may be utilised more or less satisfactorily.
For the best kinds of glass the most desirable quality in raw
materials is thus as near an approach to purity as possible under
commercial conditions, and next to that, as great a constancy of
composition as possible. For instance, the quantity of moisture
contained in a ton of sand appreciably affects the resulting
composition of the glass, and if the sand cannot be obtained
perfectly dry, it should at least contain a constant proportion of
moisture, otherwise it becomes necessary to determine, by chemical
tests, the percentage of moisture in the sand that is used from day
to day, and to adjust the quantity used in accordance with the
results of these tests, a proceeding which, of course, materially
complicates the whole process. In other cases, variable composition
is not so readily allowed for, and uncontrollable variations in the
composition of the glass result—at times the quality falls off
unaccountably, or the glass refuses to melt freely at the usual
temperature. The systematic employment of chemical analysis in the
supervision of both the raw materials and of various products will
frequently enable the manufacturer to trace the causes of such
undesirable occurrences; but however necessary such control
undoubtedly is, it cannot entirely compensate for the use of raw
materials liable to too great a variation in composition or physical
character. For not only the chemical composition, but also the
physical condition and properties of the material are of importance in
glass manufacture. Thus it is essential that materials to be used for
glass-melting should be obtainable in a reasonably fine state of
division, and in this connection it must be remembered that both
exceedingly hard bodies and soft plastic substances can only be
ground with very great difficulty. Further, where a substance occurs
naturally as a powder, this powder should be of uniform and not too
fine a grain, more especially if it belongs to the class of refractory
rather than of fluxing ingredients. In that case the presence of
coarser grains will result in their presence in the undissolved state in
the finished glass, unless excessive heat and duration of “founding”
be employed to permit of their dissolution. This applies chiefly to
siliceous and calcareous ingredients, but hardened nodules of salt-
cake may behave in a similar manner.
A further consideration in the choice of raw materials is facility of
storage. Thus limestone in the shape of large lumps of stone which
are only ground to powder as required, is readily stored, and
undergoes no deleterious change even if exposed to the weather; on
the other hand, sulphate of soda (salt-cake), if stored even in
moderately dry places, rapidly agglomerates into hard masses, at the
same time absorbing a certain percentage of moisture. Such
properties are not always to be avoided, salt-cake for example being
at the present time an indispensable ingredient in many kinds of
glass-making, but the value of a substance is in some cases
materially lessened by such causes.
The raw materials ordinarily employed in glass-making may be
grouped into the following classes:—
(1) Sources of silica.
(2) Sources of alkalies.
(3) Sources of bases other than alkalies.
(1) Sources of Silica.—The principal source of silica is sand. This
substance occurs in nature in geological deposits, often of very
considerable area and depth. These deposits of sand have always
been formed by the disintegration of a siliceous rock, and the
fragments so formed have been sifted and transported by the
agency of water, being finally deposited by a river either in the sea
(marine deposits) or in lakes (lacustrine deposits), while the action
of the water, either during transport or after deposition, has
frequently worn the individual particles into the shape of rounded
grains.
In consequence of this origin, the chemical composition of sand
varies very greatly with the nature of the rock whose denudation
gave rise to the deposit. Where rocks very rich in silica, or even
consisting of nearly pure silica, have been thus denuded, the
resulting sand is often very pure, deposits containing up to 99·9 per
cent. silica being known. More frequently, however, the sand
contains fragments of more or less decomposed felspar, which
introduce alumina, iron and alkalies into its composition. Finally,
“sands” of all ranges of composition from the pure varieties just
referred to down to the clay marls, very rich in iron and alumina, are
known.
For the best varieties of glass, viz., optical glass, flint glass and
the whitest sheet-glass, as well as for the best Bohemian glass, a
very pure variety of sand is required, preferably containing less than
0·05 per cent. of iron, and not more than 0·05 per cent. of other
impurities such as alumina, lime or alkali. As a matter of fact, sands
containing so little iron rarely contain any other impurity except
alumina in measurable quantities. The best-known deposit of such
sand in Europe is that at Fontainebleau near Paris, but equally good
sand is found at Lippe in Germany, whence sand is delivered
commercially with a guaranteed silica content of 99·98 per cent.
Sand of excellent quality, although not quite so good as the above, is
obtained at Hohenbocka in Germany (Saxony) and at a few other
places in Europe. In England no deposit of sand of such purity is at
present being exploited.
Next in order of value to these exceedingly pure sands, come
the glass-making sands of Belgium, notably of Epinal. These usually
contain from 0·2 to 0·3 per cent. of iron and rather more alumina,
but they are used very largely for the manufacture of sheet and
plate-glass. When the standard of quality is further relaxed, a large
number of sand deposits become available, and the manufacturers
of each district avail themselves of more or less local supplies; thus
in England the sands of Leighton in Bedfordshire and of Lynn on the
East Coast, are largely used. Finally, for the manufacture of the
cheapest class of bottles, sands containing up to 2 per cent. of iron
and a considerable proportion of other substances are employed.
Silica, in various states of purity, occurs in nature in a number of
other forms than that of sand. By far the commonest of these is that
of more or less compact sedimentary rock, known as “sandstone.” As
far as chemical composition is concerned, some of these stones are
admirably suited for making the best kinds of glass, although as a
rule a stone is not so homogeneous as the material of a good sand-
bed. The stone has the further disadvantage that it requires to be
crushed to powder before it can be used for glass-making, and the
crushed product is generally a mixture of grains of all sizes ranging
from a fine dust to the largest size of grain passed by the sieves
attached to the crushing machine. The presence of the very fine
particles is a distinct objection from the glass-maker’s point of view,
so that it would probably be necessary to wash the sand so as to
remove this dust—a process that in itself adds to the cost of the
crushed stone and at the same time leads to the loss of a serious
percentage of the material. Objections of the same kind apply, but
with still greater force, to the use of powdered quartz or flint as
sources of silica for the glass-maker; further, these materials are
exceedingly hard and therefore difficult to crush, so that the price of
the materials is prohibitive for glass-making purposes. The use of
ground quartz and flint is therefore confined to the ceramic
industries in which these substances serve as sources of silica for
both bodies and glazes; in former times, however, ground flint was
extensively used in the manufacture of the best kinds of glass, as
the still surviving name of “flint glass” testifies.
Minerals of the felspar class, consisting essentially of silicates of
alumina and one or more of the alkalies, are extensively used in
glass-making and should be mentioned here, since their high silica-
content (up to 70 per cent.) constitutes an effective source of silica.
As a source of this substance, however, most felspars would be far
too expensive, and their use is due to their content of alumina and
alkali.
(2) Sources of Alkali.—Originally the alkaline constituents of
glass were derived from the ashes of plants and of seaweed or
“kelp”; in both cases the alkali was obtained in the form of
carbonate and was ordinarily used in a very impure form; at the
present time, however, the original source of alkali for industrial
purposes is found in the natural deposits and other sources of the
chlorides of sodium and potassium. At the present time it is not yet
industrially possible to introduce the alkalies into glass mixtures in
the natural form of chlorides. The principal difficulty in doing this
arises from the fact that the chlorides are volatile at the temperature
of glass-melting furnaces and are only acted upon by hot silica in the
presence of water vapour. Introduced into an ordinary glass furnace,
therefore, these salts would be driven off as vapour before they
could combine with the other ingredients in the desired form of
double silicates.
Alkalies are, therefore, introduced into the glass mixture in less
volatile and more readily attackable forms. Of these the carbonate is
historically the earlier, while the sulphate is at the present time
industrially by far the more important. The Carbonate of Soda, or
soda ash, which is used in the production of some special glasses,
and is an ingredient of English flint glasses, is produced by either of
two well-known chemical processes. One of these is the “black ash,”
or “Le Blanc” process, in which the chloride is first converted into
sulphate by the direct action of sulphuric acid, and the sulphate thus
formed is converted into the carbonate by calcination with a mixture
of calcium carbonate and coal. The sodium carbonate thus formed is
separated by solution and subsequent evaporation. A purer form of
sodium carbonate can be obtained with great regularity by the
“ammonia soda” process, in which a solution of sodium chloride is
acted upon by ammonia and carbonic acid under pressure. Soda ash
produced by this process is now supplied regularly for glass-making
purposes in a state of great purity and constancy of composition. It
is upon these qualities that the great advantages of this substance
depend, since its relatively high cost precludes its use except for
special kinds of glass, and for these purposes the qualities named
are of great value.
For most purposes of glass-making, such as the production of
sheet and plate-glass of all kinds, the alkali is introduced in the form
of salt-cake—i.e., sulphate of soda. This product is obtained as the
result of the first step of the Le Blanc process of alkali manufacture
—i.e., by the action of sulphuric acid on sodium chloride; salt-cake is
thus a relatively crude product, and its use is due to the fact that it
is by far the cheapest source of alkali available for glass-making.
There are, however, certain disadvantages connected with its use.
The chief of these is the fact that silica cannot decompose salt-cake
without the aid of a reducing agent; such a reducing agent is partly
supplied by the flame-gases in the atmosphere of the furnace, but in
addition to these a certain proportion of carbon, in the form of coke,
charcoal or anthracite coal must be added to all glass mixtures
containing salt-cake. The use of a slightly incorrect quantity of
carbon for this purpose leads to disastrous results, while even under
the best conditions it is not easy to remove all traces of sulphur
compounds from glass made in this way. A further risk of trouble
arises in connection with salt-cake from the fact that it is never
entirely free from more or less deleterious impurities. According to
the exact manner in which it has been prepared, the substance
always contains a small excess either of undecomposed sodium
chloride or of free sulphuric acid, or the latter may be present in the
form of sulphate of lime. A good salt-cake, however, should contain
at least 97 per cent. of anhydrous sodium sulphate, and not more
than 1·0 per cent. of either sodium chloride or sulphuric acid. While
pure sodium sulphate is readily soluble in water, ordinary salt-cake
always leaves an insoluble residue, consisting frequently of minute
particles of clay or other material derived from the lining of the
furnace in which it was prepared, or from the tools with which it was
handled; and these impurities are liable to become deleterious to the
glass if present in any quantity. The insoluble residue should not
exceed 0·5 per cent. in amount, and in the best salt-cake is
generally under 0·2 per cent.
Salt-cake possesses certain other properties that make it
somewhat troublesome to deal with as a glass-making material.
Thus, on prolonged exposure, particularly to moist air, the powdered
salt-cake absorbs moisture from the atmosphere and undergoes
partial conversion into the crystalline form of “Glauber’s Salt,” a
process which results in the formation of exceedingly hard masses.
Ground salt-cake, therefore, cannot be stored for any length of time
without incurring the necessity of regrinding, and this accretive
action even comes into play when mixtures of glass-making
materials, containing salt-cake as one ingredient, are stored. In
practice, therefore, salt-cake can only be ground as it is wanted, and
its physical properties make it difficult to grind it at all fine, while the
dust arising from this process is peculiarly irritating, although not
seriously injurious to health.
Potash is utilised in glass-making almost entirely in the form of
carbonate, generally called “pearl-ash.” Originally derived from the
ashes of wood and other land plants, this substance is now
manufactured by processes similar to those described in the case of
soda, the raw material being potassium chloride derived from natural
deposits such as those at Stassfurth. The pearl-ash thus
commercially obtainable is a fairly pure substance, but its use is
complicated by the fact that it is strongly hygroscopic and rapidly
absorbs water from the atmosphere. Where it is desired to produce
potash glasses of constant composition, frequent analytical
determinations of the moisture contents of the pearl-ash are
necessary, and the composition of the glass mixture requires
adjustment in accordance with the results of these determinations.
The alkalies are also introduced into glass in the form of nitrates
(potassium nitrate, or saltpetre, and sodium nitrate, or nitre); but
although these substances act as sources of alkali in the glass, they
are employed essentially for the sake of their oxygen contents. Such
oxidising agents are not, of course, added to glass mixtures
containing sulphates and carbon, but are employed to purify the
mixtures containing alkali carbonates, and more especially to oxidise
the flint glasses. Since these substances are only introduced into
glass in small quantities their extreme purity is not of such great
importance to the glass-maker, and the ordinary “refined” qualities
of both nitrates are found amply pure enough to answer the highest
requirements.
A certain number of natural minerals which contain an
appreciable quantity of alkali are sometimes utilised as raw materials
for glass manufacture. The most important of these are the minerals
of the felspar class already referred to. These, however, contain a
considerable proportion of alumina, while all but the purest varieties
also contain more or less considerable quantities of iron. Some
glass-makers regard alumina as an undesirable constituent, while
others take the opposite view, and upon this view their use of
felspathic minerals will depend. For the cheaper varieties of glass,
however, such as bottle glass, felspathic minerals and rocks, such as
granite and basalt, are freely used as raw materials. Another mineral
in which both alkali and alumina are found is cryolite. This mineral is
a double fluoride of soda and alumina, whose properties are
particularly valuable in the production of opal and opalescent
glasses. As a mere source of alkali, however, cryolite is much too
expensive.
(3) Sources of Bases other than Alkalies.—The most important of
these are lime and lead oxide, the former being required for the
production of all varieties of plate and sheet-glass, as well as for
bottles and a large proportion of pressed and blown glass, while lead
is an essential ingredient of all flint glass. The only other base
having any considerable commercial importance in connection with
glass-making is barium oxide, while oxide of zinc, magnesia, and a
few other substances are used in the manufacture of special glasses
for scientific, optical or technical purposes, where glass of special
properties is required. The metallic oxides which are used for the
production of coloured glass are, of course, also basic bodies. These
will be treated in connection with coloured glasses, with the
exception of manganese dioxide, which is used in large quantities in
the manufacture of many ordinary “white” glasses.
Calcium Oxide (lime) is generally introduced into glass mixtures
in the form of either the carbonate or the hydrated oxide (slaked
lime). The carbonate may be derived either from natural sources, or
it may be of chemical origin, while the hydrate is always obtained by
the calcination of the carbonate, followed by “slaking” the lime thus
produced. Natural calcium carbonate occurs in great quantities in the
form of chalk and limestone rocks. Both varieties are used for glass-
making. Chalk is a soft friable material which is apt to clog during
the grinding operations, particularly as the natural product is
generally somewhat moist. As regards the greater part of its mass,
chalk is often found in a state of great purity, but it is frequently
contaminated by the presence of scattered masses of flint.
Chemically this impurity is not very objectionable to the glass-maker,
since it merely introduces a small proportion of silica whose
presence need scarcely be allowed for in laying down the mixture.
On the other hand, if any fragments of flint remain in the mixture
when put into the furnace, they prove very refractory, and are apt to
be found as opaque enclosures in the finished glass. Natural
limestone can also be obtained in great purity in many parts of the
world. It is generally a hard and rather brittle rock that can be
readily ground to powder of the requisite degree of fineness. Flint
concretions are not so frequently found in this material, but, on the
other hand, it is often contaminated with magnesia and iron. The
former ingredient, when present in small quantities, tends to make
the glass hard and viscous, so that limestone of the lowest possible
magnesia content should be used, especially for the harder kinds of
glass, such as plate and sheet-glass, etc. The iron contents of the
limestone used must also be low where a white glass is required; but
since a smaller quantity of limestone is used for a given weight of
glass produced than the quantity of sand used for the same
purpose, the presence of a somewhat higher percentage of iron is
permissible in the limestone as compared with the sand; for the
better varieties of glass, however, the iron should not exceed 0·3 per
cent. of the limestone.
Slaked lime is sometimes used as the source of lime for special
glasses where the process of manufacture renders it desirable to
avoid the evolution of carbonic acid gas which takes place when the
carbonate is heated and attacked by silica. When slaked lime is used
only the water vapour of the hydrate is driven off, and this occurs at
a much lower temperature. For the production of slaked lime, an
adequately pure form of limestone, preferably in the form of large
lumps, is burnt in a kiln until the carbonic acid is entirely driven off;
after cooling, the lime so formed is slaked by hand. The product so
obtained is, however, apt to vary both as regards contents of
moisture and carbonic acid, which latter is readily absorbed from the
atmosphere; the use of this material, therefore, requires frequent
analytical determinations of the lime contents and corresponding
adjustments of the mixture if constant results are required.
It is possible to introduce lime into glass mixtures in the form of
gypsum or calcium sulphate, but the decomposition of this
compound, like that of sodium sulphate, requires the intervention of
a reducing agent such as carbon, and the difficulties arising from
this source in connection with the use of salt-cake are still further
increased in the case of the calcium compound. Since limestones of
considerable purity are more or less plentiful in many districts, the
commercial value of calcium sulphate for glass-making is probably
slight.
The Compounds of Barium may best be dealt with at this stage,
since they are chemically so closely allied to the compounds of lime
just described. Barium occurs in nature in considerable quantities in
the minerals known as barytes (heavy spar) and witherite
respectively. The former is essentially sulphate of barium, while the
latter is a carbonate of barium. The use of the sulphate meets with
the same objection here as in the case of calcium sulphate discussed
above, except that the barium compound is much more easily
reduced and decomposed than the lime compound. The natural
mineral witherite is used to a considerable extent in the production
of barium glasses, and these have been found capable of replacing
lead glasses for certain purposes. On the other hand, for the best
kinds of barium glasses, viz., those required for optical purposes, the
element is introduced in the form of artificially prepared salts. Of
these the most important is the carbonate, commercially described
as “precipitated carbonate of barium”; this precipitated compound,
however, does not ordinarily correspond to the chemically pure
substance, but contains more or less considerable quantities of
sulphur compounds. The question whether these impurities are or
are not objectionable can only be determined for each particular
case, since much depends upon the special character of the glass to
be produced. Both the nitrate and the hydrate of barium are
commercially available, but they are very costly ingredients for use in
the production of even the most expensive kinds of glass; these
substances are, however, obtainable in a state of considerable purity,
although the hydrate has the inconvenient property of rapidly
absorbing carbonic acid from the atmosphere, thus becoming
converted into the carbonate.
Magnesia is another glass-forming base that is closely related,
chemically, to calcium and barium. This element is usually introduced
into glass mixtures in the form of either the carbonate or the oxide.
The carbonate occurs in nature in a more or less pure state in the
form of magnesite, and by calcination, the oxide is obtained. The
natural mineral and its product are, of course, by far the cheapest
sources of magnesia, but as the element is only used in
comparatively small quantities, the artificial precipitated carbonate or
calcined magnesia are frequently preferred. Magnesia is only
introduced intentionally in notable quantities in special glasses where
the properties it confers are of special value; in ordinary lime glasses
this element, as has already been mentioned, is to be regarded as
an undesirable impurity.
Zinc oxide lies, chemically, between the bases already discussed
on the one hand, and lead oxide on the other. This element is only
introduced into special optical glasses, a special “zinc crown” having
found some application. Chemically prepared zinc oxide is almost the
only form in which the element is used, but the very volatile
character of this substance must be borne in mind when it is
introduced into glass mixtures.
Lead is one of the most widely-used ingredients of glass; the
glasses containing this substance in notable quantity are all
characterised to a greater or less degree by similar properties, such
as considerable density and high refractive power, and are classed
together under the name “flint glasses.” Lead is now almost
universally introduced into glass mixtures in the form of red lead,
although the other oxides of lead might be employed almost equally
well. Red lead is a mixture of two oxides of lead (PbO and Pb2O3) in
approximately such proportions as to correspond to the formula
Pb3O4. It is prepared by the roasting of metallic lead in suitable
furnaces, where the molten lead is exposed to currents of hot air.
The product is obtainable in considerable purity, very small
proportions of silica, derived from the furnace bed, and of iron
derived from the tools with which the lead is handled, being the
principal foreign substances found in good red lead. Silver would be
an objectionable impurity, but owing to the modern perfect methods
of de-silvering lead, that element is rarely found in lead products.
Analytical control of red lead as used in the glass mixtures, and
consequent adjustments of the mixture, are, however, necessary
where exact constancy in the glass produced is desired. The reason
for this necessity lies in the fact that the oxygen content, and
therefore the lead-oxide (PbO) content, varies decidedly from batch
to batch, while the material as actually delivered and used frequently
contains notable proportions of moisture.
A word should perhaps be said here as to methods of handling
red lead on account of the injurious effects which the inhalation of
lead dust produces upon the workmen exposed to it. For glass-
making purposes it is not feasible to adopt the method adopted by
potters of first “fritting” the lead and thus rendering it comparatively
insoluble and innocuous; even if this were done, the difficulty would
only be moved one step further back, and would have to be
overcome by those who undertook the preparation of the frit. The
proper solution of the problem, in the writer’s opinion, is to be found
in properly preventing the formation of lead dust, or at all events in
protecting the workmen from the risk of inhaling it. Where only small
quantities of lead glass are made, and therefore only small quantities
of lead are handled and mixed at a time, it is no doubt sufficient to
provide the workmen engaged on this task with some efficient form
of respirator to be worn during the whole of the time that they are
engaged on such work, and to take the further precautions
necessary—by way of cleanliness and the provision of proper mess-
rooms—to avoid any risk of lead dust either directly or indirectly
contaminating their food. Where, however, large quantities of flint-
glass are made every day, it is possible and proper to make more
perfect arrangements for the mechanical handling and mixing of the
lead with the other ingredients by the provision of suitable mixing
and transporting machinery, so arranged as to be dust-tight. It is
only fair to state, however, that partly under their own initiative,
partly under pressure from the authorities, glass makers in this
country are complying with these requirements in an adequate
manner.
Aluminium.—There are several varieties of glass into which
alumina enters in notable quantities, the principal examples being
certain optical and many opal glasses, while most ordinary glasses
contain this substance in greater or less degree. In the latter, the
alumina is derived by the inevitable processes of solution, from the
fire-clay vessels or walls within which the molten glass is contained,
while in some cases the element is intentionally introduced in small
proportions (about 2 per cent. to 3 per cent. of Al2O3) by the use of
felspar as an ingredient of the mixture. Where larger proportions of
alumina are required, the substance is introduced in the form of the
hydrate, which is obtainable commercially in a state of almost
chemical purity, but of course at a correspondingly high cost. In opal
glasses alumina is derived partly or wholly from felspars, or in some
cases from the use of the mineral cryolite. This is a double fluoride
of aluminium and sodium which is found in great natural masses,
chiefly in Greenland. Owing to the high price of this mineral,
however, artificial substitutes of nearly identical composition and
properties have been introduced and are used successfully in the
glass and enamelling industries.
Manganese.—Although the oxides of this element really belong
to the class of colouring compounds, they are so widely used in the
manufacture of ordinary “white” glasses that it is desirable to deal
with them here. The element manganese is most usually introduced
into glass mixtures in the form of the per-oxide (MnO2), although
the lower oxide (Mn3O4) can also be used. The material ordinarily
used is the natural manganese ore, mined chiefly in Russia; the
purest forms of this ore consist almost entirely of the per-oxide, but
“brown” ores, containing more or less of the lower oxide, are also

You might also like