Data structures for InfoHash and a shared file

pull/4/head
Zlatin Balevsky 2018-07-17 21:59:00 +01:00
parent 2c6d45c569
commit b8c3a380ba
2 changed files with 98 additions and 0 deletions

View File

@ -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);
}
}

View File

@ -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;
}
}