minor changes in for/while loops. Sanity check for even number of nodes (in buildMerkleTree) has now been moved before entering the loop.

This commit is contained in:
Konstantinos Chalkias 2017-02-08 15:21:40 +00:00 committed by chalkido
parent c0bcbc381d
commit 0287876987

View File

@ -32,9 +32,8 @@ sealed class MerkleTree(val hash: SecureHash) {
var n = allLeavesHashes.size var n = allLeavesHashes.size
if (isPow2(n)) return allLeavesHashes if (isPow2(n)) return allLeavesHashes
val paddedHashes = ArrayList<SecureHash>(allLeavesHashes) val paddedHashes = ArrayList<SecureHash>(allLeavesHashes)
while (!isPow2(n)) { while (!isPow2(n++)) {
paddedHashes.add(SecureHash.zeroHash) paddedHashes.add(SecureHash.zeroHash)
n++
} }
return paddedHashes return paddedHashes
} }
@ -51,16 +50,14 @@ sealed class MerkleTree(val hash: SecureHash) {
return lastNodesList[0] //Root reached. return lastNodesList[0] //Root reached.
} else { } else {
val newLevelHashes: MutableList<MerkleTree> = ArrayList() val newLevelHashes: MutableList<MerkleTree> = ArrayList()
var i = 0
val n = lastNodesList.size val n = lastNodesList.size
while (i < n) { require((n and 1) == 0) { "Sanity check: number of nodes should be even." }
for (i in 0..n-2 step 2) {
val left = lastNodesList[i] val left = lastNodesList[i]
require(i+1 <= n-1) { "Sanity check: number of nodes should be even." }
val right = lastNodesList[i+1] val right = lastNodesList[i+1]
val newHash = left.hash.hashConcat(right.hash) val newHash = left.hash.hashConcat(right.hash)
val combined = Node(newHash, left, right) val combined = Node(newHash, left, right)
newLevelHashes.add(combined) newLevelHashes.add(combined)
i += 2
} }
return buildMerkleTree(newLevelHashes) return buildMerkleTree(newLevelHashes)
} }