Preface:

Before actually has always been thinking about not to write an article, this article because there are too many similar articles on the Internet, and as long as you will read a few articles found that a lot of articles in addition to content is remarkably similar, most of whom were from abroad a great god of the two articles on Java block chain tutorial hard translation, it is easy to cause a problem, Is that you obviously run his code, but still don’t know what blockchain is, such as how to achieve decentralization? How do not tamper with the line, and the fewer COINS why dig these problems still can not get a good explanation, this article, still is the tutorial for the source code, in addition to English comments I’ll manual translated into Chinese, what other variable name will not change, after all, the somebody else thought is right, there is no need to re-invent the wheel, Change the variable and say I wrote the code myself, then I’m no different from those people copying and reprinting online. This article is not a mechanical translation of the author’s original paper, but borrowed relevant codes. I hope that after reading it, you will roughly understand what kind of technology blockchain is, why we need blockchain and so on.

No more talking. Let’s get the food.

What is blockchain?

Blockchain is a new application mode of distributed data storage, point-to-point transmission, consensus mechanism, encryption algorithm and other computer technologies. , block chain is an important concept in the currency, it is essentially a decentralized database, at the same time as the underlying technology of the currency, it is a list of associated with the use of cryptography method produce data blocks, each block contains a number of times the currency trading information network, is used to verify the validity of the information (security) and generate a block – baidu encyclopedia.

????? I don’t get it. Move the next one.

What is blockchain? Is blockchain love

Also do not understand, and see the following a small story, limited to space, do not write the flashy.

Tomorrow is xiao Ming and Xiao Hong together 100 days anniversary, Xiao Ming wants to give Xiao Hong a big surprise, is to send her own three months of hard research and development of the robot, think of xiao Hong received a gift dancing appearance, Xiao Ming will feel this is too his mother romantic.

When Xiao Ming gave the gift to Xiao Hong the next day, the accident happened.

Hei: You can’t be together. Actually, Hei…

Xiao Ming: Oh my god, is Xiao Hong my real sister? What kind of drama is this

Hei: No, WHAT I want to say is, actually, Xiao Hong is my girlfriend.

Xiaoming: Oh my God? What makes you say Xiao Hong is your girlfriend?

Xiao Hei: then how can you say xiao Hong is your girlfriend? If I say mine, I mean mine.

My friends, remember:

Xiaoming: we fall in love of the first day, I sent a small red mouse, the second day, I sent her a keyboard, the third day, I sent her a screen, the fourth day….. On the 100th day, I gave her a robot that I had worked hard to develop. These are the proof!

Hei: ahhhhhhh, I lose, ok, xiao Hong is your girlfriend.

As a result of intentionally tampering with the fact that xiao Hong is Xiao Ming’s girlfriend, small black was pulled into the blacklist, did not find girlfriend again from now on.

In this example, Xiao Hong, Xiao Ming, and Xiao Hei are the chains in the blockchain, and before, every story between Xiao Ming and Xiao Hong from acquaintance, to acquaintance, and then to love will form a block. And all the stories happened between xiao Ming and small red will be in the form of live know all blocks in the chain of chain (too hard), so the little black said the little red is his girlfriend nature could not be true, because the whole block chain all the chain saw xiao Ming and small red is the fact that couples, if little black to tamper with the fact that little red is his girlfriend, So he would have to modify all the chains in the entire blockchain for the memory of xiao Ming and Xiao Hong, which is almost impossible to do.

It is just like the whole world knows that Trump is the president of the United States now. Now you say that Trump is not the president of the United States, but the president of the United States is founded by Chuan Jianguo. When you say that, outsiders know it is false at first sight.

This is the immutable nature of blockchain.

At the same time, if One day Xiao Ming does not love Xiao Hong and falls in love with Xiao Green, he will delete all the things related to Xiao Hong from his mobile phone and tell Xiao Green that Xiao Green is his first love and Xiao Ming only loves Xiao Green. Does it work? It doesn’t work, because the chain in the whole blockchain has watched The live broadcast of Xiao Ming and Xiao Hong, recording the evidence that Xiao Ming and Xiao Hong were once together.

This is immodifiability in blockchain.

What would happen if blockchain were applied to finance?

Before our money is in the bank account management system, if someone hacked into bank account management system, only need to put his account on behalf of the balance of the string of Numbers changed can decide how much money, in block chain, everyone is a bank, everyone is account management system, if need to modify your account balance, It is necessary to modify the information of all nodes in the whole network, which is almost impossible to achieve, so the security is greatly improved. Let alone other applications.

And bitcoin is an important application of blockchain in the field of leek cutting.

Implementing a simple blockchain in Java:

Now that we know what blockchain is, let’s go back to our roots as a developer and take a brief look at how blockchain is implemented from a technical point of view.

Blockchain, blockchain, first we have to have a block class, and this class has one of the most important characteristics, the ability to form a chain. (?????? God logic)

Let’s create a new Block class with the following code:

public class Block {

    /** * The current block hash */
    public String hash;

    /** * the hash of the previous block, which in this case implements the */ of the chain
    public String previousHash;

    /** * The current block of data, such as transaction information, etc., in the love case represents the specific events of Xiao Hong and Xiao Ming */
    private String data;

    /** ** timestamp */
    private long timeStamp;

    private int nonce;

    public Block(String hash, String previousHash, String data) {
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
    }

    public Block(String data, String previousHash) {
        this.previousHash = previousHash;
        this.data = data;
        this.timeStamp = new Date().getTime();
        this.hash = calculateHash();
    }

    public String calculateHash(a) {
        String calculatedhash = StringUtil.applySha256(
                previousHash +
                        Long.toString(timeStamp) +
                        Integer.toString(nonce) +
                        data);
        return calculatedhash;
    }

    public void mineBlock(int difficulty) {
        //Create a string with difficulty * "0"
        String target = new String(new char[difficulty]).replace('\ 0'.'0'); 
        while(! hash.substring(0, difficulty).equals(target)) { nonce ++; hash = calculateHash(); }}}Copy the code

Variable explanation:

  • Hash: Hash value of the current block
  • PreviousHash: The hash of the last block, which implements the chain, is a bit like a linked list (SHH)
  • Data: Information stored in the current block, such as xiao Ming buying lipstick for Xiao Hong.
  • TimeStamp: timeStamp, such as the time when Xiao Ming bought Xiao Hong lipstick.
  • Nonce: is just a plain radix variable.

The mineBlock () and calculateHash() methods are probably the only things you need to understand in this class, and nonce is the key variable.

In the mineBlock() method the hash operation is performed continuously until the eligible block is calculated, and the nonce is the number of times needed to change the block. In the calculateHash(), we add the nonce number to calculate the hash at once.

And look at the calculateHash() method, when we hash, we use the hash of the previous block as the parameter. Once the hash of the previous block is fake or tampered, no matter how we calculate, the hash value returned by calculateHash() method, The hash value of the block itself is almost impossible to match, making it easy to detect that the block has been tampered with.

As for the encryption algorithm, the author chooses SHA-256, which is also the encryption algorithm used by Bitcoin and is recognized as one of the most secure and advanced algorithms.

The code for the StringUtil class is shown below, and since this is not relevant to today’s topic, I won’t go into more detail.

public class StringUtil {

    public static String applySha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes("UTF-8"));
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw newRuntimeException(e); }}}Copy the code

The JsonUtil class code looks like this:

public class JsonUtil {
    public static String toJson(Object object){
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        returngson.toJson(object); }}Copy the code

Now that the basic blocks have been written, let’s test them briefly to see if we can actually find a mine.

Create three new blocks and set the mineBlock() method to 5.

The test class code is as follows:

public class BlockChainTest {

    public static void main(String[] args) {
        // block 1
        Block firstBlock = new Block("I'm block one."."0");
        firstBlock.mineBlock(5);
        System.out.println("First block hash:" + firstBlock.hash);

        // block 2
        Block secondBlock = new Block("I'm block two.", firstBlock.hash);
        secondBlock.mineBlock(5);
        System.out.println("Second block hash:" + secondBlock.hash);

        // block 3
        Block thirdBlock = new Block("I'm block three.", secondBlock.hash);
        thirdBlock.mineBlock(5);
        System.out.println("Third block hash:"+ thirdBlock.hash); }}Copy the code

The running result is as follows:

The first block hash: 0000052659276 be66678fd482825b20bd0819a800246d23d171da6270e92589c second block hash: 000000 d1f338b2dc6b02cca8ec158ca7acafa9cbf699ca97fc1ed7b260a65652 third block hash: 0000072381c11b9a160b1b1d93b75cb477c286db63bb541fcede7ab163ac696cCopy the code

Did you find anything? The first five digits of the three blocks we dug are all zeros. It’s amazing

0000052659276b

Therefore, the essence of mining is actually the process of obtaining a qualified hash through hash calculation.

So you can see why bitcoin mining is dwindling.

Because among all the calculation results, in line with the conditions of the hash is limited, and the calculate the less, just start to calculate, because there are too many qualified hash, so the work force is small, it is easy to calculate, while the later has not been calculated the eligible hash value, the less is needed to calculate the force, the greater the When there’s only one hash that meets the criteria, it’s really like looking for a needle in a haystack. Maybe that’s why a decade ago any computer could easily dig up bitcoin, but now it takes a mine of thousands of mining machines to do so

In the beginning, there were five million treasures in the desert, and people from all over the world went to look for them. In the beginning, there were many treasures, and everyone found one treasure every step. Later, there were only a few treasures to be found.

This time someone may put forward a question, how do I know you this block is not legal, look is so, in case he is not legal I do not know. It’s been changed I don’t know. Don’t panic. Let’s take our time.

public class BlockChainListTest {

    // This thing is our blockchain, storing all our block information. (Crude version)
    public static ArrayList<Block> blockChain = new ArrayList();

    // The difficulty of mining is that the first characters of the calculated hash are 0.
    public static int difficulty = 5;

    public static void main(String[] args) {
        blockChain.add(new Block("I'm block one."."0"));
        blockChain.get(0).mineBlock(difficulty);

        blockChain.add(new Block("I'm block two.", blockChain.get(blockChain.size() - 1).hash));
        blockChain.get(1).mineBlock(difficulty);

        blockChain.add(new Block("I'm block three.", blockChain.get(blockChain.size() - 1).hash));
        blockChain.get(2).mineBlock(difficulty);

        System.out.println("Is blockchain legal?" + isChainValid());
        System.out.println(JsonUtil.toJson(blockChain));
    }
    

    public static Boolean isChainValid(a){

        Block currentBlock;
        Block previousBlock;
        boolean flag = true;
        String hashTarget = new String(new char[difficulty]).replace('\ 0'.'0');

        // Iterate over the list to verify the hash
        for(int i=1; i<blockChain.size(); i++){ currentBlock = blockChain.get(i); previousBlock = blockChain.get(i-1);
            // Compare the registered hash with the calculated hash
            if(! currentBlock.hash.equals(currentBlock.calculateHash())){ System.out.println("Current hash is not equal");
                flag=false;
            }
            // Compares the current previous hash with the registered previous hash
            if(! previousBlock.hash.equals(currentBlock.previousHash)){ System.out.println("Previous hash is not equal");
                flag=false;
            }

            // Check if the block has already been calculated.
            if(! currentBlock.hash.substring(0, difficulty).equals(hashTarget)) {
                System.out.println("This block hasn't been mined yet, which means your block is not qualified.");
                flag=false; }}returnflag; }}Copy the code

The result is as follows:

Block chain is legal: true [{" hash ":" 00000 dd5f9b665c79f454adb1491af1042883f43818938191a8337202929cdeb ", "previousHash" : "0", "data": "I was the first block ", "timeStamp": 1574822479084, "nonce": 614266}, {"hash": "0000063312c3a5832a8990ad064e962c98e8ef9ffca969cc0c049cfd84773fdc", "previousHash": "00000 dd5f9b665c79f454adb1491af1042883f43818938191a8337202929cdeb", "data" : "I am the second block", "timeStamp" : 1574822480646, "nonce": 429710 }, { "hash": "00000304ecc09cca5eac2aed4875c2097a34efcab3518f4f886708a133c513db", "previousHash": "0000063312 c3a5832a8990ad064e962c98e8ef9ffca969cc0c049cfd84773fdc", "data" : "I am the third block", "timeStamp" : 1574822481635, "nonce": 262515 } ]Copy the code

IsChainValid () is how you check to see if a blockchain is valid.

Let’s start with the technical summary:

Today, this article has spent a lot of space in the understanding of how to block chain on this concept, we must first know what the thing is, can do, we’ll learn in the process of thinking will be clear and many articles in the late, if there are (at once), still along the thinking of foreign leaders, to achieve a block can trade chain, of course, Code is still not the focus of the next article, considering that most people are just expanding their knowledge to understand a blockchain technology, and have no intention of switching to blockchain. Therefore, the next article will focus on the understanding of UTXO (Unspent Transaction Outputs), the core concept of Bitcoin, to briefly understand how blockchain is decentralized Transaction.

Finally, we will migrate our program to the Web and realize a cross-era blockchain product – don’t make money

Relevant code has been uploaded to my Github. Make sure you hit “STAR” ahhhhhhh

Long march always feeling, to a star line

Hanshu development notes

Welcome to like, follow me, have good fruit to eat (funny)