Skip to content
Permalink
Browse files
JCLOUDS-457: Added TreeHash util class and its test.
The TreeHash class stores two HashCodes, the linear and the
tree HashCode. The TreeHash class also has an static inner class
named Hasher, which allows us to calculate the hashes.

Both Hashes (tree and linear) are needed for the upload archive
and the multipart upload operations. When completing a multipart
upload operation we also need to calculate the tree hash of the
individual part's hashes.
  • Loading branch information
rcoedo authored and gaul committed Jun 16, 2014
1 parent 690364b commit 30c6e6477f5918299bee64e4adbc324ff7fb6fd5
Show file tree
Hide file tree
Showing 2 changed files with 230 additions and 0 deletions.
@@ -0,0 +1,142 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.glacier.util;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jclouds.io.Payload;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Lists;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingInputStream;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;

public class TreeHash {
private final HashCode treeHash;
private final HashCode linearHash;

private TreeHash(HashCode treeHash, HashCode linearHash) {
this.treeHash = checkNotNull(treeHash, "treeHash");
this.linearHash = checkNotNull(linearHash, "linearHash");
}

public HashCode getLinearHash() {
return linearHash;
}

public HashCode getTreeHash() {
return treeHash;
}

@Override
public int hashCode() {
return Objects.hashCode(this.treeHash, this.linearHash);
}

@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TreeHash other = (TreeHash) obj;
return Objects.equal(this.treeHash, other.treeHash) && Objects.equal(this.linearHash, other.linearHash);
}

@Override
public String toString() {
return "TreeHash [treeHash=" + treeHash + ", linearHash=" + linearHash + "]";
}

public static class Hasher {
private static final int CHUNK_SIZE = 1024 * 1024;

private static HashCode hashList(Collection<HashCode> hashList) {
List<HashCode> result = Lists.newArrayList();
while (hashList.size() > 1) {
//Hash pairs of values and add them to the result list.
for (Iterator<HashCode> it = hashList.iterator(); it.hasNext();) {
HashCode hc1 = it.next();
if (it.hasNext()) {
HashCode hc2 = it.next();
result.add(Hashing.sha256().newHasher()
.putBytes(hc1.asBytes())
.putBytes(hc2.asBytes())
.hash());
} else {
result.add(hc1);
}
}
hashList = result;
result = Lists.newArrayList();
}
return hashList.iterator().next();
}

/**
* Builds the Hash and the TreeHash values of the payload.
*
* @return The calculated TreeHash.
* @see <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html" />
*/
public static TreeHash buildTreeHashFromPayload(Payload payload) throws IOException {
InputStream is = null;
try {
is = checkNotNull(payload, "payload").openStream();
ArrayList<HashCode> list = Lists.newArrayList();
HashingInputStream linearHis = new HashingInputStream(Hashing.sha256(), is);
while (true) {
HashingInputStream chunkedHis = new HashingInputStream(
Hashing.sha256(), ByteStreams.limit(linearHis, CHUNK_SIZE));
long count = ByteStreams.copy(chunkedHis, ByteStreams.nullOutputStream());
if (count == 0) {
break;
}
list.add(chunkedHis.hash());
}
//The result list contains exactly one element now.
return new TreeHash(hashList(list), linearHis.hash());
} finally {
Closeables.closeQuietly(is);
}
}

/**
* Builds a TreeHash based on a map of hashed chunks.
*
* @return The calculated TreeHash.
* @see <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html" />
*/
public static HashCode buildTreeHashFromMap(Map<Integer, HashCode> map) {
checkArgument(!map.isEmpty(), "The map cannot be empty.");
return hashList(ImmutableSortedMap.copyOf(map).values());
}
}
}
@@ -0,0 +1,88 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.glacier.util;

import static org.testng.Assert.assertEquals;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import org.jclouds.io.ByteSources;
import org.jclouds.io.payloads.ByteSourcePayload;
import org.testng.annotations.Test;

import com.google.common.collect.Maps;
import com.google.common.hash.HashCode;
import com.google.common.io.ByteSource;

@Test(groups = "unit", testName = "TreeHasherTest")
public class TreeHashTest {

private static final int MB = 1024 * 1024;

@Test
public void testTreeHasherWith1MBPayload() throws IOException {
TreeHash th = TreeHash.Hasher.buildTreeHashFromPayload(new ByteSourcePayload(getData(1 * MB)));
assertEquals(th.getLinearHash(),
HashCode.fromString("9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360"));
assertEquals(th.getTreeHash(),
HashCode.fromString("9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360"));
}

@Test
public void testTreeHasherWith2MBPayload() throws IOException {
TreeHash th = TreeHash.Hasher.buildTreeHashFromPayload(new ByteSourcePayload(getData(2 * MB)));
assertEquals(th.getLinearHash(),
HashCode.fromString("5256ec18f11624025905d057d6befb03d77b243511ac5f77ed5e0221ce6d84b5"));
assertEquals(th.getTreeHash(),
HashCode.fromString("560c2c9333c719cb00cfdffee3ba293db17f58743cdd1f7e4055373ae6300afa"));
}

@Test
public void testTreeHasherWith3MBPayload() throws IOException {
TreeHash th = TreeHash.Hasher.buildTreeHashFromPayload(new ByteSourcePayload(getData(3 * MB)));
assertEquals(th.getLinearHash(),
HashCode.fromString("6f850bc94ae6f7de14297c01616c36d712d22864497b28a63b81d776b035e656"));
assertEquals(th.getTreeHash(),
HashCode.fromString("70239f4f2ead7561f69d48b956b547edef52a1280a93c262c0b582190be7db17"));
}

@Test
public void testTreeHasherWithMoreThan3MBPayload() throws IOException {
TreeHash th = TreeHash.Hasher.buildTreeHashFromPayload(new ByteSourcePayload(getData(3 * MB + 512 * 1024)));
assertEquals(th.getLinearHash(),
HashCode.fromString("34c8bdd269f89a091cf17d5d23503940e0abf61c4b6544e42854b9af437f31bb"));
assertEquals(th.getTreeHash(),
HashCode.fromString("daede4eb580f914dacd5e0bdf7015c937fd615c1e6c6552d25cb04a8b7219828"));
}

@Test
public void testBuildTreeHashFromMap() throws IOException {
Map<Integer, HashCode> map = Maps.newTreeMap();
map.put(2, HashCode.fromString("9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360"));
map.put(1, HashCode.fromString("9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360"));
HashCode treehash = TreeHash.Hasher.buildTreeHashFromMap(map);
assertEquals(treehash, HashCode.fromString("560c2c9333c719cb00cfdffee3ba293db17f58743cdd1f7e4055373ae6300afa"));
}

private ByteSource getData(int size) {
byte[] array = new byte[1024];
Arrays.fill(array, (byte) 'a');
return ByteSources.repeatingArrayByteSource(array).slice(0, size);
}
}

0 comments on commit 30c6e64

Please sign in to comment.