Those lucky enough to become digital RMB users recently can use the digital RMB App to make payments. Here are some screenshots to see what the digital yuan looks like.

When it comes to digital RMB, we have to say blockchain. Today, I would like to share with you a study note written in the past.

Concept of popularity

When it comes to blockchain, three concepts need to be declared: blockchain, virtual currency and digital currency. Blockchain is not equal to virtual currency, and virtual currency is not equal to digital currency.

Often said blockchain refers to its technology, is a new way of distributed data management; Mention block chain, a lot of people will associate it with virtual currency “COINS” fire, “the etheric fang”, “dog currency” virtual currency, these can only be considered one of the “derivatives” of block chain technology, therefore block chain can never be “flat” is equal to the virtual currency, promote a large number of development block chain technology in our country, rather than the virtual currency, Virtual currencies are banned in China.

The digital RMB mentioned at the beginning is a digital currency issued by the People’s Bank of China. It is a liability of the People’s Bank of China, with national credit endorsement and equivalent to legal tender. Its functional attributes are exactly the same as banknotes, but in digital form. Digital currency is first and foremost money, while virtual currency is just a token with no currency attributes and only a narrow sense of value (or consensus value).

What is blockchain technology?

So now back to blockchain technology, what is blockchain technology?

A blockchain is a decentralized digital transaction ledger, a growing list of electronic records that will be retained for the long term and secured by encryption (an algorithmic code). Blockchain ledger data is distributed across a network of computers. Users can interact directly with stored data in real time, without the need for intermediaries (” middlemen “or resellers) to verify transactions. The technology provides an independent, tamper-proof and transparent platform for parties in the blockchain to securely store, transmit and process sensitive information.

After saying what is blockchain technology, now let’s talk about what the front-end can learn from blockchain technology. Blockchain projects have a nice property that they are open source, so we can learn some technical knowledge from open source code. Let’s take the Ethereum Network state visualization project to learn its architecture and the application of WebSocket.

Ethereum network state platform EthStats

EthStats is a visual platform for tracking the status of the Ethereum network. It uses WebSockets technology to receive statistics from running nodes and output data according to different rules. Users can intuitively understand the status of the Ethereum nodes through the website.

Disclaimer: The following content is not now, so the interface may be different from now, but the architecture and technology themselves are still worth learning.

Ethstats monitors node information (node name, node running environment, running time, computing power, number of peers, Pending transactions, latest block number and HASH, total difficulty, block transactions), network average HASHRATE, and Gas Limit, number of active nodes, and tertiary block data can be accessed in real time through this website. This paper introduces the implementation of the whole platform, can provide us with some implementation reference, and deepen the understanding of WebSocket technology.

The overall structure

The platform involves two projects

  • Ethereum Network Intelligence API
  • Ethereum Network Stats

Ethereum Network Intelligence API

Back-end services that run with Ethereum nodes and track network state, synchronizing information over JSON-RPC and WebSockets to Eth – NetStats. Here are some key implementations.

  • Determine whether a node is online: The node status is determined by sending a Node-ping message to EthStats via webSocket timing (3 seconds) and listening for a PONG message to receive the response

    Node.prototype.ping = function () { this._latency = _.now(); socket.emit("node-ping", { id: this.id, clientTime: _.now(), }); }; Socket. on("node-pong", function (data) {var now = _.now(); var latency = Math.ceil((now - data.clientTime) / 2); socket.emit("latency", { id: self.id, latency: latency, }); }); ` ` `Copy the code
  • Other data synchronization messages

    // block this.emit("block", this.prepareBlock()); This.emit ("pending", this.preparePending())); This.emit ("stats", stats); Stats = {active: false, mining: false, hashRate: 0, peers: 0, pending: 0, gasPrice: 0, block: {active: false, mining: false, hashRate: 0, peers: 0, pending: 0, gasPrice: 0, block: { number: 0, hash: "?" , difficulty: 0, totalDifficulty: 0, transactions: [], uncles: [], }, syncing: false, uptime: 0, }; ` ` `Copy the code

Ethereum Network Stats (EthStats)

The project uses WebSockets to receive statistics from running nodes and output them to the front-end rendering via the WebSocket interface, so there are two WebSocket interfaces, one for receiving node data synchronized from Ethereum Network Intelligence. The default address is: Ws: / / localhost: 3000 / API; One for the front calls to present data, the default address: ws: / / localhost: 3000 / primus

Data sent by the Ethereum Network Intelligence API is received and processed before being sent to the front-end for rendering. Encapsulated data includes:

Write ({action: "charts", data: history,}); write({action: "charts", data: history,}); Write ({action: "add", data: info,}); // Add node information. Write ({action: "update", data: stats,}); Write ({action: "block", data: stats,}); Write ({action: "pending", data: stats,}); Write ({action: "inactive", data: stats,});Copy the code

WebSocket and compatibility

WebSocket is introduced

WebSocket is a protocol for full duplex communication over a single TCP connection. It simplifies the data exchange between the client and the server and allows the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

By default, port 80 is used for WS and port 443 is used for WSS.

WebSocket versus HTTP

Also as an application layer protocol, WebSocket is increasingly practiced in modern software development and has many similarities with HTTP.

  • The same

    1. It’s all the same TCP based, it’s all reliability transport protocol.
    2. Both are application layer protocols.
  • The difference between

    1. WebSocket is a two-way communication protocol that simulates the Socket protocol and can send or receive information in both directions. HTTP is one-way.
    2. Websockets require a handshake between the browser and the server to establish a connection. HTTP is a connection initiated by the browser to the server that the server does not know about in advance.
  • Contact: When WebSocket establishes a handshake, data is transmitted over HTTP. Once established, the HTTP protocol is not required for actual transmission.

Why WebSocket instead of HTTP

HTTP1.1 uses persistent Connection by default. Multiple Request/Response message pairs can be transmitted over a TCP connection. But the basic HTTP model is still one Request for one Response. The following solutions are commonly used for two-way communication:

  • Polling (polling) : The client starts sending requests to the server at intervals, regardless of whether the server has had an update or not. The result may be new updates coming from the server, or nothing at all, returning empty messages. Regardless of the result, the client will proceed to the next round of polling at the next scheduled point in time. Disadvantages waste a lot of traffic (more than half of the requests are useless), put a lot of pressure on the server, and are not real-time.

  • Long-connection or long-polling: the client suspends a request immediately and does not start Polling until the server starts to update it. On the server side has updated and push information before this period, the client will not have a new redundant request, the server to the client also what all need not stem, retaining only the most basic connection information, once the server updates will be pushed to the client, the client will make the corresponding processing, processing after launch again the next round of the request, Disadvantages will cause server hold connection will consume resources, return data sequence is not guaranteed, difficult to manage and maintain. The long connection can be implemented in two ways:

    • Long-polling based on Ajax: The browser sends an XMLHttpRequest request. After receiving the request, the server blocks the request until it has data or times out. After the browser processes the returned information (timeout or valid data), the browser sends a request again to establish a connection. In the meantime, new data may arrive on the server, and the server will choose to save the data until the connection is re-established, and the browser will retrieve all the data at once.

    • HTTP Streaming Method Based on Iframe and HTMLFile The usual practice is to embed a hidden iframe in the page, then make the SRC attribute of the iframe point to a server address we requested, and to update the data on the page, wrap the data update operation as a JS function, passing the function name as a parameter to the address. Every time there is data update, return the call to the client function, and the new data will be filled with the parameters of the JS function in the return content, such as return:

      <script type="text/javascript">window.parent("data")</script>
      Copy the code

    This means that the client view is updated by calling the client update function with data as an argument.

Websocket greatly reduces unnecessary network traffic and latency compared to intermittent or long polling solutions that simulate full-duplex connections. In addition, the application of Websocket takes the burden off the server, allowing existing machines to support more concurrent connections. As shown below:

WebSocket compatibility

With the popularity of HTML5, most modern browsers (IE10+) already support WebSocket natively. The following are browsers that support WebSocket protocol:

Simple implementation

Node.js authoring servers can use the WS library. Primus is used in Ethstats, whereas the WS implementation is lighter and more suitable for writing a simple implementation.

  • The server code is as follows, listening on port 3000. When a new connection request arrives, a log is printed and a message is sent to the client. Logs are also generated when a message is received from the client.

    var WebSocket = require('ws');
    var wss = new WebSocket.Server({
        port: 3000
    });
    wss.on('connection', function connection(ws) {
        console.log('Server:Starting socket connection');
        ws.on('message', function incoming(message) {
            console.log('Server: Received: %s', message);
        });
        ws.send('world');
    });
    Copy the code
  • The client code is as follows: initiates a WebSocket connection to port 3000 and prints logs.

    <html>
        <head>
            <title>WebSocket</title>
            <script>
                var ws = new WebSocket('ws://localhost:3000');
                ws.onopen = function () {
                    console.log('Ws Onopen');
                    ws.send('From Client: Hello');
                };
                ws.onmessage = function (e) {
                    console.log('ws onmessage');
                    console.log('From Server: ' + e.data);
                };
            </script>
        </head>
    </html>
    Copy the code

conclusion

The open source property of blockchain project makes me curious about technology and never miss the opportunity to learn.