📜  Java区块链的实现

📅  最后修改于: 2021-05-07 08:55:36             🧑  作者: Mango

区块链是数字加密货币比特币的骨干技术。

  • 区块链是称为区块的记录列表,这些记录使用链接列表链接在一起并使用密码技术。
  • 每个块包含自己的数字指纹(称为哈希),上一个块的哈希,时间戳和所进行的事务处理的数据,从而使其更安全地防止任何类型的数据泄露。
  • 因此,如果更改一个块的数据,则其哈希也将更改。如果更改了哈希值,则其哈希值将不同于包含前一个块的哈希值的下一个块,从而影响其后所有块的哈希值。更改哈希值,然后将其与其他块进行比较,可以检查区块链。

区块链的实现:以下是区块链实现中使用的功能。

  1. 创建块:要创建一个块,要实现一个Block类。在类块中:
    • 哈希将包含块的哈希,并且
    • previousHash将包含上一个块的哈希。
    • 字符串数据用于存储块的数据,
    • “ long timeStamp”用于存储块的时间戳。在这里,long数据类型用于存储毫秒数。
    • computeHash()生成哈希

    下面是类块的实现:

    // Java implementation for creating
    // a block in a Blockchain
      
    import java.util.Date;
      
    public class Block {
      
        // Every block contains
        // a hash, previous hash and
        // data of the transaction made
        public String hash;
        public String previousHash;
        private String data;
        private long timeStamp;
      
        // Constructor for the block
        public Block(String data,
                     String previousHash)
        {
            this.data = data;
            this.previousHash
                = previousHash;
            this.timeStamp
                = new Date().getTime();
            this.hash
                = calculateHash();
        }
      
        // Function to calculate the hash
        public String calculateHash()
        {
            // Calling the "crypt" class
            // to calculate the hash
            // by using the previous hash,
            // timestamp and the data
            String calculatedhash
                = crypt.sha256(
                    previousHash
                    + Long.toString(timeStamp)
                    + data);
      
            return calculatedhash;
        }
    }
    
  2. 生成哈希:为了生成哈希,使用了SHA256算法。

    下面是该算法的实现。

    // Java program for Generating Hashes
      
    import java.security.MessageDigest;
      
    public class crypt {
      
        // Function that takes the string input
        // and returns the hashed string.
        public static String sha256(String input)
        {
            try {
                MessageDigest sha
                    = MessageDigest
                          .getInstance(
                              "SHA-256");
                int i = 0;
      
                byte[] hash
                    = sha.digest(
                        input.getBytes("UTF-8"));
      
                // hexHash will contain
                // the Hexadecimal hash
                StringBuffer hexHash
                    = new StringBuffer();
      
                while (i < hash.length) {
                    String hex
                        = Integer.toHexString(
                            0xff & hash[i]);
                    if (hex.length() == 1)
                        hexHash.append('0');
                    hexHash.append(hex);
                    i++;
                }
      
                return hexHash.toString();
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    
  3. 存储块:现在,让我们通过调用Block Class的构造函数将块及其哈希值存储在Block类型的ArrayList中。
    // Java implementation to store
    // blocks in an ArrayList
      
    import java.util.ArrayList;
      
    public class GFG {
      
        // ArrayList to store the blocks
        public static ArrayList blockchain
            = new ArrayList();
      
        // Driver code
        public static void main(String[] args)
        {
            // Adding the data to the ArrayList
            blockchain.add(new Block(
                "First block", "0"));
            blockchain.add(new Block(
                "Second block",
                blockchain
                    .get(blockchain.size() - 1)
                    .hash));
      
            blockchain.add(new Block(
                "Third block",
                blockchain
                    .get(blockchain.size() - 1)
                    .hash));
      
            blockchain.add(new Block(
                "Fourth block",
                blockchain
                    .get(blockchain.size() - 1)
                    .hash));
      
            blockchain.add(new Block(
                "Fifth block",
                blockchain
                    .get(blockchain.size() - 1)
                    .hash));
        }
    }
    
  4. 区块链有效性:最后,我们需要通过创建一个布尔方法来检查BlockChain的有效性。该方法将在“ Main”类中实现,并检查哈希值是否等于计算得出的哈希值。如果所有哈希均等于计算出的哈希,则该块有效。

    下面是有效性的实现:

    // Java implementation to check
    // validity of the blockchain
      
    // Function to check
    // validity of the blockchain
    public static Boolean isChainValid()
    {
        Block currentBlock;
        Block previousBlock;
      
        // Iterating through
        // all the blocks
        for (int i = 1;
             i < blockchain.size();
             i++) {
      
            // Storing the current block
            // and the previous block
            currentBlock = blockchain.get(i);
            previousBlock = blockchain.get(i - 1);
      
            // Checking if the current hash
            // is equal to the
            // calculated hash or not
            if (!currentBlock.hash
                     .equals(
                         currentBlock
                             .calculateHash())) {
                System.out.println(
                    "Hashes are not equal");
                return false;
            }
      
            // Checking of the previous hash
            // is equal to the calculated
            // previous hash or not
            if (!previousBlock
                     .hash
                     .equals(
                         currentBlock
                             .previousHash)) {
                System.out.println(
                    "Previous Hashes are not equal");
                return false;
            }
        }
      
        // If all the hashes are equal
        // to the calculated hashes,
        // then the blockchain is valid
        return true;
    }
    

区块链的优势:

  1. Blokchain是系统的分布式网络。因此,数据泄露非常难以执行。
  2. 由于区块链会产生每个区块的哈希值,因此很难进行恶意攻击。
  3. 数据篡改将更改每个块的哈希,这将使区块链无效