MODERN COMPUTING**
This chapter provides an overview of a few select areas of modern computing. Given the diversity and breadth in computing, I had a wide range of topics to choose from. The areas I chose are by no means an exhaustive list of the interesting things happening in computing today. Instead, they represent a handful of topics that I believe are worth your consideration. In this chapter we cover apps, virtualization, cloud computing, Bitcoin, and more. We wrap up with a final project that brings together many of the topics covered in this book.
Apps
Since the early days of computing, people have referred to software programs that are used directly by users as applications . This term was shortened to app as a convenience, and in the past, the two terms were interchangeable. However, since Apple opened the iPhone App Store in 2008, the word app has taken on a distinct meaning. Although there is no standard technical definition for what makes a software program an app, apps tend to share a number of common characteristics.
Apps are designed for end users. Apps often target a mobile device, such as a smartphone or tablet. Apps are typically distributed through an internet-based digital storefront (an app store ), such as Apple’s App Store, the Google Play Store, or the Microsoft Store. Apps have limited access to the system on which they run, and often must declare what specific capabilities they require to operate. Apps tend to use touchscreens as their primary means of user input. The term app , when used alone, usually implies software installed on a device that makes direct use of the operating system’s API. In other words, the term app usually means a native app , an app built for a particular operating system. In contrast, web apps are apps designed with web technology (HTML, CSS, and JavaScript), and are not tied to a particular OS. Figure 13-1 provides a high-level look at native apps and web apps.
Figure 13-1: Native apps are built for a particular OS. Web apps are built using web technology.
As shown in Figure 13-1 , native apps are typically installed from an app store and are designed to utilize the capabilities of a specific operating system. Web apps typically run from a website and are designed to use web technologies. Web apps run in a browser or another process that renders web content. Let’s now look at both native apps and web apps in more detail.
Native Apps
As mentioned earlier, native apps are built for a particular operating system. Apple’s App Store and the similar app stores that followed it ushered in a new era of native software development, giving developers new platforms to target, new methods of distributing their software, and new ways to make money with software. The current state of native app development is largely focused on two platforms: iOS and Android. Software is certainly still developed for other operating systems, but often that software doesn’t have the typical characteristics of an app (mobile-friendly, touch-input based, distributed via an app store, and so forth).
Android and iOS differ in their programming languages, APIs, and more. Therefore, writing an app that runs on both iOS and Android requires either maintaining separate codebases or the use of a cross-platform framework like Xamarin, React Native, Flutter, or Unity. These cross-platform solutions abstract the underlying details of each operating system API, making it possible for developers to write code that can be built to run on multiple platforms. Many native apps also rely on web services, meaning that app developers must not only write and maintain code for iOS and Android, but they must also build or integrate with web services.
Developing a cross-platform, web-connected app requires a good deal of work and expertise! In the past, developers would often focus on just one platform, such as Windows PCs or Macs. Things are certainly more complicated today for the developer targeting multiple platforms and the web. Platform competition is generally a good thing for users, but it does mean more work for developers.
Interestingly, the current state of app development could have turned out quite differently. When the iPhone was announced in January 2007, Steve Jobs (Apple’s CEO at the time) had this to say about third-party app development on the iPhone:
The full Safari engine is inside of iPhone. And so, you can write amazing Web 2.0 and Ajax apps that look exactly and behave exactly like apps on the iPhone. And these apps can integrate perfectly with iPhone services. They can make a call, they can send an email, they can look up a location on Google Maps. And guess what? There’s no SDK that you need!
NOTE
An SDK (software development kit) is a collection of software used by developers to build applications for a particular platform .
Based on this quote, Apple’s original plan for third-party app development was to simply let developers build app-like websites that could make use of the iPhone’s capabilities. Native app development would be limited to the apps that Apple developed and included with the iPhone, such as the Camera, Mail, and Calendar apps.
At the time, using the web as a platform for application development wasn’t common. Apple’s position was forward-looking. Unfortunately, the underlying technologies of the web in 2007 were arguably not mature enough to position the web as a true app platform. By October 2007, Apple changed its message, announcing that Apple would allow developers to build native apps for the iPhone. Apple opened the App Store in 2008 as the only supported mechanism for distributing native iPhone apps to users.
Apple’s policy reversal benefited the company, as the App Store became a source of revenue for Apple. There is a fee to register as an App Store developer, plus Apple takes a percentage of every sale. The App Store and native iPhone development also opened the door for exclusive content, apps that only worked on Apple devices.
The App Store also presents benefits to end users. A curated list of apps with ratings is helpful, and the store provides a measure of consumer trust. Apps that make it into the App Store must meet certain quality guidelines. A centralized payment service means users don’t have to give their payment information to multiple companies. Apps are automatically updated, an advantage over traditional PC software, although not an advantage over the web, since web apps are also updated without user involvement.
With the success of Apple’s App Store, other companies created similar digital storefronts for distributing software. The Google Play Store, Microsoft Store, and Amazon Appstore all operate on a similar model to Apple’s store and provide similar benefits. Although this system has generally worked well for these companies and for end users, it has also created a complex environment for developers: multiple stores, multiple platforms, and varying technologies. Each digital marketplace has its own requirements that app developers must meet, and each store takes a percentage of sales revenue.
Web Apps
Alongside the rise of native apps, the web matured into a platform that’s quite capable of running apps. A mature version of HTML known as HTML5 was introduced, and web browsers became more capable and consistent in their handling of content. Browser developers made their implementations of JavaScript compliant with the ECMAScript 5 standard, providing a better foundation for JavaScript code. Outside of browser updates, the web developer community embraced (and continues to embrace) a concept known as responsive web design , an approach that ensures web content renders well no matter the size of screen on which it’s displayed. Using responsive design techniques, web developers can maintain a single website that works well across diverse devices, rather than creating separate websites that target different devices. Also, multiple web development frameworks , such as Angular and React, have been released in recent years. These frameworks make it easier for developers to write and maintain web apps —websites that behave like apps.
Developers have realized that modern web technology can be used to build experiences that closely resemble native apps, and many developers build websites that function as apps. Some developers have chosen to forgo native apps altogether and only build web apps. The advantages of this approach are that a web app will run on any device with a modern web browser, and the code only has to be written once. However, web apps also have some disadvantages. Web apps don’t have access to the full range of device capabilities, tend to be slower than native apps, require the user to be online, and generally aren’t listed in app stores.
To address some of the disadvantages of web apps, Progressive Web Apps (PWAs) offer a set of technologies and guidelines that help bridge the gap between native apps and web apps. A PWA is just a website with a few extra features that help it be more app-like. A Progressive Web App must be served over HTTPS, render appropriately on mobile devices, be able to load while offline once downloaded, provide a manifest to the browser that describes the app, and transition quickly between pages. To the end user, running a PWA should feel as responsive and natural as running a native app. If a website meets the criteria for a PWA, modern web browsers give users the option of adding an icon for the PWA to their home screen or desktop. Doing so means that users can launch the web app just like they would launch a native app. The app opens in its own window, rather than in a browser window, and generally behaves like a native app.
PWAs can potentially offer great benefits to developers who wish to use web technologies for their apps but don’t want to build multiple apps for different platforms. However, there are still some drawbacks to PWAs. A significant one is that PWAs don’t appear in app stores. Mobile operating systems have been training users for years that apps should be obtained through app stores. Users aren’t accustomed to browsing to a web page to get an app. At the time of this writing, only the Microsoft Store allows PWAs to be published directly to the store. Other platforms expect PWAs to be installed from the browser or repackaged as a native app that renders the web content. This repackaged app can then be submitted to the store. Another potential drawback is that PWAs may not look like native apps; they will usually look essentially the same on all platforms, although some might consider this a good thing. PWAs still don’t have the performance of a native app or access to all the capabilities of the underlying platform, but depending on the needs of the app, this isn’t necessarily an issue.
Virtualization and Emulation
When is a computer not a physical device? When it’s a virtual computer, of course! Virtualization is the process of using software to create a virtual representation of a computer. A related technology, emulation , allows applications designed for a certain type of device to run on a totally different type of device. In this section we explore both virtualization and emulation.
Virtualization
A virtual computer, known as a virtual machine (VM) , runs an operating system just like a physical computer. In turn, applications run on that operating system. From the perspective of the application, the virtualized hardware acts like a physical computer. Virtualization enables several useful scenarios. A computer running one operating system can run another operating system in a virtual machine. For example, a computer running Windows can run an instance of Linux in a virtual machine. Virtual machines also allow datacenters to host multiple virtual servers on a single physical server. This provides a way for internet hosting companies to easily and quickly provide dedicated servers to their customers, as long as the customer is fine with a virtual server. VMs can be easily backed up, restored, and deployed.
A hypervisor is a software platform that runs virtual machines. There are two types of hypervisors, as illustrated in Figure 13-2 .
Figure 13-2: Type 1 and type 2 hypervisors
As shown on the left side of Figure 13-2 , a hypervisor can interact directly with underlying hardware, actually placing the hypervisor below the kernel in the technology stack. The hypervisor talks to the physical hardware and presents virtualized hardware to the OS kernel. This is known as a type 1 hypervisor . In contrast, type 2 hypervisors , shown on the right in Figure 13-2 , run as an application on an operating system. Microsoft’s Hyper-V and VMware ESX are type 1 hypervisors, whereas VMware Player and VirtualBox are examples of type 2 hypervisors.
Another popular approach for virtualization is the use of containers. A container provides an isolated user mode environment in which to run applications. Unlike a virtual machine, a container shares a kernel with the host OS and with other containers running on the same computer. A process running in a container can only see a subset of the resources available on the physical machine. For example, every container can be granted its own isolated filesystem. Containers provide the isolation of a VM without the overhead of running a separate kernel for each VM. In general, containers are limited to running the same operating system as the host since the kernel is shared. Some container technologies, like OpenVZ, are used to virtualize the entire user mode portion of operating systems, whereas others, like Docker, are used to run individual applications in isolated containers.
NOTE
You may recall that an operating system process was also described as a “container” in Chapter 10 —this isn’t the same thing as a virtualization container .
Emulation
Emulation is the use of software to make one type of device behave like another type of device. Emulation and virtualization are similar in that they both provide a virtual environment for running software, but whereas virtualization offers up a slice of the underlying hardware, emulation presents virtual hardware that’s unlike the physical hardware in use. For example, a virtual machine or container running on an x86 processor runs software compiled for x86, directly making use of the physical CPU. In contrast, an emulator (a program that performs emulation) running on x86 hardware can run software compiled for a completely different processor. Emulators often also provide other virtual hardware besides the processor.
For example, a complete emulator for the Sega Genesis (a video game system from the 1990s) will emulate a Motorola 68000 processor, a Yamaha YM2612 sound chip, input controllers, and every other piece of hardware found in a Sega Genesis. At runtime, such an emulator translates CPU instructions originally designed to run on a Sega Genesis to capabilities implemented in x86 code. This introduces significant overhead, since each CPU instruction must be translated, but a sufficiently fast modern computer can still emulate the much slower Sega Genesis at full speed. The result is the ability to run software intended for one platform on a completely different platform, as shown in Figure 13-3 .
Figure 13-3: Code compiled for System A can run on an emulator for System A
Emulation plays an important role in preserving software designed for obsolete platforms. As computing platforms age, it becomes increasingly difficult to find working hardware. Emulation is commonly used by software developers who want to bring old software to a modern platform. The original source code may be lost, or the task of modernizing it may be burdensome. In such cases, investing in an emulator allows the original compiled code to run on a new platform without modification.
PROCESS VIRTUAL MACHINES
There’s another type of virtual machine that shares some traits with emulators. A process virtual machine runs an application within an execution environment that abstracts the details of the underlying operating system. It’s similar to an emulator in that it provides a platform for execution that’s decoupled from the hardware and OS on which it runs. However, unlike an emulator, a process VM isn’t trying to simulate real hardware. Rather, it provides an environment designed for running platform-independent software. As we discussed in Chapter 9 , Java and .NET make use of process virtual machines that run bytecode.
Cloud Computing
Cloud computing is the delivery of computing services over the internet. In this section, we’ll look at various types of cloud computing, but first let’s quickly review the history of remote computing.
The History of Remote Computing
Since the beginning of computing, we can observe a pendulum swing from remote, centralized computing (servers accessed from terminals), to local computing (desktop computers), and now back to remote computing (the web) accessed from smart, local devices (such as smartphones). Many applications today rely on a combination of remote computing and local computing. In the case of the web, some code runs in a browser and some code runs on a web server. The devices we carry in our pockets today are significantly more powerful than the room-sized computers from the early days of computing, yet much of what we want to do on those devices involves communicating with other computers, so it makes sense that the responsibility of processing should be shared between local devices and remote servers.
With this reemergence of remote computing came a need for organizations to maintain servers. In the past, this meant purchasing a physical server, configuring it as needed, connecting it to the network, and letting it run in a closet somewhere. The organization had physical access to the machine and complete control over its configuration. However, maintaining a server (or a fleet of servers) can be a complex and costly endeavor. This includes the costs of purchasing and maintaining hardware, keeping up with software updates, dealing with security concerns and capacity planning concerns, managing the networking configuration, and so forth. Often the skillset and expertise required for this work doesn’t align well with the purpose of an organization. Even a technology-focused company doesn’t necessarily want to be in the business of maintaining servers. This is where cloud computing comes in.
Cloud computing delivers remote computing capabilities over the internet (the cloud ). Underlying hardware is maintained by a cloud services company (the cloud provider ), freeing the organization or user in need of such capabilities (the cloud consumer ) from maintaining servers. Cloud computing allows for the purchase of computing services on demand, as needed. For the cloud consumer, this means releasing control of certain things and trusting a third party to deliver reliable service. Cloud computing takes many forms; let’s look at some of those forms here.
The Categories of Cloud Computing
The various categories of cloud computing are typically defined by the line that divides the responsibility between the cloud provider and the cloud consumer. Figure 13-4 provides an overview of four categories of cloud computing (IaaS, PaaS, FaaS, and SaaS) and their respective divisions of responsibility. We’ll look at each of these categories momentarily.
Figure 13-4: Distribution of responsibility in various types of cloud offerings
The vertical stacks in Figure 13-4 represent the components needed to run an application. No matter which category of cloud computing is used, all the components need to be present—the difference across categories lies in whether the cloud provider or the cloud consumer is responsible for managing each component. The various components in each stack should look familiar, since we’ve covered these topics already. However, runtime requires an explanation. A runtime environment is the environment in which an application executes, including any needed libraries, interpreters, process virtual machines, and so forth. Let’s now cover the four categories of cloud computing shown in Figure 13-4 , progressing from left to right.
Infrastructure as a Service (IaaS) is a cloud computing scenario in which a cloud provider manages hardware and virtualization only, allowing the consumer to manage the operating system, runtime environment, application code, and data. A consumer of IaaS typically gets an internet-connected, virtual computer to use as they see fit, typically as a server of some sort. This virtual computer is usually implemented as a hypervisor-based virtual machine or a container of the user mode portion of a Linux distribution. The consumer of an IaaS virtual server has access to the virtual computer’s operating system and is able to configure it however they wish. This gives the consumer maximum flexibility, but it also means that the responsibility of maintaining the system’s software (including the operating system, third-party software, and so forth) sits squarely on the shoulders of the consumer. IaaS provides a virtual computer, and the consumer is responsible for everything that runs on that computer. Here are some examples of IaaS: Amazon Elastic Compute Cloud (EC2), Microsoft Azure Virtual Machines, and Google Compute Engine.
Platform as a Service (PaaS) gives the cloud provider more responsibility. In a PaaS scenario, the cloud provider manages not only hardware and virtualization, but also the operating system and runtime environment that the consumer wishes to use. A PaaS consumer develops an application that’s targeted to run on their chosen cloud platform, taking advantage of the various capabilities that are unique to that platform. Cloud consumers of PaaS offerings don’t need to concern themselves with maintaining the underlying OS or runtime environment. The cloud consumer can just focus on their application code. Although the provider does abstract away the details of the underlying system, the consumer still needs to manage what resources are provisioned by the provider to handle their application. This includes the amount of storage required and the type of allocated virtual machines. PaaS provides a managed platform for running code, and the consumer is responsible for the application that runs on that platform. Here are some examples of PaaS: Amazon Web Services Elastic Beanstalk, Microsoft Azure App Service, and Google App Engine.
Function as a Service (FaaS) takes the PaaS model one step further. It does not require the consumer to deploy a full application or to provision platform instances ahead of time. Instead, a consumer only needs to deploy their code (a function) that runs in response to certain events. For example, a developer could write a function that returns the distance to the nearest grocery store. This function could run in response to a web browser sending its current GPS coordinates to a URL. This event-driven model means that the cloud provider is responsible for an on-demand invocation of the consumer’s code. The consumer no longer needs to have application code running all the time, waiting for requests. This can simplify things for the consumer and reduce costs, although it can mean a slower response time when a request comes in if the function code isn’t already running.
FaaS is a type of serverless computing , a cloud computing model where consumers do not have to deal with managing servers or virtual machines. Of course, the term is a misnomer; servers are actually required to run the code, it’s just that the consumer doesn’t have to think about them! FaaS provides an event-driven platform for running code, and the consumer is responsible for the code that runs in response to events. Some examples of FaaS include Amazon Web Services Lambda, Microsoft Azure Functions, and Google Cloud Functions.
Software as a Service (SaaS) is a fundamentally different type of cloud service. SaaS delivers an application to the consumer that’s fully managed in the cloud. Whereas IaaS, PaaS, and FaaS are for software engineering teams who want to run their own code in the cloud, SaaS delivers a complete cloud application to end users or organizations, already written. So much software runs in the cloud today that this may seem unremarkable, but it stands in contrast to a user or organization installing and maintaining software on their local devices and network. SaaS provides a complete application managed in the cloud, and the consumer is only responsible for the data they store in that application. Even management of data is partially handled by the provider, including the details of how the data is stored, backed up, and so forth. Some examples of SaaS include Microsoft 365, Google G Suite, and Dropbox.
Some of the major players in the cloud provider space are Amazon Web Services, Microsoft Azure, Google Cloud Platform, IBM Cloud, Oracle Cloud, and Alibaba Cloud.
The Deep Web and Dark Web
You have probably read news about nefarious happenings on the dark web or the deep web. Unfortunately, the two terms are often confused, but they have distinct meanings. The web can be divided into three broad segments: the surface web, the deep web, and the dark web, as illustrated in Figure 13-5 .
Figure 13-5: The surface web, deep web, and dark web
Content that’s freely available for anyone to access is part of the surface web . Public blogs, news sites, and public Twitter posts are all examples of surface web content. The surface web is indexed by search engines, and sometimes the surface web is defined as content that can be found with a search engine.
The deep web is web content that cannot be accessed without logging in to a website or web service. Most internet users access deep web content on a regular basis. Checking your bank balance, reading your email through a website like Gmail, logging in to Facebook, looking at your personal shopping history on Amazon—these are all examples of deep web activities. The deep web is simply content that’s not publicly available and generally requires a password of some sort to access. Most users don’t want their email or bank balances to be publicly available, so there’s a good reason why this type of content isn’t public and cannot be indexed by search engines.
The dark web is web content that requires specialized software to access. You cannot access the dark web using only a standard web browser. The most prevalent dark web technology is Tor (the onion router) . Through a system of encryption and relays, Tor allows for anonymous access to the web, preventing a user’s ISP from monitoring which sites are accessed, and preventing sites from knowing their visitor’s IP address. Additionally, Tor allows users to access websites known as onion services that cannot be accessed at all without Tor—these sites are part of the dark web. Tor hides the IP addresses of onion services, making them anonymous as well. As you might expect, the anonymity of the dark web is sometimes exploited for criminal purposes. However, there are legitimate uses for the privacy afforded by the dark web, such as whistleblowing and political discussion. I recommend caution when accessing content on the dark web.
Bitcoin
A cryptocurrency is a digital asset intended to be used for financial transactions, as a substitute for a traditional currency like the US dollar. Users of cryptocurrencies maintain a balance of that currency, much like at a traditional bank, and can spend their currency on goods and services. Some users treat cryptocurrencies primarily as an investment rather than a means of commerce, making it more akin to something like gold for those users. Unlike traditional currencies, cryptocurrencies are typically decentralized, with no single organization controlling their use.
Bitcoin Basics
Introduced in 2009, Bitcoin was the first decentralized cryptocurrency, and it’s the most well-known today. Since then, a large number of alternate cryptocurrencies (known as altcoins ) have sprung up, but none have challenged the dominance of Bitcoin. Bitcoin’s main unit of currency is also simply called bitcoin , abbreviated BTC .
Bitcoin and similar cryptocurrencies are based on blockchain technology. In a blockchain, information is grouped into data structures called blocks , and blocks are linked together chronologically. That is, when a new block is created, it’s added to the end of a blockchain. In the case of Bitcoin, blocks hold transaction records, tracking the movement of bitcoins. Figure 13-6 illustrates the Bitcoin blockchain.
Figure 13-6: Bitcoin’s blockchain links chronological blocks of transaction records.
Blockchains operate over a network such as the internet, with multiple computers working together to process transactions and update the blockchain. The computers that work together to process Bitcoin transactions are known as the Bitcoin network . A computer that connects to the Bitcoin network is called a node , and certain nodes hold a copy of the blockchain; there is no single master copy. Encryption and decryption are employed to ensure the integrity of transactions and prevent tampering with the data in the blockchain. Once written, blockchain data is immutable—it can’t be changed. Bitcoin’s blockchain is a public, decentralized, immutable ledger of transactions. This ledger is used to record all events that occur on the Bitcoin network, such as the transfer of bitcoins.
Bitcoin Wallets
An end user’s bitcoins are stored in a Bitcoin wallet . However, more accurately, a Bitcoin wallet holds a collection of cryptographic key pairs, as illustrated in Figure 13-7 .
Figure 13-7: A Bitcoin wallet contains key pairs. A Bitcoin address is derived from a public key.
As shown in Figure 13-7 , each key pair in a wallet consists of two numbers—a private key and a public key. The private key is a randomly generated 256-bit number. This number must be kept secret; anyone who knows the private key can spend the bitcoins associated with the key pair. The public key , which is used to receive bitcoins, is derived from the private key. When receiving bitcoins, the public key is represented as a Bitcoin address , a text string generated from the public key. Here’s an example Bitcoin address: 13pB1brJqea4DYXkUKv5n44HCgBkJHa2v1 .
Let’s say I have one bitcoin that I want to send you. This bitcoin is associated with an address that I control. That is, I have the private key for this address. If you give me the text string representation of a Bitcoin address that you control, I can send my bitcoin to your address. You don’t need to (and shouldn’t) send me your private key. I’m able to send my bitcoin to you because I have the private key for my address, which allows me to spend my bitcoin. Conversely, I can’t transfer any bitcoins out of your address because I don’t have your private key.
Bitcoin Transactions
Let’s take a closer look at how this works. A transfer of bitcoins is known as a transaction . To send bitcoins, wallet software constructs a transaction specifying the details of the transfer, digitally signs it with a private key, and broadcasts the transaction to the Bitcoin network. The computers in the Bitcoin network verify the transaction and add it to a new block on the blockchain. Figure 13-8 illustrates a Bitcoin transaction.
Figure 13-8: A Bitcoin transaction moves 0.5 bitcoin to address B (ignoring any transaction fee).
As shown in Figure 13-8 , a transaction contains inputs and outputs, representing where the bitcoin is coming from and going to. On the left of this figure we have a previous transaction, where only the output is shown; the input of the previous transaction isn’t relevant to our discussion. In the previous transaction, 0.5 BTC was sent to address A.
On the right side of Figure 13-8 we have a new transaction, which moves 0.5 BTC from address A to address B. For simplicity, this transaction has only a single input and single output. The input represents the source of the bitcoin to be transferred. You might expect this to be a Bitcoin address, but it isn’t. Instead, the input is the previous transaction’s output. Let’s say that address A is my address, and I want to send 0.5 bitcoin to your address, address B. Now, I know that previously 0.5 BTC was sent to my address, so I can use that previous transaction’s output as an input to a new transaction, allowing me to send that 0.5 bitcoin to you. The output portion of a transaction contains the address where the bitcoin is sent.
Although you can think of an address as having a balance of bitcoin, the amount of bitcoin associated with an address isn’t stored in a Bitcoin wallet, nor is the balance directly stored in the blockchain. Instead, the history of transactions association with that address is stored in the blockchain, and from that history the balance for a certain address may be calculated. As a reminder, Bitcoin wallets simply contain the keys that enable Bitcoin transactions.
Bitcoin Mining
The process of maintaining the Bitcoin blockchain is known as Bitcoin mining . Computers from around the globe add blocks of transactions to the blockchain—these computers are called miners . Figure 13-9 illustrates the process of mining bitcoins.
Figure 13-9: Bitcoin mining
In order to add a block of transactions to the blockchain, a miner must verify the transactions included in the block (ensuring that each transaction is syntactically correct, that the input coins haven’t already been spent, and so forth), and it must also complete a computationally difficult problem. Requiring miners to solve such a problem prevents tampering with the blockchain, since altering a block would require solving the problem for the altered block and for every block that comes after it in the blockchain. This system of solving a difficult problem as a means of deterring unwanted behavior is known as proof of work .
Arriving at a solution to the computational problem involves a significant number of trial-and-error calculations. The solution is hard to produce but easy to verify. The first miner to complete the problem is awarded a sum of bitcoins. This is how new bitcoins are generated and introduced into the system. In this way, Bitcoin mining is similar to traditional mining—miners perform work and may “strike gold” under the right circumstances. In addition to being awarded newly minted bitcoins, the miner is also able to claim a fee for each transaction included in the block, which is deducted from the total amount of bitcoins sent in the transaction. Bitcoin is designed to only allow for 21 million coins to be mined in total. Once this number is reached, Bitcoin miners will no longer be awarded bitcoins, and will instead rely on transaction fees to fund their operations.
BITCOIN BEGINNINGS
The Bitcoin blockchain began when the first block, known as the genesis block , was mined in 2009. This block was mined by Satoshi Nakamoto, who is credited with inventing Bitcoin. “Satoshi Nakamoto” is presumed to be a pseudonym; this person’s identity is disputed at the time of this writing.
For Bitcoin mining to be profitable, the costs of operating mining hardware must not exceed the value of bitcoins awarded. Bitcoin mining hardware tends to be power-hungry, and so the electricity bill for people mining Bitcoin can be high. Bitcoin was originally mined on regular computers, but today specialized, costly hardware is used to mine as quickly as possible (remember, the award goes to the first computer to solve the problem). These costs, plus the highly volatile price of bitcoins, mean that Bitcoin mining is not a guaranteed path to profit!
The Bitcoin blockchain is public—all transactions can be viewed by anyone. However, the blockchain contains no records of the personal identity of the people transferring bitcoins. So while an address’s balance and transaction history are public, there’s no easy way to tie that address to a human. For that reason, Bitcoin is attractive to those who wish to remain anonymous, such as those who run commerce sites on the dark web.
Blockchain technology is closely associated with cryptocurrencies, where it’s used as a financial ledger, but blockchains can be used for other purposes as well. Any system that needs a tamper-resistant history of records could make use of a blockchain. Time will tell if Bitcoin or other cryptocurrencies are successful in the long run, but regardless, we may see blockchain technology leveraged in other novel ways.
Virtual Reality and Augmented Reality
Two technologies that have the potential to fundamentally change how we interact with computers are virtual reality (VR) and augmented reality (AR). Virtual reality is a form of computing that immerses a user in a three-dimensional virtual space, typically displayed by a headset. VR allows the user to interface with virtual objects via a variety of input methods, including the user’s gaze, voice commands, and specialized handheld controllers. In contrast, augmented reality overlays virtual elements onto the real world, either through a headset or by the user looking “through” a handheld portable device, like a smartphone or tablet. VR immerses the user in another world; AR alters the real world.
Although various attempts at VR have been made for several decades, it wasn’t until the 2010s that VR became more mainstream. Google helped popularize VR in 2014 with Google Cardboard , named for the idea that a VR headset can be constructed from cardboard, lenses, and a smartphone. Specially-designed Cardboard apps present VR content to the user by rendering content for the left eye on half of the smartphone screen and content for the right eye on the other half of the screen, shown in Figure 13-10 .
Figure 13-10: An app designed for Google Cardboard presenting in VR mode
Apps designed for Cardboard rely on the smartphone’s ability to detect gyroscopic movement, allowing the display to update as the user moves their head. Such a headset is said to have 3 degrees of freedom (3DoF) ; the headset can track limited head movement, but it cannot otherwise track movement in space. This allows a user to look around, but not move around using the headset. Cardboard also supports a basic one-button input. Cardboard is simple, but effective. It introduced VR to many users who probably wouldn’t have tried it otherwise.
A more immersive experience requires 6 degrees of freedom (6DoF) ; where the user can move around in VR by physically moving their body in real space. Some VR headsets support 6DoF, and VR controllers can have either 3DoF or 6DoF. A 6DoF controller, held in the user’s hand, can track the position of the controller in VR space, allowing for more natural interactions with the VR environment.
The consumer market has seen a number of VR solutions released since Google Cardboard. Some rely on smartphones (Samsung Gear VR, Google Daydream). Others use a personal computer for processing, with a connected VR headset and controllers (Oculus Rift, HTC Vive, Windows Mixed Reality). Still others are standalone devices, not requiring a smartphone or PC (Oculus Go, Oculus Quest, Lenovo Mirage Solo). In general, the PC-connected solutions provide the highest graphical fidelity, and are also the most expensive, particularly when considering the cost of the required computer.
As mentioned earlier, augmented reality, or AR, is a similar but distinct technology. While VR attempts to completely immerse the user in a virtual world, AR overlays virtual elements onto the real world. This can be accomplished using a mobile device, where a rear-facing camera is used to observe the real world while simulated elements are overlaid on what is seen by the camera. Advanced AR techniques allow software to understand the physical elements in a room so that overlaid virtual elements can interact seamlessly with the environment. AR is implemented in basic form in mobile apps, but it’s more fully realized in dedicated devices such as Google Glass, Magic Leap’s headset, and Microsoft HoloLens. Such AR devices are worn on the head and superimpose computer generated graphics on a user’s field of view. Users are able to interact with virtual elements using various methods, such as voice commands or hand tracking.
The various VR and AR technologies (referred to together as XR ) present multiple platforms for software developers to target. Many VR developers rely on existing game engines that are typically used for building 3D games, such as the Unity game engine or the Unreal game engine. These engines are familiar to game developers already, and they make it relatively easy for the developers to build their software for multiple VR platforms. Web developers can develop VR and AR content using JavaScript APIs known as WebVR and WebXR . Of the two, WebVR came first and was focused on VR specifically. WebXR followed, with support for both AR and VR.
The Internet of Things
Traditionally we think of servers as providing services on the internet, and users interacting with those servers via internet-connected personal computing devices, such as PCs, laptops, and smartphones. In recent years we’ve seen the growth of new types of devices connecting to the internet—speakers, televisions, thermostats, doorbells, cars, lightbulbs, you name it! This concept of connecting all kinds of devices to the internet is known as the Internet of Things (IoT) .
Costs and physical size of electronic components are decreasing, Wi-Fi and cellular internet access are widespread, and consumers expect their devices to be “smarter.” All of this has contributed to the trend of connecting everything to the internet. IoT devices typically don’t operate without some kind of web service supporting them, so the rise of cloud computing has also furthered the spread of the Internet of Things. For consumers, IoT devices are prominent in the “smart home,” where all types of home appliances can be monitored and controlled. In business, IoT devices can be found in manufacturing, healthcare, transportation, and more.
Although these types of connected devices bring clear benefits, these devices also introduce risks. Security of such devices is a particular area of concern. Not every IoT device is well secured against attacks from malicious parties. Even if the data on the device isn’t of interest to an attacker, the device can act as a foothold in an otherwise well-defended network, or it can be used as a launch point for a remote attack against a different target. Particularly for consumers, an IoT device seems innocuous enough, and security concerns often aren’t top of mind when connecting such a device to a home network.
Privacy is another risk presented by IoT devices. Many of these devices, by their nature, collect data. That data is often sent to a cloud service for processing. How much should end users trust the organizations that operate these services with their personal data? Even a well-intentioned organization can be a victim of a data breach, and user data may be exposed in unexpected ways. Devices like smart speakers must be listening all the time, waiting for verbal commands. This presents a risk of accidental recording of private conversations. Modern day readers of George Orwell’s novel 1984 may find a certain irony in seeing consumers of today willingly trading privacy for convenience.
Another risk with IoT devices is that their full functionality often depends on a cloud service. If a device’s internet connection goes down, that device may temporarily become less useful. A greater concern is that a device’s manufacturer will likely someday permanently turn off the service that supports the device. At that point, the smart device will revert to a dumb device!
NOTE
Please see Project #41 on page 311 , where you can use what you’ve learned about hardware, software, and the web to build a network-connected “vending machine” IoT device .
Summary
In this chapter we covered a variety of topics related to modern computing. You learned about apps, both native and web-based. You explored how virtualization and emulation allow computers to run software on virtualized hardware. You saw how cloud computing provides new platforms for running software. You learned how the surface web, deep web, and dark web differ, and how cryptocurrencies like Bitcoin enable decentralized payment systems. We touched on virtual reality and augmented reality and how they enable unique user interfaces for computing. You learned about IoT, and had an opportunity to build an internet-connected “vending machine.”
As we near the end of this book, let’s review some major computing concepts and see how they fit together. Computers are binary digital devices, where everything is represented as a 0 or 1, on or off. Binary logic, also known as Boolean logic, provides the foundation for computing operations. Computers are implemented using digital electrical circuits where voltage levels represent binary states—a low voltage is 0, and a high voltage is 1. Digital logic gates are transistor-based circuits that enable Boolean operations such as AND and OR. Such logic gates can be arranged to create more complex circuits, such as counters, memory devices, and addition circuits. These types of circuits provide a conceptual foundation for computer hardware: a central processing unit (CPU) that executes instructions, random access memory (RAM) that stores instructions and data while powered, and input/output (I/O) devices that interact with the outside world.
Computers are programmable; they can perform new tasks without changing their hardware. Instructions that tell a computer what to do are known as software or code. CPUs execute machine code, whereas software developers typically write source code in a higher-level programming language. Computer programs typically run on an operating system—software that communicates with computer hardware and provides an environment for the execution of programs. Computers communicate using the internet, a globally connected set of computer networks that all use the TCP/IP protocol suite. A popular use of the internet is the World Wide Web, a set of distributed, addressable, linked resources, delivered by HTTP over the internet. All of these technologies provide an environment where modern computing innovations can flourish.
I hope this book has given you a fuller understanding of how computers work. We covered a great deal of ground, and yet we only scratched the surface of most topics. If some particular area grabbed your attention, I’d encourage you to continue learning about that subject—read about it online, take a class, watch videos, or buy another book! There’s a wealth of knowledge about computing to be discovered.
PROJECT #41: USE PYTHON TO CONTROL A VENDING MACHINE CIRCUIT
Prerequisites: Project #7 (on page 105 ) and #8 (on page 107 ) where you built a vending machine circuit. A Raspberry Pi, running Raspberry Pi OS. I recommend that you flip to Appendix B and read the entire “Raspberry Pi” section on page 341 if you haven’t already.
In this project, you’ll use what you’ve learned about hardware, software, and the web to build a network-connected “vending machine” IoT device. Back in Chapter 6 you built a vending machine circuit using push buttons, an LED, and digital logic gates. For this project, you’ll update that device. You’ll keep the buttons and LED, but you’ll replace the logic gates with Python code running on a Raspberry Pi. This will allow you to add capabilities in software easily, such as the ability to connect to the device over the network.
For this project, you’ll need the following components:
- Breadboard
- LED
- Current-limiting resistor to use with your LED; approximately 220Ω
- Two switches or pushbuttons that fit a breadboard
- Jumper wires, including 4 male-to-female wires
- Raspberry Pi
GPIO
Besides its tiny size and low cost, the Raspberry Pi has another feature that sets it apart from a typical computer—its GPIO pins. Each general-purpose input/output (GPIO) pin can be designated as an electrical input or output. When a pin acts as an input, code running on the Raspberry Pi can read the pin as high at 3.3V, or as low at 0V. The Raspberry Pi even has internal pull-up and pull-down resistors, enabled through software, so you no longer have to add such resistors to your input buttons. When a pin acts as an output, it can be set to high (3.3V) or low (0V), all controlled through software. Some pins are always set to ground, 5V, or 3.3V. The pins are referenced in software by number. Figure 13-11 shows the GPIO pin designations.
As you can see in Figure 13-11 , the GPIO numbers don’t correspond to the pin numbers. The pins, shown in the gray box, are simply numbered 1 through 40, starting in the upper left and ending in the lower right. For example, the second pin down on the left side is GPIO 2 and pin number 3. When you reference these GPIO pins in code, you need to use the GPIO number rather than the pin number.
Figure 13-11: Raspberry Pi GPIO pins
BUILD THE CIRCUIT
Before writing any code, connect your circuit components to a breadboard and to the Raspberry Pi GPIO pins as shown in Figure 13-12 .
Figure 13-12: Raspberry Pi vending machine circuit diagram
I’d recommend powering off your Raspberry Pi before connecting anything to the GPIO pins. For the connections between the GPIO pins and the breadboard, use a male-to-female jumper wire. You can connect the female end of the wire to the GPIO pin, and the male end of the wire to the breadboard.
If you use the pin numbers shown in Figure 13-12 , the VEND LED, VEND button, and COIN button are connected to three consecutive GPIO pins on the Raspberry Pi. You also need to connect one of the GND pins (I’d recommend pin 9) to the breadboard’s negative power column, so you can easily connect the buttons and LED to ground.
You may have noticed that this circuit’s input switches are wired differently from the switches you used in Project #7 (on page 105 ) and #8 (on page 107 ). In those projects, you connected a switch to 5V on one side and to a pull-down resistor/input pin on the other side. The circuit was designed so that an open switch was expected to be a low voltage, whereas a closed switch was expected to be a high voltage. Here, things are just the opposite—a closed switch is low, and an open switch is high. Internally, the Raspberry Pi pulls the GPIO pin high when the switch is open (or nothing is connected).
Figure 13-13 shows this circuit built on a breadboard.
Figure 13-13: Raspberry Pi vending machine circuit on a breadboard
Once your circuit is connected and you have verified your connections, power on your Raspberry Pi. You may see the LED turn on, and that’s fine, since you haven’t run any code yet to set the LED to a particular state.
TEST YOUR CIRCUIT
Before entering the vending machine code, let’s write a simple program to test that the circuit is properly connected and to give you a feel for working with GPIO in Python. For interacting with the GPIO pins, we’re going to use GPIO Zero , a Python library that makes it easy to work with physical devices such as buttons and LEDs. Use the text editor of your choice to create a new file named gpiotest.py in the root of your home folder. Enter the following Python code into your text editor. Indentation matters in Python, so make sure you indent appropriately.
from time import sleep ❶
from gpiozero import LED, Button ❷
button = Button(3) ❸
led = LED(2) ❹
while True: ❺
led.off()
button.wait_for_press()
led.on()
sleep(1)
This simple program imports the sleep function ❶ and the LED and Button classes from the GPIO Zero library ❷ . It then creates a variable named button that represents the physical button on GPIO 3 ❸ . Similarly, an led variable is created to represent the LED connected to GPIO 2 ❹ . The program then enters an infinite loop ❺ that turns the LED off, waits for the button to be pressed, and then turns the LED on for one second before going through the loop again.
Once the file is saved, you can run it using the Python interpreter like so:
$ python3 gpiotest.py
When you start the program, nothing should happen at first, except perhaps the LED may turn off if it was previously on. If you press the button connected to GPIO 3, the LED should turn on for one second, and then turn off. You can repeat this as long as the program is running.
Our simple program didn’t include any graceful way to exit, so to end the program, press CTRL -C on the keyboard. When you exit the program in this way, the Python interpreter shows you a “Traceback” of the recent function calls—this is normal.
If the program doesn’t work as expected, double-check the code you entered and review “ Troubleshooting Circuits ” on page 340 .
A VENDING MACHINE PROGRAM
In Project #7 (on page 105 ) and #8 (on page 107 ), the vending machine’s logic was controlled by an SR latch, an AND gate, and a capacitor. You can now replace all of that with a program on the Raspberry Pi. This new design also gets rid of the COIN LED. Previously, the COIN LED turned on if a coin had been inserted. With this new design, the program instead prints the count of coin credits. Each time a coin is inserted, the credit count should go up one, and each time a vend operation occurs the credit count should go down by one.
The requirements for this device are the following:
- Pressing the COIN button increases the credit count by one.
- Pressing the VEND button simulates vending an item. If the credit count is greater than 0, the VEND LED briefly turns on and the credit count decreases by one. If the credit count is 0, nothing happens when the VEND button is pressed.
- Every actionable button press, whether COIN or VEND, causes the program to print the current number of credits.
Use the text editor of your choice to create a new file named vending.py in the root of your home folder. Enter the following Python code into your text editor:
from time import sleep ❶
from gpiozero import LED, Button
vend_led = LED(2) ❷
vend_button = Button(3)
coin_button = Button(4)
coin_count = 0 ❸
vend_count = 0
def print_credits(): ❹
print('Credits: {0}'.format(coin_count - vend_count))
def coin_button_pressed(): ❺
global coin_count
coin_count += 1
print_credits()
def vend_button_pressed(): ❻
global vend_count
if coin_count > vend_count:
vend_count += 1
print_credits()
vend_led.on()
sleep(0.3)
vend_led.off()
coin_button.when_pressed = coin_button_pressed ❼
vend_button.when_pressed = vend_button_pressed
input('Press Enter to exit the program.\n') ❽
First, the code imports the sleep function, LED class, and Button class ❶ , all of which are used later in the program. Next, three variables are declared that represent the physical components attached to GPIO pins— vend_led on GPIO 2, vend_button on GPIO 3, and coin_button on GPIO 4 ❷ . The variable coin_count is declared to track the number of times the COIN button has been pressed, and the variable vend_count tracks the number of times that a vending operation has occurred ❸ . These two variables are used to calculate the number of credits.
The print_credits function ❹ prints the number of available credits, which is simply the difference between coin_count and vend_count .
The coin_button_pressed function ❺ is the code that runs when the COIN button is pressed. It increments coin_count and prints the number of credits. The global coin_count statement allows the global variable coin_count to be modified within the coin_button_pressed function.
The vend_button_pressed function ❻ is the code that runs when the VEND button is pressed. If there are credits remaining ( coin_count > vend_count ), then the function increments vend_count , prints the number of credits, and turns the LED on for 0.3 seconds.
Setting coin_button.when_pressed = coin_button_pressed ❼ associates the coin_button_pressed function with coin_button on GPIO 4 so that the function runs when the button is pressed. Similarly, vend_button_pressed is associated with vend_button .
Finally, we call the input function ❽ . This function prints a message to the screen and waits for the user to press the ENTER key. This is a simple way to the keep the program running. Without this line of code, the program would reach its end and stop running before the user had a chance to interact with the buttons.
Once the file is saved, you can run it using the Python interpreter like so:
$ python3 vending.py
When you start the program, you should immediately see Press Enter to exit the program displayed to the terminal window. At this point try pressing the COIN button, which is connected to GPIO 4. You should see the program print Credits: 1 . Next try pressing the VEND button. The LED should briefly light up, and the program should print Credits: 0 . Try pressing the VEND button again—nothing should happen. Try pressing COIN and VEND multiple times and make sure the program works as expected. When you’re finished testing the program, press ENTER to end the program.
As you can see, a Raspberry Pi, or similar device, can replicate in software the same logic that we previously implemented in hardware. However, a software-based solution is much easier to modify. New features can be added by changing a few lines of code rather than adding new chips and wiring. A Raspberry Pi is actually overkill for what we wanted to do here; the same thing could be accomplished with a less capable computing device at even lower cost, but the principle is the same.
AN IOT VENDING MACHINE
Let’s say that the operator of the vending machine wants to be able to check the machine’s status remotely, over the internet. Since you’re using a Raspberry Pi for your vending machine’s logic, you can take things a step further and make this an IoT vending machine! You can add a simple web server to the program, allowing someone to connect to the device’s IP address from a web browser and see how many times a coin has been inserted and how many times a vending operation occurred.
Python makes this relatively easy, because it includes a simple web server library, http.server . You just need to construct some HTML that includes the data you want to send and write a handler for incoming GET requests. You also need to start the web server when the program begins.
Use the text editor of your choice to edit your existing vending.py file in the root of your home folder. Start by inserting the following import statement as the first line of the file (leaving all the existing code intact, just shifted down a line):
from http.server import BaseHTTPRequestHandler, HTTPServer
Next, remove the entire input line at the bottom of the file and add this code to the end of the file:
HTML_CONTENT = """
<!DOCTYPE html>
Vending Info
Total Coins Inserted: {0}
Total Vending Operations: {1}
"""
class WebHandler(BaseHTTPRequestHandler): ❶
def do_GET(self): ❷
self.send_response(200) ❸
self.send_header('Content-type', 'text/html') ❹
self.end_headers()
response_body = HTML_CONTENT.format(coin_count, vend_count).encode() ❺
self.wfile.write(response_body)
print('Press CTRL-C to exit program.')
server = HTTPServer(('', 8080), WebHandler) ❻
try: ❼
server.serve_forever() ❽
except KeyboardInterrupt:
pass
finally:
server.server_close() ❾
HTML_CONTENT is a multiline string that defines the HTML code that the program sends over the network. This block of HTML code represents a simple web page with a <title> , a <h1> heading, and two <p> paragraphs that describe the state of the vending machine. Specific values in these paragraphs are represented as placeholders {0} and {1} . These values are filled in by the program when it runs. Since this is HTML, the spacing and line breaks within this string don’t matter.
The WebHandler class ❶ describes how the web server handles incoming HTTP requests. It inherits from the BaseHTTPRequestHandler class, meaning that it has the same methods and fields as BaseHTTPRequestHandler . However, this just gives you a generic HTTP request handler; you still need to specify how your program will respond to specific HTTP requests. In this case, the program only needs to respond to HTTP GET requests, so the code defines the do_GET method ❷ . This method is invoked when a GET request comes to the server, and it replies with the following:
- A 200 status code indicating success ❸
- A Content-type: text/html header that tells the browser to expect the response to be HTML ❹
- The HTML string that was defined earlier, but with the two placeholders replaced by the values of coin_count and vend_count ❺
A web server instance is created using the HTTPServer class ❻ . Here you specify that the server name can be anything and that the HTTP server listens on port 8080 ('', 8080) . This is also where you specify to use the WebHandler class for inbound HTTP requests.
The web server starts with server.serve_forever() ❽ . This is placed in a try/except/finally block ❼ so that the server continues running until a KeyboardInterrupt exception occurs (generated by CTRL -C). When this happens, server.server_close() is called to clean up, and the program ends ❾ .
Once the file is saved, you can run the file using the Python interpreter like so:
$ python3 vending.py
The program should behave as it did before when you press the COIN or VEND buttons. However, now you can also connect to the device from a web browser and see data about the vending machine. To do this, you need a device on the same local network as the Raspberry Pi, unless your Pi is directly connected to the internet with a public IP address, in which case any device on the internet should be able to connect to it. If you don’t have another device, you can launch a web browser on the Raspberry Pi itself and let the Raspberry Pi act as both the client and server.
You need to find the IP address of your Raspberry Pi. We did this in Project #30 on page 255 if you want to review the details, but this is the command you want to use:
$ ifconfig
Once you have the IP address of your Raspberry Pi, open a web browser on the device you want to use as your client. In the address bar, enter the following: http://IP:8080 , replacing IP with your Raspberry Pi’s IP address. The end result should look something like this: http://192.168.1.41:8080 . Once you’ve entered this into the browser’s address bar, you should see the web page load with the count of coins and vending operations. Each time you request this page, you should see the Python program print information about the request to the terminal. Once the web page is loaded, it won’t automatically reload, so if you press the COIN or VEND buttons additional times and want to see the latest values, you need to refresh your browser’s view of the page. To stop this program, use CTRL -C on the keyboard.
Recall from Chapter 12 that websites are either static or dynamic. The site you ran in the Chapter 12 projects was static—it served content that was built ahead of time. In contrast, the vending machine site in this chapter is dynamic. It generates an HTML response when a request comes in. Specifically, it updates the coin and vending values in the HTML content before responding.
As a bonus challenge, try modifying the program to also display the “credits” value on the web page. This value should match the last credits value that was printed to the terminal.