This chapter covers
- Why a blockchain may need a server
- The longest chain rule
- How to create a Node.js WebSocket server in TypeScript
- Practical use of TypeScript interfaces, abstract classes, access qualifiers, enums, and generics
In the previous chapter, you learned that each block miner can take a number of pending transactions, create a valid block that includes the proof of work, and add the new block to the blockchain. This workflow is easy to follow when there is only one miner creating the proof of work. Realistically, there could be thousands of miners around the world trying to find the valid hash for a block with the same transactions, which may cause conflicts.
In this chapter, we’ll use TypeScript to create a server that uses the WebSocket protocol to broadcast messages to the blockchain’s nodes. The web clients can also make requests of this server.
While writing code in TypeScript remains our main activity, we’ll use several JavaScript packages for the first time in this book:
- ws— A Node.js library that supports the WebSocket protocol
- express— A small Node.js framework offering HTTP support
- nodemon— A tool that restarts Node.js-based apps when script file changes are detected
- lit-html— HTML templates in JavaScript for rendering to the browser’s DOM
These packages are included in the package.json file as dependencies (see section 10.4.2).