|
| 1 | +package org.ipfs; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Multihash { |
| 7 | + enum Type { |
| 8 | + sha1(0x11, 20), |
| 9 | + sha2_256(0x12, 32), |
| 10 | + sha2_512(0x13, 64), |
| 11 | + sha3(0x14, 64), |
| 12 | + blake2b(0x40, 64), |
| 13 | + blake2s(0x41, 32); |
| 14 | + |
| 15 | + public int index, length; |
| 16 | + |
| 17 | + Type(int index, int length) { |
| 18 | + this.index = index; |
| 19 | + this.length = length; |
| 20 | + } |
| 21 | + |
| 22 | + private static Map<Integer, Type> lookup = new TreeMap<>(); |
| 23 | + static { |
| 24 | + for (Type t: Type.values()) |
| 25 | + lookup.put(t.index, t); |
| 26 | + } |
| 27 | + |
| 28 | + public static Type lookup(int t) { |
| 29 | + if (!lookup.containsKey(t)) |
| 30 | + throw new IllegalStateException("Unknown Multihash type: "+t); |
| 31 | + return lookup.get(t); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public final Type type; |
| 36 | + public final byte size; |
| 37 | + public final byte[] hash; |
| 38 | + |
| 39 | + public Multihash(Type type, byte size, byte[] hash) { |
| 40 | + if ((size & 0xff) != hash.length) |
| 41 | + throw new IllegalStateException("Incorrect size: " + (size&0xff) + " != "+hash.length); |
| 42 | + if (hash.length != type.length) |
| 43 | + throw new IllegalStateException("Incorrect hash length: " + hash.length + " != "+type.length); |
| 44 | + this.type = type; |
| 45 | + this.size = size; |
| 46 | + this.hash = hash; |
| 47 | + } |
| 48 | + |
| 49 | + public Multihash(byte[] multihash) { |
| 50 | + this(Type.lookup(multihash[0] & 0xff), multihash[1], Arrays.copyOfRange(multihash, 2, multihash.length)); |
| 51 | + } |
| 52 | + |
| 53 | + public byte[] toBytes() { |
| 54 | + byte[] res = new byte[hash.length+2]; |
| 55 | + res[0] = (byte)type.index; |
| 56 | + res[1] = (byte)hash.length; |
| 57 | + System.arraycopy(hash, 0, res, 2, hash.length); |
| 58 | + return res; |
| 59 | + } |
| 60 | + |
| 61 | + public String toHex() { |
| 62 | + StringBuilder res = new StringBuilder(); |
| 63 | + for (byte b: toBytes()) |
| 64 | + res.append(String.format("%x", b&0xff)); |
| 65 | + return res.toString(); |
| 66 | + } |
| 67 | + |
| 68 | + public static Multihash fromHex(String hex) { |
| 69 | + if (hex.length() % 2 != 0) |
| 70 | + throw new IllegalStateException("Uneven number of hex digits!"); |
| 71 | + ByteArrayOutputStream bout = new ByteArrayOutputStream(); |
| 72 | + for (int i=0; i < hex.length()-1; i+= 2) |
| 73 | + bout.write(Integer.valueOf(hex.substring(i, i+2), 16)); |
| 74 | + return new Multihash(bout.toByteArray()); |
| 75 | + } |
| 76 | +} |
0 commit comments