Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop the block chain of JavaScript

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to develop the block chain in JavaScript". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "JavaScript how to develop the block chain" bar!

Develop and implement a simple block chain with JavaScript. Through this development process, you will understand what blockchain technology is: blockchain is a distributed database, the storage structure is a growing linked list, which contains many ordered records.

However, in general, when we talk about blockchain, we also talk about the problem of using blockchain to solve, the two are easy to be confused. Such is the case with blockchain-based projects such as popular Bitcoin and Ethernet Fong. The term "blockchain" is often associated with concepts such as transactions, smart contracts, and cryptocurrencies.

This makes understanding the blockchain unnecessarily complicated, especially if you want to understand the source code. I'm going to help you understand it with a super-simple blockchain implemented by 200 lines of JS, which I named NaiveChain. You can see more technical details at Github.

Block structure

The first logical step is to determine the block structure. To keep things as simple as possible, we choose only the most necessary parts: index (subscript), timestamp (timestamp), data (data), hash (hash), and previous hash (pre-hash).

The hash value of the previous block must be found in this block to ensure the integrity of the whole chain.

Class Block {constructor (index, previousHash, timestamp, data, hash) {this.index = index;this.previousHash = previousHash.toString (); this.timestamp = timestthis.data = data;this.hash = hash.toString ();}} Block Hash

In order to preserve the complete data, you must hash blocks. SHA-256 encrypts the contents of the block, and recording this value should have nothing to do with "mining", because there is no need to solve the problem of workload proof.

Var calculateHash = (index, previousHash, timestamp, data) = > {return CryptoJS.SHA256 (index + previousHash + timestamp + data) .toString ();}; Block generation

To generate a block, you must know the hash value of the previous block, and then create the rest of the required content (= index, hash, data and timestamp). The data portion of the block is provided by the end user.

Var generateNextBlock = (blockData) = > {var previousBlock = getLatestBlock (); var nextIndex = previousBlock.index + 1 nextHash nextTimestamp = new Date (). GetTime () / 1000 nextHash = calculateHash (nextIndex, previousBlock.hash, nextTimestamp, blockData); return new Block (nextIndex, previousBlock.hash, nextTimestamp, blockData, nextHash);}; storage of blocks

The Javascript array in memory is used to store the chunk chain. The first block of the block chain is often referred to as the "origin block" and is hard-coded.

Var getGenesisBlock = () = > {return new Block (0, "0", 1465154705, "my genesis blockquote!", "816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7");}; var blockchain = [getGenesisBlock ()]; confirm the integrity of the block

You must be able to confirm the integrity of a block or an entire chain at all times. This is especially important when we receive new chunks from other nodes and need to decide whether to accept or reject them.

Var isValidNewBlock = (newBlock, previousBlock) = > {if (previousBlock.index + 1! = = newBlock.index) {console.log ('invalid index'); return false;} else if (previousBlock.hash! = = newBlock.previousHash) {console.log (' invalid previoushash'); return false;} else if (calculateHashForBlock (newBlock)! = = newBlock.hash) {console.log ('invalid hash:' + calculateHashForBlock (newBlock) +'+ newBlock.hash); return false;} return true;}; choose the longest chain

There should be only one clear set of blocks in the chain at any time. In case of conflict (for example, when block 72 is generated by both nodes), the chain with the maximum number of blocks is selected.

Var replaceChain = (newBlocks) = > {if (isValidChain (newBlocks) & & newBlocks.length > blockchain.length) {console.log ('Received blockchain is valid. Replacing current blockchain with received blockchain'); blockchain = newBlocks; broadcast (responseLatestMsg ());} else {console.log (' Received blockchain invalid');}}; Communication with other nodes

The essence of a node is to share and synchronize block chains with other nodes. The following rules can ensure network synchronization.

When a node generates a new block, it spreads the block over the network.

When a node connects to a new peer, it queries for the latest block.

When a node encounters a block whose index is greater than the index of all current blocks, it adds the block to its current chain.

Or query the block throughout the block chain.

I didn't use the tool to automatically discover peer. The location (URL) of the peers must be added manually.

Node control

The user must be able to control the node to some extent. This can be achieved by setting up a HTTP server.

Var initHttpServer = () = > {var app = express (); app.use (bodyParser.json ()); app.get ('/ blocks', (req, res) = > res.send (JSON.stringify (blockchain); app.post ('/ mineBlock', (req, res) = > {var newBlock = generateNextBlock (req.body.data); addBlock (newBlock); broadcast (responseLatestMsg () Console.log ('block added:' + JSON.stringify (newBlock)); res.send ();}); app.get ('/ peers', (req, res) = > {res.send (sockets.map (s = > s._socket.remoteAddress +':'+ s._socket.remotePort);}); app.post ('/ addPeer', (req, res) = > {connectToPeers ([req.body.peer])) Res.send ();}); app.listen (http_port, () = > console.log ('Listening http on port:' + http_port);}

Users can interact with nodes in the following ways:

List all blocks

Create a new block with user-provided content

List or add peers

The following example of Curl is the most direct way to control nodes:

# get all blocks from the nodecurl http://localhost:3001/blocks system Architecture

It is important to point out that the node actually presents two web servers: one (HTTP server) is for the user to control the node, and the other (Websocket HTTP server).

At this point, I believe that everyone on the "JavaScript how to develop the block chain" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report