SHA256
Добавить линии связей и параметров пользователя
This commit is contained in:
@@ -13,5 +13,5 @@
|
||||
// public static final short TEXT = 1; // сообщения да надо
|
||||
// public static final short REACTION = 2; // реакции не надо
|
||||
// public static final short CONNECTION = 3; // связи (friend/contact/follow) да надо
|
||||
// public static final short USER_PARAM = 4; // параметры профиля да надо
|
||||
// public static final short USER_PROFILE= 4; // профиль пользователя да надо
|
||||
//}
|
||||
+14
-12
@@ -1,21 +1,23 @@
|
||||
package blockchain.body;
|
||||
|
||||
/**
|
||||
* BodyHasLine — для типов, которые имеют линейные поля в body.
|
||||
* BodyHasLine — типы блоков, которые входят в проверяемую логическую линию.
|
||||
*
|
||||
* Line-prefix (BigEndian) в НАЧАЛЕ bodyBytes:
|
||||
* [4] lineCode код линии (root-идентификатор):
|
||||
* - 0 для дефолтной линии/канала "0" (root = HEADER, blockNumber=0)
|
||||
* - для канала "X": blockNumber root-блока канала (CREATE_CHANNEL)
|
||||
* Общая семантика:
|
||||
* prevLineBlockGlobalNumber — GLOBAL blockNumber предыдущего блока этой линии;
|
||||
* prevLineBlockHash32 — hash32 предыдущего блока этой линии;
|
||||
* lineSeq — порядковый номер шага линии.
|
||||
*
|
||||
* [4] prevLineBlockGlobalNumber глобальный номер предыдущего блока в этой линии
|
||||
* [32] prevLineBlockHash32 hash32 предыдущего блока в этой линии
|
||||
* lineCode — логический идентификатор линии:
|
||||
* - 0 для фиксированных системных линий (TECH, CONNECTION, USER_PROFILE)
|
||||
* и для дефолтного канала, корнем которого является HEADER #0;
|
||||
* - для пользовательского канала: GLOBAL blockNumber его CREATE_CHANNEL root.
|
||||
*
|
||||
* [4] lineSeq порядковый номер сообщения внутри линии (1..N)
|
||||
* Важно: lineCode не обязан физически присутствовать в body. Для фиксированных
|
||||
* USER_PROFILE и CONNECTION он выводится из msg_type и метод lineCode() возвращает 0.
|
||||
* Для TEXT-каналов и TECH-блоков lineCode хранится в body явно.
|
||||
*
|
||||
* Важно:
|
||||
* - Проверка связности линии (prevLineBlockGlobalNumber ↔ prevLineBlockHash32) и корректности lineSeq
|
||||
* выполняется на сервере/в БД при вставке (а не в body.check()).
|
||||
* Полная проверка хвоста линии, prev hash и lineSeq выполняется сервером при AddBlock.
|
||||
*/
|
||||
public interface BodyHasLine {
|
||||
|
||||
@@ -26,4 +28,4 @@ public interface BodyHasLine {
|
||||
byte[] prevLineBlockHash32();
|
||||
|
||||
int lineSeq();
|
||||
}
|
||||
}
|
||||
|
||||
+39
-26
@@ -7,7 +7,10 @@ import java.nio.ByteOrder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
/** CONNECTION with line fields and canonical external target. */
|
||||
/**
|
||||
* CONNECTION with one fixed connection-history line and canonical external target.
|
||||
* lineCode is not stored in body: the logical connection line always has code 0.
|
||||
*/
|
||||
public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasLine {
|
||||
public static final short TYPE = 3;
|
||||
public static final short VER = 1;
|
||||
@@ -15,10 +18,9 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
||||
|
||||
public final short subType;
|
||||
public final short version;
|
||||
public final int lineCode;
|
||||
public final int prevLineNumber;
|
||||
public final byte[] prevLineHash32;
|
||||
public final int thisLineNumber;
|
||||
public final int prevConnectionBlockNumber;
|
||||
public final byte[] prevConnectionBlockHash32;
|
||||
public final int connectionSequence;
|
||||
public final String toLogin;
|
||||
public final int toForkNumber;
|
||||
public final int toBlockGlobalNumber;
|
||||
@@ -26,47 +28,59 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
||||
|
||||
public ConnectionBody(short subType, short version, byte[] bodyBytes) {
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
this.subType = subType; this.version = version;
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
BodyTargetSupport.ensureMin(bb, 4 + 4 + 32 + 4 + 1 + 1 + 2 + 4 + 32, "ConnectionBody too short");
|
||||
this.lineCode = bb.getInt(); this.prevLineNumber = bb.getInt(); this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32); this.thisLineNumber = bb.getInt();
|
||||
BodyTargetSupport.ensureMin(bb, 4 + 32 + 4 + 1 + 1 + 2 + 4 + 32, "ConnectionBody too short");
|
||||
this.prevConnectionBlockNumber = bb.getInt();
|
||||
this.prevConnectionBlockHash32 = new byte[32];
|
||||
bb.get(this.prevConnectionBlockHash32);
|
||||
this.connectionSequence = bb.getInt();
|
||||
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
|
||||
this.toLogin = t.login(); this.toForkNumber = t.forkNumber(); this.toBlockGlobalNumber = t.blockNumber(); this.toBlockHash32 = t.blockHash32();
|
||||
this.toLogin = t.login();
|
||||
this.toForkNumber = t.forkNumber();
|
||||
this.toBlockGlobalNumber = t.blockNumber();
|
||||
this.toBlockHash32 = t.blockHash32();
|
||||
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected ConnectionBody tail");
|
||||
}
|
||||
|
||||
public ConnectionBody(int lineCode, int prevLineNumber, byte[] prevLineHash32, int thisLineNumber, short subType,
|
||||
public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType,
|
||||
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
|
||||
if (lineCode < 0 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||
this.lineCode = lineCode; this.prevLineNumber = prevLineNumber;
|
||||
this.prevLineHash32 = prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32);
|
||||
this.thisLineNumber = thisLineNumber; this.subType = subType; this.version = VER;
|
||||
this.toLogin = toLogin; this.toForkNumber = toForkNumber; this.toBlockGlobalNumber = toBlockGlobalNumber; this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
|
||||
this.prevConnectionBlockNumber = prevConnectionBlockNumber;
|
||||
this.prevConnectionBlockHash32 = prevConnectionBlockHash32 == null ? new byte[32] : Arrays.copyOf(prevConnectionBlockHash32, 32);
|
||||
this.connectionSequence = connectionSequence;
|
||||
this.subType = subType;
|
||||
this.version = VER;
|
||||
this.toLogin = toLogin;
|
||||
this.toForkNumber = toForkNumber;
|
||||
this.toBlockGlobalNumber = toBlockGlobalNumber;
|
||||
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
|
||||
}
|
||||
|
||||
@Override public ConnectionBody check() {
|
||||
if (lineCode < 0 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||
if (prevLineNumber == -1) {
|
||||
if (!isAllZero32(prevLineHash32) || thisLineNumber != -1) throw new IllegalArgumentException("Bad empty connection line anchor");
|
||||
} else if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
|
||||
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||
if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
|
||||
if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid");
|
||||
if (connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
|
||||
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override public byte[] toBytes() {
|
||||
check();
|
||||
ByteBuffer bb = ByteBuffer.allocate(4 + 4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
|
||||
ByteBuffer bb = ByteBuffer.allocate(4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
|
||||
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
@Override public int lineCode() { return lineCode; }
|
||||
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
|
||||
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevLineHash32, 32); }
|
||||
@Override public int lineSeq() { return thisLineNumber; }
|
||||
@Override public int lineCode() { return 0; }
|
||||
@Override public int prevLineBlockGlobalNumber() { return prevConnectionBlockNumber; }
|
||||
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevConnectionBlockHash32, 32); }
|
||||
@Override public int lineSeq() { return connectionSequence; }
|
||||
@Override public String toLogin() { return toLogin; }
|
||||
@Override public Integer toForkNumber() { return toForkNumber; }
|
||||
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
|
||||
@@ -87,5 +101,4 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
||||
|| v == (MsgSubType.CONNECTION_SHINE_SEEN & 0xFFFF) || v == (MsgSubType.CONNECTION_SHINE_UNSEEN & 0xFFFF)
|
||||
|| v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) || v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_UNCONFIRMED & 0xFFFF);
|
||||
}
|
||||
private static boolean isAllZero32(byte[] b) { if (b == null || b.length != 32) return false; for (byte v : b) if (v != 0) return false; return true; }
|
||||
}
|
||||
|
||||
@@ -11,10 +11,15 @@ import java.util.Objects;
|
||||
/**
|
||||
* TECH_FORK body (type=0, subType=2, version=1).
|
||||
*
|
||||
* Записывается первым новым блоком после точной перепубликации выбранного
|
||||
* префикса старой цепочки новым blockchain key.
|
||||
* TECH_FORK является обычным шагом общей TECH-линии. Поэтому body начинается
|
||||
* тем же line-prefix, что и TECH_CREATE_CHANNEL.
|
||||
*
|
||||
* body bytes (BigEndian):
|
||||
* [4] lineCode (=0 для TECH-линии)
|
||||
* [4] prevLineNumber
|
||||
* [32] prevLineHash32
|
||||
* [4] thisLineNumber
|
||||
*
|
||||
* [32] parentBlockchainKey
|
||||
* [4] forkPointBlockNumber
|
||||
* [32] forkPointBlockHash32
|
||||
@@ -27,7 +32,7 @@ import java.util.Objects;
|
||||
* [2] commentUtf8Length
|
||||
* [N] comment UTF-8 (0..1024 bytes)
|
||||
*/
|
||||
public final class ForkBody implements BodyRecord {
|
||||
public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
|
||||
public static final short TYPE = 0;
|
||||
public static final short VER = 1;
|
||||
@@ -40,10 +45,18 @@ public final class ForkBody implements BodyRecord {
|
||||
public static final int REASON_RECOVERY = 4;
|
||||
|
||||
public static final int MAX_COMMENT_UTF8_LEN = 1024;
|
||||
private static final int FIXED_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
|
||||
private static final int LINE_PREFIX_LEN = 4 + 4 + 32 + 4;
|
||||
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
|
||||
private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
|
||||
|
||||
public final short subType;
|
||||
public final short version;
|
||||
|
||||
public final int lineCode;
|
||||
public final int prevLineNumber;
|
||||
public final byte[] prevLineHash32;
|
||||
public final int thisLineNumber;
|
||||
|
||||
public final byte[] parentBlockchainKey32;
|
||||
public final int forkPointBlockNumber;
|
||||
public final byte[] forkPointBlockHash32;
|
||||
@@ -71,6 +84,12 @@ public final class ForkBody implements BodyRecord {
|
||||
}
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
this.lineCode = bb.getInt();
|
||||
this.prevLineNumber = bb.getInt();
|
||||
this.prevLineHash32 = new byte[32];
|
||||
bb.get(this.prevLineHash32);
|
||||
this.thisLineNumber = bb.getInt();
|
||||
|
||||
this.parentBlockchainKey32 = new byte[32];
|
||||
bb.get(this.parentBlockchainKey32);
|
||||
this.forkPointBlockNumber = bb.getInt();
|
||||
@@ -95,7 +114,11 @@ public final class ForkBody implements BodyRecord {
|
||||
this.comment = new String(commentBytes, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public ForkBody(byte[] parentBlockchainKey32,
|
||||
public ForkBody(int lineCode,
|
||||
int prevLineNumber,
|
||||
byte[] prevLineHash32,
|
||||
int thisLineNumber,
|
||||
byte[] parentBlockchainKey32,
|
||||
int forkPointBlockNumber,
|
||||
byte[] forkPointBlockHash32,
|
||||
long forkPointTimestampMs,
|
||||
@@ -107,6 +130,10 @@ public final class ForkBody implements BodyRecord {
|
||||
String comment) {
|
||||
this.subType = SUBTYPE;
|
||||
this.version = VER;
|
||||
this.lineCode = lineCode;
|
||||
this.prevLineNumber = prevLineNumber;
|
||||
this.prevLineHash32 = copy32(prevLineHash32, "prevLineHash32");
|
||||
this.thisLineNumber = thisLineNumber;
|
||||
this.parentBlockchainKey32 = copy32(parentBlockchainKey32, "parentBlockchainKey32");
|
||||
this.forkPointBlockNumber = forkPointBlockNumber;
|
||||
this.forkPointBlockHash32 = copy32(forkPointBlockHash32, "forkPointBlockHash32");
|
||||
@@ -127,6 +154,11 @@ public final class ForkBody implements BodyRecord {
|
||||
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
|
||||
throw new IllegalArgumentException("ForkBody version must be 1");
|
||||
}
|
||||
if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0");
|
||||
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
|
||||
require32(prevLineHash32, "prevLineHash32");
|
||||
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
|
||||
|
||||
require32(parentBlockchainKey32, "parentBlockchainKey32");
|
||||
require32(forkPointBlockHash32, "forkPointBlockHash32");
|
||||
require32(parentTipBlockHash32, "parentTipBlockHash32");
|
||||
@@ -155,6 +187,10 @@ public final class ForkBody implements BodyRecord {
|
||||
check();
|
||||
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.putInt(lineCode);
|
||||
bb.putInt(prevLineNumber);
|
||||
bb.put(prevLineHash32);
|
||||
bb.putInt(thisLineNumber);
|
||||
bb.put(parentBlockchainKey32);
|
||||
bb.putInt(forkPointBlockNumber);
|
||||
bb.put(forkPointBlockHash32);
|
||||
@@ -169,6 +205,11 @@ public final class ForkBody implements BodyRecord {
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
@Override public int lineCode() { return lineCode; }
|
||||
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
|
||||
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevLineHash32, 32); }
|
||||
@Override public int lineSeq() { return thisLineNumber; }
|
||||
|
||||
public static boolean isReasonSupported(int code) {
|
||||
return code == REASON_ROUTINE_ROTATION
|
||||
|| code == REASON_POSSIBLE_COMPROMISE
|
||||
|
||||
+38
-64
@@ -11,16 +11,16 @@ import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* UserParamBody — type=4, ver=1 (в заголовке блока).
|
||||
* UserParamBody — type=4, ver=1 (в документации: USER_PROFILE).
|
||||
*
|
||||
* subType (в заголовке блока):
|
||||
* 1 = TEXT_TEXT
|
||||
*
|
||||
* bodyBytes (BigEndian), новый формат:
|
||||
* [4] lineCode
|
||||
* [4] prevLineNumber
|
||||
* [32] prevLineHash32
|
||||
* [4] thisLineNumber
|
||||
* USER_PROFILE имеет единственную фиксированную линию, поэтому lineCode в body не хранится.
|
||||
* bodyBytes (BigEndian):
|
||||
* [4] prevProfileBlockNumber — GLOBAL blockNumber предыдущего USER_PROFILE-блока
|
||||
* [32] prevProfileBlockHash32 — hash32 предыдущего USER_PROFILE-блока
|
||||
* [4] profileSequence — порядковый номер изменения профиля (1..N)
|
||||
*
|
||||
* [2] keyLenBytes (uint16)
|
||||
* [N] keyUtf8
|
||||
@@ -35,14 +35,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
||||
|
||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||
|
||||
public final short subType; // из header
|
||||
public final short version; // из header
|
||||
public final short subType;
|
||||
public final short version;
|
||||
|
||||
// line
|
||||
public final int lineCode;
|
||||
public final int prevLineNumber;
|
||||
public final byte[] prevLineHash32;
|
||||
public final int thisLineNumber;
|
||||
public final int prevProfileBlockNumber;
|
||||
public final byte[] prevProfileBlockHash32;
|
||||
public final int profileSequence;
|
||||
|
||||
public final String paramKey;
|
||||
public final String paramValue;
|
||||
@@ -60,21 +58,17 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
||||
throw new IllegalArgumentException("Bad UserParam subType: " + (this.subType & 0xFFFF));
|
||||
}
|
||||
|
||||
// минимум: lineCode(4)+line(4+32+4) + keyLen(2)+key(1) + valLen(2)+val(1)
|
||||
if (bodyBytes.length < 4 + (4 + 32 + 4) + 2 + 1 + 2 + 1) {
|
||||
// prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1)
|
||||
if (bodyBytes.length < 4 + 32 + 4 + 2 + 1 + 2 + 1) {
|
||||
throw new IllegalArgumentException("UserParamBody too short");
|
||||
}
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
|
||||
this.lineCode = bb.getInt();
|
||||
|
||||
this.prevLineNumber = bb.getInt();
|
||||
|
||||
this.prevLineHash32 = new byte[32];
|
||||
bb.get(this.prevLineHash32);
|
||||
|
||||
this.thisLineNumber = bb.getInt();
|
||||
this.prevProfileBlockNumber = bb.getInt();
|
||||
this.prevProfileBlockHash32 = new byte[32];
|
||||
bb.get(this.prevProfileBlockHash32);
|
||||
this.profileSequence = bb.getInt();
|
||||
|
||||
int keyLen = Short.toUnsignedInt(bb.getShort());
|
||||
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
|
||||
@@ -99,25 +93,21 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
||||
if (this.paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
|
||||
}
|
||||
|
||||
public UserParamBody(int lineCode,
|
||||
int prevLineNumber,
|
||||
byte[] prevLineHash32,
|
||||
int thisLineNumber,
|
||||
public UserParamBody(int prevProfileBlockNumber,
|
||||
byte[] prevProfileBlockHash32,
|
||||
int profileSequence,
|
||||
String paramKey,
|
||||
String paramValue) {
|
||||
|
||||
Objects.requireNonNull(paramKey, "paramKey == null");
|
||||
Objects.requireNonNull(paramValue, "paramValue == null");
|
||||
|
||||
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
||||
|
||||
this.subType = MsgSubType.USER_PARAM_TEXT_TEXT;
|
||||
this.version = VER;
|
||||
|
||||
this.lineCode = lineCode;
|
||||
this.prevLineNumber = prevLineNumber;
|
||||
this.prevLineHash32 = (prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
|
||||
this.thisLineNumber = thisLineNumber;
|
||||
this.prevProfileBlockNumber = prevProfileBlockNumber;
|
||||
this.prevProfileBlockHash32 = (prevProfileBlockHash32 == null ? new byte[32] : Arrays.copyOf(prevProfileBlockHash32, 32));
|
||||
this.profileSequence = profileSequence;
|
||||
|
||||
if (paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
|
||||
if (paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
|
||||
@@ -128,17 +118,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
||||
|
||||
@Override
|
||||
public UserParamBody check() {
|
||||
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
||||
|
||||
if ((subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF))
|
||||
if ((subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF)) {
|
||||
throw new IllegalArgumentException("Bad UserParam subType: " + (subType & 0xFFFF));
|
||||
|
||||
if (prevLineNumber == -1) {
|
||||
if (!isAllZero32(prevLineHash32)) throw new IllegalArgumentException("prevLineHash32 must be zero when prevLineNumber=-1");
|
||||
if (thisLineNumber != -1) throw new IllegalArgumentException("thisLineNumber must be -1 when prevLineNumber=-1");
|
||||
} else {
|
||||
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
|
||||
}
|
||||
if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0");
|
||||
if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid");
|
||||
if (profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1");
|
||||
|
||||
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
|
||||
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
|
||||
@@ -148,30 +133,25 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
||||
|
||||
@Override
|
||||
public byte[] toBytes() {
|
||||
check();
|
||||
byte[] keyUtf8 = paramKey.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] valUtf8 = paramValue.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
|
||||
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
|
||||
|
||||
int cap = 4 + (4 + 32 + 4)
|
||||
int cap = 4 + 32 + 4
|
||||
+ 2 + keyUtf8.length
|
||||
+ 2 + valUtf8.length;
|
||||
|
||||
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
|
||||
|
||||
bb.putInt(lineCode);
|
||||
|
||||
bb.putInt(prevLineNumber);
|
||||
bb.put(prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
|
||||
bb.putInt(thisLineNumber);
|
||||
|
||||
bb.putInt(prevProfileBlockNumber);
|
||||
bb.put(prevProfileBlockHash32);
|
||||
bb.putInt(profileSequence);
|
||||
bb.putShort((short) keyUtf8.length);
|
||||
bb.put(keyUtf8);
|
||||
|
||||
bb.putShort((short) valUtf8.length);
|
||||
bb.put(valUtf8);
|
||||
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
@@ -187,15 +167,9 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isAllZero32(byte[] b) {
|
||||
if (b == null || b.length != 32) return true;
|
||||
for (int i = 0; i < 32; i++) if (b[i] != 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ====================== BodyHasLine ====================== */
|
||||
@Override public int lineCode() { return lineCode; }
|
||||
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
|
||||
@Override public byte[] prevLineBlockHash32() { return prevLineHash32 == null ? null : Arrays.copyOf(prevLineHash32, 32); }
|
||||
@Override public int lineSeq() { return thisLineNumber; }
|
||||
}
|
||||
/* USER_PROFILE имеет единственную линию, логический lineCode всегда 0. */
|
||||
@Override public int lineCode() { return 0; }
|
||||
@Override public int prevLineBlockGlobalNumber() { return prevProfileBlockNumber; }
|
||||
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevProfileBlockHash32, 32); }
|
||||
@Override public int lineSeq() { return profileSequence; }
|
||||
}
|
||||
|
||||
@@ -16,6 +16,10 @@ final class ForkBodyTest {
|
||||
byte[] tipHash = filled(32, 0x33);
|
||||
|
||||
ForkBody source = new ForkBody(
|
||||
0,
|
||||
77,
|
||||
filled(32, 0x44),
|
||||
5,
|
||||
parentKey,
|
||||
120,
|
||||
forkHash,
|
||||
@@ -33,6 +37,9 @@ final class ForkBodyTest {
|
||||
BodyRecordParser.parse(ForkBody.TYPE, ForkBody.SUBTYPE, ForkBody.VER, source.toBytes())
|
||||
);
|
||||
|
||||
assertEquals(0, parsed.lineCode);
|
||||
assertEquals(77, parsed.prevLineNumber);
|
||||
assertEquals(5, parsed.thisLineNumber);
|
||||
assertArrayEquals(parentKey, parsed.parentBlockchainKey32);
|
||||
assertEquals(120, parsed.forkPointBlockNumber);
|
||||
assertArrayEquals(forkHash, parsed.forkPointBlockHash32);
|
||||
@@ -46,6 +53,10 @@ final class ForkBodyTest {
|
||||
@Test
|
||||
void routineRotationMayDiscardNothing() {
|
||||
ForkBody body = new ForkBody(
|
||||
0,
|
||||
0,
|
||||
filled(32, 9),
|
||||
1,
|
||||
filled(32, 1),
|
||||
10,
|
||||
filled(32, 2),
|
||||
@@ -63,6 +74,10 @@ final class ForkBodyTest {
|
||||
@Test
|
||||
void rejectedWhenDiscardCountDoesNotMatchForkPointAndTip() {
|
||||
ForkBody body = new ForkBody(
|
||||
0,
|
||||
0,
|
||||
filled(32, 9),
|
||||
1,
|
||||
filled(32, 1),
|
||||
10,
|
||||
filled(32, 2),
|
||||
|
||||
+5
-11
@@ -59,7 +59,7 @@ final class TargetLoginFormatTest {
|
||||
assertEquals(5, parsedEditPost.toBlockGlobalNumber());
|
||||
|
||||
ConnectionBody connection = new ConnectionBody(
|
||||
0, -1, new byte[32], -1,
|
||||
0, HASH, 1,
|
||||
MsgSubType.CONNECTION_FOLLOW,
|
||||
"alice", 3, 0, HASH
|
||||
);
|
||||
@@ -84,16 +84,10 @@ final class TargetLoginFormatTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void forkZeroIsRejectedForNewProtocol() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new ReactionBody(MsgSubType.REACTION_LIKE, "alice", 0, 42, HASH));
|
||||
|
||||
byte[] encoded = new ReactionBody(MsgSubType.REACTION_LIKE, "alice", 1, 42, HASH).toBytes();
|
||||
int forkOffset = 1 + "alice".getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
|
||||
encoded[forkOffset] = 0;
|
||||
encoded[forkOffset + 1] = 0;
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, encoded));
|
||||
void forkZeroIsReservedButStillDecodableAsHistoricalUnknown() {
|
||||
ReactionBody source = new ReactionBody(MsgSubType.REACTION_LIKE, "alice", 0, 42, HASH);
|
||||
ReactionBody parsed = new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, source.toBytes()).check();
|
||||
assertEquals(0, parsed.toForkNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -122,6 +122,19 @@ public final class BlocksDAO {
|
||||
}
|
||||
public BlockEntry getByNumber(String bchName,int blockNumber)throws SQLException{try(Connection c=db.getConnection()){return getByNumber(c,bchName,blockNumber);} }
|
||||
|
||||
/** Последний принятый блок конкретной логической линии в текущем physical fork. */
|
||||
public BlockEntry getLastLineBlock(Connection c, String bchName, int msgType, int lineCode) throws SQLException {
|
||||
String sql = baseSelect()+" WHERE login=? AND fork_number=? AND msg_type=? AND line_code=? ORDER BY block_number DESC LIMIT 1";
|
||||
ChainRef r=chainRef(bchName);
|
||||
try(PreparedStatement ps=c.prepareStatement(sql)){
|
||||
ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,msgType); ps.setInt(4,lineCode);
|
||||
try(ResultSet rs=ps.executeQuery()){ return rs.next()?mapRow(rs):null; }
|
||||
}
|
||||
}
|
||||
public BlockEntry getLastLineBlock(String bchName, int msgType, int lineCode) throws SQLException {
|
||||
try(Connection c=db.getConnection()){ return getLastLineBlock(c,bchName,msgType,lineCode); }
|
||||
}
|
||||
|
||||
public List<BlockEntry> listRangeByNumber(String bchName,int from,int to)throws SQLException{try(Connection c=db.getConnection()){return listRangeByNumber(c,bchName,from,to);} }
|
||||
public List<BlockEntry> listRangeByNumber(Connection c,String bchName,int from,int to)throws SQLException{
|
||||
String sql=baseSelect()+" WHERE login=? AND fork_number=? AND block_number>=? AND block_number<=? ORDER BY block_number ASC";
|
||||
|
||||
@@ -523,7 +523,7 @@ CREATE TABLE IF NOT EXISTS blocks (
|
||||
block_bytes BYTEA NOT NULL,
|
||||
to_login TEXT,
|
||||
to_bch_name TEXT,
|
||||
to_fork_number INTEGER CHECK (to_fork_number IS NULL OR (to_fork_number >= 1 AND to_fork_number <= 999)),
|
||||
to_fork_number INTEGER CHECK (to_fork_number IS NULL OR (to_fork_number >= 0 AND to_fork_number <= 999)),
|
||||
to_block_number INTEGER CHECK (to_block_number IS NULL OR to_block_number >= 0),
|
||||
to_block_hash BYTEA,
|
||||
block_hash BYTEA NOT NULL,
|
||||
@@ -1110,6 +1110,7 @@ LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
prev_block RECORD;
|
||||
tail_block_number INTEGER;
|
||||
BEGIN
|
||||
IF NEW.line_code IS NULL
|
||||
AND NEW.prev_line_number IS NULL
|
||||
@@ -1149,26 +1150,35 @@ BEGIN
|
||||
RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH';
|
||||
END IF;
|
||||
|
||||
IF NEW.prev_line_number = NEW.line_code THEN
|
||||
SELECT block_number
|
||||
INTO tail_block_number
|
||||
FROM blocks
|
||||
WHERE bch_name = NEW.bch_name
|
||||
AND msg_type = NEW.msg_type
|
||||
AND line_code = NEW.line_code
|
||||
ORDER BY block_number DESC
|
||||
LIMIT 1;
|
||||
|
||||
IF tail_block_number IS NULL THEN
|
||||
IF NEW.prev_line_number <> NEW.line_code THEN
|
||||
RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL';
|
||||
END IF;
|
||||
IF NEW.this_line_number <> (CASE WHEN NEW.msg_type = 1 THEN 0 ELSE 1 END) THEN
|
||||
RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
IF NEW.prev_line_number <> tail_block_number THEN
|
||||
RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL';
|
||||
END IF;
|
||||
|
||||
IF prev_block.this_line_number IS NULL THEN
|
||||
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
|
||||
END IF;
|
||||
|
||||
IF NEW.msg_type = 1 THEN
|
||||
IF NEW.this_line_number <> prev_block.this_line_number
|
||||
AND NEW.this_line_number <> prev_block.this_line_number + 1 THEN
|
||||
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
|
||||
END IF;
|
||||
ELSE
|
||||
IF NEW.this_line_number <> prev_block.this_line_number + 1 THEN
|
||||
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
|
||||
END IF;
|
||||
IF NEW.this_line_number <> prev_block.this_line_number + 1 THEN
|
||||
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
@@ -2436,7 +2446,7 @@ $$;
|
||||
|
||||
-- Physical chain integrity uses numeric fork identity.
|
||||
CREATE OR REPLACE FUNCTION shine_blocks_line_integrity_bi() RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||
DECLARE prev_block RECORD;
|
||||
DECLARE prev_block RECORD; tail_block_number INTEGER;
|
||||
BEGIN
|
||||
IF NEW.line_code IS NULL AND NEW.prev_line_number IS NULL AND NEW.prev_line_hash IS NULL AND NEW.this_line_number IS NULL THEN RETURN NEW; END IF;
|
||||
IF NEW.msg_type NOT IN (0,1,3,4) THEN RAISE EXCEPTION 'LINE_ERR_UNSUPPORTED_TYPE_WITH_LINE'; END IF;
|
||||
@@ -2445,15 +2455,17 @@ BEGIN
|
||||
IF NOT FOUND THEN RAISE EXCEPTION 'LINE_ERR_NO_PREV'; END IF;
|
||||
IF prev_block.block_hash IS DISTINCT FROM NEW.prev_line_hash THEN RAISE EXCEPTION 'LINE_ERR_PREV_HASH_MISMATCH'; END IF;
|
||||
IF NEW.prev_line_number<>NEW.line_code AND prev_block.line_code IS DISTINCT FROM NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH'; END IF;
|
||||
IF NEW.prev_line_number=NEW.line_code THEN
|
||||
IF NEW.this_line_number<>(CASE WHEN NEW.msg_type=1 THEN 0 ELSE 1 END) THEN RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS'; END IF; RETURN NEW;
|
||||
SELECT block_number INTO tail_block_number FROM blocks_store
|
||||
WHERE login=NEW.login AND fork_number=NEW.fork_number AND msg_type=NEW.msg_type AND line_code=NEW.line_code
|
||||
ORDER BY block_number DESC LIMIT 1;
|
||||
IF tail_block_number IS NULL THEN
|
||||
IF NEW.prev_line_number<>NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF;
|
||||
IF NEW.this_line_number<>(CASE WHEN NEW.msg_type=1 THEN 0 ELSE 1 END) THEN RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF NEW.prev_line_number<>tail_block_number THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF;
|
||||
IF prev_block.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
|
||||
IF NEW.msg_type=1 THEN
|
||||
IF NEW.this_line_number<>prev_block.this_line_number AND NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
|
||||
ELSE
|
||||
IF NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
|
||||
END IF;
|
||||
IF NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
|
||||
+112
-29
@@ -8,6 +8,7 @@ import blockchain.body.BodyHasTarget;
|
||||
import blockchain.body.ConnectionBody;
|
||||
import blockchain.body.CreateChannelBody;
|
||||
import blockchain.body.HeaderBody;
|
||||
import blockchain.body.ForkBody;
|
||||
import blockchain.body.StatusActionBody;
|
||||
import blockchain.body.TextReplyBody;
|
||||
import blockchain.body.TextLineBody;
|
||||
@@ -195,6 +196,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
case "limit_check_failed" -> "Ошибка проверки лимита размера";
|
||||
case "bad_block_format" -> "Некорректный формат блока";
|
||||
case "bad_app_tag" -> "Некорректный тестовый тег ANS-104";
|
||||
case "bad_type_tag" -> "Некорректный индексный t-тег ANS-104";
|
||||
case "bad_channel_tag" -> "Некорректный тег канала ANS-104";
|
||||
case "bad_block_body" -> "Некорректное тело блока";
|
||||
case "bad_channel_name" -> "Некорректное название канала";
|
||||
@@ -204,9 +206,15 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
case "bad_blockchain_key_len" -> "Некорректный ключ блокчейна в состоянии (ожидалось 32 байта)";
|
||||
case "signature_verify_failed" -> "Ошибка проверки подписи блока";
|
||||
case "bad_signature" -> "Некорректная подпись блока";
|
||||
case "prev_line_block_not_found" -> "Не найден блок prevLineNumber для проверки линии";
|
||||
case "prev_line_block_not_found", "line_root_not_found" -> "Не найден root/prev блок логической линии";
|
||||
case "bad_line_code" -> "Некорректный код логической линии";
|
||||
case "bad_line_root" -> "Некорректный root логической линии";
|
||||
case "bad_line_state" -> "Повреждено состояние логической линии";
|
||||
case "bad_prev_line_number" -> "Блок не продолжает текущий хвост логической линии";
|
||||
case "bad_prev_line_hash" -> "Некорректный prevLineHash";
|
||||
case "db_error_prev_line_check" -> "Ошибка БД при проверке prevLine";
|
||||
case "bad_line_sequence" -> "Некорректный порядковый номер логической линии";
|
||||
case "unsupported_line_body" -> "Этот body не поддерживает логическую линию";
|
||||
case "db_error_prev_line_check", "db_error_line_check" -> "Ошибка БД при проверке логической линии";
|
||||
case "channel_name_already_exists" -> "Такое название канала уже занято";
|
||||
case "repost_disabled" -> "Репосты временно отключены до будущей реализации";
|
||||
case "entrypoint_edit_forbidden" -> "TEXT_ENTRYPOINT нельзя редактировать через TEXT_EDIT_POST";
|
||||
@@ -312,6 +320,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_app_tag", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
|
||||
// Signed secondary index for the fixed SHiNE streams.
|
||||
String expectedTypeTag = expectedTypeTag(block);
|
||||
String actualTypeTag = block.getDataItem().tagValue("t");
|
||||
if (expectedTypeTag != null) {
|
||||
if (!expectedTypeTag.equals(actualTypeTag)) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_type_tag", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
} else if (actualTypeTag != null) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_type_tag", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
|
||||
// body.check()
|
||||
try {
|
||||
block.body.check();
|
||||
@@ -540,6 +559,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_blockchain_key_len", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
|
||||
if (serverLastNum == -1 && block.body instanceof HeaderBody headerBody
|
||||
&& !Arrays.equals(headerBody.initialBlockchainKey32, pubKey32)) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_initial_key_mismatch", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
|
||||
// 6) ANS-104 Ed25519 подпись и owner
|
||||
boolean sigOk;
|
||||
try {
|
||||
@@ -556,7 +580,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_signature", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
|
||||
// 7) line columns (only for BodyHasLine)
|
||||
// 7) line columns + strict continuity check.
|
||||
Integer lineCode = null;
|
||||
Integer prevLineNumber = null;
|
||||
byte[] prevLineHash32 = null;
|
||||
@@ -568,33 +592,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
prevLineHash32 = bl.prevLineBlockHash32();
|
||||
thisLineNumber = bl.lineSeq();
|
||||
|
||||
// Нормализация: пустой line anchor (-1) не пишем в DB projection
|
||||
if (prevLineNumber != null && prevLineNumber == -1) {
|
||||
lineCode = null;
|
||||
prevLineNumber = null;
|
||||
prevLineHash32 = null;
|
||||
thisLineNumber = null;
|
||||
}
|
||||
|
||||
// Если prevLineNumber задан — проверяем его хэш
|
||||
if (prevLineNumber != null) {
|
||||
try {
|
||||
byte[] dbPrevHash = blocksDAO.getHashByNumber(blockchainName, prevLineNumber);
|
||||
if (dbPrevHash == null) {
|
||||
log.warn("AddBlock: prev_line_block_not_found (login={}, blockchainName={}, blockNumber={}, prevLineNumber={})",
|
||||
login, blockchainName, block.blockNumber, prevLineNumber);
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "prev_line_block_not_found", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
if (!Arrays.equals(dbPrevHash, require32OrThrow(prevLineHash32, "prevLineHash32 invalid"))) {
|
||||
log.warn("AddBlock: bad_prev_line_hash (login={}, blockchainName={}, blockNumber={}, prevLineNumber={})",
|
||||
login, blockchainName, block.blockNumber, prevLineNumber);
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_prev_line_hash", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("AddBlock: db_error_prev_line_check (login={}, blockchainName={}, blockNumber={})",
|
||||
login, blockchainName, block.blockNumber, e);
|
||||
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_prev_line_check", serverLastNum, serverLastHashHex);
|
||||
try {
|
||||
String lineError = validateLineContinuity(blockchainName, block, bl);
|
||||
if (lineError != null) {
|
||||
log.warn("AddBlock: {} (login={}, blockchainName={}, blockNumber={}, lineCode={}, prevLineNumber={}, lineSeq={})",
|
||||
lineError, login, blockchainName, block.blockNumber, lineCode, prevLineNumber, thisLineNumber);
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, lineError, serverLastNum, serverLastHashHex);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("AddBlock: db_error_line_check (login={}, blockchainName={}, blockNumber={})",
|
||||
login, blockchainName, block.blockNumber, e);
|
||||
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_line_check", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -755,6 +763,81 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
/* ====================== Helpers ====================================== */
|
||||
/* ===================================================================== */
|
||||
|
||||
private static String expectedTypeTag(BchBlockEntry block) {
|
||||
int type = block.type & 0xffff;
|
||||
return switch (type) {
|
||||
case 0 -> "tech";
|
||||
case 3 -> "conn";
|
||||
case 4 -> "prof";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет не просто существование prev-блока, а именно продолжение текущего хвоста линии.
|
||||
* Это запрещает боковые ветки линии и гарантирует монотонный sequence.
|
||||
*/
|
||||
private String validateLineContinuity(String blockchainName, BchBlockEntry block, BodyHasLine line) throws Exception {
|
||||
int type = block.type & 0xffff;
|
||||
int lineCode = line.lineCode();
|
||||
int rootBlockNumber;
|
||||
int firstSequence;
|
||||
|
||||
if (block.body instanceof UserParamBody || block.body instanceof ConnectionBody) {
|
||||
if (lineCode != 0) return "bad_line_code";
|
||||
rootBlockNumber = 0;
|
||||
firstSequence = 1;
|
||||
} else if (block.body instanceof CreateChannelBody || block.body instanceof ForkBody) {
|
||||
if (lineCode != 0) return "bad_line_code";
|
||||
rootBlockNumber = 0;
|
||||
firstSequence = 1;
|
||||
} else if (block.body instanceof TextLineBody) {
|
||||
if (lineCode < 0) return "bad_line_code";
|
||||
rootBlockNumber = lineCode;
|
||||
// Channel sequence is zero-based after its root anchor.
|
||||
firstSequence = 0;
|
||||
} else {
|
||||
return "unsupported_line_body";
|
||||
}
|
||||
|
||||
BlockEntry root = blocksDAO.getByNumber(blockchainName, rootBlockNumber);
|
||||
if (root == null) return "line_root_not_found";
|
||||
if (rootBlockNumber == 0) {
|
||||
try {
|
||||
if (!(new BchBlockEntry(root.getBlockBytes()).body instanceof HeaderBody)) return "bad_line_root";
|
||||
} catch (Exception e) {
|
||||
return "bad_line_root";
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
if (!(new BchBlockEntry(root.getBlockBytes()).body instanceof CreateChannelBody)) return "bad_line_root";
|
||||
} catch (Exception e) {
|
||||
return "bad_line_root";
|
||||
}
|
||||
}
|
||||
|
||||
BlockEntry tail = blocksDAO.getLastLineBlock(blockchainName, type, lineCode);
|
||||
int expectedPrevNumber;
|
||||
byte[] expectedPrevHash;
|
||||
int expectedSequence;
|
||||
if (tail == null) {
|
||||
expectedPrevNumber = rootBlockNumber;
|
||||
expectedPrevHash = root.getBlockHash();
|
||||
expectedSequence = firstSequence;
|
||||
} else {
|
||||
if (tail.getThisLineNumber() == null) return "bad_line_state";
|
||||
expectedPrevNumber = tail.getBlockNumber();
|
||||
expectedPrevHash = tail.getBlockHash();
|
||||
expectedSequence = Math.addExact(tail.getThisLineNumber(), 1);
|
||||
}
|
||||
|
||||
if (line.prevLineBlockGlobalNumber() != expectedPrevNumber) return "bad_prev_line_number";
|
||||
byte[] suppliedPrevHash = require32OrThrow(line.prevLineBlockHash32(), "prevLineHash32 invalid");
|
||||
if (!Arrays.equals(expectedPrevHash, suppliedPrevHash)) return "bad_prev_line_hash";
|
||||
if (line.lineSeq() != expectedSequence) return "bad_line_sequence";
|
||||
return null;
|
||||
}
|
||||
|
||||
private String expectedChannelSlug(String blockchainName, BchBlockEntry block, ChannelNameStateEntry justCreated) throws Exception {
|
||||
if (block.body instanceof CreateChannelBody) {
|
||||
return justCreated == null ? null : justCreated.getSlug();
|
||||
|
||||
+15
@@ -101,6 +101,11 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
|
||||
if (!block.getDataItem().hasTag("App", "test5590")) {
|
||||
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_APP_TAG", "Отсутствует App=test5590");
|
||||
}
|
||||
String expectedTypeTag = expectedTypeTag(block);
|
||||
String actualTypeTag = block.getDataItem().tagValue("t");
|
||||
if (expectedTypeTag != null ? !expectedTypeTag.equals(actualTypeTag) : actualTypeTag != null) {
|
||||
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_TYPE_TAG", "Некорректный t-тег candidate DataItem");
|
||||
}
|
||||
if (!requestPrevHashMatches(req.getPrevBlockHash(), block.prevHash32)) {
|
||||
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_PREV_HASH_MISMATCH", "prevBlockHash запроса не совпадает с блоком");
|
||||
}
|
||||
@@ -221,4 +226,14 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
|
||||
if (value == null) return "";
|
||||
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
|
||||
}
|
||||
private static String expectedTypeTag(BchBlockEntry block) {
|
||||
int type = block.type & 0xffff;
|
||||
return switch (type) {
|
||||
case 0 -> "tech";
|
||||
case 3 -> "conn";
|
||||
case 4 -> "prof";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+13
@@ -148,6 +148,9 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
|
||||
if (!Arrays.equals(candidate.getHash32(), stored.getBlockHash())) return "KEY_ROTATION_STORED_HASH_MISMATCH";
|
||||
if (!Arrays.equals(candidate.getDataItemId32(), stored.getDataItemId())) return "KEY_ROTATION_STORED_DATAITEM_MISMATCH";
|
||||
if (!candidate.getDataItem().hasTag("App", "test5590")) return "KEY_ROTATION_BAD_APP_TAG";
|
||||
String expectedTypeTag = expectedTypeTag(candidate);
|
||||
String actualTypeTag = candidate.getDataItem().tagValue("t");
|
||||
if (expectedTypeTag != null ? !expectedTypeTag.equals(actualTypeTag) : actualTypeTag != null) return "KEY_ROTATION_BAD_TYPE_TAG";
|
||||
if (!BchCryptoVerifier.verifyBlock(candidate, newBlockchainKey)) return "KEY_ROTATION_BAD_SIGNATURE";
|
||||
|
||||
if (i == 0) {
|
||||
@@ -215,4 +218,14 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
|
||||
if (value == null) return "";
|
||||
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
|
||||
}
|
||||
private static String expectedTypeTag(BchBlockEntry block) {
|
||||
int type = block.type & 0xffff;
|
||||
return switch (type) {
|
||||
case 0 -> "tech";
|
||||
case 3 -> "conn";
|
||||
case 4 -> "prof";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -81,6 +81,8 @@ public final class AddBlockSender {
|
||||
|
||||
List<Ans104DataItem.Tag> tags = new ArrayList<>();
|
||||
tags.add(new Ans104DataItem.Tag("App", "test5590"));
|
||||
String typeTag = typeTagFor(type);
|
||||
if (typeTag != null) tags.add(new Ans104DataItem.Tag("t", typeTag));
|
||||
String channelSlug = channelSlugFor(body);
|
||||
if (channelSlug != null) tags.add(new Ans104DataItem.Tag("c_test5590", channelSlug));
|
||||
|
||||
@@ -167,6 +169,7 @@ public final class AddBlockSender {
|
||||
private static short typeOf(BodyRecord body) {
|
||||
if (body instanceof HeaderBody) return HeaderBody.TYPE;
|
||||
if (body instanceof CreateChannelBody) return CreateChannelBody.TYPE;
|
||||
if (body instanceof ForkBody) return ForkBody.TYPE;
|
||||
if (body instanceof TextLineBody || body instanceof TextReplyBody || body instanceof TextRatingBody) return TextLineBody.TYPE;
|
||||
if (body instanceof StatusActionBody) return StatusActionBody.TYPE;
|
||||
if (body instanceof ReactionBody) return ReactionBody.TYPE;
|
||||
@@ -178,6 +181,7 @@ public final class AddBlockSender {
|
||||
private static short subTypeOf(BodyRecord body) {
|
||||
if (body instanceof HeaderBody hb) return hb.subType;
|
||||
if (body instanceof CreateChannelBody cb) return cb.subType;
|
||||
if (body instanceof ForkBody fb) return fb.subType;
|
||||
if (body instanceof TextLineBody tb) return tb.subType;
|
||||
if (body instanceof TextReplyBody tb) return tb.subType;
|
||||
if (body instanceof TextRatingBody tb) return tb.subType;
|
||||
@@ -191,6 +195,7 @@ public final class AddBlockSender {
|
||||
private static short versionOf(BodyRecord body) {
|
||||
if (body instanceof HeaderBody hb) return hb.version;
|
||||
if (body instanceof CreateChannelBody cb) return cb.version;
|
||||
if (body instanceof ForkBody fb) return fb.version;
|
||||
if (body instanceof TextLineBody tb) return tb.version;
|
||||
if (body instanceof TextReplyBody tb) return tb.version;
|
||||
if (body instanceof TextRatingBody tb) return tb.version;
|
||||
@@ -203,6 +208,15 @@ public final class AddBlockSender {
|
||||
|
||||
// ---------- Frame v1 + signed channel tag helpers ----------
|
||||
|
||||
private static String typeTagFor(short type) {
|
||||
return switch (type & 0xFFFF) {
|
||||
case 0 -> "tech";
|
||||
case 3 -> "conn";
|
||||
case 4 -> "prof";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private String channelSlugFor(BodyRecord body) {
|
||||
if (body instanceof CreateChannelBody ccb) {
|
||||
return shine.db.channels.ChannelNameRules.toCanonicalSlug(ccb.channelName);
|
||||
|
||||
@@ -3,6 +3,7 @@ package test.it.blockchain;
|
||||
import blockchain.body.BodyRecord;
|
||||
import blockchain.body.BodyHasLine;
|
||||
import blockchain.body.CreateChannelBody;
|
||||
import blockchain.body.ForkBody;
|
||||
import blockchain.body.TextLineBody;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -16,10 +17,10 @@ import java.util.Map;
|
||||
* - map blockNumber -> hash32
|
||||
*
|
||||
* Линии:
|
||||
* - TECH (type=0): только CREATE_CHANNEL (hasLine), root = HEADER
|
||||
* - TECH (type=0): CREATE_CHANNEL и TECH_FORK, root = HEADER
|
||||
* - TEXT (type=1): линии каналов, root = HEADER (канал "0") или CREATE_CHANNEL (канал "X")
|
||||
* - CONNECTION (type=3): одна линия
|
||||
* - USER_PARAM (type=4): одна линия
|
||||
* - USER_PROFILE (type=4): одна линия
|
||||
*
|
||||
* ВАЖНО:
|
||||
* - prevLineNumber — это GLOBAL blockNumber предыдущего блока линии.
|
||||
@@ -277,16 +278,18 @@ public final class ChainState {
|
||||
|
||||
int t = type & 0xFFFF;
|
||||
|
||||
// ---- TECH (CREATE_CHANNEL) ----
|
||||
if (t == TYPE_TECH && body instanceof CreateChannelBody ccb) {
|
||||
// ---- TECH (CREATE_CHANNEL / TECH_FORK) ----
|
||||
if (t == TYPE_TECH && body instanceof BodyHasLine tech) {
|
||||
techLine.lastGlobalNumber = blockNumber;
|
||||
techLine.lastHashHex = hex64;
|
||||
techLine.lastThisLineNumber = ccb.thisLineNumber;
|
||||
|
||||
// ВАЖНО: CREATE_CHANNEL — это root нового текстового канала:
|
||||
// lineCode для этого канала = blockNumber CREATE_CHANNEL
|
||||
registerTextChannelRoot(blockNumber, hash32);
|
||||
techLine.lastThisLineNumber = tech.lineSeq();
|
||||
|
||||
if (body instanceof CreateChannelBody) {
|
||||
// CREATE_CHANNEL одновременно является root нового текстового канала.
|
||||
registerTextChannelRoot(blockNumber, hash32);
|
||||
} else if (!(body instanceof ForkBody)) {
|
||||
throw new IllegalStateException("Unknown TECH line body: " + body.getClass());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -331,11 +331,7 @@ public class IT_03_AddBlock_NoAuth {
|
||||
|
||||
var ln = st.nextLineByType(ChainState.TYPE_CONNECTION);
|
||||
|
||||
// КОНСТРУКТОР ИЗ ТВОЕГО КОДА:
|
||||
// ConnectionBody(int lineCode, int prevLineNumber, byte[] prevLineHash32, int thisLineNumber,
|
||||
// short subType, String toLogin, int toBlockGlobalNumber, byte[] toBlockHash32)
|
||||
sender.send(new ConnectionBody(
|
||||
0, // lineCode для connection линии
|
||||
ln.prevLineNumber,
|
||||
ln.prevLineHash32,
|
||||
ln.thisLineNumber,
|
||||
|
||||
@@ -132,7 +132,6 @@ public final class SeedDataPopulationHelper {
|
||||
ChainState state = stateFor(login);
|
||||
ChainState.NextLine line = state.nextLineByType(ChainState.TYPE_USER_PARAM);
|
||||
sender.send(new UserParamBody(
|
||||
0,
|
||||
line.prevLineNumber,
|
||||
line.prevLineHash32,
|
||||
line.thisLineNumber,
|
||||
@@ -148,7 +147,6 @@ public final class SeedDataPopulationHelper {
|
||||
ChainState.NextLine line = state.nextLineByType(ChainState.TYPE_CONNECTION);
|
||||
|
||||
sender.send(new ConnectionBody(
|
||||
0,
|
||||
line.prevLineNumber,
|
||||
line.prevLineHash32,
|
||||
line.thisLineNumber,
|
||||
|
||||
Reference in New Issue
Block a user