From b8c3a380ba49c884ccb5e3a81366d7f45c0ce230 Mon Sep 17 00:00:00 2001 From: Zlatin Balevsky Date: Tue, 17 Jul 2018 21:59:00 +0100 Subject: [PATCH] Data structures for InfoHash and a shared file --- .../main/java/com/muwire/core/InfoHash.java | 75 +++++++++++++++++++ .../main/java/com/muwire/core/SharedFile.java | 23 ++++++ 2 files changed, 98 insertions(+) create mode 100644 core/src/main/java/com/muwire/core/InfoHash.java create mode 100644 core/src/main/java/com/muwire/core/SharedFile.java diff --git a/core/src/main/java/com/muwire/core/InfoHash.java b/core/src/main/java/com/muwire/core/InfoHash.java new file mode 100644 index 00000000..fc2a463d --- /dev/null +++ b/core/src/main/java/com/muwire/core/InfoHash.java @@ -0,0 +1,75 @@ +package com.muwire.core; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +import net.i2p.data.Base32; + +public class InfoHash { + + private static final int SIZE = 0x1 << 5; + + private final byte[] root; + private final byte[] hashList; + + private final int hashCode; + + public InfoHash(byte[] root, byte[] hashList) { + if (root.length != SIZE) + throw new IllegalArgumentException("invalid root size "+root.length); + if (hashList != null && hashList.length % SIZE != 0) + throw new IllegalArgumentException("invalid hashList size " + hashList.length); + this.root = root; + this.hashList = hashList; + hashCode = root[0] << 24 | + root[1] << 16 | + root[2] << 8 | + root[3]; + } + + public InfoHash(byte[] root) { + this(root, null); + } + + public InfoHash(String base32) { + this(Base32.decode(base32)); + } + + public static InfoHash fromHashList(byte []hashList) { + try { + MessageDigest sha256 = MessageDigest.getInstance("SHA256"); + byte[] root = sha256.digest(hashList); + return new InfoHash(root, hashList); + } catch (NoSuchAlgorithmException impossible) { + impossible.printStackTrace(); + System.exit(1); + } + return null; + } + + public byte[] getRoot() { + return root; + } + + public byte[] getHashList() { + return hashList; + } + + @Override + public int hashCode() { + return hashCode; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof InfoHash)) { + return false; + } + InfoHash other = (InfoHash) o; + return Arrays.equals(root, other.root); + } +} diff --git a/core/src/main/java/com/muwire/core/SharedFile.java b/core/src/main/java/com/muwire/core/SharedFile.java new file mode 100644 index 00000000..1d8efbb8 --- /dev/null +++ b/core/src/main/java/com/muwire/core/SharedFile.java @@ -0,0 +1,23 @@ +package com.muwire.core; + +import java.io.File; + +public class SharedFile { + + private final File file; + private final InfoHash infoHash; + + public SharedFile(File file, InfoHash infoHash) { + this.file = file; + this.infoHash = infoHash; + } + + public File getFile() { + return file; + } + + public InfoHash getInfoHash() { + return infoHash; + } + +}