ITPub博客

首页 > 区块链 > 区块链 > 一整套基于Java开发的的区块链系统

一整套基于Java开发的的区块链系统

区块链 作者:Gb16978 时间:2022-07-18 09:18:17 0 删除 编辑

整个区块链通过链的循环进行验证,以确保一个区块的哈希仍然与前一个区块的哈希匹配。

这是 SimpleBlockChain.java的  validate()方法实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean validate() {
 
         String previousHash = null ;
         for (Block<T> block : chain) {
             String currentHash = block.getHash();
             if (!currentHash.equals(previousHash)) {
                 return false ;
             }
 
             previousHash = currentHash;
 
         }
 
         return true ;
 
     }

下面是模块中的方法。从事务列表中创建Merkle树的java类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public List<String> merkleTree() {       
         ArrayList<String> tree = new ArrayList<>();
         // Start by adding all the hashes of the transactions as leaves of the
         // tree.
         for (T t : transactions) {
             tree.add(t.hash());
         }
         int levelOffset = 0 ; // Offset in the list where the currently processed
                                 // level starts.
         // Step through each level, stopping when we reach the root (levelSize
         // == 1).
     for ( int levelSize = transactions.size(); levelSize > 1 ; levelSize = (levelSize + 1 ) / 2 ) {
             // For each pair of nodes on that level:
             for ( int left = 0 ; left < levelSize; left += 2 ) {
                 // The right hand node can be the same as the left hand, in the
                 // case where we don't have enough
                 // transactions.
                 int right = Math.min(left + 1 , levelSize - 1 );
                 String tleft = tree.get(levelOffset + left);
                 String tright = tree.get(levelOffset + right);
                 tree.add(SHA256.generateHash(tleft + tright));
             }
             // Move to the next level.
             levelOffset += levelSize;
         }
         return tree;
     }


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70019421/viewspace-2906141/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
软件开发:Gb16978 薇

注册时间:2022-06-28

  • 博文量
    15
  • 访问量
    6821