200 lines of code to implement a simple block chain application __ Block chain

Source: Internet
Author: User
Tags curl javascript array
The basic concept of a block chain is simple: a distributed database that stores an ever-growing list,list containing many sequential records. In general, however, when we talk about block chains, we also talk about the problem of using block chains, which can easily be confused. This is the case for a block-chain project like the popular Bitcoin and the Etheric square. The term "block chain" is often closely linked to concepts like trading, smart contracts, and cryptographic currencies.

This makes it much more difficult to understand the block chain, especially if you want to understand the source code. I will use the 200 line JS implementation of the super simple block chain to help you understand it, I gave this code named Naivechain. Block Structure

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


This block must be able to find the hash value of the previous block in order to ensure the integrity of the entire chain.

Class Block {
    Constructor (index, Previoushash, timestamp, data, hash) {
        this.index = index;
        This.previoushash = Previoushash.tostring ();
        This.timestamp = timestamp;
        This.data = data;
        This.hash = Hash.tostring ();
    }
}
Block Hash

In order to save the full data, you must hash the block. SHA-256 will encrypt the contents of the block, recording this value should have nothing to do with "digging", because there is no need to solve the problem of work proof.

var Calculatehash = (index, Previoushash, timestamp, data) => {return
    cryptojs.sha256 (index + Previoushash + times Tamp + data). ToString ();
Building of Blocks

To generate a block, you must know the hash value of the previous block, and then create the rest of the desired 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;
    var nexttimestamp = new Date (). GetTime ()/1000;
    var Nexthash = Calculatehash (Nextindex, Previousblock.hash, Nexttimestamp, blockdata);
    Return to new block (Nextindex, Previousblock.hash, Nexttimestamp, Blockdata, Nexthash);
Storage of BlocksAn in-memory JavaScript array is used to store block chains. The first block of a block chain is usually called the "origin block" and is hard-coded.
var getgenesisblock = () => {return
    new blocks (0, "0", 1465154705, "My Genesis block!!", "816534932C2B7154836DA6AFC 367695e6337db8a921823784c14378abed4f7d7 ");
var blockchain = [Getgenesisblock ()];
confirm the integrity of the blockAt any time you must be able to confirm whether a block or a whole chain of blocks is complete. This is especially important when we receive new chunks from other nodes and need to decide 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;
};
Select the longest chainThere should be only a clear set of blocks in the chain at any time. In the event of a conflict (for example, when two nodes are generated for block 72nd), a chain with the largest 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 nodesThe essence of nodes is to share and synchronize block chains with other nodes, and 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 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 queries the block in the whole block chain.
As shown in some typical communication scenarios that occur when a node follows a protocol described above, I do not use the automatic Discovery Peer tool. The location (URL) of the peers must be added manually.
node control in a way the user must be able to control the node. This can be achieved by building an 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 the following methods and nodes:
List all blocks to create a new block with user-supplied content list or add peers
The following Curl example is the most direct way to control a node:
#get all blocks from the node
Curl Http://localhost:3001/blocks
ArchitectureIt should be noted that the node actually represents two Web servers: one (HTTP server) is for the user to control the node, and the other (Websocket HTTP server).

The main components of Naivechain
SummaryThe purpose of creating naivechain is to demonstrate and learn, because it does not have a "mining" algorithm (PoS. PoW) that cannot be used in a public network, but it implements the basic characteristics of the block chain operation.
reference materialsHttps://github.com/lhartikk/naivechain
https://medium.com/@lhartikk/A-BLOCKCHAIN-IN-200-LINES-OF-CODE-963CC1CC0E54#.NEE3PFYM6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.