SHA256
HEADER v3, primary аккаунты и подтверждения
This commit is contained in:
@@ -55,7 +55,7 @@ PDA 1.2 использует три постоянные роли ключей:
|
||||
|
||||
## Синхронизация пользовательских blockchain
|
||||
|
||||
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync пока может оставаться как inert legacy, но не должен включаться в runtime.
|
||||
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync удалён; не восстанавливать его. `ListBlockchainHeads` остаётся read-only API тестового издателя.
|
||||
|
||||
## Деплой
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ public final class BodyRecordParser {
|
||||
// TECH supports Header v1 and CreateChannel current format (ver=1).
|
||||
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
|
||||
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
|
||||
&& (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.VER_CC0 & 0xFFFF))) {
|
||||
&& (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.VER_LICENSE & 0xFFFF) || v == HeaderBody.VER_IDENTITY)) {
|
||||
return new HeaderBody(subType, version, bodyBytes).check();
|
||||
}
|
||||
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
|
||||
|
||||
+2
-1
@@ -17,8 +17,9 @@ public final class ContentBodyParser {
|
||||
public static BodyRecord parseForCore(CoreRecord core, ContentRecord content) {
|
||||
if (!java.util.Arrays.equals(core.contentHash32(), content.contentHash32()))
|
||||
throw new IllegalArgumentException("CONTENT hash не совпадает с CORE");
|
||||
if (content.version() != 1) throw new IllegalArgumentException("Неподдерживаемая версия CONTENT body");
|
||||
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)))
|
||||
throw new IllegalArgumentException("Неподдерживаемая версия CONTENT body");
|
||||
if (header != (core.blockNumber() == 0)) throw new IllegalArgumentException("HEADER только в CORE №0");
|
||||
CoreRecord.Line line = core.line();
|
||||
int expected = switch (content.type()) {
|
||||
|
||||
+105
-20
@@ -9,13 +9,17 @@ import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* HeaderBody — TECH type=0, subType=0; version=1 legacy / version=2 CC0.
|
||||
* HeaderBody — TECH type=0, subType=0; version=1 legacy / version=2 license / version=3 identity.
|
||||
*
|
||||
* bodyBytes (BigEndian):
|
||||
* [TAG_LEN] tag ASCII
|
||||
* [1] loginLength (uint8)
|
||||
* [N] login UTF-8
|
||||
* [15] ASCII "license:CC0-1.0" (version=2 only)
|
||||
* [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.
|
||||
@@ -25,7 +29,10 @@ import java.util.Objects;
|
||||
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_CC0 = 2;
|
||||
public static final short VER_LICENSE = 2;
|
||||
public static final short VER_IDENTITY = 3;
|
||||
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);
|
||||
@@ -41,15 +48,18 @@ 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 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) throw new IllegalArgumentException("HeaderBody version must be 1 or 2");
|
||||
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 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");
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
@@ -60,17 +70,48 @@ public final class HeaderBody implements BodyRecord {
|
||||
this.tag = parsedTag;
|
||||
|
||||
int loginLen = Byte.toUnsignedInt(bb.get());
|
||||
if (loginLen <= 0 || bb.remaining() != loginLen + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0))
|
||||
if (loginLen <= 0 || bb.remaining() < loginLen + 32 + (version == VER_LICENSE ? 1 : 0))
|
||||
throw new IllegalArgumentException("Bad HeaderBody login/key/license length");
|
||||
byte[] loginBytes = new byte[loginLen];
|
||||
bb.get(loginBytes);
|
||||
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
|
||||
if (version == VER_CC0) {
|
||||
byte[] actual = new byte[LICENSE_BYTES.length];
|
||||
bb.get(actual);
|
||||
if (!Arrays.equals(actual, LICENSE_BYTES)) throw new IllegalArgumentException("Unsupported HEADER license");
|
||||
this.license = LICENSE_CC0;
|
||||
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");
|
||||
}
|
||||
} else {
|
||||
this.accountType = null;
|
||||
this.previousAccounts = java.util.List.of();
|
||||
legacyCc0Encoding = false;
|
||||
this.license = null;
|
||||
}
|
||||
this.initialBlockchainKey32 = new byte[32];
|
||||
@@ -81,19 +122,34 @@ public final class HeaderBody implements BodyRecord {
|
||||
|
||||
// Legacy constructor is kept for historical fixtures and importing v1 blocks.
|
||||
public HeaderBody(String login, byte[] initialBlockchainKey32) {
|
||||
this(login, initialBlockchainKey32, VER);
|
||||
this(login, initialBlockchainKey32, VER, null, false);
|
||||
}
|
||||
|
||||
/** HEADER для CORE v2 / CONTENT v1: сохраняет login и начальный ключ, без поля лицензии. */
|
||||
public static HeaderBody forCoreContent(String login, byte[] initialBlockchainKey32) {
|
||||
return new HeaderBody(login, initialBlockchainKey32, VER);
|
||||
return new HeaderBody(login, initialBlockchainKey32, VER, null, false);
|
||||
}
|
||||
|
||||
public static HeaderBody licensedCc0(String login, byte[] initialBlockchainKey32) {
|
||||
return new HeaderBody(login, initialBlockchainKey32, VER_CC0);
|
||||
return new HeaderBody(login, initialBlockchainKey32, VER_LICENSE, LICENSE_CC0, true);
|
||||
}
|
||||
|
||||
private HeaderBody(String login, byte[] initialBlockchainKey32, short version) {
|
||||
/** Новый HEADER v2: произвольная строка лицензии, включая пустую. */
|
||||
public static HeaderBody licensed(String login, byte[] initialBlockchainKey32, String license) {
|
||||
return new HeaderBody(login, initialBlockchainKey32, VER_LICENSE, Objects.requireNonNull(license), false);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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");
|
||||
this.subType = SUBTYPE_COMPAT;
|
||||
@@ -101,15 +157,20 @@ public final class HeaderBody implements BodyRecord {
|
||||
this.tag = TAG;
|
||||
this.login = login;
|
||||
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
|
||||
this.license = version == VER_CC0 ? LICENSE_CC0 : null;
|
||||
this.license = license;
|
||||
this.accountType = accountType;
|
||||
this.previousAccounts = java.util.List.copyOf(previousAccounts);
|
||||
this.legacyCc0Encoding = legacyCc0Encoding;
|
||||
check();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeaderBody check() {
|
||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("Bad HeaderBody version");
|
||||
if (version == VER_CC0 && !LICENSE_CC0.equals(license)) throw new IllegalArgumentException("Bad HEADER CC0 license");
|
||||
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))
|
||||
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");
|
||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||
@@ -121,6 +182,19 @@ public final class HeaderBody implements BodyRecord {
|
||||
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");
|
||||
}
|
||||
}
|
||||
requireNonZeroKey(initialBlockchainKey32);
|
||||
return this;
|
||||
}
|
||||
@@ -129,11 +203,22 @@ public final class HeaderBody implements BodyRecord {
|
||||
public byte[] toBytes() {
|
||||
check();
|
||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0)).order(ByteOrder.BIG_ENDIAN);
|
||||
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[] 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_CC0) bb.put(LICENSE_BYTES);
|
||||
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);
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
+48
-1
@@ -42,7 +42,54 @@ public final class StageAProtocolChecks {
|
||||
var header = HeaderBody.forCoreContent("Alice@shine", OWNER);
|
||||
testBody(0,HEADER_COMPAT,header,null,0);
|
||||
ok(header.license == null,"HEADER без CC0");
|
||||
bad(() -> parseSemantic(new ContentRecord(0,0,2,HeaderBody.licensedCc0("Alice",OWNER).toBytes())),"CC0 HEADER");
|
||||
var old = HeaderBody.licensedCc0("Alice", OWNER);
|
||||
eq(parseSemantic(new ContentRecord(0,0,2,old.toBytes())).toBytes(), old.toBytes(), "historical CC0 HEADER");
|
||||
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 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");
|
||||
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");
|
||||
}
|
||||
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");
|
||||
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 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");
|
||||
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");
|
||||
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(()->HeaderBody.identity("Alice@shine",OWNER,"",2,List.of()),"unknown type");
|
||||
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",0,List.of("Bob@free")),"alternative predecessor");
|
||||
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("alice@shine")),"self predecessor");
|
||||
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("Bob@free","bob@free")),"duplicate predecessor");
|
||||
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("Bob,old")),"comma in predecessor");
|
||||
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");
|
||||
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,
|
||||
|
||||
@@ -36,6 +36,9 @@ public final class DatabaseInitializer {
|
||||
public static final int SCHEMA_VERSION_43 = 43;
|
||||
public static final int SCHEMA_VERSION_44 = 44;
|
||||
public static final int SCHEMA_VERSION_45 = 45;
|
||||
public static final int SCHEMA_VERSION_46 = 46;
|
||||
public static final int SCHEMA_VERSION_47 = 47;
|
||||
public static final int SCHEMA_VERSION_48 = 48;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||
@@ -52,6 +55,9 @@ public final class DatabaseInitializer {
|
||||
public static final String POSTGRES_MIGRATION_V43_RESOURCE = "postgres/migration_v43.sql";
|
||||
public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.sql";
|
||||
public static final String POSTGRES_MIGRATION_V45_RESOURCE = "postgres/migration_v45.sql";
|
||||
public static final String POSTGRES_MIGRATION_V46_RESOURCE = "postgres/migration_v46.sql";
|
||||
public static final String POSTGRES_MIGRATION_V47_RESOURCE = "postgres/migration_v47.sql";
|
||||
public static final String POSTGRES_MIGRATION_V48_RESOURCE = "postgres/migration_v48.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -203,9 +209,21 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_45) {
|
||||
if (currentVersion == SCHEMA_VERSION_45) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V46_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion == SCHEMA_VERSION_46) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V47_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion == SCHEMA_VERSION_47) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V48_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_48) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 45, found " + currentVersion);
|
||||
"Unsupported SHiNE DB v2 schema version: expected 48, found " + currentVersion);
|
||||
}
|
||||
normalizeBlockchainStateKeysToBase64(conn);
|
||||
}
|
||||
|
||||
+2
@@ -87,6 +87,7 @@ public final class BlockchainResyncCleanupDAO {
|
||||
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
|
||||
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate();
|
||||
}
|
||||
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,ref.login());ps.execute();}
|
||||
c.commit();
|
||||
return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState);
|
||||
}catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); }
|
||||
@@ -214,6 +215,7 @@ public final class BlockchainResyncCleanupDAO {
|
||||
)
|
||||
""")){ps.setString(1,login);ps.executeUpdate();}
|
||||
|
||||
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,login);ps.execute();}
|
||||
// Recompute all message aggregates whose target belongs to this user. This also fixes
|
||||
// external reactions/replies that intentionally survive this user's rebuild.
|
||||
try(PreparedStatement ps=c.prepareStatement("""
|
||||
|
||||
@@ -22,14 +22,19 @@ public final class BlocksDAO {
|
||||
}
|
||||
|
||||
public void insert(Connection c, BlockEntry e) throws SQLException {
|
||||
insert(c, e, null, null);
|
||||
}
|
||||
|
||||
public void insert(Connection c, BlockEntry e, Integer accountType, List<String> previousAccounts) throws SQLException {
|
||||
String sql = """
|
||||
INSERT INTO blocks_store (
|
||||
login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
|
||||
to_login,to_fork_number,to_block_number,to_block_hash,
|
||||
block_hash,block_signature,data_item_id,
|
||||
arweave_publish_pending,arweave_published_at_ms,
|
||||
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number,
|
||||
header_account_type,header_previous_accounts
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
@@ -53,6 +58,12 @@ public final class BlocksDAO {
|
||||
setNullableInt(ps, i++, e.getPrevLineNumber());
|
||||
setNullableBytes(ps, i++, e.getPrevLineHash());
|
||||
setNullableInt(ps, i++, e.getThisLineNumber());
|
||||
if (accountType == null) {
|
||||
ps.setNull(i++, Types.SMALLINT); ps.setNull(i, Types.ARRAY);
|
||||
} else {
|
||||
ps.setInt(i++, accountType);
|
||||
ps.setArray(i, c.createArrayOf("text", previousAccounts.toArray(String[]::new)));
|
||||
}
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import shine.db.DbController;
|
||||
import shine.db.entities.SyncServerEntry;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DAO локальной таблицы серверов-партнёров для будущей межсерверной синхронизации.
|
||||
*/
|
||||
public final class SyncServersDAO {
|
||||
|
||||
private static volatile SyncServersDAO instance;
|
||||
private final DbController db = DbController.getInstance();
|
||||
|
||||
private SyncServersDAO() {}
|
||||
|
||||
public static SyncServersDAO getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (SyncServersDAO.class) {
|
||||
if (instance == null) instance = new SyncServersDAO();
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public List<SyncServerEntry> listAll() throws SQLException {
|
||||
try (Connection c = db.getConnection()) {
|
||||
return listAll(c);
|
||||
}
|
||||
}
|
||||
|
||||
public List<SyncServerEntry> listAll(Connection c) throws SQLException {
|
||||
String sql = """
|
||||
SELECT login, server_address, updated_at_ms
|
||||
FROM sync_servers
|
||||
ORDER BY login
|
||||
""";
|
||||
List<SyncServerEntry> result = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql);
|
||||
ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
result.add(mapRow(rs));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Полностью заменяет список партнёров актуальным снимком из Solana PDA.
|
||||
*/
|
||||
public void replaceAll(List<SyncServerEntry> entries) throws SQLException {
|
||||
try (Connection c = db.getConnection()) {
|
||||
replaceAll(c, entries);
|
||||
}
|
||||
}
|
||||
|
||||
public void replaceAll(Connection c, List<SyncServerEntry> entries) throws SQLException {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try (Statement st = c.createStatement()) {
|
||||
st.executeUpdate("DELETE FROM sync_servers");
|
||||
String sql = """
|
||||
INSERT INTO sync_servers (
|
||||
login, server_address, updated_at_ms
|
||||
) VALUES (?, ?, ?)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
for (SyncServerEntry entry : entries) {
|
||||
ps.setString(1, entry.getLogin());
|
||||
ps.setString(2, safe(entry.getServerAddress()));
|
||||
ps.setLong(3, entry.getUpdatedAtMs());
|
||||
ps.addBatch();
|
||||
}
|
||||
ps.executeBatch();
|
||||
}
|
||||
c.commit();
|
||||
} catch (Exception e) {
|
||||
try { c.rollback(); } catch (Exception ignored) {}
|
||||
if (e instanceof SQLException sqlEx) throw sqlEx;
|
||||
throw new SQLException("Не удалось обновить таблицу sync_servers", e);
|
||||
} finally {
|
||||
try { c.setAutoCommit(oldAutoCommit); } catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
private SyncServerEntry mapRow(ResultSet rs) throws SQLException {
|
||||
SyncServerEntry entry = new SyncServerEntry();
|
||||
entry.setLogin(rs.getString("login"));
|
||||
entry.setServerAddress(rs.getString("server_address"));
|
||||
entry.setUpdatedAtMs(rs.getLong("updated_at_ms"));
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static String safe(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ public final class UserParamsDAO {
|
||||
// -------------------- UPSERT (IF NEWER) --------------------
|
||||
|
||||
public int upsertIfNewer(Connection c, UserParamEntry e) throws SQLException {
|
||||
if ("account_role".equalsIgnoreCase(e.getParam()) && hasDeclaredIdentity(c, e.getLogin())) return 0;
|
||||
String sql = """
|
||||
INSERT INTO users_params (
|
||||
login,
|
||||
@@ -108,6 +109,13 @@ public final class UserParamsDAO {
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasDeclaredIdentity(Connection c, String login) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT 1 FROM account_identity_state WHERE login=LOWER(?)")) {
|
||||
ps.setString(1, login);
|
||||
try (ResultSet rs = ps.executeQuery()) { return rs.next(); }
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------- SELECT --------------------
|
||||
|
||||
public UserParamEntry getByLoginAndParam(Connection c, String login, String param) throws SQLException {
|
||||
|
||||
@@ -61,10 +61,10 @@ public final class UserProfileStateDAO {
|
||||
String where = switch (String.valueOf(listType)) {
|
||||
case "friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=14 AND NOT EXISTS (SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(cs.login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)";
|
||||
case "close_friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=10";
|
||||
case "primary_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)";
|
||||
case "primary_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)";
|
||||
case "shine_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(cs.to_login)";
|
||||
case "shine_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(cs.to_login)";
|
||||
case "primary_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,cs.to_login)";
|
||||
case "primary_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,cs.to_login)";
|
||||
case "shine_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,cs.to_login)";
|
||||
case "shine_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,cs.to_login)";
|
||||
default -> throw new IllegalArgumentException("Unsupported listType: " + listType);
|
||||
};
|
||||
boolean received = "primary_received".equals(listType) || "shine_received".equals(listType);
|
||||
@@ -77,9 +77,9 @@ public final class UserProfileStateDAO {
|
||||
COALESCE(up.ava_ar,'') AS ava_ar,
|
||||
up.account_role, up.shine_status,
|
||||
EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=80
|
||||
AND shine_is_primary(x.login) AND shine_target_accepts_primary_confirmation(x.to_login)) AS primary_confirmed,
|
||||
AND shine_can_confirm_primary(x.login,x.to_login)) AS primary_confirmed,
|
||||
EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=70
|
||||
AND shine_is_primary(x.login) AND shine_is_shining(x.login) AND shine_target_accepts_shine_confirmation(x.to_login)) AS shine_confirmed,
|
||||
AND shine_can_confirm_shine(x.login,x.to_login)) AS shine_confirmed,
|
||||
CASE
|
||||
WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=10) THEN 'close_friend'
|
||||
WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=14) THEN 'friend'
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package shine.db.entities;
|
||||
|
||||
/**
|
||||
* Запись о сервере-партнёре, с которым текущий сервер должен синхронизироваться.
|
||||
*/
|
||||
public class SyncServerEntry {
|
||||
|
||||
private String login;
|
||||
private String serverAddress;
|
||||
private long updatedAtMs;
|
||||
|
||||
public SyncServerEntry() {}
|
||||
|
||||
public SyncServerEntry(String login, String serverAddress, long updatedAtMs) {
|
||||
this.login = login;
|
||||
this.serverAddress = serverAddress;
|
||||
this.updatedAtMs = updatedAtMs;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getServerAddress() {
|
||||
return serverAddress;
|
||||
}
|
||||
|
||||
public void setServerAddress(String serverAddress) {
|
||||
this.serverAddress = serverAddress;
|
||||
}
|
||||
|
||||
public long getUpdatedAtMs() {
|
||||
return updatedAtMs;
|
||||
}
|
||||
|
||||
public void setUpdatedAtMs(long updatedAtMs) {
|
||||
this.updatedAtMs = updatedAtMs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
-- HEADER V3: производные данные хранятся рядом с физическим блоком #0.
|
||||
-- V1/V2: NULL, прежняя логика профиля. Указанные аккаунты не меняют никакие голоса.
|
||||
BEGIN;
|
||||
ALTER TABLE blocks_store ADD COLUMN header_account_type SMALLINT;
|
||||
ALTER TABLE blocks_store ADD COLUMN header_previous_accounts TEXT[];
|
||||
ALTER TABLE blocks_store ADD CONSTRAINT chk_header_identity CHECK (
|
||||
(header_account_type IS NULL AND header_previous_accounts IS NULL) OR
|
||||
(block_number=0 AND msg_type=0 AND msg_sub_type=0
|
||||
AND header_account_type IS NOT NULL AND header_account_type IN (0,1)
|
||||
AND header_previous_accounts IS NOT NULL AND cardinality(header_previous_accounts)<=10
|
||||
AND (header_account_type=1 OR cardinality(header_previous_accounts)=0)));
|
||||
CREATE VIEW account_identity_state AS
|
||||
SELECT LOWER(b.login) AS login, b.header_account_type AS account_type,
|
||||
3 AS header_version, b.block_hash AS header_hash, b.header_previous_accounts AS previous_accounts
|
||||
FROM blocks_store b
|
||||
WHERE b.block_number=0 AND b.header_account_type IS NOT NULL
|
||||
AND b.fork_number=shine_active_fork(b.login,0);
|
||||
CREATE VIEW account_predecessors AS
|
||||
SELECT i.login, p.previous_login
|
||||
FROM account_identity_state i CROSS JOIN LATERAL unnest(i.previous_accounts) AS p(previous_login);
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
|
||||
RETURNS VOID
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
v_first_name TEXT := '';
|
||||
v_last_name TEXT := '';
|
||||
v_ava_ar TEXT := '';
|
||||
v_account_role TEXT := NULL;
|
||||
v_shine TEXT := NULL;
|
||||
v_updated BIGINT := 0;
|
||||
BEGIN
|
||||
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
|
||||
|
||||
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
|
||||
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
|
||||
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
|
||||
MAX(value) FILTER (WHERE param = 'account_role'),
|
||||
MAX(value) FILTER (WHERE param = 'shine'),
|
||||
COALESCE(MAX(time_ms), 0)
|
||||
INTO v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated
|
||||
FROM users_params
|
||||
WHERE LOWER(login) = LOWER(p_login);
|
||||
|
||||
v_account_role := COALESCE(
|
||||
(SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
|
||||
FROM account_identity_state WHERE login = LOWER(p_login)),
|
||||
LOWER(BTRIM(COALESCE(v_account_role, ''))));
|
||||
IF v_account_role NOT IN ('primary', 'non_voting') THEN v_account_role := NULL; END IF;
|
||||
|
||||
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
|
||||
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
|
||||
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
|
||||
|
||||
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
|
||||
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
|
||||
ON CONFLICT (login) DO UPDATE SET
|
||||
first_name = EXCLUDED.first_name,
|
||||
last_name = EXCLUDED.last_name,
|
||||
ava_ar = EXCLUDED.ava_ar,
|
||||
account_role = EXCLUDED.account_role,
|
||||
shine_status = EXCLUDED.shine_status,
|
||||
updated_at_ms = EXCLUDED.updated_at_ms;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Вызывать после записи HEADER и при завершении восстановления канонической цепи.
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_header_identity(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM shine_refresh_user_profile(p_login);
|
||||
PERFORM shine_refresh_related_user_stats(p_login);
|
||||
PERFORM shine_refresh_message_qualified_likes_for_actor(p_login);
|
||||
END $$;
|
||||
UPDATE db_schema_version SET schema_version=46,
|
||||
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,82 @@
|
||||
-- Official = signed canonical HEADER V3 / account_type=1. Legacy USER_PARAM is not proof.
|
||||
BEGIN;
|
||||
CREATE OR REPLACE FUNCTION shine_is_primary(p_login TEXT)
|
||||
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
|
||||
SELECT EXISTS (SELECT 1 FROM account_identity_state
|
||||
WHERE login=LOWER(p_login) AND account_type=1)
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
|
||||
RETURNS VOID
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
v_first_name TEXT := '';
|
||||
v_last_name TEXT := '';
|
||||
v_ava_ar TEXT := '';
|
||||
v_account_role TEXT := NULL;
|
||||
v_shine TEXT := NULL;
|
||||
v_updated BIGINT := 0;
|
||||
BEGIN
|
||||
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
|
||||
|
||||
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
|
||||
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
|
||||
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
|
||||
MAX(value) FILTER (WHERE param = 'account_role'),
|
||||
MAX(value) FILTER (WHERE param = 'shine'),
|
||||
COALESCE(MAX(time_ms), 0)
|
||||
INTO v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated
|
||||
FROM users_params
|
||||
WHERE LOWER(login) = LOWER(p_login);
|
||||
|
||||
v_account_role := COALESCE(
|
||||
(SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
|
||||
FROM account_identity_state WHERE login = LOWER(p_login)),
|
||||
CASE WHEN LOWER(BTRIM(COALESCE(v_account_role, ''))) = 'non_voting'
|
||||
THEN 'non_voting' ELSE NULL END);
|
||||
IF v_account_role NOT IN ('primary', 'non_voting') THEN v_account_role := NULL; END IF;
|
||||
|
||||
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
|
||||
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
|
||||
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
|
||||
|
||||
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
|
||||
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
|
||||
ON CONFLICT (login) DO UPDATE SET
|
||||
first_name = EXCLUDED.first_name,
|
||||
last_name = EXCLUDED.last_name,
|
||||
ava_ar = EXCLUDED.ava_ar,
|
||||
account_role = EXCLUDED.account_role,
|
||||
shine_status = EXCLUDED.shine_status,
|
||||
updated_at_ms = EXCLUDED.updated_at_ms;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Remove obsolete legacy Primary projections, leaving the original signed history intact.
|
||||
-- The shared predicate also serves social graph confirmations; refresh affected projections.
|
||||
DO $$
|
||||
DECLARE r RECORD;
|
||||
BEGIN
|
||||
FOR r IN
|
||||
UPDATE user_profile_state ups SET account_role=NULL
|
||||
WHERE ups.account_role='primary' AND NOT shine_is_primary(ups.login)
|
||||
RETURNING login
|
||||
LOOP
|
||||
PERFORM shine_refresh_related_user_stats(r.login);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- Recalculate both qualified counters, not the all-accounts count.
|
||||
-- The aggregate returns zeros even if no qualifying reaction exists.
|
||||
UPDATE message_stats ms SET (primary_likes_count, shining_likes_count) = (
|
||||
SELECT COUNT(*) FILTER (WHERE shine_is_primary(rs.from_login))::INTEGER,
|
||||
COUNT(*) FILTER (WHERE shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login))::INTEGER
|
||||
FROM reactions_state rs
|
||||
WHERE rs.reaction_type=1 AND rs.last_sub_type=1
|
||||
AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number
|
||||
AND rs.to_block_hash=ms.to_block_hash
|
||||
);
|
||||
UPDATE db_schema_version SET schema_version=47,
|
||||
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,109 @@
|
||||
-- Только канонический HEADER V3 определяет Primary. История не меняется.
|
||||
BEGIN;
|
||||
CREATE OR REPLACE FUNCTION shine_target_accepts_primary_confirmation(p_login TEXT)
|
||||
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
|
||||
SELECT shine_is_primary(p_login)
|
||||
$$;
|
||||
CREATE OR REPLACE FUNCTION shine_target_accepts_shine_confirmation(p_login TEXT)
|
||||
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
|
||||
SELECT shine_is_primary(p_login) AND NOT EXISTS (
|
||||
SELECT 1 FROM user_profile_state WHERE LOWER(login)=LOWER(p_login) AND shine_status='not_interested')
|
||||
$$;
|
||||
CREATE OR REPLACE FUNCTION shine_can_confirm_primary(p_actor TEXT,p_target TEXT)
|
||||
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
|
||||
SELECT COALESCE(LOWER(p_actor)<>LOWER(p_target)
|
||||
AND shine_is_primary(p_actor) AND shine_target_accepts_primary_confirmation(p_target),FALSE)
|
||||
$$;
|
||||
CREATE OR REPLACE FUNCTION shine_can_confirm_shine(p_actor TEXT,p_target TEXT)
|
||||
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
|
||||
SELECT COALESCE(LOWER(p_actor)<>LOWER(p_target)
|
||||
AND shine_is_primary(p_actor) AND shine_is_shining(p_actor)
|
||||
AND shine_target_accepts_shine_confirmation(p_target),FALSE)
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
|
||||
RETURNS VOID
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
v_first_name TEXT := '';
|
||||
v_last_name TEXT := '';
|
||||
v_ava_ar TEXT := '';
|
||||
v_account_role TEXT := NULL;
|
||||
v_shine TEXT := NULL;
|
||||
v_updated BIGINT := 0;
|
||||
BEGIN
|
||||
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
|
||||
|
||||
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
|
||||
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
|
||||
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
|
||||
MAX(value) FILTER (WHERE param = 'shine'),
|
||||
COALESCE(MAX(time_ms), 0)
|
||||
INTO v_first_name, v_last_name, v_ava_ar, v_shine, v_updated
|
||||
FROM users_params
|
||||
WHERE LOWER(login) = LOWER(p_login);
|
||||
|
||||
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
|
||||
INTO v_account_role FROM account_identity_state WHERE login = LOWER(p_login);
|
||||
|
||||
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
|
||||
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
|
||||
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
|
||||
|
||||
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
|
||||
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
|
||||
ON CONFLICT (login) DO UPDATE SET
|
||||
first_name = EXCLUDED.first_name,
|
||||
last_name = EXCLUDED.last_name,
|
||||
ava_ar = EXCLUDED.ava_ar,
|
||||
account_role = EXCLUDED.account_role,
|
||||
shine_status = EXCLUDED.shine_status,
|
||||
updated_at_ms = EXCLUDED.updated_at_ms;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
|
||||
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
|
||||
BEGIN
|
||||
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
|
||||
-- Архивная связь может прийти до регистрации цели в локальном каталоге.
|
||||
-- Не создавать строку статистики без владельца FK, но сохранить подписанную связь.
|
||||
SELECT i.login INTO p_login FROM user_identity_current i WHERE i.normalized_login=LOWER(p_login);
|
||||
IF p_login IS NULL THEN RETURN; END IF;
|
||||
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
|
||||
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
|
||||
SELECT p_login,
|
||||
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
|
||||
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,p_login)),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_can_confirm_primary(p_login,cs.to_login)),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,p_login)),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_can_confirm_shine(p_login,cs.to_login)),v_now
|
||||
ON CONFLICT(login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count,following_users_count=EXCLUDED.following_users_count,following_channels_count=EXCLUDED.following_channels_count,close_friends_count=EXCLUDED.close_friends_count,friends_count=EXCLUDED.friends_count,primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count,primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count,shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count,shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count,updated_at_ms=EXCLUDED.updated_at_ms;
|
||||
END $$;
|
||||
|
||||
-- Обновить роль в существующих карточках; не переписывать исходные параметры/блоки.
|
||||
UPDATE user_profile_state ups SET account_role = (
|
||||
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
|
||||
FROM account_identity_state WHERE login=LOWER(ups.login))
|
||||
WHERE account_role IS DISTINCT FROM (
|
||||
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
|
||||
FROM account_identity_state WHERE login=LOWER(ups.login));
|
||||
-- У аккаунтов с HEADER, но без параметров, также должна существовать карточка.
|
||||
DO $$ DECLARE r RECORD; BEGIN
|
||||
FOR r IN SELECT login FROM account_identity_state i
|
||||
WHERE NOT EXISTS (SELECT 1 FROM user_profile_state p WHERE LOWER(p.login)=i.login)
|
||||
LOOP PERFORM shine_refresh_user_profile(r.login); END LOOP;
|
||||
-- Все старые участники подтверждений, в том числе с устаревшими ненулевыми счётчиками.
|
||||
FOR r IN SELECT login FROM user_stats_state
|
||||
UNION SELECT login FROM connections_state WHERE rel_type IN (70,80)
|
||||
UNION SELECT to_login FROM connections_state WHERE rel_type IN (70,80)
|
||||
LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP;
|
||||
END $$;
|
||||
UPDATE db_schema_version SET schema_version=48,
|
||||
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
|
||||
COMMIT;
|
||||
@@ -488,15 +488,6 @@ CREATE TABLE IF NOT EXISTS test_free_avatar_uploads (
|
||||
CREATE INDEX IF NOT EXISTS idx_test_free_avatar_uploads_updated
|
||||
ON test_free_avatar_uploads(updated_at_ms);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_servers (
|
||||
login TEXT PRIMARY KEY,
|
||||
server_address TEXT NOT NULL DEFAULT '',
|
||||
updated_at_ms BIGINT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_servers_updated
|
||||
ON sync_servers(updated_at_ms);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS blockchain_state (
|
||||
blockchain_name TEXT PRIMARY KEY,
|
||||
login TEXT NOT NULL REFERENCES solana_user_pda_current(login),
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
-- Запускать psql -v ON_ERROR_STOP=1 -f <этот файл> на отдельной тестовой БД после миграции 48.
|
||||
-- Фикстуры временные; проверяются действующие SQL-функции, изменения откатываются.
|
||||
BEGIN;
|
||||
SET LOCAL search_path TO pg_temp, public;
|
||||
CREATE TEMP TABLE account_identity_state(login TEXT PRIMARY KEY,account_type SMALLINT);
|
||||
CREATE TEMP TABLE user_profile_state (LIKE public.user_profile_state INCLUDING ALL);
|
||||
CREATE TEMP TABLE user_stats_state (LIKE public.user_stats_state INCLUDING ALL);
|
||||
CREATE TEMP TABLE user_identity_current(login TEXT PRIMARY KEY,normalized_login TEXT UNIQUE);
|
||||
CREATE TEMP TABLE users_params(login TEXT,param TEXT,value TEXT,time_ms BIGINT);
|
||||
CREATE TEMP TABLE connections_state(login TEXT,rel_type INTEGER,to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA);
|
||||
CREATE TEMP TABLE channel_names_state(owner_login TEXT,channel_type_code INTEGER,is_deleted BOOLEAN,channel_root_block_number INTEGER,channel_root_block_hash BYTEA);
|
||||
INSERT INTO account_identity_state VALUES ('alice@free',1),('bob@free',1),('alt@free',0),('optout@free',1);
|
||||
INSERT INTO user_identity_current SELECT login,lower(login) FROM account_identity_state;
|
||||
INSERT INTO user_identity_current VALUES ('legacy@free','legacy@free');
|
||||
INSERT INTO users_params VALUES ('alice@free','shine','shining',1),('alt@free','shine','shining',1),('legacy@free','account_role','primary',1),('optout@free','shine','not_interested',1);
|
||||
SELECT shine_refresh_user_profile(login) FROM user_identity_current;
|
||||
DO $$ BEGIN
|
||||
IF NOT shine_can_confirm_primary('ALICE@FREE','bob@free') OR NOT shine_can_confirm_shine('alice@free','bob@free') THEN RAISE EXCEPTION 'Primary pair rejected'; END IF;
|
||||
IF shine_can_confirm_primary('alice@free','alt@free') OR shine_can_confirm_primary('alt@free','alice@free') OR shine_can_confirm_primary('legacy@free','alice@free') OR shine_can_confirm_primary('alice@free','legacy@free') OR shine_can_confirm_primary('alice@free','missing@free') OR shine_can_confirm_primary('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid primary pair accepted'; END IF;
|
||||
IF shine_can_confirm_shine('alice@free','alt@free') OR shine_can_confirm_shine('alt@free','alice@free') OR shine_can_confirm_shine('bob@free','alice@free') OR shine_can_confirm_shine('alice@free','optout@free') OR shine_can_confirm_shine('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid shine pair accepted'; END IF;
|
||||
IF (SELECT account_role FROM user_profile_state WHERE login='legacy@free') IS NOT NULL THEN RAISE EXCEPTION 'Legacy role leaked into profile'; END IF;
|
||||
END $$;
|
||||
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash) VALUES
|
||||
('alice@free',80,'bob@free',0,'\x00'),('alice@free',70,'bob@free',0,'\x00'),
|
||||
('alice@free',80,'alt@free',0,'\x00'),('alice@free',70,'alt@free',0,'\x00'),
|
||||
('alt@free',80,'bob@free',0,'\x00'),('alt@free',70,'bob@free',0,'\x00'),
|
||||
('legacy@free',80,'bob@free',0,'\x00'),('alice@free',80,'alice@free',0,'\x00');
|
||||
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
|
||||
SELECT shine_refresh_user_stats('missing@free');
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='bob@free' AND primary_confirmations_received_count=1 AND shine_confirmations_received_count=1) THEN RAISE EXCEPTION 'Wrong Bob counters'; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND primary_confirmations_given_count=1 AND shine_confirmations_given_count=1 AND primary_confirmations_received_count=0) THEN RAISE EXCEPTION 'Wrong Alice counters'; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alt@free' AND primary_confirmations_received_count=0 AND primary_confirmations_given_count=0 AND shine_confirmations_received_count=0 AND shine_confirmations_given_count=0) THEN RAISE EXCEPTION 'Alternative counters not zero'; END IF;
|
||||
IF (SELECT COUNT(*) FROM connections_state)<>8 THEN RAISE EXCEPTION 'Raw history changed'; END IF;
|
||||
END $$;
|
||||
ROLLBACK;
|
||||
-4
@@ -158,7 +158,6 @@ import server.logic.ws_protocol.JSON.messages.entyties.Net_UpsertPushToken_Reque
|
||||
// --- NEW: Ping ---
|
||||
import server.logic.ws_protocol.JSON.handlers.system.Net_GetServerInfo_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.Net_GetCallIceConfig_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.Net_GetSyncUserProfile_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.Net_ClientErrorLog_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.Net_ClientDebugLog_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.Net_ListBlockchainHeads_Handler;
|
||||
@@ -170,7 +169,6 @@ import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientErrorLog
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientDebugLog_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetCallIceConfig_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetServerInfo_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetSyncUserProfile_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchainHeads_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
|
||||
@@ -295,7 +293,6 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("Ping", new Net_Ping_Handler()),
|
||||
Map.entry("GetServerInfo", new Net_GetServerInfo_Handler()),
|
||||
Map.entry("ListBlockchainHeads", new Net_ListBlockchainHeads_Handler()),
|
||||
Map.entry("GetSyncUserProfile", new Net_GetSyncUserProfile_Handler()),
|
||||
Map.entry("GetCallIceConfig", new Net_GetCallIceConfig_Handler()),
|
||||
Map.entry("ClientErrorLog", new Net_ClientErrorLog_Handler()),
|
||||
Map.entry("ClientDebugLog", new Net_ClientDebugLog_Handler()),
|
||||
@@ -411,7 +408,6 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("Ping", Net_Ping_Request.class),
|
||||
Map.entry("GetServerInfo", Net_GetServerInfo_Request.class),
|
||||
Map.entry("ListBlockchainHeads", Net_ListBlockchainHeads_Request.class),
|
||||
Map.entry("GetSyncUserProfile", Net_GetSyncUserProfile_Request.class),
|
||||
Map.entry("GetCallIceConfig", Net_GetCallIceConfig_Request.class),
|
||||
Map.entry("ClientErrorLog", Net_ClientErrorLog_Request.class),
|
||||
Map.entry("ClientDebugLog", Net_ClientDebugLog_Request.class),
|
||||
|
||||
+29
-12
@@ -211,6 +211,11 @@ 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 "previous_account_not_found" -> "Указанный предыдущий аккаунт не найден";
|
||||
case "primary_vote_not_allowed" -> "Подтверждать официальность могут только разные основные аккаунты";
|
||||
case "shine_vote_not_allowed" -> "Подтверждать сияние может только сияющий основной аккаунт другого основного аккаунта, принимающего подтверждения";
|
||||
case "account_type_immutable" -> "Тип аккаунта зафиксирован в HEADER и не может быть изменён";
|
||||
case "header_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации";
|
||||
case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER";
|
||||
case "bad_channel_name" -> "Некорректное название канала";
|
||||
@@ -385,6 +390,15 @@ 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 (publishToArweave) {
|
||||
for (String previous : headerBody.previousAccounts) {
|
||||
if (currentUsersDAO.getByLogin(previous) == null)
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "previous_account_not_found", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
}
|
||||
CurrentUserEntry registeredOwner = currentUsersDAO.getByLogin(login);
|
||||
if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin())
|
||||
|| !login.equalsIgnoreCase(registeredOwner.getLogin())) {
|
||||
@@ -692,7 +706,9 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
be.setEditedByBlockNumber(be.getToBlockNumber());
|
||||
}
|
||||
|
||||
if (block.body instanceof ConnectionBody connectionBody) {
|
||||
// Архивные блоки уже подписаны; их допустимость для текущего рейтинга
|
||||
// определяет проекция, а не порядок восстановления разных пользователей.
|
||||
if (publishToArweave && block.body instanceof ConnectionBody connectionBody) {
|
||||
String votingError = validateConnectionVotingRights(login, block.subType & 0xFFFF, connectionBody.toLogin());
|
||||
if (votingError != null) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, votingError, serverLastNum, serverLastHashHex);
|
||||
@@ -701,6 +717,10 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
|
||||
UserParamEntry upsertedParam = null;
|
||||
if (block.body instanceof UserParamBody upBody) {
|
||||
if (publishToArweave && ("account_role".equalsIgnoreCase(upBody.paramKey.strip())
|
||||
|| "official".equalsIgnoreCase(upBody.paramKey.strip()))) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "account_type_immutable", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
String effectiveLogin = (st.getLogin() != null && !st.getLogin().isBlank())
|
||||
? st.getLogin()
|
||||
: login;
|
||||
@@ -867,20 +887,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
private String validateConnectionVotingRights(String actorLogin, int subType, String targetLogin) {
|
||||
if (subType != (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)
|
||||
&& subType != (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF)) return null;
|
||||
if (targetLogin == null || targetLogin.isBlank()) return "bad_connection_target";
|
||||
String sql = subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)
|
||||
? "SELECT shine_is_primary(?), shine_target_accepts_primary_confirmation(?)"
|
||||
: "SELECT (shine_is_primary(?) AND shine_is_shining(?)), shine_target_accepts_shine_confirmation(?)";
|
||||
if (targetLogin == null || targetLogin.isBlank() || targetLogin.equalsIgnoreCase(actorLogin))
|
||||
return "bad_connection_target";
|
||||
boolean primary = subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF);
|
||||
String sql = primary
|
||||
? "SELECT shine_can_confirm_primary(?,?)"
|
||||
: "SELECT shine_can_confirm_shine(?,?)";
|
||||
try (Connection c = shine.db.DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
if (subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)) {
|
||||
ps.setString(1, actorLogin); ps.setString(2, targetLogin);
|
||||
} else {
|
||||
ps.setString(1, actorLogin); ps.setString(2, actorLogin); ps.setString(3, targetLogin);
|
||||
}
|
||||
ps.setString(1, actorLogin); ps.setString(2, targetLogin);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next() || !rs.getBoolean(1)) return subType == 80 ? "primary_vote_not_allowed" : "shine_vote_not_allowed";
|
||||
if (!rs.getBoolean(2)) return subType == 80 ? "target_non_voting" : "target_shine_not_interested";
|
||||
if (!rs.next() || !rs.getBoolean(1)) return primary ? "primary_vote_not_allowed" : "shine_vote_not_allowed";
|
||||
}
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
|
||||
+9
-1
@@ -1,6 +1,7 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils;
|
||||
|
||||
import blockchain.BchBlockEntry;
|
||||
import blockchain.body.HeaderBody;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.BlocksDAO;
|
||||
import shine.db.dao.ChannelNameStateDAO;
|
||||
@@ -76,7 +77,14 @@ public final class BlockchainWriter {
|
||||
st.setUpdatedAtMs(nowMs);
|
||||
stateDAO.upsert(c, st);
|
||||
|
||||
blocksDAO.insert(c, be);
|
||||
if (block.body instanceof HeaderBody header && header.accountType != null) {
|
||||
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();
|
||||
}
|
||||
} else {
|
||||
blocksDAO.insert(c, be);
|
||||
}
|
||||
|
||||
if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
|
||||
if (channelNameStateEntry != null) {
|
||||
|
||||
+2
-2
@@ -48,7 +48,7 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
|
||||
COALESCE(ups.first_name, '') AS first_name,
|
||||
COALESCE(ups.last_name, '') AS last_name,
|
||||
COALESCE(ups.ava_ar, '') AS avatar_ar,
|
||||
COALESCE(ups.account_role, 'unknown') AS account_role,
|
||||
shine_is_primary(rs.from_login) AS is_primary,
|
||||
COALESCE(ups.shine_status, 'unknown') AS shine_status
|
||||
FROM reactions_state rs
|
||||
LEFT JOIN user_profile_state ups ON LOWER(ups.login) = LOWER(rs.from_login)
|
||||
@@ -77,7 +77,7 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
|
||||
user.setAvatarAr(avatar.ar());
|
||||
user.setAvatarPr(avatar.pr());
|
||||
|
||||
boolean isOfficial = "primary".equalsIgnoreCase(rs.getString("account_role"));
|
||||
boolean isOfficial = rs.getBoolean("is_primary");
|
||||
boolean isShining = "shining".equalsIgnoreCase(rs.getString("shine_status"));
|
||||
if (isOfficial && isShining) shining.add(user);
|
||||
else if (isOfficial) official.add(user);
|
||||
|
||||
+4
-6
@@ -130,26 +130,24 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
|
||||
sql = outgoing ? """
|
||||
SELECT DISTINCT cs.to_login AS peer FROM connections_state cs
|
||||
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=80
|
||||
AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)
|
||||
AND shine_can_confirm_primary(cs.login,cs.to_login)
|
||||
ORDER BY peer
|
||||
""" : """
|
||||
SELECT DISTINCT cs.login AS peer FROM connections_state cs
|
||||
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80
|
||||
AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)
|
||||
AND shine_can_confirm_primary(cs.login,cs.to_login)
|
||||
ORDER BY peer
|
||||
""";
|
||||
} else {
|
||||
sql = outgoing ? """
|
||||
SELECT DISTINCT cs.to_login AS peer FROM connections_state cs
|
||||
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=70
|
||||
AND shine_is_primary(cs.login) AND shine_is_shining(cs.login)
|
||||
AND shine_target_accepts_shine_confirmation(cs.to_login)
|
||||
AND shine_can_confirm_shine(cs.login,cs.to_login)
|
||||
ORDER BY peer
|
||||
""" : """
|
||||
SELECT DISTINCT cs.login AS peer FROM connections_state cs
|
||||
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70
|
||||
AND shine_is_primary(cs.login) AND shine_is_shining(cs.login)
|
||||
AND shine_target_accepts_shine_confirmation(cs.to_login)
|
||||
AND shine_can_confirm_shine(cs.login,cs.to_login)
|
||||
ORDER BY peer
|
||||
""";
|
||||
}
|
||||
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.system;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetSyncUserProfile_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetSyncUserProfile_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.CurrentUsersDAO;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.CurrentUserEntry;
|
||||
|
||||
/**
|
||||
* GetSyncUserProfile — server-to-server профиль пользователя для межсерверной синхронизации.
|
||||
* Нужен, чтобы принимающий сервер мог создать локальную runtime-проекцию пользователя
|
||||
* и blockchain_state без прямого запроса в Solana RPC.
|
||||
*/
|
||||
public final class Net_GetSyncUserProfile_Handler implements JsonMessageHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetSyncUserProfile_Handler.class);
|
||||
private final CurrentUsersDAO usersDAO = CurrentUsersDAO.getInstance();
|
||||
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
Net_GetSyncUserProfile_Request req = (Net_GetSyncUserProfile_Request) baseRequest;
|
||||
|
||||
String login = req.getLogin() == null ? "" : req.getLogin().trim();
|
||||
if (login.isEmpty()) {
|
||||
return NetExceptionResponseFactory.error(
|
||||
req,
|
||||
WireCodes.Status.BAD_REQUEST,
|
||||
"BAD_FIELDS",
|
||||
"Некорректные поля: login"
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
CurrentUserEntry user = usersDAO.getByLogin(login);
|
||||
|
||||
Net_GetSyncUserProfile_Response resp = new Net_GetSyncUserProfile_Response();
|
||||
resp.setOp(req.getOp());
|
||||
resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK);
|
||||
|
||||
if (user == null) {
|
||||
resp.setExists(false);
|
||||
return resp;
|
||||
}
|
||||
|
||||
BlockchainStateEntry state = stateDAO.getByBlockchainName(user.getBlockchainName());
|
||||
if (state == null) {
|
||||
log.warn("GetSyncUserProfile: blockchain_state not found for login={} blockchainName={}",
|
||||
user.getLogin(), user.getBlockchainName());
|
||||
return NetExceptionResponseFactory.error(
|
||||
req,
|
||||
WireCodes.Status.NOT_FOUND,
|
||||
"BLOCKCHAIN_STATE_NOT_FOUND",
|
||||
"Состояние блокчейна пользователя не найдено"
|
||||
);
|
||||
}
|
||||
|
||||
resp.setExists(true);
|
||||
resp.setLogin(user.getLogin());
|
||||
resp.setBlockchainName(user.getBlockchainName());
|
||||
resp.setSolanaKey(user.getSolanaKey());
|
||||
resp.setBlockchainKey(user.getBlockchainKey());
|
||||
resp.setClientKey(user.getClientKey());
|
||||
resp.setBlockchainSizeLimitBytes(state.getSizeLimit());
|
||||
return resp;
|
||||
} catch (Exception e) {
|
||||
log.error("❌ Internal error GetSyncUserProfile login={}", login, e);
|
||||
return NetExceptionResponseFactory.error(
|
||||
req,
|
||||
WireCodes.Status.INTERNAL_ERROR,
|
||||
"INTERNAL_ERROR",
|
||||
NetExceptionResponseFactory.detailedMessage("Внутренняя ошибка сервера при GetSyncUserProfile", e)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.system.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
/**
|
||||
* Запрос межсерверного профиля пользователя для синхронизации.
|
||||
*/
|
||||
public class Net_GetSyncUserProfile_Request extends Net_Request {
|
||||
|
||||
private String login;
|
||||
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.system.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
|
||||
/**
|
||||
* Ответ межсерверного профиля пользователя для синхронизации.
|
||||
*/
|
||||
public class Net_GetSyncUserProfile_Response extends Net_Response {
|
||||
|
||||
private Boolean exists;
|
||||
private String login;
|
||||
private String blockchainName;
|
||||
private String solanaKey;
|
||||
private String blockchainKey;
|
||||
private String clientKey;
|
||||
private Long blockchainSizeLimitBytes;
|
||||
|
||||
public Boolean getExists() { return exists; }
|
||||
public void setExists(Boolean exists) { this.exists = exists; }
|
||||
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
|
||||
public String getBlockchainName() { return blockchainName; }
|
||||
public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; }
|
||||
|
||||
public String getSolanaKey() { return solanaKey; }
|
||||
public void setSolanaKey(String solanaKey) { this.solanaKey = solanaKey; }
|
||||
|
||||
public String getBlockchainKey() { return blockchainKey; }
|
||||
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
|
||||
|
||||
public String getClientKey() { return clientKey; }
|
||||
public void setClientKey(String clientKey) { this.clientKey = clientKey; }
|
||||
|
||||
public Long getBlockchainSizeLimitBytes() { return blockchainSizeLimitBytes; }
|
||||
public void setBlockchainSizeLimitBytes(Long blockchainSizeLimitBytes) { this.blockchainSizeLimitBytes = blockchainSizeLimitBytes; }
|
||||
}
|
||||
+13
@@ -54,8 +54,19 @@ public class Net_ListUserParams_Handler implements JsonMessageHandler {
|
||||
UserParamsDAO dao = UserParamsDAO.getInstance();
|
||||
|
||||
List<UserParamEntry> entries;
|
||||
Integer accountType = null;
|
||||
List<String> previousAccounts = null;
|
||||
try (Connection c = db.getConnection()) {
|
||||
entries = dao.getByLogin(c, login);
|
||||
try (var ps = c.prepareStatement("SELECT account_type,previous_accounts FROM account_identity_state WHERE login=LOWER(?)")) {
|
||||
ps.setString(1, login);
|
||||
try (var rs = ps.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
accountType = rs.getInt(1);
|
||||
previousAccounts = List.of((String[])rs.getArray(2).getArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Net_ListUserParams_Response resp = new Net_ListUserParams_Response();
|
||||
@@ -78,6 +89,8 @@ public class Net_ListUserParams_Handler implements JsonMessageHandler {
|
||||
items.add(it);
|
||||
}
|
||||
resp.setParams(items);
|
||||
resp.setAccountType(accountType);
|
||||
resp.setPreviousAccounts(previousAccounts);
|
||||
|
||||
return resp;
|
||||
|
||||
|
||||
+4
@@ -63,6 +63,10 @@ public class Net_UpsertUserParam_Handler implements JsonMessageHandler {
|
||||
|
||||
final String login = req.getLogin().trim();
|
||||
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");
|
||||
}
|
||||
final long timeMs = req.getTime_ms();
|
||||
final String value = req.getValue();
|
||||
final String clientKeyB64 = req.getClient_key().trim();
|
||||
|
||||
+6
@@ -31,6 +31,12 @@ import java.util.List;
|
||||
public class Net_ListUserParams_Response extends Net_Response {
|
||||
|
||||
private String login;
|
||||
private Integer accountType;
|
||||
private List<String> previousAccounts;
|
||||
public Integer getAccountType() { return accountType; }
|
||||
public void setAccountType(Integer accountType) { this.accountType = accountType; }
|
||||
public List<String> getPreviousAccounts() { return previousAccounts; }
|
||||
public void setPreviousAccounts(List<String> previousAccounts) { this.previousAccounts = previousAccounts; }
|
||||
private List<Item> params = new ArrayList<>();
|
||||
|
||||
public String getLogin() { return login; }
|
||||
|
||||
-263
@@ -1,263 +0,0 @@
|
||||
package server.sync;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.Base64Ws;
|
||||
import shine.db.dao.BlocksDAO;
|
||||
import shine.db.dao.SyncServersDAO;
|
||||
import shine.db.entities.BlockEntry;
|
||||
import shine.db.entities.SyncServerEntry;
|
||||
import utils.blockchain.BlockchainNameUtil;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* @deprecated Legacy direct server-to-server blockchain sync. Not compatible with segmented forks; Arweave/Turbo is supported.
|
||||
* Фоновая репликация AddBlock через общий постоянный WSS-пул на серверы
|
||||
* из локальной таблицы sync_servers.
|
||||
*/
|
||||
@Deprecated
|
||||
public final class AddBlockSyncService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AddBlockSyncService.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(
|
||||
1,
|
||||
Math.max(2, Runtime.getRuntime().availableProcessors()),
|
||||
60L,
|
||||
TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue<>(10_000),
|
||||
new ThreadFactory() {
|
||||
private final AtomicLong n = new AtomicLong(1);
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
Thread t = new Thread(r, "sync-addblock-" + n.getAndIncrement());
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
}
|
||||
},
|
||||
new ThreadPoolExecutor.DiscardPolicy()
|
||||
);
|
||||
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final SyncServersDAO syncServersDAO = SyncServersDAO.getInstance();
|
||||
|
||||
public void replicateAsync(String blockchainName, int blockNumber) {
|
||||
if (!isEnabled()) {
|
||||
log.debug("AddBlock sync skipped: blockchain.sync.enabled=false blockchainName={} blockNumber={}",
|
||||
blockchainName, blockNumber);
|
||||
return;
|
||||
}
|
||||
EXECUTOR.execute(() -> {
|
||||
try {
|
||||
replicate(blockchainName, blockNumber);
|
||||
} catch (Exception e) {
|
||||
log.error("AddBlock sync failed unexpectedly (blockchainName={}, blockNumber={})",
|
||||
blockchainName, blockNumber, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isEnabled() {
|
||||
// Legacy peer replication is disabled in PDA 1.2; Arweave is the synchronization source.
|
||||
return false;
|
||||
}
|
||||
|
||||
private void replicate(String blockchainName, int blockNumber) throws Exception {
|
||||
String ownerLogin = normalize(BlockchainNameUtil.loginFromBlockchainName(blockchainName));
|
||||
if (ownerLogin == null) {
|
||||
log.warn("AddBlock sync skipped: cannot derive owner login from blockchainName={}", blockchainName);
|
||||
return;
|
||||
}
|
||||
|
||||
List<SyncServerEntry> partners = syncServersDAO.listAll();
|
||||
if (partners.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
BlockEntry currentBlock = blocksDAO.getByNumber(blockchainName, blockNumber);
|
||||
if (currentBlock == null || currentBlock.getBlockBytes() == null) {
|
||||
log.warn("AddBlock sync skipped: block not found in DB (blockchainName={}, blockNumber={})",
|
||||
blockchainName, blockNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
for (SyncServerEntry partner : partners) {
|
||||
if (partner == null) continue;
|
||||
String partnerLogin = normalize(partner.getLogin());
|
||||
if (partnerLogin == null) continue;
|
||||
if (partnerLogin.equals(ownerLogin)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
replicateToPartner(partner, blockchainName, blockNumber, currentBlock);
|
||||
} catch (Exception e) {
|
||||
log.warn("AddBlock sync aborted for partner login={} blockchainName={} blockNumber={} reason={}",
|
||||
partnerLogin, blockchainName, blockNumber, e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void replicateToPartner(SyncServerEntry partner, String blockchainName, int blockNumber, BlockEntry currentBlock) throws Exception {
|
||||
String wsUrl = ServerConnectionPool.buildWsUrl(partner.getServerAddress());
|
||||
if (wsUrl == null) {
|
||||
log.warn("AddBlock sync skipped: invalid server_address for partner login={} address={}",
|
||||
partner.getLogin(), partner.getServerAddress());
|
||||
return;
|
||||
}
|
||||
|
||||
AddBlockPushResult firstTry = pushBlock(partner, blockchainName, currentBlock);
|
||||
if (firstTry.ok()) {
|
||||
log.info("AddBlock sync ok: partner={} blockchainName={} blockNumber={}",
|
||||
partner.getLogin(), blockchainName, blockNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
if (firstTry.serverAlreadyHasBlock(blockNumber)) {
|
||||
log.info("AddBlock sync skipped: partner already has block. partner={} blockchainName={} blockNumber={} remoteLast={}",
|
||||
partner.getLogin(), blockchainName, blockNumber, firstTry.serverLastGlobalNumber());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!firstTry.needsBackfill()) {
|
||||
log.warn("AddBlock sync failed without backfill: partner={} blockchainName={} blockNumber={} code={}",
|
||||
partner.getLogin(), blockchainName, blockNumber, firstTry.code());
|
||||
return;
|
||||
}
|
||||
|
||||
int remoteLast = firstTry.serverLastGlobalNumber();
|
||||
int fromBlockNumber = remoteLast + 1;
|
||||
if (fromBlockNumber > blockNumber) {
|
||||
log.info("AddBlock sync skipped: partner already caught up during backfill window. partner={} blockchainName={} remoteLast={} target={}",
|
||||
partner.getLogin(), blockchainName, remoteLast, blockNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
List<BlockEntry> missingBlocks = blocksDAO.listRangeByNumber(blockchainName, fromBlockNumber, blockNumber);
|
||||
if (missingBlocks.isEmpty()) {
|
||||
log.warn("AddBlock sync backfill failed: local range empty partner={} blockchainName={} from={} to={}",
|
||||
partner.getLogin(), blockchainName, fromBlockNumber, blockNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
for (BlockEntry blockEntry : missingBlocks) {
|
||||
AddBlockPushResult backfillResult = pushBlock(partner, blockchainName, blockEntry);
|
||||
if (!backfillResult.ok()) {
|
||||
log.warn("AddBlock sync backfill failed: partner={} blockchainName={} blockNumber={} code={}",
|
||||
partner.getLogin(), blockchainName, blockEntry.getBlockNumber(), backfillResult.code());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
log.info("AddBlock sync backfill ok: partner={} blockchainName={} from={} to={}",
|
||||
partner.getLogin(), blockchainName, fromBlockNumber, blockNumber);
|
||||
}
|
||||
|
||||
private AddBlockPushResult pushBlock(SyncServerEntry partner, String blockchainName, BlockEntry blockEntry) throws Exception {
|
||||
JsonNode response = sendAddBlock(partner, blockchainName, blockEntry);
|
||||
int status = response.path("status").asInt(500);
|
||||
if (status >= 200 && status < 300) {
|
||||
return AddBlockPushResult.success();
|
||||
}
|
||||
|
||||
String code = textOrEmpty(response, "code");
|
||||
if (code.isBlank()) {
|
||||
code = textOrEmpty(response, "error");
|
||||
}
|
||||
JsonNode payload = response.path("payload");
|
||||
int serverLastGlobalNumber = payload.path("serverLastGlobalNumber").asInt(Integer.MIN_VALUE);
|
||||
String serverLastGlobalHash = payload.path("serverLastGlobalHash").asText("");
|
||||
|
||||
return new AddBlockPushResult(false, status, code, serverLastGlobalNumber, serverLastGlobalHash);
|
||||
}
|
||||
|
||||
private JsonNode sendAddBlock(SyncServerEntry partner, String blockchainName, BlockEntry blockEntry) throws Exception {
|
||||
String jsonTemplate = buildAddBlockJsonTemplate(blockchainName, blockEntry);
|
||||
return ServerConnectionPool.getInstance().request(
|
||||
partner.getLogin(),
|
||||
partner.getServerAddress(),
|
||||
jsonTemplate,
|
||||
ServerConnectionPool.Priority.BULK);
|
||||
}
|
||||
|
||||
private String buildAddBlockJsonTemplate(String blockchainName, BlockEntry blockEntry) throws Exception {
|
||||
String prevHashHex = blockEntry.getBlockNumber() <= 0
|
||||
? ""
|
||||
: toHex(extractPrevHash32(blockEntry.getBlockBytes()));
|
||||
String blockBytesB64 = Base64Ws.encode(blockEntry.getBlockBytes());
|
||||
|
||||
String safeBlockchainName = MAPPER.writeValueAsString(blockchainName);
|
||||
String safePrevHashHex = MAPPER.writeValueAsString(prevHashHex);
|
||||
String safeBlockBytes = MAPPER.writeValueAsString(blockBytesB64);
|
||||
return """
|
||||
{
|
||||
"op":"AddBlock",
|
||||
"requestId":%s,
|
||||
"payload":{
|
||||
"blockchainName":%s,
|
||||
"blockNumber":%d,
|
||||
"prevBlockHash":%s,
|
||||
"blockBytesB64":%s
|
||||
}
|
||||
}
|
||||
""".formatted("%s", safeBlockchainName, blockEntry.getBlockNumber(), safePrevHashHex, safeBlockBytes);
|
||||
}
|
||||
|
||||
private static byte[] extractPrevHash32(byte[] blockBytes) {
|
||||
if (blockBytes == null || blockBytes.length < 44) {
|
||||
return new byte[32];
|
||||
}
|
||||
byte[] out = new byte[32];
|
||||
System.arraycopy(blockBytes, 12, out, 0, 32);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String textOrEmpty(JsonNode node, String field) {
|
||||
return node == null ? "" : node.path(field).asText("");
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
if (value == null) return null;
|
||||
String s = value.trim().toLowerCase(Locale.ROOT);
|
||||
return s.isEmpty() ? null : s;
|
||||
}
|
||||
|
||||
private static String toHex(byte[] bytes) {
|
||||
if (bytes == null) return "";
|
||||
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
sb.append(Character.forDigit((b >>> 4) & 0xF, 16));
|
||||
sb.append(Character.forDigit(b & 0xF, 16));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private record AddBlockPushResult(
|
||||
boolean ok,
|
||||
int status,
|
||||
String code,
|
||||
int serverLastGlobalNumber,
|
||||
String serverLastGlobalHash
|
||||
) {
|
||||
static AddBlockPushResult success() {
|
||||
return new AddBlockPushResult(true, 200, "", Integer.MIN_VALUE, "");
|
||||
}
|
||||
|
||||
boolean needsBackfill() {
|
||||
return !ok && ("bad_prev_hash".equalsIgnoreCase(code) || "bad_block_number".equalsIgnoreCase(code));
|
||||
}
|
||||
|
||||
boolean serverAlreadyHasBlock(int targetBlockNumber) {
|
||||
return !ok
|
||||
&& serverLastGlobalNumber != Integer.MIN_VALUE
|
||||
&& serverLastGlobalNumber >= targetBlockNumber;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
package server.sync;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Минимальный клиент для межсерверных JSON-op запросов по WSS.
|
||||
*/
|
||||
public final class RemoteBlockchainSyncClient {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
public List<RemoteBlockchainHead> listBlockchainHeads(String serverAddressRaw) throws Exception {
|
||||
return listBlockchainHeads(null, serverAddressRaw);
|
||||
}
|
||||
|
||||
public List<RemoteBlockchainHead> listBlockchainHeads(String serverLogin, String serverAddressRaw) throws Exception {
|
||||
JsonNode response = send(serverLogin, serverAddressRaw, """
|
||||
{
|
||||
"op":"ListBlockchainHeads",
|
||||
"requestId":%s,
|
||||
"payload":{}
|
||||
}
|
||||
""");
|
||||
|
||||
int status = response.path("status").asInt(500);
|
||||
if (status < 200 || status >= 300) {
|
||||
throw new IllegalStateException("ListBlockchainHeads failed: status=" + status + " code=" + errorCode(response));
|
||||
}
|
||||
|
||||
List<RemoteBlockchainHead> result = new ArrayList<>();
|
||||
JsonNode items = response.path("payload").path("blockchains");
|
||||
if (!items.isArray()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode item : items) {
|
||||
result.add(new RemoteBlockchainHead(
|
||||
item.path("blockchainName").asText(""),
|
||||
item.path("lastBlockNumber").asInt(-1),
|
||||
item.path("lastBlockHash").asText(""),
|
||||
item.path("fileSizeBytes").asLong(0L)
|
||||
));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public RemoteSyncUserProfile getSyncUserProfile(String serverAddressRaw, String login) throws Exception {
|
||||
return getSyncUserProfile(null, serverAddressRaw, login);
|
||||
}
|
||||
|
||||
public RemoteSyncUserProfile getSyncUserProfile(String serverLogin, String serverAddressRaw, String login) throws Exception {
|
||||
String safeLogin = MAPPER.writeValueAsString(login);
|
||||
JsonNode response = send(serverLogin, serverAddressRaw, """
|
||||
{
|
||||
"op":"GetSyncUserProfile",
|
||||
"requestId":%s,
|
||||
"payload":{
|
||||
"login":%s
|
||||
}
|
||||
}
|
||||
""".formatted("%s", safeLogin));
|
||||
|
||||
int status = response.path("status").asInt(500);
|
||||
if (status == 404) {
|
||||
return null;
|
||||
}
|
||||
if (status < 200 || status >= 300) {
|
||||
throw new IllegalStateException("GetSyncUserProfile failed: status=" + status + " code=" + errorCode(response));
|
||||
}
|
||||
|
||||
JsonNode payload = response.path("payload");
|
||||
if (!payload.path("exists").asBoolean(false)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new RemoteSyncUserProfile(
|
||||
payload.path("login").asText(login),
|
||||
payload.path("blockchainName").asText(""),
|
||||
payload.path("solanaKey").asText(""),
|
||||
payload.path("blockchainKey").asText(""),
|
||||
payload.path("clientKey").asText(""),
|
||||
payload.path("blockchainSizeLimitBytes").asLong(0L)
|
||||
);
|
||||
}
|
||||
|
||||
public RemoteBlockchainBlock getBlockchainBlock(
|
||||
String serverAddressRaw, String blockchainName, int blockNumber
|
||||
) throws Exception {
|
||||
return getBlockchainBlock(null, serverAddressRaw, blockchainName, blockNumber);
|
||||
}
|
||||
|
||||
public RemoteBlockchainBlock getBlockchainBlock(
|
||||
String serverLogin, String serverAddressRaw, String blockchainName, int blockNumber
|
||||
) throws Exception {
|
||||
String safeBlockchainName = MAPPER.writeValueAsString(blockchainName);
|
||||
JsonNode response = send(serverLogin, serverAddressRaw, """
|
||||
{
|
||||
"op":"GetBlockchainBlock",
|
||||
"requestId":%s,
|
||||
"payload":{
|
||||
"blockchainName":%s,
|
||||
"blockNumber":%d
|
||||
}
|
||||
}
|
||||
""".formatted("%s", safeBlockchainName, blockNumber));
|
||||
|
||||
int status = response.path("status").asInt(500);
|
||||
if (status == 404) {
|
||||
return null;
|
||||
}
|
||||
if (status < 200 || status >= 300) {
|
||||
throw new IllegalStateException("GetBlockchainBlock failed: status=" + status + " code=" + errorCode(response));
|
||||
}
|
||||
|
||||
JsonNode payload = response.path("payload");
|
||||
return new RemoteBlockchainBlock(
|
||||
payload.path("blockchainName").asText(blockchainName),
|
||||
payload.path("blockNumber").asInt(blockNumber),
|
||||
payload.path("blockHash").asText(""),
|
||||
payload.path("blockBytesB64").asText("")
|
||||
);
|
||||
}
|
||||
|
||||
private JsonNode send(String serverLogin, String serverAddressRaw, String jsonTemplate) throws Exception {
|
||||
return ServerConnectionPool.getInstance().request(
|
||||
serverLogin,
|
||||
serverAddressRaw,
|
||||
jsonTemplate,
|
||||
ServerConnectionPool.Priority.BULK);
|
||||
}
|
||||
|
||||
private static String errorCode(JsonNode response) {
|
||||
String code = response.path("code").asText("");
|
||||
if (!code.isBlank()) return code;
|
||||
return response.path("error").asText("");
|
||||
}
|
||||
|
||||
static String buildWsUrl(String serverAddressRaw) {
|
||||
return ServerConnectionPool.buildWsUrl(serverAddressRaw);
|
||||
}
|
||||
|
||||
public record RemoteBlockchainHead(
|
||||
String blockchainName,
|
||||
int lastBlockNumber,
|
||||
String lastBlockHash,
|
||||
long fileSizeBytes
|
||||
) {}
|
||||
|
||||
public record RemoteBlockchainBlock(
|
||||
String blockchainName,
|
||||
int blockNumber,
|
||||
String blockHash,
|
||||
String blockBytesB64
|
||||
) {}
|
||||
|
||||
public record RemoteSyncUserProfile(
|
||||
String login,
|
||||
String blockchainName,
|
||||
String solanaKey,
|
||||
String blockchainKey,
|
||||
String clientKey,
|
||||
long blockchainSizeLimitBytes
|
||||
) {}
|
||||
|
||||
}
|
||||
-6
@@ -4,9 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import shine.db.dao.SyncServersDAO;
|
||||
import shine.db.dao.UserAccessServersCurrentDAO;
|
||||
import shine.db.entities.SyncServerEntry;
|
||||
import shine.db.entities.UserAccessServerRouteEntry;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
@@ -136,10 +134,6 @@ public final class ServerConnectionPool implements AutoCloseable {
|
||||
try {
|
||||
String ownLogin = normalizeLogin(AppConfig.getInstance().getParam(SERVER_LOGIN_CONFIG));
|
||||
Map<String, String> discovered = new LinkedHashMap<>();
|
||||
for (SyncServerEntry entry : SyncServersDAO.getInstance().listAll()) {
|
||||
if (entry == null) continue;
|
||||
putDiscovered(discovered, ownLogin, entry.getLogin(), entry.getServerAddress());
|
||||
}
|
||||
for (UserAccessServerRouteEntry entry : UserAccessServersCurrentDAO.getInstance().listDistinctServers()) {
|
||||
if (entry == null) continue;
|
||||
putDiscovered(discovered, ownLogin, entry.getServerLogin(), entry.getServerUrl());
|
||||
|
||||
@@ -1,427 +0,0 @@
|
||||
package server.sync;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Exception_Response;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.BlockchainLocks;
|
||||
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request;
|
||||
import shine.db.dao.BlockchainResyncCleanupDAO;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.SyncServersDAO;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
import shine.db.entities.SyncServerEntry;
|
||||
import server.sync.BlockchainResyncGuard;
|
||||
import utils.blockchain.BlockchainNameUtil;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* @deprecated Legacy direct server-to-server blockchain sync. Not compatible with segmented forks; Arweave/Turbo is supported.
|
||||
* Плановый межсерверный sync блокчейнов.
|
||||
* Сейчас реализует:
|
||||
* - догоняющую синхронизацию отсутствующего хвоста;
|
||||
* - базовый full-resync при divergence, если удалённая цепочка сильнее.
|
||||
*/
|
||||
@Deprecated
|
||||
public final class PeriodicBlockchainSyncService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PeriodicBlockchainSyncService.class);
|
||||
private static final long PERIOD_HOURS = 12L;
|
||||
private static final AtomicBoolean STARTED = new AtomicBoolean(false);
|
||||
private static final ScheduledExecutorService EXECUTOR = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
Thread t = new Thread(r, "periodic-blockchain-sync");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
}
|
||||
});
|
||||
|
||||
private static final RemoteBlockchainSyncClient REMOTE = new RemoteBlockchainSyncClient();
|
||||
private static final Net_AddBlock_Handler ADD_BLOCK_HANDLER = new Net_AddBlock_Handler();
|
||||
private static final BlockchainStateDAO STATE_DAO = BlockchainStateDAO.getInstance();
|
||||
private static final SyncServersDAO SYNC_SERVERS_DAO = SyncServersDAO.getInstance();
|
||||
private static final BlockchainResyncCleanupDAO RESYNC_CLEANUP_DAO = BlockchainResyncCleanupDAO.getInstance();
|
||||
private static final SolanaUserPdaCurrentDAO SOLANA_USER_PDA_CURRENT_DAO = SolanaUserPdaCurrentDAO.getInstance();
|
||||
|
||||
private PeriodicBlockchainSyncService() {}
|
||||
|
||||
public static void startOrLog() {
|
||||
if (!isEnabled()) {
|
||||
log.info("Periodic blockchain sync disabled by blockchain.sync.enabled=false");
|
||||
return;
|
||||
}
|
||||
if (!STARTED.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
EXECUTOR.scheduleWithFixedDelay(
|
||||
PeriodicBlockchainSyncService::runCycleSafe,
|
||||
0L,
|
||||
PERIOD_HOURS,
|
||||
TimeUnit.HOURS
|
||||
);
|
||||
log.info("Periodic blockchain sync scheduled: startup + every {} hours", PERIOD_HOURS);
|
||||
}
|
||||
|
||||
private static boolean isEnabled() {
|
||||
// PDA 1.2 удаляет sync_servers: пользовательские блокчейны синхронизируются через Arweave.
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void runCycleSafe() {
|
||||
try {
|
||||
runCycle();
|
||||
} catch (Exception e) {
|
||||
log.error("Periodic blockchain sync failed unexpectedly", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void runCycle() throws Exception {
|
||||
SyncServersBootstrapService.refreshFromSolanaOrLog();
|
||||
List<SyncServerEntry> partners = SYNC_SERVERS_DAO.listAll();
|
||||
if (partners.isEmpty()) {
|
||||
log.info("Periodic blockchain sync skipped: sync_servers is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
for (SyncServerEntry partner : partners) {
|
||||
if (partner == null) continue;
|
||||
try {
|
||||
syncPartner(partner);
|
||||
} catch (Exception e) {
|
||||
log.warn("Periodic blockchain sync partner failed: login={} reason={}",
|
||||
partner.getLogin(), String.valueOf(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void syncPartner(SyncServerEntry partner) throws Exception {
|
||||
String partnerLogin = normalize(partner.getLogin());
|
||||
if (partnerLogin == null) return;
|
||||
|
||||
List<RemoteBlockchainSyncClient.RemoteBlockchainHead> remoteHeads =
|
||||
REMOTE.listBlockchainHeads(partner.getLogin(), partner.getServerAddress());
|
||||
|
||||
for (RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead : remoteHeads) {
|
||||
if (remoteHead == null || remoteHead.blockchainName() == null || remoteHead.blockchainName().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
BlockchainStateEntry localState = STATE_DAO.getByBlockchainName(remoteHead.blockchainName());
|
||||
if (localState == null) {
|
||||
syncMissingTail(partner, remoteHead, -1, "");
|
||||
continue;
|
||||
}
|
||||
|
||||
int localLast = localState.getLastBlockNumber();
|
||||
String localHash = toHex32(localState.getLastBlockHash());
|
||||
|
||||
if (localLast < remoteHead.lastBlockNumber()) {
|
||||
syncMissingTail(partner, remoteHead, localLast, localHash);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (localLast == remoteHead.lastBlockNumber()) {
|
||||
if (localHash.equalsIgnoreCase(remoteHead.lastBlockHash())) {
|
||||
continue;
|
||||
}
|
||||
if (isRemoteStronger(localState, remoteHead)) {
|
||||
log.warn("Periodic blockchain sync: divergence detected, remote chain is stronger, starting full resync. partner={} blockchainName={} localLast={} localHash={} remoteHash={} localSize={} remoteSize={}",
|
||||
partnerLogin,
|
||||
remoteHead.blockchainName(),
|
||||
localLast,
|
||||
localHash,
|
||||
remoteHead.lastBlockHash(),
|
||||
localState.getFileSizeBytes(),
|
||||
remoteHead.fileSizeBytes());
|
||||
resyncFromScratch(partner, remoteHead);
|
||||
} else {
|
||||
log.info("Periodic blockchain sync skipped: local chain is stronger or equal. partner={} blockchainName={} localLast={} remoteLast={} localSize={} remoteSize={}",
|
||||
partnerLogin,
|
||||
remoteHead.blockchainName(),
|
||||
localLast,
|
||||
remoteHead.lastBlockNumber(),
|
||||
localState.getFileSizeBytes(),
|
||||
remoteHead.fileSizeBytes());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
log.info("Periodic blockchain sync skipped: local chain is not weaker. partner={} blockchainName={} localLast={} remoteLast={}",
|
||||
partnerLogin, remoteHead.blockchainName(), localLast, remoteHead.lastBlockNumber());
|
||||
}
|
||||
}
|
||||
|
||||
private static void syncMissingTail(
|
||||
SyncServerEntry partner,
|
||||
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead,
|
||||
int localLast,
|
||||
String localHash
|
||||
) throws Exception {
|
||||
String partnerLogin = normalize(partner.getLogin());
|
||||
if (!ensureLocalChainExists(partner, remoteHead.blockchainName())) {
|
||||
log.warn("Periodic blockchain sync: cannot prepare local chain. partner={} blockchainName={}",
|
||||
partnerLogin, remoteHead.blockchainName());
|
||||
return;
|
||||
}
|
||||
|
||||
int fromBlockNumber = Math.max(localLast + 1, 0);
|
||||
for (int blockNumber = fromBlockNumber; blockNumber <= remoteHead.lastBlockNumber(); blockNumber++) {
|
||||
RemoteBlockchainSyncClient.RemoteBlockchainBlock remoteBlock =
|
||||
REMOTE.getBlockchainBlock(
|
||||
partner.getLogin(), partner.getServerAddress(), remoteHead.blockchainName(), blockNumber);
|
||||
if (remoteBlock == null) {
|
||||
log.warn("Periodic blockchain sync: remote block not found. partner={} blockchainName={} blockNumber={}",
|
||||
partnerLogin, remoteHead.blockchainName(), blockNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
LocalAddBlockApplyResult result = applyBlockLocally(remoteBlock, blockNumber == 0 ? "" : localHash);
|
||||
if (!result.ok()) {
|
||||
if ("bad_prev_hash".equalsIgnoreCase(result.code()) || "bad_block_number".equalsIgnoreCase(result.code())) {
|
||||
log.warn("Periodic blockchain sync: divergence detected during replay, starting full resync. partner={} blockchainName={} blockNumber={} code={}",
|
||||
partnerLogin, remoteHead.blockchainName(), blockNumber, result.code());
|
||||
resyncFromScratch(partner, remoteHead);
|
||||
} else {
|
||||
log.warn("Periodic blockchain sync: local AddBlock rejected remote block. partner={} blockchainName={} blockNumber={} code={} message={}",
|
||||
partnerLogin, remoteHead.blockchainName(), blockNumber, result.code(), result.message());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
localHash = result.serverLastHash();
|
||||
}
|
||||
|
||||
log.info("Periodic blockchain sync ok: partner={} blockchainName={} from={} to={}",
|
||||
partnerLogin, remoteHead.blockchainName(), fromBlockNumber, remoteHead.lastBlockNumber());
|
||||
}
|
||||
|
||||
static void resyncFromScratch(
|
||||
SyncServerEntry partner,
|
||||
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead
|
||||
) throws Exception {
|
||||
if (partner == null || remoteHead == null || remoteHead.blockchainName() == null || remoteHead.blockchainName().isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String blockchainName = remoteHead.blockchainName();
|
||||
String partnerLogin = normalize(partner.getLogin());
|
||||
|
||||
if (!BlockchainResyncGuard.tryBegin(blockchainName)) {
|
||||
log.warn("Blockchain resync skipped: already in progress for blockchainName={}", blockchainName);
|
||||
return;
|
||||
}
|
||||
|
||||
ReentrantLock chainLock = BlockchainLocks.lockFor(blockchainName);
|
||||
chainLock.lock();
|
||||
boolean success = false;
|
||||
try {
|
||||
BlockchainResyncCleanupDAO.CleanupResult cleanup =
|
||||
RESYNC_CLEANUP_DAO.cleanupBlockchainForFullResync(blockchainName);
|
||||
log.info("Blockchain resync cleanup finished: blockchainName={} login={} deletedReactionsState={} deletedConnectionsState={} deletedBlocks={} deletedState={}",
|
||||
blockchainName,
|
||||
cleanup.login(),
|
||||
cleanup.deletedReactionsStateRows(),
|
||||
cleanup.deletedConnectionsStateRows(),
|
||||
cleanup.deletedBlocksRows(),
|
||||
cleanup.deletedBlockchainStateRows());
|
||||
|
||||
if (!ensureLocalChainExists(partner, blockchainName)) {
|
||||
throw new IllegalStateException("failed to recreate local chain state for " + blockchainName);
|
||||
}
|
||||
|
||||
boolean replayOk = replayRemoteChainFromStart(partner, remoteHead);
|
||||
if (!replayOk) {
|
||||
throw new IllegalStateException("failed to replay remote chain for " + blockchainName);
|
||||
}
|
||||
|
||||
success = true;
|
||||
log.info("Blockchain resync completed: partner={} blockchainName={} blocks=0..{}",
|
||||
partnerLogin, blockchainName, remoteHead.lastBlockNumber());
|
||||
} finally {
|
||||
chainLock.unlock();
|
||||
BlockchainResyncGuard.end(blockchainName);
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
throw new IllegalStateException("Blockchain resync did not complete for " + blockchainName);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean replayRemoteChainFromStart(
|
||||
SyncServerEntry partner,
|
||||
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead
|
||||
) throws Exception {
|
||||
String blockchainName = remoteHead.blockchainName();
|
||||
String partnerLogin = normalize(partner.getLogin());
|
||||
|
||||
return BlockchainResyncGuard.withBypass(blockchainName, () -> {
|
||||
String localPrevHash = "";
|
||||
for (int blockNumber = 0; blockNumber <= remoteHead.lastBlockNumber(); blockNumber++) {
|
||||
RemoteBlockchainSyncClient.RemoteBlockchainBlock remoteBlock =
|
||||
REMOTE.getBlockchainBlock(
|
||||
partner.getLogin(), partner.getServerAddress(), blockchainName, blockNumber);
|
||||
if (remoteBlock == null) {
|
||||
log.warn("Blockchain resync: remote block not found. partner={} blockchainName={} blockNumber={}",
|
||||
partnerLogin, blockchainName, blockNumber);
|
||||
return false;
|
||||
}
|
||||
|
||||
LocalAddBlockApplyResult result = applyBlockLocally(remoteBlock, localPrevHash);
|
||||
if (!result.ok()) {
|
||||
log.warn("Blockchain resync: AddBlock rejected replay block. partner={} blockchainName={} blockNumber={} code={} message={}",
|
||||
partnerLogin, blockchainName, blockNumber, result.code(), result.message());
|
||||
return false;
|
||||
}
|
||||
|
||||
localPrevHash = result.serverLastHash();
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isRemoteStronger(BlockchainStateEntry localState,
|
||||
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead) {
|
||||
if (localState == null || remoteHead == null) return false;
|
||||
|
||||
int localLast = localState.getLastBlockNumber();
|
||||
int remoteLast = remoteHead.lastBlockNumber();
|
||||
if (remoteLast != localLast) {
|
||||
return remoteLast > localLast;
|
||||
}
|
||||
|
||||
long localSize = localState.getFileSizeBytes();
|
||||
long remoteSize = remoteHead.fileSizeBytes();
|
||||
if (remoteSize != localSize) {
|
||||
return remoteSize > localSize;
|
||||
}
|
||||
|
||||
String localHash = toHex32(localState.getLastBlockHash()).toLowerCase(Locale.ROOT);
|
||||
String remoteHash = normalizeHex64(remoteHead.lastBlockHash());
|
||||
return remoteHash.compareTo(localHash) > 0;
|
||||
}
|
||||
|
||||
private static LocalAddBlockApplyResult applyBlockLocally(
|
||||
RemoteBlockchainSyncClient.RemoteBlockchainBlock remoteBlock,
|
||||
String prevHash
|
||||
) {
|
||||
Net_AddBlock_Request req = new Net_AddBlock_Request();
|
||||
req.setOp("AddBlock");
|
||||
req.setRequestId("periodic-sync-local");
|
||||
req.setBlockchainName(remoteBlock.blockchainName());
|
||||
req.setBlockNumber(remoteBlock.blockNumber());
|
||||
req.setPrevBlockHash(prevHash == null ? "" : prevHash);
|
||||
req.setBlockBytesB64(remoteBlock.blockBytesB64());
|
||||
|
||||
Net_Response response = ADD_BLOCK_HANDLER.handle(req, null);
|
||||
if (response.getStatus() >= 200 && response.getStatus() < 300) {
|
||||
server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Response ok =
|
||||
(server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Response) response;
|
||||
return new LocalAddBlockApplyResult(true, "", "", ok.getServerLastGlobalHash());
|
||||
}
|
||||
|
||||
Net_Exception_Response error = (Net_Exception_Response) response;
|
||||
return new LocalAddBlockApplyResult(false, error.getCode(), error.getMessage(), "");
|
||||
}
|
||||
|
||||
private static boolean ensureLocalChainExists(SyncServerEntry partner, String blockchainName) {
|
||||
try {
|
||||
BlockchainStateEntry existingState = STATE_DAO.getByBlockchainName(blockchainName);
|
||||
if (hasValidBlockchainKey(existingState)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ensureLocalChainStateFromCurrentPostgresSnapshot(blockchainName, existingState)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String login = BlockchainNameUtil.loginFromBlockchainName(blockchainName);
|
||||
if (login == null || login.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.warn("Periodic blockchain sync: failed to ensure local chain exists for blockchainName={} reason={}",
|
||||
blockchainName, String.valueOf(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean ensureLocalChainStateFromCurrentPostgresSnapshot(String blockchainName,
|
||||
BlockchainStateEntry existingState) throws Exception {
|
||||
SolanaUserPdaCurrentEntry currentUser = SOLANA_USER_PDA_CURRENT_DAO.getByBlockchainName(blockchainName);
|
||||
if (currentUser == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BlockchainStateEntry state = new BlockchainStateEntry();
|
||||
state.setBlockchainName(currentUser.getBlockchainName());
|
||||
state.setLogin(currentUser.getLogin());
|
||||
state.setBlockchainKey(currentUser.getBlockchainKey());
|
||||
state.setSizeLimit(currentUser.getPaidLimitBytes());
|
||||
state.setFileSizeBytes(existingState == null ? 0L : existingState.getFileSizeBytes());
|
||||
state.setLastBlockNumber(existingState == null ? -1 : existingState.getLastBlockNumber());
|
||||
state.setLastBlockHash(existingState == null ? null : existingState.getLastBlockHash());
|
||||
state.setUpdatedAtMs(System.currentTimeMillis());
|
||||
|
||||
if (existingState == null) {
|
||||
STATE_DAO.insertIfMissing(state);
|
||||
} else {
|
||||
STATE_DAO.upsert(state);
|
||||
}
|
||||
|
||||
return hasValidBlockchainKey(STATE_DAO.getByBlockchainName(blockchainName));
|
||||
}
|
||||
|
||||
private static boolean hasValidBlockchainKey(BlockchainStateEntry state) {
|
||||
if (state == null) {
|
||||
return false;
|
||||
}
|
||||
byte[] keyBytes = state.getBlockchainKeyBytes();
|
||||
return keyBytes != null && keyBytes.length == 32;
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
if (value == null) return null;
|
||||
String s = value.trim().toLowerCase(Locale.ROOT);
|
||||
return s.isEmpty() ? null : s;
|
||||
}
|
||||
|
||||
private static String toHex32(byte[] bytes32) {
|
||||
byte[] bytes = bytes32;
|
||||
if (bytes == null || bytes.length != 32) {
|
||||
bytes = new byte[32];
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(64);
|
||||
for (byte b : bytes) {
|
||||
sb.append(Character.forDigit((b >>> 4) & 0xF, 16));
|
||||
sb.append(Character.forDigit(b & 0xF, 16));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String normalizeHex64(String value) {
|
||||
if (value == null) return "";
|
||||
String s = value.trim().toLowerCase(Locale.ROOT);
|
||||
return s.length() == 64 ? s : "";
|
||||
}
|
||||
|
||||
private record LocalAddBlockApplyResult(
|
||||
boolean ok,
|
||||
String code,
|
||||
String message,
|
||||
String serverLastHash
|
||||
) {}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package server.sync;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.handlers.auth.SolanaUserPdaImportService;
|
||||
import shine.db.dao.SyncServersDAO;
|
||||
import shine.db.entities.SyncServerEntry;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* При старте сервера читает server PDA текущего сервера, затем PDA партнёров из
|
||||
* sync_servers и сохраняет их логины/адреса в локальную таблицу sync_servers.
|
||||
*/
|
||||
public final class SyncServersBootstrapService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SyncServersBootstrapService.class);
|
||||
private static final String CONFIG_KEY = "server.SHiNE.login";
|
||||
|
||||
private SyncServersBootstrapService() {}
|
||||
|
||||
public static void refreshFromSolanaOrLog() {
|
||||
try {
|
||||
SyncServersDAO.getInstance().replaceAll(List.of());
|
||||
log.info("Legacy sync_servers disabled: blockchain synchronization uses Arweave");
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to clear legacy sync_servers table", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
if (value == null) return null;
|
||||
String s = value.trim().toLowerCase();
|
||||
return s.isEmpty() ? null : s;
|
||||
}
|
||||
|
||||
private static String safe(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,8 @@ import server.archive.ArweaveBlockSyncScheduler;
|
||||
import server.debug.DebugApiConfigurator;
|
||||
import server.files.DmFileApiConfigurator;
|
||||
import server.files.PublicFileApiConfigurator;
|
||||
import server.sync.PeriodicBlockchainSyncService;
|
||||
import server.sync.PeriodicDmDeliveryService;
|
||||
import server.sync.SolanaUsersSyncStartupService;
|
||||
import server.sync.SyncServersBootstrapService;
|
||||
import server.sync.ServerConnectionPool;
|
||||
import shine.db.DbController;
|
||||
import utils.config.AppConfig;
|
||||
@@ -61,18 +59,6 @@ public final class WsServer {
|
||||
log.info("Не удалось прочитать параметр server.port, используем порт по умолчанию {}", port);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 1.1) Загрузка списка серверов синхронизации из Solana PDA
|
||||
// ============================================================
|
||||
// Legacy direct server-to-server sync is retired. Do not bootstrap sync_servers.
|
||||
// Arweave/Turbo is the supported blockchain recovery/synchronization source.
|
||||
|
||||
// ============================================================
|
||||
// 1.2) Плановый межсерверный sync блокчейнов
|
||||
// ============================================================
|
||||
// Legacy direct server-to-server blockchain sync is intentionally disabled.
|
||||
// PeriodicBlockchainSyncService is retained only as deprecated historical code.
|
||||
|
||||
// ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
|
||||
FreeRegistrationApiBootstrap.startOrThrow();
|
||||
ArweaveBlockPublisherScheduler.startOrLog();
|
||||
|
||||
@@ -89,10 +89,6 @@ public final class AddBlockSender {
|
||||
int prefix = (type == 3 || type == 4) ? 40 : 44;
|
||||
bodyBytes = Arrays.copyOfRange(bodyBytes, prefix, bodyBytes.length);
|
||||
}
|
||||
if (body instanceof HeaderBody h) {
|
||||
bodyBytes = HeaderBody.forCoreContent(h.login, h.initialBlockchainKey32).toBytes();
|
||||
version = 1;
|
||||
}
|
||||
ContentRecord content = new ContentRecord(type & 0xffff, subType & 0xffff, version & 0xffff, bodyBytes);
|
||||
Ans104DataItem contentItem = CoreContentTransport.sign(content.toBytes(), List.of(), loginPrivKey);
|
||||
CoreRecord core = new CoreRecord(prevHash32, blockNumber, tsSec, content.contentHash32(), contentItem.id32(), line);
|
||||
|
||||
@@ -77,7 +77,7 @@ public class IT_03_AddBlock_NoAuth {
|
||||
ChainState st1 = new ChainState();
|
||||
AddBlockSender sender1 = new AddBlockSender(ws, st1, u1, bch1, TestConfig.getBlockchainPrivatKey(u1));
|
||||
|
||||
sender1.send(new HeaderBody(u1, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u1))), t);
|
||||
sender1.send(HeaderBody.identity(u1, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u1)), "", HeaderBody.ALTERNATIVE, java.util.List.of()), t);
|
||||
assertTrue(st1.hasHeader());
|
||||
|
||||
int u1HeaderBlock = 0;
|
||||
@@ -195,7 +195,7 @@ public class IT_03_AddBlock_NoAuth {
|
||||
ChainState st2 = new ChainState();
|
||||
AddBlockSender sender2 = new AddBlockSender(ws, st2, u2, bch2, TestConfig.getBlockchainPrivatKey(u2));
|
||||
|
||||
sender2.send(new HeaderBody(u2, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u2))), t);
|
||||
sender2.send(HeaderBody.identity(u2, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u2)), "", HeaderBody.ALTERNATIVE, java.util.List.of()), t);
|
||||
assertTrue(st2.hasHeader());
|
||||
|
||||
int u2HeaderBlock = 0;
|
||||
@@ -267,7 +267,7 @@ public class IT_03_AddBlock_NoAuth {
|
||||
ChainState st3 = new ChainState();
|
||||
AddBlockSender sender3 = new AddBlockSender(ws, st3, u3, bch3, TestConfig.getBlockchainPrivatKey(u3));
|
||||
|
||||
sender3.send(new HeaderBody(u3, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u3))), t);
|
||||
sender3.send(HeaderBody.identity(u3, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u3)), "", HeaderBody.ALTERNATIVE, java.util.List.of()), t);
|
||||
assertTrue(st3.hasHeader());
|
||||
|
||||
int u3HeaderBlock = 0;
|
||||
|
||||
@@ -97,6 +97,9 @@ public class IT_04_UserParams_NoAuth {
|
||||
assertNotNull(lp2.signatureB64);
|
||||
|
||||
r.ok("ListUserParams OK");
|
||||
for (String reserved : new String[]{"account_role", "official", "ACCOUNT_ROLE"}) {
|
||||
upsertUserParam(r, login, reserved, t1b + 10, "primary", clientKeyB64, clientPrivKey, timeout, 400);
|
||||
}
|
||||
|
||||
} catch (Throwable e) {
|
||||
r.fail("IT_04 упал: " + e.getMessage());
|
||||
@@ -110,6 +113,10 @@ public class IT_04_UserParams_NoAuth {
|
||||
// =================================================================================
|
||||
|
||||
private static void upsertUserParam_OK(TestResult r, String login, String param, long timeMs, String value, String clientKeyB64, byte[] clientPrivKey, Duration timeout) {
|
||||
upsertUserParam(r, login, param, timeMs, value, clientKeyB64, clientPrivKey, timeout, 200);
|
||||
}
|
||||
|
||||
private static void upsertUserParam(TestResult r, String login, String param, long timeMs, String value, String clientKeyB64, byte[] clientPrivKey, Duration timeout, int expectedStatus) {
|
||||
String signatureB64 = signUserParam(clientPrivKey, login, param, timeMs, value);
|
||||
|
||||
String reqJson = """
|
||||
@@ -129,7 +136,8 @@ public class IT_04_UserParams_NoAuth {
|
||||
|
||||
try (WsSession ws = WsSession.open()) {
|
||||
String resp = ws.call("UpsertUserParam(" + param + ")", reqJson, timeout);
|
||||
assertEquals(200, JsonParsers.status(resp), "UpsertUserParam expected 200, resp=" + resp);
|
||||
assertEquals(expectedStatus, JsonParsers.status(resp), "UpsertUserParam expected " + expectedStatus + ", resp=" + resp);
|
||||
if (expectedStatus == 400) assertTrue(resp.contains("account_type_immutable"), resp);
|
||||
r.ok("UpsertUserParam(" + param + "): OK");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ public final class SeedDataPopulationHelper {
|
||||
}
|
||||
|
||||
public void createUsersAndHeaders(List<UserSpec> users) {
|
||||
for (UserSpec user : users) initHeader(user.login);
|
||||
for (UserSpec user : users) initHeader(user.login, Boolean.TRUE.equals(user.official));
|
||||
}
|
||||
|
||||
public void applyProfiles(List<UserSpec> users) {
|
||||
@@ -62,8 +62,7 @@ public final class SeedDataPopulationHelper {
|
||||
if (notBlank(user.address)) upsertProfileParam(user.login, "address", user.address);
|
||||
if (notBlank(user.web)) upsertProfileParam(user.login, "web", user.web);
|
||||
if (notBlank(user.phone)) upsertProfileParam(user.login, "phone", user.phone);
|
||||
if (user.official != null) upsertProfileParam(user.login, "official", user.official ? "yes" : "no");
|
||||
if (user.shine != null) upsertProfileParam(user.login, "shine", user.shine ? "yes" : "no");
|
||||
if (user.shine != null) upsertProfileParam(user.login, "shine", user.shine ? "shining" : "unknown");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,10 +157,10 @@ public final class SeedDataPopulationHelper {
|
||||
), timeout);
|
||||
}
|
||||
|
||||
private void initHeader(String login) {
|
||||
private void initHeader(String login, boolean primary) {
|
||||
ChainState state = new ChainState();
|
||||
AddBlockSender sender = new AddBlockSender(ws, state, login, bch(login), keys.blockchainPrivate32);
|
||||
sender.send(new HeaderBody(login, Ed25519Util.derivePublicKey(keys.blockchainPrivate32)), timeout);
|
||||
sender.send(HeaderBody.identity(login, Ed25519Util.derivePublicKey(keys.blockchainPrivate32), "", primary ? HeaderBody.PRIMARY : HeaderBody.ALTERNATIVE, java.util.List.of()), timeout);
|
||||
|
||||
byte[] headerHash = state.getHash32(0);
|
||||
if (headerHash == null || headerHash.length != 32) {
|
||||
|
||||
@@ -14,7 +14,7 @@ import static org.junit.jupiter.api.Assertions.fail;
|
||||
* Заполняет тестовую соц-сеть через API:
|
||||
* - пользователи должны уже существовать в актуальном PDA snapshot;
|
||||
* - HEADER и остальные блоки пишутся через AddBlock;
|
||||
* - параметры профиля (имя, фамилия, пол, адрес, web, phone, official, shine) через AddBlock USER_PARAM;
|
||||
* - параметры профиля (имя, фамилия, пол, адрес, web, phone, shine; official задаётся в HEADER) через AddBlock USER_PARAM;
|
||||
* - связи (close friend/contact/follow/parent/child/sibling) через AddBlock CONNECTION;
|
||||
* - посты через AddBlock TEXT_POST.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user