Java implements a simple blockchain

The blockchain can be simply abstracted into storing each block in a linked list. Every time a new block is added, it is placed at the end of the linked list, and a unique hash is formed through the transfer of information between blocks to ensure that the block The data of the chain has not been tampered with.

Realization of blocks

The basic properties of a block are:

  • The hash value of the current block

  • hash value of the previous block

  • The data value of the current block

  • Timestamp of the current block

Among them, by encrypting the hash of the previous block (0 if it is the first block), the data value of the current block and the current timestamp, a unique hash value belonging to the current block can be generated.

public class Block {
    public String hash;//当前块的哈希值
    public String previousHash;//前一个块的哈希值
    private String data;//当前块的数据
    private long timeStamp;//当前块的时间戳

    //初始化区块
    public Block(String data, String previousHash) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = System.currentTimeMillis();
        this.hash = calculateHash();
    }

    //通过sha256散列算法生成hash值
    public String calculateHash() {
        String calculatedhash = 
            StringUtil.applySha256(previousHash 
                                   +Long.toString(timeStamp) 
                                   +data);
        return calculatedhash;
    }

}

sha256 hash algorithm

The reason why SHA256 is selected is that its size is just right. On the one hand, the possibility of generating duplicate hash values ​​is very small; Large, then the size of 256 bits is more appropriate.

public class StringUtil {
    public static String applySha256(String input){
        try {
            //指定使用的加密算法为SHA-256
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            //计算当前输入数据的散列值
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.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 new RuntimeException(e);
        }
    }
}

test

Create a linked list to store blocks, thus forming a blockchain.

public class NoobChain {

    public static ArrayList<Block> blockchain = new ArrayList<Block>();

    public static void main(String[] args) {
        //将每一个块添加到区块链中
        //传入块的信息:当前块的数据信息、上一块的hash值
        blockchain.add(new Block("The first block", "0"));
        blockchain.add(new Block("The second block", blockchain.get(blockchain.size() - 1).hash));
        blockchain.add(new Block("The third block", blockchain.get(blockchain.size() - 1).hash));

        //将区块链用整齐的格式打印出来
        String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
        System.out.println(blockchainJson);
    }
}

Check the integrity of the blockchain

Checking the integrity of the blockchain is achieved by verifying whether the hashes of the current block and the previous block are correct. Since each node of the blockchain cannot be modified after it is generated, when the hash value of a certain block changes, it proves that its data and other information have been tampered with, and the blockchain is no longer complete.

     //判断区块链是否有效
    public static Boolean isChainValid() {
        Block currentBlock;
        Block previousBlock;
        //通过检查哈希值来判断是否是一个有效的区块链
        for (int i = 1; i < blockchain.size(); i++) {
            currentBlock = blockchain.get(i);
            previousBlock = blockchain.get(i - 1);
            //比较块中的注册hash和再次计算的hash值是否相同
            if (!currentBlock.hash.equals(currentBlock.calculateHash())) {
                System.out.println("Current Hashes not equal");
                return false;
            }
            //比较前一个块的hash值和当前块的previousHash值是否相同
            if (!previousBlock.hash.equals(currentBlock.previousHash)) {
                System.out.println("Previous Hashes not equal");
                return false;
            }
        }
        return true;
    }

A change in any block in the blockchain will result in a change in the hash. This function returns false, which proves that the blockchain is invalid.

This article refers to: java development blockchain only needs 150 lines of code

Java source code is kept on GitHub

Guess you like

Origin blog.csdn.net/m0_51561690/article/details/128687066