This chapter covers:
- Why a blockchain may need a server
- The meaning of the longest chain rule
- How to create a Node.js WebSocket server in TypeScript
- Practical illustrations of using TypeScript interfaces, abstract classes, access qualifiers, enums, and generics
In the previous chapter, we 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 utilizes WebSocket protocol for broadcasting messages to the blockchain’s nodes. The web clients can also make requests to 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 WebSocket protocol
- express - a small Node.js framework offering HTTP support
- nodemon - a tool that restarts node.js-based apps when the script file changes are detected
- lit-html - HTML templates in JavaScript for rendering to the browser’s DOM
These packages are included in the file package.json as dependencies (see section 10.4.2).