一整套基於Java開發的的區塊鏈系統

Gb16978 發表於 2022-07-18
Java 區塊鏈

整個區塊鏈通過鏈的迴圈進行驗證,以確保一個區塊的雜湊仍然與前一個區塊的雜湊匹配。

這是 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部落格 ” ,連結:http://blog.itpub.net/70019421/viewspace-2906141/,如需轉載,請註明出處,否則將追究法律責任。