Coverage Summary for Class: BlockHashesHelper (co.rsk.core.bc)
Class |
Class, %
|
Method, %
|
Line, %
|
BlockHashesHelper |
100%
(1/1)
|
66.7%
(4/6)
|
39%
(16/41)
|
1 package co.rsk.core.bc;
2
3 import co.rsk.crypto.Keccak256;
4 import co.rsk.trie.Trie;
5 import org.ethereum.core.Block;
6 import org.ethereum.core.Transaction;
7 import org.ethereum.core.TransactionReceipt;
8 import org.ethereum.db.ReceiptStore;
9 import org.ethereum.db.TransactionInfo;
10 import org.ethereum.util.RLP;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.Optional;
15
16 public class BlockHashesHelper {
17
18 private BlockHashesHelper() {
19 // helper class
20 }
21
22 public static byte[] calculateReceiptsTrieRoot(List<TransactionReceipt> receipts, boolean isRskip126Enabled) {
23 Trie trie = calculateReceiptsTrieRootFor(receipts);
24 if (isRskip126Enabled) {
25 return trie.getHash().getBytes();
26 }
27
28 return trie.getHashOrchid(false).getBytes();
29 }
30
31 public static Trie calculateReceiptsTrieRootFor(List<TransactionReceipt> receipts) {
32 Trie receiptsTrie = new Trie();
33 for (int i = 0; i < receipts.size(); i++) {
34 receiptsTrie = receiptsTrie.put(RLP.encodeInt(i), receipts.get(i).getEncoded());
35 }
36
37 return receiptsTrie;
38 }
39
40 public static List<Trie> calculateReceiptsTrieRootFor(Block block, ReceiptStore receiptStore, Keccak256 txHash)
41 throws BlockHashesHelperException {
42 Keccak256 bhash = block.getHash();
43
44 List<Transaction> transactions = block.getTransactionsList();
45 List<TransactionReceipt> receipts = new ArrayList<>();
46
47 int ntxs = transactions.size();
48 int ntx = -1;
49
50 for (int k = 0; k < ntxs; k++) {
51 Transaction transaction = transactions.get(k);
52 Keccak256 txh = transaction.getHash();
53
54 Optional<TransactionInfo> txinfoOpt = receiptStore.get(txh, bhash);
55 if (!txinfoOpt.isPresent()) {
56 throw new BlockHashesHelperException(String.format("Missing receipt for transaction %s in block %s", txh, bhash));
57 }
58
59 TransactionInfo txinfo = txinfoOpt.get();
60 receipts.add(txinfo.getReceipt());
61
62 if (txh.equals(txHash)) {
63 ntx = k;
64 }
65 }
66
67 if (ntx == -1) {
68 return null;
69 }
70 Trie trie = calculateReceiptsTrieRootFor(receipts);
71 List<Trie> nodes = trie.getNodes(RLP.encodeInt(ntx));
72
73 return nodes;
74 }
75
76 public static byte[] getTxTrieRoot(List<Transaction> transactions, boolean isRskip126Enabled) {
77 Trie trie = getTxTrieRootFor(transactions);
78 if (isRskip126Enabled) {
79 return trie.getHash().getBytes();
80 }
81
82 return trie.getHashOrchid(false).getBytes();
83 }
84
85 private static Trie getTxTrieRootFor(List<Transaction> transactions) {
86 Trie txsState = new Trie();
87 if (transactions == null) {
88 return txsState;
89 }
90
91 for (int i = 0; i < transactions.size(); i++) {
92 Transaction transaction = transactions.get(i);
93 txsState = txsState.put(RLP.encodeInt(i), transaction.getEncoded());
94 }
95
96 return txsState;
97 }
98 }