Унифицировать HEADER в формате 1.0

This commit is contained in:
AidarKC
2026-12-02 17:57:28 +03:00
parent 58e4bac3c8
commit c61cbf239c
24 changed files with 230 additions and 394 deletions
@@ -16,10 +16,10 @@ public final class BodyRecordParser {
int v = version & 0xFFFF;
int st = subType & 0xFFFF;
// TECH supports Header v1 and CreateChannel current format (ver=1).
// TECH accepts only the current 1.0 body format.
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
&& (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.VER_LICENSE & 0xFFFF) || v == HeaderBody.VER_IDENTITY)) {
&& v == (HeaderBody.VER & 0xFFFF)) {
return new HeaderBody(subType, version, bodyBytes).check();
}
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
@@ -18,7 +18,7 @@ public final class ContentBodyParser {
if (!java.util.Arrays.equals(core.contentHash32(), content.contentHash32()))
throw new IllegalArgumentException("CONTENT hash не совпадает с CORE");
boolean header = content.type() == 0 && content.subType() == MsgSubType.HEADER_COMPAT;
if (content.version() != 1 && !(header && (content.version() == HeaderBody.VER_LICENSE || content.version() == HeaderBody.VER_IDENTITY)))
if (content.version() != 1)
throw new IllegalArgumentException("Неподдерживаемая версия CONTENT body");
if (header != (core.blockNumber() == 0)) throw new IllegalArgumentException("HEADER только в CORE №0");
CoreRecord.Line line = core.line();
@@ -6,37 +6,23 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
/**
* HeaderBody — TECH type=0, subType=0; version=1 legacy / version=2 license / version=3 identity.
* HEADER 1.0 — TECH type=0, subType=0, version=1.
*
* bodyBytes (BigEndian):
* [TAG_LEN] tag ASCII
* [1] loginLength (uint8)
* [N] login UTF-8
* [1] accountType (v3 only, 0 alternative / 1 primary)
* [2+N] previous accounts CSV (v3 primary only, u16 length)
* [1] licenseLength (uint8, version>=2)
* [M] license UTF-8 (version>=2)
* Historical v2: fixed ASCII "license:CC0-1.0" instead of length + text.
* [32] initialBlockchainKey32
*
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
* It is historical identity metadata and MUST remain byte-for-byte unchanged when a
* preserved prefix (including block #0) is republished into later forks.
* [TAG_LEN] tag ASCII; [1] login length; [N] login UTF-8;
* [1] accountType (0 alternative / 1 primary);
* [2+N] previous accounts CSV for Primary only;
* [1] license length; [M] arbitrary license UTF-8; [32] initial blockchain key.
*/
public final class HeaderBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 1; // Legacy Frame v1 and new CONTENT v1 (without CC0)
public static final short VER_LICENSE = 2;
public static final short VER_IDENTITY = 3;
public static final short VER = 1;
public static final int ALTERNATIVE = 0, PRIMARY = 1;
public static final short VER_CC0 = VER_LICENSE; // historical source compatibility
public static final String LICENSE_CC0 = "CC0-1.0";
public static final String LICENSE_FIELD_CC0 = "license:" + LICENSE_CC0;
private static final byte[] LICENSE_BYTES = LICENSE_FIELD_CC0.getBytes(StandardCharsets.US_ASCII);
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public static final short SUBTYPE_COMPAT = 0;
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
@@ -48,153 +34,108 @@ public final class HeaderBody implements BodyRecord {
public final String tag;
public final String login;
public final byte[] initialBlockchainKey32;
public final Integer accountType; // null for legacy HEADER
public final java.util.List<String> previousAccounts;
public final String license; // null for legacy HEADER v1
private final boolean legacyCc0Encoding;
public final int accountType;
public final List<String> previousAccounts;
public final String license;
public HeaderBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (version != VER && version != VER_CC0 && version != VER_IDENTITY) throw new IllegalArgumentException("HeaderBody version must be 1, 2 or 3");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32 + (version == VER_LICENSE ? 1 : 0))
throw new IllegalArgumentException("HeaderBody too short");
if ((subType & 0xFFFF) != SUBTYPE_COMPAT) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (version != VER) throw new IllegalArgumentException("HeaderBody version must be 1.0");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
byte[] tagBytes = new byte[TAG_LEN];
bb.get(tagBytes);
String parsedTag = new String(tagBytes, StandardCharsets.US_ASCII);
if (!TAG.equals(parsedTag)) throw new IllegalArgumentException("Bad tag: " + parsedTag);
this.tag = parsedTag;
this.tag = new String(tagBytes, StandardCharsets.US_ASCII);
if (!TAG.equals(tag)) throw new IllegalArgumentException("Bad tag: " + tag);
int loginLen = Byte.toUnsignedInt(bb.get());
if (loginLen <= 0 || bb.remaining() < loginLen + 32 + (version == VER_LICENSE ? 1 : 0))
throw new IllegalArgumentException("Bad HeaderBody login/key/license length");
if (loginLen == 0 || bb.remaining() < loginLen + 34) throw new IllegalArgumentException("Bad HEADER login length");
byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes);
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
if (version == VER_IDENTITY) {
if (bb.remaining() < 34) throw new IllegalArgumentException("Truncated HEADER identity");
this.accountType = Byte.toUnsignedInt(bb.get());
if (accountType == PRIMARY) {
if (bb.remaining() < 35) throw new IllegalArgumentException("Truncated HEADER previous accounts");
int size = Short.toUnsignedInt(bb.getShort());
if (size > bb.remaining() - 33) throw new IllegalArgumentException("Bad HEADER previous accounts length");
byte[] previous = new byte[size]; bb.get(previous);
String csv = BodyTargetSupport.decodeStrictUtf8(previous, "HEADER previous accounts");
this.previousAccounts = csv.isEmpty() ? java.util.List.of() : java.util.List.of(csv.split(",", -1));
} else {
this.previousAccounts = java.util.List.of();
}
int size = Byte.toUnsignedInt(bb.get());
if (bb.remaining() != size + 32) throw new IllegalArgumentException("Bad HEADER license length");
byte[] field = new byte[size]; bb.get(field);
this.license = BodyTargetSupport.decodeStrictUtf8(field, "HEADER license");
this.legacyCc0Encoding = false;
} else if (version == VER_LICENSE) {
this.accountType = null;
this.previousAccounts = java.util.List.of();
int fieldLength = bb.remaining() - 32;
if (fieldLength > 256) throw new IllegalArgumentException("HEADER license too long");
byte[] field = new byte[fieldLength];
bb.get(field);
legacyCc0Encoding = Arrays.equals(field, LICENSE_BYTES);
if (legacyCc0Encoding) {
this.license = LICENSE_CC0;
} else {
int length = Byte.toUnsignedInt(field[0]);
if (fieldLength != 1 + length) throw new IllegalArgumentException("Bad HEADER license length");
this.license = BodyTargetSupport.decodeStrictUtf8(Arrays.copyOfRange(field, 1, fieldLength), "HEADER license");
}
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HEADER login");
this.accountType = Byte.toUnsignedInt(bb.get());
List<String> parsedPrevious;
if (accountType == PRIMARY) {
if (bb.remaining() < 35) throw new IllegalArgumentException("Truncated HEADER previous accounts");
int size = Short.toUnsignedInt(bb.getShort());
if (size > bb.remaining() - 33) throw new IllegalArgumentException("Bad HEADER previous accounts length");
byte[] previous = new byte[size];
bb.get(previous);
String csv = BodyTargetSupport.decodeStrictUtf8(previous, "HEADER previous accounts");
parsedPrevious = csv.isEmpty() ? List.of() : List.of(csv.split(",", -1));
} else if (accountType == ALTERNATIVE) {
parsedPrevious = List.of();
} else {
this.accountType = null;
this.previousAccounts = java.util.List.of();
legacyCc0Encoding = false;
this.license = null;
throw new IllegalArgumentException("Bad HEADER account type");
}
this.previousAccounts = parsedPrevious;
int licenseSize = Byte.toUnsignedInt(bb.get());
if (bb.remaining() != licenseSize + 32) throw new IllegalArgumentException("Bad HEADER license length");
byte[] licenseBytes = new byte[licenseSize];
bb.get(licenseBytes);
this.license = BodyTargetSupport.decodeStrictUtf8(licenseBytes, "HEADER license");
this.initialBlockchainKey32 = new byte[32];
bb.get(this.initialBlockchainKey32);
requireNonZeroKey(this.initialBlockchainKey32);
bb.get(initialBlockchainKey32);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail");
check();
}
// Legacy constructor is kept for historical fixtures and importing v1 blocks.
/** Creates the canonical 1.0 HEADER for a Primary account. */
public HeaderBody(String login, byte[] initialBlockchainKey32) {
this(login, initialBlockchainKey32, VER, null, false);
this(login, initialBlockchainKey32, "", PRIMARY, List.of());
}
/** HEADER для CORE v2 / CONTENT v1: сохраняет login и начальный ключ, без поля лицензии. */
public static HeaderBody forCoreContent(String login, byte[] initialBlockchainKey32) {
return new HeaderBody(login, initialBlockchainKey32, VER, null, false);
}
public static HeaderBody licensedCc0(String login, byte[] initialBlockchainKey32) {
return new HeaderBody(login, initialBlockchainKey32, VER_LICENSE, LICENSE_CC0, true);
}
/** Новый HEADER v2: произвольная строка лицензии, включая пустую. */
public static HeaderBody licensed(String login, byte[] initialBlockchainKey32, String license) {
return new HeaderBody(login, initialBlockchainKey32, VER_LICENSE, Objects.requireNonNull(license), false);
return new HeaderBody(login, initialBlockchainKey32);
}
public static HeaderBody identity(String login, byte[] initialBlockchainKey32, String license,
int accountType, java.util.List<String> previousAccounts) {
return new HeaderBody(login, initialBlockchainKey32, VER_IDENTITY, license, false, accountType, previousAccounts);
int accountType, List<String> previousAccounts) {
return new HeaderBody(login, initialBlockchainKey32, license, accountType, previousAccounts);
}
private HeaderBody(String login, byte[] initialBlockchainKey32, short version, String license, boolean legacyCc0Encoding) {
this(login, initialBlockchainKey32, version, license, legacyCc0Encoding, null, java.util.List.of());
}
private HeaderBody(String login, byte[] initialBlockchainKey32, short version, String license, boolean legacyCc0Encoding,
Integer accountType, java.util.List<String> previousAccounts) {
Objects.requireNonNull(login, "login == null");
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
private HeaderBody(String login, byte[] initialBlockchainKey32, String license,
int accountType, List<String> previousAccounts) {
this.subType = SUBTYPE_COMPAT;
this.version = version;
this.version = VER;
this.tag = TAG;
this.login = login;
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
this.license = license;
this.login = Objects.requireNonNull(login, "login == null");
this.initialBlockchainKey32 = Arrays.copyOf(Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null"), initialBlockchainKey32.length);
this.license = Objects.requireNonNull(license, "license == null");
this.accountType = accountType;
this.previousAccounts = java.util.List.copyOf(previousAccounts);
this.legacyCc0Encoding = legacyCc0Encoding;
this.previousAccounts = List.copyOf(Objects.requireNonNull(previousAccounts, "previousAccounts == null"));
check();
}
@Override
public HeaderBody check() {
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (version != VER && version != VER_CC0 && version != VER_IDENTITY) throw new IllegalArgumentException("Bad HeaderBody version");
if (version != VER && (license == null || !StandardCharsets.UTF_8.newEncoder().canEncode(license)
|| license.getBytes(StandardCharsets.UTF_8).length > 255))
if ((subType & 0xFFFF) != SUBTYPE_COMPAT || version != VER) throw new IllegalArgumentException("Bad HeaderBody version");
if (!StandardCharsets.UTF_8.newEncoder().canEncode(license) || license.getBytes(StandardCharsets.UTF_8).length > 255)
throw new IllegalArgumentException("HEADER license must be 0..255 UTF-8 bytes");
if (version == VER && license != null) throw new IllegalArgumentException("Legacy HEADER must not contain a license");
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
if (login.isBlank()) throw new IllegalArgumentException("Login is blank");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
// Namespace остаётся lowercase, регистр локальной части сохраняется байт-в-байт.
boolean legacyLogin = login.matches("^[A-Za-z0-9_]+$");
boolean namespacedLogin = loginUtf8.length <= 30 && login.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$");
if (!legacyLogin && !namespacedLogin) {
throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
}
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
if (version == VER_IDENTITY) {
if (accountType == null || (accountType != ALTERNATIVE && accountType != PRIMARY))
throw new IllegalArgumentException("Bad HEADER account type");
if (previousAccounts.size() > 10 || (accountType == ALTERNATIVE && !previousAccounts.isEmpty()))
throw new IllegalArgumentException("Bad HEADER previous account count");
java.util.Set<String> seen = new java.util.HashSet<>();
seen.add(login.toLowerCase(java.util.Locale.ROOT));
for (String prev : previousAccounts) {
if (!(prev.matches("^[A-Za-z0-9_]{1,255}$") || (prev.length() <= 30 && prev.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$")))
|| !seen.add(prev.toLowerCase(java.util.Locale.ROOT)))
throw new IllegalArgumentException("Bad, duplicate or self HEADER previous account");
}
if (!legacyLogin && !namespacedLogin) throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
if (loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
if (accountType != ALTERNATIVE && accountType != PRIMARY) throw new IllegalArgumentException("Bad HEADER account type");
if (previousAccounts.size() > 10 || (accountType == ALTERNATIVE && !previousAccounts.isEmpty()))
throw new IllegalArgumentException("Bad HEADER previous account count");
var seen = new java.util.HashSet<String>();
seen.add(login.toLowerCase(Locale.ROOT));
for (String prev : previousAccounts) {
if (!(prev.matches("^[A-Za-z0-9_]{1,255}$") || (prev.length() <= 30 && prev.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$")))
|| !seen.add(prev.toLowerCase(Locale.ROOT)))
throw new IllegalArgumentException("Bad, duplicate or self HEADER previous account");
}
byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
if (previous.length > 0xFFFF) throw new IllegalArgumentException("HEADER previous accounts are too long");
requireNonZeroKey(initialBlockchainKey32);
return this;
}
@@ -203,23 +144,13 @@ public final class HeaderBody implements BodyRecord {
public byte[] toBytes() {
check();
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
byte[] licenseUtf8 = version != VER ? license.getBytes(StandardCharsets.UTF_8) : new byte[0];
int licenseSize = version != VER ? (legacyCc0Encoding ? LICENSE_BYTES.length : 1 + licenseUtf8.length) : 0;
byte[] licenseUtf8 = license.getBytes(StandardCharsets.UTF_8);
byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
int identitySize = version == VER_IDENTITY ? 1 + (accountType == PRIMARY ? 2 + previous.length : 0) : 0;
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32 + licenseSize + identitySize).order(ByteOrder.BIG_ENDIAN);
bb.put(TAG_ASCII);
bb.put((byte) loginUtf8.length);
bb.put(loginUtf8);
if (version == VER_IDENTITY) {
bb.put((byte)(int)accountType);
if (accountType == PRIMARY) bb.putShort((short)previous.length).put(previous);
}
if (version != VER) {
if (legacyCc0Encoding) bb.put(LICENSE_BYTES);
else bb.put((byte) licenseUtf8.length).put(licenseUtf8);
}
bb.put(initialBlockchainKey32);
int identitySize = 1 + (accountType == PRIMARY ? 2 + previous.length : 0);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + identitySize + 1 + licenseUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
bb.put(TAG_ASCII).put((byte) loginUtf8.length).put(loginUtf8).put((byte) accountType);
if (accountType == PRIMARY) bb.putShort((short) previous.length).put(previous);
bb.put((byte) licenseUtf8.length).put(licenseUtf8).put(initialBlockchainKey32);
return bb.array();
}
@@ -232,6 +163,6 @@ public final class HeaderBody implements BodyRecord {
@Override
public String toString() {
return "HeaderBody{version=" + version + ", login='" + login + "', license=" + license + ", initialBlockchainKey32=<32 bytes>}";
return "HeaderBody{version=1.0, login='" + login + "', accountType=" + accountType + ", license=" + license + ", initialBlockchainKey32=<32 bytes>}";
}
}
@@ -41,43 +41,41 @@ public final class StageAProtocolChecks {
private static void checkBodies() throws Exception {
var header = HeaderBody.forCoreContent("Alice@shine", OWNER);
testBody(0,HEADER_COMPAT,header,null,0);
ok(header.license == null,"HEADER без CC0");
var old = HeaderBody.licensedCc0("Alice", OWNER);
eq(parseSemantic(new ContentRecord(0,0,2,old.toBytes())).toBytes(), old.toBytes(), "historical CC0 HEADER");
ok(header.license.isEmpty() && header.accountType == HeaderBody.PRIMARY,"canonical HEADER 1.0");
for (String license : new String[]{"", "CC0-1.0", "CC-BY-NC-4.0", "Лицензия 🌞", "x".repeat(255)}) {
var h = HeaderBody.licensed("Alice@shine", OWNER, license);
var c = new ContentRecord(0,0,2,h.toBytes());
var h = HeaderBody.identity("Alice@shine", OWNER, license, HeaderBody.PRIMARY, List.of());
var c = new ContentRecord(0,0,1,h.toBytes());
var parsed = (HeaderBody) parseSemantic(c);
ok(license.equals(parsed.license), "arbitrary license");
eq(h.toBytes(), parsed.toBytes(), "HEADER v2 roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(), h.toBytes(), "HEADER v2 create");
eq(h.toBytes(), parsed.toBytes(), "HEADER 1.0 roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(), h.toBytes(), "HEADER 1.0 create");
var contentItem = CoreContentTransport.sign(c.toBytes(), List.of(), SEED);
var coreRecord = core(0,null,c,contentItem.id32());
var coreItem = sign(coreRecord,CoreContentTransport.coreTags(coreRecord));
var pair = BchBlockEntry.fromCoreContent(CoreContentContainer.pack(coreItem, contentItem));
ok(license.equals(((HeaderBody)pair.body).license), "signed HEADER v2 pair");
eq(pair.getContentRecord().bodyBytes(), h.toBytes(), "signed HEADER v2 exact bytes");
bad(() -> parseSemantic(new ContentRecord(0,0,2,Arrays.copyOf(h.toBytes(),h.toBytes().length-1))), "truncated HEADER v2");
ok(license.equals(((HeaderBody)pair.body).license), "signed HEADER 1.0 pair");
eq(pair.getContentRecord().bodyBytes(), h.toBytes(), "signed HEADER 1.0 exact bytes");
bad(() -> parseSemantic(new ContentRecord(0,0,1,Arrays.copyOf(h.toBytes(),h.toBytes().length-1))), "truncated HEADER 1.0");
}
bad(() -> HeaderBody.licensed("Alice",OWNER,"x".repeat(256)), "license too long");
byte[] invalidUtf8 = HeaderBody.licensed("Alice",OWNER,"x").toBytes();
invalidUtf8[12] = (byte)0xff;
bad(() -> parseSemantic(new ContentRecord(0,0,2,invalidUtf8)), "invalid license UTF8");
bad(() -> HeaderBody.identity("Alice",OWNER,"x".repeat(256),HeaderBody.PRIMARY,List.of()), "license too long");
byte[] invalidUtf8 = HeaderBody.identity("Alice",OWNER,"x",HeaderBody.PRIMARY,List.of()).toBytes();
invalidUtf8[15] = (byte)0xff;
bad(() -> parseSemantic(new ContentRecord(0,0,1,invalidUtf8)), "invalid license UTF8");
for (int type : new int[]{0,1}) {
for (List<String> prev : type == 0 ? List.of(List.<String>of()) : List.of(List.<String>of(), List.of("Bob@free", "Old@shine"), java.util.stream.IntStream.range(0,10).mapToObj(n -> "old"+n+"@free").toList())) {
var h = HeaderBody.identity("Alice@shine",OWNER,"Лицензия",type,prev);
var c = new ContentRecord(0,0,3,h.toBytes());
var c = new ContentRecord(0,0,1,h.toBytes());
var parsed = (HeaderBody) parseSemantic(c);
ok(parsed.accountType == type && parsed.previousAccounts.equals(prev) && parsed.license.equals("Лицензия"), "HEADER v3 role and predecessors");
eq(parsed.toBytes(), h.toBytes(), "HEADER v3 byte roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(),h.toBytes(),"HEADER v3 create");
ok(parsed.accountType == type && parsed.previousAccounts.equals(prev) && parsed.license.equals("Лицензия"), "HEADER 1.0 role and predecessors");
eq(parsed.toBytes(), h.toBytes(), "HEADER 1.0 byte roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(),h.toBytes(),"HEADER 1.0 create");
var contentItem = CoreContentTransport.sign(c.toBytes(),List.of(),SEED);
var coreRecord = core(0,null,c,contentItem.id32());
var pair = BchBlockEntry.fromCoreContent(CoreContentContainer.pack(sign(coreRecord,CoreContentTransport.coreTags(coreRecord)),contentItem));
ok(((HeaderBody)pair.body).previousAccounts.equals(prev),"signed HEADER v3 pair");
ok(((HeaderBody)pair.body).previousAccounts.equals(prev),"signed HEADER 1.0 pair");
for(int n=0;n<h.toBytes().length;n++) {
byte[] cut=Arrays.copyOf(h.toBytes(),n);
bad(()->parseSemantic(new ContentRecord(0,0,3,cut)),"truncated HEADER v3");
bad(()->parseSemantic(new ContentRecord(0,0,1,cut)),"truncated HEADER 1.0");
}
}
}
@@ -89,7 +87,7 @@ public final class StageAProtocolChecks {
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,java.util.stream.IntStream.range(0,11).mapToObj(n->"old"+n+"@free").toList()),"eleven predecessors");
byte[] invalidRole = HeaderBody.identity("Alice@shine",OWNER,"",0,List.of()).toBytes();
invalidRole[6+"Alice@shine".length()] = 2;
bad(()->parseSemantic(new ContentRecord(0,0,3,invalidRole)),"invalid parsed role");
bad(()->parseSemantic(new ContentRecord(0,0,1,invalidRole)),"invalid parsed role");
var create=new CreateChannelContentBody("Новости","Описание",(short)1,(short)1);
testBody(0,TECH_CREATE_CHANNEL,create,line(CoreRecord.TECH),1);
eq(create.toBytes(),Arrays.copyOfRange(new CreateChannelBody(0,0,HASH,1,"Новости","Описание",(short)1,(short)1).toBytes(),44,
@@ -108,38 +108,19 @@ final class TargetLoginFormatTest {
}
@Test
void licensedHeaderV2IncludesExactCc0ConstantAndParsesAlongsideV1() {
HeaderBody v2 = HeaderBody.licensedCc0("Alice@shine", INITIAL_KEY);
assertEquals(HeaderBody.VER_CC0, v2.version);
assertEquals("CC0-1.0", v2.license);
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, v2.toBytes()).check();
assertEquals("Alice@shine", parsed.login);
assertEquals("CC0-1.0", parsed.license);
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
assertArrayEquals(v2.toBytes(), parsed.toBytes());
void headerV10CarriesIdentityAndArbitraryLicense() {
HeaderBody header = HeaderBody.identity("Alice@shine", INITIAL_KEY, "Лицензия 🌞", HeaderBody.PRIMARY, java.util.List.of("Bob@free"));
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, header.toBytes()).check();
assertEquals(1, parsed.version);
assertEquals("Лицензия 🌞", parsed.license);
assertEquals(HeaderBody.PRIMARY, parsed.accountType);
assertEquals(java.util.List.of("Bob@free"), parsed.previousAccounts);
assertArrayEquals(header.toBytes(), parsed.toBytes());
HeaderBody legacy = new HeaderBody("Alice@shine", INITIAL_KEY);
assertNull(new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, legacy.toBytes()).license);
assertEquals(legacy.toBytes().length + 15, v2.toBytes().length);
byte[] expectedLicenseMarker = "license:CC0-1.0".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
int markerOffset = 5 + 1 + "Alice@shine".getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
assertArrayEquals(expectedLicenseMarker, java.util.Arrays.copyOfRange(v2.toBytes(), markerOffset, markerOffset + 15));
assertArrayEquals(INITIAL_KEY, java.util.Arrays.copyOfRange(v2.toBytes(), markerOffset + 15, v2.toBytes().length));
byte[] invalid = v2.toBytes();
invalid[markerOffset + 8] = (byte)'X';
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, invalid));
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, (short) 2, header.toBytes()));
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, v2.toBytes()));
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, legacy.toBytes()));
byte[] swapped = v2.toBytes();
System.arraycopy(INITIAL_KEY, 0, swapped, markerOffset, 32);
System.arraycopy(expectedLicenseMarker, 0, swapped, markerOffset + 32, 15);
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, swapped));
() -> HeaderBody.identity("Alice@shine", INITIAL_KEY, "x".repeat(256), HeaderBody.PRIMARY, java.util.List.of()));
}
@Test
@@ -238,7 +238,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "limit_check_failed" -> "Ошибка проверки лимита размера";
case "bad_block_format" -> "Некорректный формат блока";
case "bad_block_body" -> "Некорректное тело блока";
case "header_v3_required" -> "Для нового блокчейна требуется HEADER V3 с типом аккаунта";
case "header_v1_required" -> "Для нового блокчейна требуется HEADER 1.0 с типом аккаунта";
case "previous_account_not_found" -> "Указанный предыдущий аккаунт не найден";
case "primary_vote_not_allowed" -> "Подтверждать официальность могут только разные основные аккаунты";
case "shine_vote_not_allowed" -> "Подтверждать сияние может только сияющий основной аккаунт другого основного аккаунта, принимающего подтверждения";
@@ -433,9 +433,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки.
// Проверка точная: другой регистр не может создать альтернативное "официальное" имя.
try {
// Исторические V1/V2 принимаются при импорте; новый прямой AddBlock требует V3.
if (publishToArweave && headerBody.version != HeaderBody.VER_IDENTITY)
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_v3_required", serverLastNum, serverLastHashHex);
if (headerBody.version != HeaderBody.VER)
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_v1_required", serverLastNum, serverLastHashHex);
if (publishToArweave) {
for (String previous : headerBody.previousAccounts) {
if (currentUsersDAO.getByLogin(previous) == null)
@@ -77,7 +77,7 @@ public final class BlockchainWriter {
st.setUpdatedAtMs(nowMs);
stateDAO.upsert(c, st);
if (block.body instanceof HeaderBody header && header.accountType != null) {
if (block.body instanceof HeaderBody header) {
blocksDAO.insert(c, be, header.accountType, header.previousAccounts);
try (var ps = c.prepareStatement("SELECT shine_refresh_header_identity(?)")) {
ps.setString(1, be.getLogin()); ps.execute();
@@ -65,7 +65,7 @@ public class Net_UpsertUserParam_Handler implements JsonMessageHandler {
final String param = req.getParam().trim();
if ("account_role".equalsIgnoreCase(param) || "official".equalsIgnoreCase(param)) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
"account_type_immutable", "Тип аккаунта определяется только HEADER V3");
"account_type_immutable", "Тип аккаунта определяется только HEADER 1.0");
}
if ("gender".equalsIgnoreCase(param)) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "gender_disabled", "Пол не используется");