SHA256
364 lines
15 KiB
Java
364 lines
15 KiB
Java
package blockchain;
|
|
|
|
import utils.crypto.Ed25519Util;
|
|
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.nio.ByteBuffer;
|
|
import java.nio.ByteOrder;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.security.MessageDigest;
|
|
import java.util.ArrayList;
|
|
import java.util.Arrays;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
import java.util.Objects;
|
|
|
|
/**
|
|
* Minimal ANS-104 DataItem parser/verifier used by SHiNE.
|
|
*
|
|
* SHiNE accepts only generic Ed25519 signature type 2:
|
|
* uint16le signatureType
|
|
* signature[64]
|
|
* owner[32]
|
|
* target_present[1] + target[32] when present
|
|
* anchor_present[1] + anchor[32] when present
|
|
* tags_count uint64le
|
|
* tags_size uint64le
|
|
* avro_tags[tags_size]
|
|
* data[*]
|
|
*
|
|
* The signing message matches the deployed arbundles/Turbo DataItem implementation:
|
|
* deepHash(["dataitem", "1", signatureType, owner, target, anchor, rawAvroTags, data]).
|
|
*/
|
|
public final class Ans104DataItem {
|
|
public static final int SIGNATURE_TYPE_ED25519 = 2;
|
|
public static final int SIGNATURE_LEN = 64;
|
|
public static final int OWNER_LEN = 32;
|
|
public static final int OPTIONAL_FIELD_LEN = 32;
|
|
public static final int ID_LEN = 32;
|
|
public static final int MAX_DATA_ITEM_BYTES = 8 * 1024 * 1024;
|
|
public static final int MAX_TAGS_BYTES = 64 * 1024;
|
|
public static final long MAX_TAGS_COUNT = 128;
|
|
|
|
public record Tag(String name, String value) {}
|
|
|
|
private final int signatureType;
|
|
private final byte[] signature;
|
|
private final byte[] owner;
|
|
private final byte[] target;
|
|
private final byte[] anchor;
|
|
private final long tagsCount;
|
|
private final byte[] rawTags;
|
|
private final List<Tag> tags;
|
|
private final byte[] data;
|
|
private final byte[] rawBytes;
|
|
private final byte[] id;
|
|
|
|
public Ans104DataItem(byte[] bytes) {
|
|
Objects.requireNonNull(bytes, "bytes == null");
|
|
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8 + 1) {
|
|
throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length);
|
|
}
|
|
if (bytes.length > MAX_DATA_ITEM_BYTES) {
|
|
throw new IllegalArgumentException("ANS-104 DataItem too large: " + bytes.length);
|
|
}
|
|
|
|
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
|
|
this.signatureType = Short.toUnsignedInt(bb.getShort());
|
|
if (signatureType != SIGNATURE_TYPE_ED25519) {
|
|
throw new IllegalArgumentException("Unsupported ANS-104 signature type: " + signatureType + " (expected 2)");
|
|
}
|
|
|
|
this.signature = readExact(bb, SIGNATURE_LEN, "signature");
|
|
this.owner = readExact(bb, OWNER_LEN, "owner");
|
|
this.target = readOptional32(bb, "target");
|
|
this.anchor = readOptional32(bb, "anchor");
|
|
|
|
this.tagsCount = readUnsignedLongAsNonNegative(bb, "tags_count");
|
|
long tagsSizeLong = readUnsignedLongAsNonNegative(bb, "tags_size");
|
|
if (tagsCount > MAX_TAGS_COUNT) {
|
|
throw new IllegalArgumentException("Too many ANS-104 tags: " + tagsCount);
|
|
}
|
|
if (tagsSizeLong > MAX_TAGS_BYTES || tagsSizeLong > bb.remaining()) {
|
|
throw new IllegalArgumentException("Bad ANS-104 tags_size: " + tagsSizeLong + ", remaining=" + bb.remaining());
|
|
}
|
|
this.rawTags = readExact(bb, (int) tagsSizeLong, "tags");
|
|
this.tags = Collections.unmodifiableList(parseAvroTags(rawTags, tagsCount));
|
|
this.data = new byte[bb.remaining()];
|
|
bb.get(this.data);
|
|
this.rawBytes = Arrays.copyOf(bytes, bytes.length);
|
|
this.id = sha256(signature);
|
|
}
|
|
|
|
public int signatureType() { return signatureType; }
|
|
public byte[] signature64() { return Arrays.copyOf(signature, signature.length); }
|
|
public byte[] owner32() { return Arrays.copyOf(owner, owner.length); }
|
|
public byte[] target() { return Arrays.copyOf(target, target.length); }
|
|
public byte[] anchor() { return Arrays.copyOf(anchor, anchor.length); }
|
|
public long tagsCount() { return tagsCount; }
|
|
public byte[] rawTags() { return Arrays.copyOf(rawTags, rawTags.length); }
|
|
public List<Tag> tags() { return tags; }
|
|
public byte[] data() { return Arrays.copyOf(data, data.length); }
|
|
public byte[] rawBytes() { return Arrays.copyOf(rawBytes, rawBytes.length); }
|
|
public byte[] id32() { return Arrays.copyOf(id, id.length); }
|
|
|
|
public String tagValue(String name) {
|
|
if (name == null) return null;
|
|
for (Tag tag : tags) {
|
|
if (name.equals(tag.name())) return tag.value();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public boolean hasTag(String name, String value) {
|
|
for (Tag tag : tags) {
|
|
if (Objects.equals(name, tag.name()) && Objects.equals(value, tag.value())) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public boolean verifySignature() {
|
|
return Ed25519Util.verify(signingMessage(), signature, owner);
|
|
}
|
|
|
|
public boolean ownerEquals(byte[] expectedOwner32) {
|
|
return expectedOwner32 != null && expectedOwner32.length == OWNER_LEN && Arrays.equals(owner, expectedOwner32);
|
|
}
|
|
|
|
public byte[] signingMessage() {
|
|
return buildSigningMessage(owner, target, anchor, tags, data);
|
|
}
|
|
|
|
/**
|
|
* Builds the exact ANS-104 signing message for generic Ed25519 DataItems.
|
|
* Useful for SHiNE clients/tests that must sign a DataItem before serializing it.
|
|
*/
|
|
public static byte[] buildSigningMessage(byte[] owner32, List<Tag> tags, byte[] data) {
|
|
return buildSigningMessage(owner32, new byte[0], new byte[0], tags, data);
|
|
}
|
|
|
|
public static byte[] buildSigningMessage(byte[] owner32, byte[] target, byte[] anchor, List<Tag> tags, byte[] data) {
|
|
requireLen(owner32, OWNER_LEN, "owner");
|
|
byte[] safeTarget = target == null ? new byte[0] : Arrays.copyOf(target, target.length);
|
|
byte[] safeAnchor = anchor == null ? new byte[0] : Arrays.copyOf(anchor, anchor.length);
|
|
if (!(safeTarget.length == 0 || safeTarget.length == OPTIONAL_FIELD_LEN)) {
|
|
throw new IllegalArgumentException("target must be empty or 32 bytes");
|
|
}
|
|
if (!(safeAnchor.length == 0 || safeAnchor.length == OPTIONAL_FIELD_LEN)) {
|
|
throw new IllegalArgumentException("anchor must be empty or 32 bytes");
|
|
}
|
|
List<Tag> safeTags = validateTags(tags);
|
|
byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length);
|
|
|
|
byte[] rawTags = serializeAvroTags(safeTags);
|
|
return deepHash(List.of(
|
|
utf8("dataitem"),
|
|
utf8("1"),
|
|
utf8(Integer.toString(SIGNATURE_TYPE_ED25519)),
|
|
Arrays.copyOf(owner32, owner32.length),
|
|
safeTarget,
|
|
safeAnchor,
|
|
rawTags,
|
|
safeData
|
|
));
|
|
}
|
|
|
|
/** Serialize one SHiNE-ready ANS-104 DataItem with empty target/anchor. */
|
|
public static byte[] serializeEd25519(byte[] signature64, byte[] owner32, List<Tag> tags, byte[] data) {
|
|
requireLen(signature64, SIGNATURE_LEN, "signature");
|
|
requireLen(owner32, OWNER_LEN, "owner");
|
|
List<Tag> safeTags = validateTags(tags);
|
|
byte[] rawTags = serializeAvroTags(safeTags);
|
|
byte[] safeData = data == null ? new byte[0] : data;
|
|
|
|
ByteArrayOutputStream out = new ByteArrayOutputStream(
|
|
2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8 + rawTags.length + safeData.length);
|
|
writeU16LE(out, SIGNATURE_TYPE_ED25519);
|
|
out.writeBytes(signature64);
|
|
out.writeBytes(owner32);
|
|
out.write(0); // target absent
|
|
out.write(0); // anchor absent
|
|
writeU64LE(out, safeTags.size());
|
|
writeU64LE(out, rawTags.length);
|
|
out.writeBytes(rawTags);
|
|
out.writeBytes(safeData);
|
|
return out.toByteArray();
|
|
}
|
|
|
|
private static byte[] readOptional32(ByteBuffer bb, String name) {
|
|
if (!bb.hasRemaining()) throw new IllegalArgumentException("Missing " + name + " presence byte");
|
|
int present = Byte.toUnsignedInt(bb.get());
|
|
if (present == 0) return new byte[0];
|
|
if (present != 1) throw new IllegalArgumentException("Bad " + name + " presence byte: " + present);
|
|
return readExact(bb, OPTIONAL_FIELD_LEN, name);
|
|
}
|
|
|
|
private static byte[] readExact(ByteBuffer bb, int len, String field) {
|
|
if (len < 0 || bb.remaining() < len) {
|
|
throw new IllegalArgumentException("ANS-104 " + field + " truncated: need=" + len + " remaining=" + bb.remaining());
|
|
}
|
|
byte[] out = new byte[len];
|
|
bb.get(out);
|
|
return out;
|
|
}
|
|
|
|
private static long readUnsignedLongAsNonNegative(ByteBuffer bb, String field) {
|
|
if (bb.remaining() < 8) throw new IllegalArgumentException("Missing ANS-104 " + field);
|
|
long v = bb.getLong();
|
|
if (v < 0) throw new IllegalArgumentException("ANS-104 " + field + " exceeds signed long range");
|
|
return v;
|
|
}
|
|
|
|
private static List<Tag> validateTags(List<Tag> tags) {
|
|
List<Tag> safe = tags == null ? List.of() : List.copyOf(tags);
|
|
if (safe.size() > MAX_TAGS_COUNT) {
|
|
throw new IllegalArgumentException("Too many ANS-104 tags: " + safe.size());
|
|
}
|
|
for (Tag tag : safe) {
|
|
if (tag == null || tag.name() == null || tag.value() == null || tag.name().isEmpty() || tag.value().isEmpty()) {
|
|
throw new IllegalArgumentException("ANS-104 tag name/value must be non-empty");
|
|
}
|
|
if (utf8(tag.name()).length > 1024) throw new IllegalArgumentException("ANS-104 tag name exceeds 1024 bytes");
|
|
if (utf8(tag.value()).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
|
|
}
|
|
return safe;
|
|
}
|
|
|
|
private static byte[] serializeAvroTags(List<Tag> tags) {
|
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
|
if (!tags.isEmpty()) {
|
|
writeAvroLong(out, tags.size());
|
|
for (Tag tag : tags) {
|
|
writeAvroString(out, tag.name());
|
|
writeAvroString(out, tag.value());
|
|
}
|
|
}
|
|
writeAvroLong(out, 0); // array terminator; also the complete encoding for an empty array
|
|
byte[] raw = out.toByteArray();
|
|
if (raw.length > MAX_TAGS_BYTES) throw new IllegalArgumentException("ANS-104 tags exceed " + MAX_TAGS_BYTES + " bytes");
|
|
return raw;
|
|
}
|
|
|
|
private static void writeAvroString(ByteArrayOutputStream out, String value) {
|
|
byte[] bytes = utf8(value);
|
|
writeAvroLong(out, bytes.length);
|
|
out.writeBytes(bytes);
|
|
}
|
|
|
|
private static void writeAvroLong(ByteArrayOutputStream out, long value) {
|
|
long n = (value << 1) ^ (value >> 63);
|
|
while ((n & ~0x7fL) != 0) {
|
|
out.write((int) ((n & 0x7f) | 0x80));
|
|
n >>>= 7;
|
|
}
|
|
out.write((int) n);
|
|
}
|
|
|
|
private static void writeU16LE(ByteArrayOutputStream out, int value) {
|
|
out.write(value & 0xff);
|
|
out.write((value >>> 8) & 0xff);
|
|
}
|
|
|
|
private static void writeU64LE(ByteArrayOutputStream out, long value) {
|
|
for (int i = 0; i < 8; i++) out.write((int) ((value >>> (8 * i)) & 0xff));
|
|
}
|
|
|
|
private static void requireLen(byte[] bytes, int expected, String name) {
|
|
if (bytes == null || bytes.length != expected) {
|
|
throw new IllegalArgumentException(name + " must be " + expected + " bytes");
|
|
}
|
|
}
|
|
|
|
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
|
|
AvroCursor c = new AvroCursor(raw);
|
|
List<Tag> out = new ArrayList<>();
|
|
while (!c.eof()) {
|
|
long count = c.readLong();
|
|
if (count == 0) break;
|
|
if (count < 0) {
|
|
count = -count;
|
|
long blockBytes = c.readLong();
|
|
if (blockBytes < 0) throw new IllegalArgumentException("Negative Avro tag block size");
|
|
}
|
|
if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) {
|
|
throw new IllegalArgumentException("Too many Avro tags");
|
|
}
|
|
for (long i = 0; i < count; i++) {
|
|
String name = c.readString();
|
|
String value = c.readString();
|
|
if (name.isEmpty() || value.isEmpty()) throw new IllegalArgumentException("ANS-104 tag name/value must be non-empty");
|
|
if (name.getBytes(StandardCharsets.UTF_8).length > 1024) throw new IllegalArgumentException("ANS-104 tag name exceeds 1024 bytes");
|
|
if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
|
|
out.add(new Tag(name, value));
|
|
}
|
|
}
|
|
if (!c.eof()) {
|
|
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
|
|
}
|
|
if (out.size() != declaredCount) {
|
|
throw new IllegalArgumentException("ANS-104 tags_count mismatch: declared=" + declaredCount + " parsed=" + out.size());
|
|
}
|
|
return out;
|
|
}
|
|
|
|
private static final class AvroCursor {
|
|
private final byte[] data;
|
|
private int p;
|
|
private AvroCursor(byte[] data) { this.data = data == null ? new byte[0] : data; }
|
|
boolean eof() { return p == data.length; }
|
|
long readLong() {
|
|
long raw = 0;
|
|
int shift = 0;
|
|
while (true) {
|
|
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
|
|
int b = data[p++] & 0xff;
|
|
raw |= (long) (b & 0x7f) << shift;
|
|
if ((b & 0x80) == 0) break;
|
|
shift += 7;
|
|
if (shift > 63) throw new IllegalArgumentException("Avro long too large");
|
|
}
|
|
return (raw >>> 1) ^ -(raw & 1L);
|
|
}
|
|
String readString() {
|
|
long len = readLong();
|
|
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
|
|
throw new IllegalArgumentException("Bad Avro string length: " + len);
|
|
}
|
|
String s = new String(data, p, (int) len, StandardCharsets.UTF_8);
|
|
p += (int) len;
|
|
return s;
|
|
}
|
|
}
|
|
|
|
private static byte[] deepHash(Object item) {
|
|
if (item instanceof byte[] bytes) {
|
|
return deepHashBlob(bytes);
|
|
}
|
|
if (item instanceof List<?> items) {
|
|
byte[] acc = sha384(utf8("list" + items.size()));
|
|
for (Object child : items) {
|
|
acc = sha384(concat(acc, deepHash(child)));
|
|
}
|
|
return acc;
|
|
}
|
|
throw new IllegalArgumentException("Unsupported deepHash item: " + (item == null ? "null" : item.getClass()));
|
|
}
|
|
|
|
private static byte[] deepHashBlob(byte[] bytes) {
|
|
byte[] tag = utf8("blob" + bytes.length);
|
|
return sha384(concat(sha384(tag), sha384(bytes)));
|
|
}
|
|
|
|
private static byte[] utf8(String s) { return s.getBytes(StandardCharsets.UTF_8); }
|
|
private static byte[] sha256(byte[] b) { return digest("SHA-256", b); }
|
|
private static byte[] sha384(byte[] b) { return digest("SHA-384", b); }
|
|
private static byte[] digest(String alg, byte[] b) {
|
|
try { return MessageDigest.getInstance(alg).digest(b); }
|
|
catch (Exception e) { throw new IllegalStateException(alg + " unavailable", e); }
|
|
}
|
|
private static byte[] concat(byte[] a, byte[] b) {
|
|
ByteArrayOutputStream out = new ByteArrayOutputStream(a.length + b.length);
|
|
out.writeBytes(a); out.writeBytes(b); return out.toByteArray();
|
|
}
|
|
}
|