HEADER v3, primary аккаунты и подтверждения

This commit is contained in:
AidarKC
2026-11-27 12:29:24 +03:00
parent f9e7c4ef94
commit ae430e84c7
89 changed files with 1201 additions and 1596 deletions
@@ -54,7 +54,7 @@ inline bool buildPair(uint16_t type,uint16_t subtype,uint16_t version,const Byte
constexpr uint32_t MAX_NUMBER=2147482623,PROFILE=2147483645,CONNECTION=2147483646,TECH=2147483647; constexpr uint32_t MAX_NUMBER=2147482623,PROFILE=2147483645,CONNECTION=2147483646,TECH=2147483647;
const bool header=type==0&&subtype==0,tech=type==0&&subtype==1,fixed=type==3||type==4; const bool header=type==0&&subtype==0,tech=type==0&&subtype==1,fixed=type==3||type==4;
const bool channel=type==1&&(subtype==10||subtype==11||subtype==50||subtype==90||subtype==92||subtype==100||subtype==110||subtype==120||subtype==130); const bool channel=type==1&&(subtype==10||subtype==11||subtype==50||subtype==90||subtype==92||subtype==100||subtype==110||subtype==120||subtype==130);
if(version!=1||number>MAX_NUMBER||header!=(number==0)||(type==0&&!header&&!tech)||body.size()>8*1024*1024-124)return false; if((version!=1&&!(header&&(version==2||version==3)))||number>MAX_NUMBER||header!=(number==0)||(type==0&&!header&&!tech)||body.size()>8*1024*1024-124)return false;
if(header&&std::any_of(prev,prev+32,[](uint8_t b){return b!=0;}))return false; if(header&&std::any_of(prev,prev+32,[](uint8_t b){return b!=0;}))return false;
const size_t prefix=fixed?40:(tech||channel?44:0),offset=fixed?0:4; const size_t prefix=fixed?40:(tech||channel?44:0),offset=fixed?0:4;
if(body.size()<prefix)return false; if(body.size()<prefix)return false;
+1 -1
View File
@@ -55,7 +55,7 @@ PDA 1.2 использует три постоянные роли ключей:
## Синхронизация пользовательских blockchain ## Синхронизация пользовательских 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). // TECH supports Header v1 and CreateChannel current format (ver=1).
if (t == (CreateChannelBody.TYPE & 0xFFFF)) { if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
if (st == (HeaderBody.SUBTYPE_COMPAT & 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(); return new HeaderBody(subType, version, bodyBytes).check();
} }
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF) if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
@@ -17,8 +17,9 @@ public final class ContentBodyParser {
public static BodyRecord parseForCore(CoreRecord core, ContentRecord content) { public static BodyRecord parseForCore(CoreRecord core, ContentRecord content) {
if (!java.util.Arrays.equals(core.contentHash32(), content.contentHash32())) if (!java.util.Arrays.equals(core.contentHash32(), content.contentHash32()))
throw new IllegalArgumentException("CONTENT hash не совпадает с CORE"); 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; 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"); if (header != (core.blockNumber() == 0)) throw new IllegalArgumentException("HEADER только в CORE №0");
CoreRecord.Line line = core.line(); CoreRecord.Line line = core.line();
int expected = switch (content.type()) { int expected = switch (content.type()) {
@@ -9,13 +9,17 @@ import java.util.Arrays;
import java.util.Objects; 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): * bodyBytes (BigEndian):
* [TAG_LEN] tag ASCII * [TAG_LEN] tag ASCII
* [1] loginLength (uint8) * [1] loginLength (uint8)
* [N] login UTF-8 * [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 * [32] initialBlockchainKey32
* *
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1. * 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 final class HeaderBody implements BodyRecord {
public static final short TYPE = 0; 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 = 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_CC0 = "CC0-1.0";
public static final String LICENSE_FIELD_CC0 = "license:" + LICENSE_CC0; public static final String LICENSE_FIELD_CC0 = "license:" + LICENSE_CC0;
private static final byte[] LICENSE_BYTES = LICENSE_FIELD_CC0.getBytes(StandardCharsets.US_ASCII); 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 tag;
public final String login; public final String login;
public final byte[] initialBlockchainKey32; 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 public final String license; // null for legacy HEADER v1
private final boolean legacyCc0Encoding;
public HeaderBody(short subType, short version, byte[] bodyBytes) { public HeaderBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0"); 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 (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_CC0 ? LICENSE_BYTES.length : 0)) if (bodyBytes.length < TAG_LEN + 1 + 1 + 32 + (version == VER_LICENSE ? 1 : 0))
throw new IllegalArgumentException("HeaderBody too short"); throw new IllegalArgumentException("HeaderBody too short");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
@@ -60,17 +70,48 @@ public final class HeaderBody implements BodyRecord {
this.tag = parsedTag; this.tag = parsedTag;
int loginLen = Byte.toUnsignedInt(bb.get()); 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"); throw new IllegalArgumentException("Bad HeaderBody login/key/license length");
byte[] loginBytes = new byte[loginLen]; byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes); bb.get(loginBytes);
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login"); this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
if (version == VER_CC0) { if (version == VER_IDENTITY) {
byte[] actual = new byte[LICENSE_BYTES.length]; if (bb.remaining() < 34) throw new IllegalArgumentException("Truncated HEADER identity");
bb.get(actual); this.accountType = Byte.toUnsignedInt(bb.get());
if (!Arrays.equals(actual, LICENSE_BYTES)) throw new IllegalArgumentException("Unsupported HEADER license"); if (accountType == PRIMARY) {
this.license = LICENSE_CC0; 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 { } else {
this.accountType = null;
this.previousAccounts = java.util.List.of();
legacyCc0Encoding = false;
this.license = null; this.license = null;
} }
this.initialBlockchainKey32 = new byte[32]; 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. // Legacy constructor is kept for historical fixtures and importing v1 blocks.
public HeaderBody(String login, byte[] initialBlockchainKey32) { public HeaderBody(String login, byte[] initialBlockchainKey32) {
this(login, initialBlockchainKey32, VER); this(login, initialBlockchainKey32, VER, null, false);
} }
/** HEADER для CORE v2 / CONTENT v1: сохраняет login и начальный ключ, без поля лицензии. */ /** HEADER для CORE v2 / CONTENT v1: сохраняет login и начальный ключ, без поля лицензии. */
public static HeaderBody forCoreContent(String login, byte[] initialBlockchainKey32) { 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) { 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(login, "login == null");
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null"); Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
this.subType = SUBTYPE_COMPAT; this.subType = SUBTYPE_COMPAT;
@@ -101,15 +157,20 @@ public final class HeaderBody implements BodyRecord {
this.tag = TAG; this.tag = TAG;
this.login = login; this.login = login;
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length); 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(); check();
} }
@Override @Override
public HeaderBody check() { public HeaderBody check() {
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0"); 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 && version != VER_CC0 && version != VER_IDENTITY) throw new IllegalArgumentException("Bad HeaderBody version");
if (version == VER_CC0 && !LICENSE_CC0.equals(license)) throw new IllegalArgumentException("Bad HEADER CC0 license"); 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 (version == VER && license != null) throw new IllegalArgumentException("Legacy HEADER must not contain a license");
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank"); if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8); 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)"); 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 (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); requireNonZeroKey(initialBlockchainKey32);
return this; return this;
} }
@@ -129,11 +203,22 @@ public final class HeaderBody implements BodyRecord {
public byte[] toBytes() { public byte[] toBytes() {
check(); check();
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8); 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(TAG_ASCII);
bb.put((byte) loginUtf8.length); bb.put((byte) loginUtf8.length);
bb.put(loginUtf8); 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); bb.put(initialBlockchainKey32);
return bb.array(); return bb.array();
} }
@@ -42,7 +42,54 @@ public final class StageAProtocolChecks {
var header = HeaderBody.forCoreContent("Alice@shine", OWNER); var header = HeaderBody.forCoreContent("Alice@shine", OWNER);
testBody(0,HEADER_COMPAT,header,null,0); testBody(0,HEADER_COMPAT,header,null,0);
ok(header.license == null,"HEADER без CC0"); 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); var create=new CreateChannelContentBody("Новости","Описание",(short)1,(short)1);
testBody(0,TECH_CREATE_CHANNEL,create,line(CoreRecord.TECH),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, 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_43 = 43;
public static final int SCHEMA_VERSION_44 = 44; public static final int SCHEMA_VERSION_44 = 44;
public static final int SCHEMA_VERSION_45 = 45; 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_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.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"; 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_V43_RESOURCE = "postgres/migration_v43.sql";
public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.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_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() {} private DatabaseInitializer() {}
@@ -203,9 +209,21 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE); runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn); 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( 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); normalizeBlockchainStateKeysToBase64(conn);
} }
@@ -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=?")){ 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(); 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(); c.commit();
return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState); 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); } }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();} """)){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 // Recompute all message aggregates whose target belongs to this user. This also fixes
// external reactions/replies that intentionally survive this user's rebuild. // external reactions/replies that intentionally survive this user's rebuild.
try(PreparedStatement ps=c.prepareStatement(""" try(PreparedStatement ps=c.prepareStatement("""
@@ -22,14 +22,19 @@ public final class BlocksDAO {
} }
public void insert(Connection c, BlockEntry e) throws SQLException { 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 = """ String sql = """
INSERT INTO blocks_store ( INSERT INTO blocks_store (
login,fork_number,block_number,msg_type,msg_sub_type,block_bytes, login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_fork_number,to_block_number,to_block_hash, to_login,to_fork_number,to_block_number,to_block_hash,
block_hash,block_signature,data_item_id, block_hash,block_signature,data_item_id,
arweave_publish_pending,arweave_published_at_ms, arweave_publish_pending,arweave_published_at_ms,
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number,
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) header_account_type,header_previous_accounts
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1; int i = 1;
@@ -53,6 +58,12 @@ public final class BlocksDAO {
setNullableInt(ps, i++, e.getPrevLineNumber()); setNullableInt(ps, i++, e.getPrevLineNumber());
setNullableBytes(ps, i++, e.getPrevLineHash()); setNullableBytes(ps, i++, e.getPrevLineHash());
setNullableInt(ps, i++, e.getThisLineNumber()); 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(); 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) -------------------- // -------------------- UPSERT (IF NEWER) --------------------
public int upsertIfNewer(Connection c, UserParamEntry e) throws SQLException { public int upsertIfNewer(Connection c, UserParamEntry e) throws SQLException {
if ("account_role".equalsIgnoreCase(e.getParam()) && hasDeclaredIdentity(c, e.getLogin())) return 0;
String sql = """ String sql = """
INSERT INTO users_params ( INSERT INTO users_params (
login, 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 -------------------- // -------------------- SELECT --------------------
public UserParamEntry getByLoginAndParam(Connection c, String login, String param) throws SQLException { 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)) { 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 "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 "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_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_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_can_confirm_primary(cs.login,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_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_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_can_confirm_shine(cs.login,cs.to_login)";
default -> throw new IllegalArgumentException("Unsupported listType: " + listType); default -> throw new IllegalArgumentException("Unsupported listType: " + listType);
}; };
boolean received = "primary_received".equals(listType) || "shine_received".equals(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, COALESCE(up.ava_ar,'') AS ava_ar,
up.account_role, up.shine_status, 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 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 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 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=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' 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 CREATE INDEX IF NOT EXISTS idx_test_free_avatar_uploads_updated
ON test_free_avatar_uploads(updated_at_ms); 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 ( CREATE TABLE IF NOT EXISTS blockchain_state (
blockchain_name TEXT PRIMARY KEY, blockchain_name TEXT PRIMARY KEY,
login TEXT NOT NULL REFERENCES solana_user_pda_current(login), login TEXT NOT NULL REFERENCES solana_user_pda_current(login),
@@ -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;
@@ -158,7 +158,6 @@ import server.logic.ws_protocol.JSON.messages.entyties.Net_UpsertPushToken_Reque
// --- NEW: Ping --- // --- NEW: Ping ---
import server.logic.ws_protocol.JSON.handlers.system.Net_GetServerInfo_Handler; 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_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_ClientErrorLog_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ClientDebugLog_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_ClientDebugLog_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ListBlockchainHeads_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_ClientDebugLog_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetCallIceConfig_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_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_ListBlockchainHeads_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_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; 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("Ping", new Net_Ping_Handler()),
Map.entry("GetServerInfo", new Net_GetServerInfo_Handler()), Map.entry("GetServerInfo", new Net_GetServerInfo_Handler()),
Map.entry("ListBlockchainHeads", new Net_ListBlockchainHeads_Handler()), Map.entry("ListBlockchainHeads", new Net_ListBlockchainHeads_Handler()),
Map.entry("GetSyncUserProfile", new Net_GetSyncUserProfile_Handler()),
Map.entry("GetCallIceConfig", new Net_GetCallIceConfig_Handler()), Map.entry("GetCallIceConfig", new Net_GetCallIceConfig_Handler()),
Map.entry("ClientErrorLog", new Net_ClientErrorLog_Handler()), Map.entry("ClientErrorLog", new Net_ClientErrorLog_Handler()),
Map.entry("ClientDebugLog", new Net_ClientDebugLog_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("Ping", Net_Ping_Request.class),
Map.entry("GetServerInfo", Net_GetServerInfo_Request.class), Map.entry("GetServerInfo", Net_GetServerInfo_Request.class),
Map.entry("ListBlockchainHeads", Net_ListBlockchainHeads_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("GetCallIceConfig", Net_GetCallIceConfig_Request.class),
Map.entry("ClientErrorLog", Net_ClientErrorLog_Request.class), Map.entry("ClientErrorLog", Net_ClientErrorLog_Request.class),
Map.entry("ClientDebugLog", Net_ClientDebugLog_Request.class), Map.entry("ClientDebugLog", Net_ClientDebugLog_Request.class),
@@ -211,6 +211,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "limit_check_failed" -> "Ошибка проверки лимита размера"; case "limit_check_failed" -> "Ошибка проверки лимита размера";
case "bad_block_format" -> "Некорректный формат блока"; case "bad_block_format" -> "Некорректный формат блока";
case "bad_block_body" -> "Некорректное тело блока"; 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_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации";
case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER"; case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER";
case "bad_channel_name" -> "Некорректное название канала"; case "bad_channel_name" -> "Некорректное название канала";
@@ -385,6 +390,15 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки. // HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки.
// Проверка точная: другой регистр не может создать альтернативное "официальное" имя. // Проверка точная: другой регистр не может создать альтернативное "официальное" имя.
try { 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); CurrentUserEntry registeredOwner = currentUsersDAO.getByLogin(login);
if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin()) if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin())
|| !login.equalsIgnoreCase(registeredOwner.getLogin())) { || !login.equalsIgnoreCase(registeredOwner.getLogin())) {
@@ -692,7 +706,9 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
be.setEditedByBlockNumber(be.getToBlockNumber()); 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()); String votingError = validateConnectionVotingRights(login, block.subType & 0xFFFF, connectionBody.toLogin());
if (votingError != null) { if (votingError != null) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, votingError, serverLastNum, serverLastHashHex); 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; UserParamEntry upsertedParam = null;
if (block.body instanceof UserParamBody upBody) { 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()) String effectiveLogin = (st.getLogin() != null && !st.getLogin().isBlank())
? st.getLogin() ? st.getLogin()
: login; : login;
@@ -867,20 +887,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private String validateConnectionVotingRights(String actorLogin, int subType, String targetLogin) { private String validateConnectionVotingRights(String actorLogin, int subType, String targetLogin) {
if (subType != (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) if (subType != (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)
&& subType != (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF)) return null; && subType != (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF)) return null;
if (targetLogin == null || targetLogin.isBlank()) return "bad_connection_target"; if (targetLogin == null || targetLogin.isBlank() || targetLogin.equalsIgnoreCase(actorLogin))
String sql = subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) return "bad_connection_target";
? "SELECT shine_is_primary(?), shine_target_accepts_primary_confirmation(?)" boolean primary = subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF);
: "SELECT (shine_is_primary(?) AND shine_is_shining(?)), shine_target_accepts_shine_confirmation(?)"; String sql = primary
? "SELECT shine_can_confirm_primary(?,?)"
: "SELECT shine_can_confirm_shine(?,?)";
try (Connection c = shine.db.DbController.getInstance().getConnection(); try (Connection c = shine.db.DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(sql)) { PreparedStatement ps = c.prepareStatement(sql)) {
if (subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)) { ps.setString(1, actorLogin); ps.setString(2, targetLogin);
ps.setString(1, actorLogin); ps.setString(2, targetLogin);
} else {
ps.setString(1, actorLogin); ps.setString(2, actorLogin); ps.setString(3, targetLogin);
}
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (!rs.next() || !rs.getBoolean(1)) return subType == 80 ? "primary_vote_not_allowed" : "shine_vote_not_allowed"; if (!rs.next() || !rs.getBoolean(1)) return primary ? "primary_vote_not_allowed" : "shine_vote_not_allowed";
if (!rs.getBoolean(2)) return subType == 80 ? "target_non_voting" : "target_shine_not_interested";
} }
return null; return null;
} catch (Exception e) { } catch (Exception e) {
@@ -1,6 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils; package server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils;
import blockchain.BchBlockEntry; import blockchain.BchBlockEntry;
import blockchain.body.HeaderBody;
import shine.db.dao.BlockchainStateDAO; import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO; import shine.db.dao.BlocksDAO;
import shine.db.dao.ChannelNameStateDAO; import shine.db.dao.ChannelNameStateDAO;
@@ -76,7 +77,14 @@ public final class BlockchainWriter {
st.setUpdatedAtMs(nowMs); st.setUpdatedAtMs(nowMs);
stateDAO.upsert(c, st); 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 (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
if (channelNameStateEntry != null) { if (channelNameStateEntry != null) {
@@ -48,7 +48,7 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
COALESCE(ups.first_name, '') AS first_name, COALESCE(ups.first_name, '') AS first_name,
COALESCE(ups.last_name, '') AS last_name, COALESCE(ups.last_name, '') AS last_name,
COALESCE(ups.ava_ar, '') AS avatar_ar, 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 COALESCE(ups.shine_status, 'unknown') AS shine_status
FROM reactions_state rs FROM reactions_state rs
LEFT JOIN user_profile_state ups ON LOWER(ups.login) = LOWER(rs.from_login) 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.setAvatarAr(avatar.ar());
user.setAvatarPr(avatar.pr()); 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")); boolean isShining = "shining".equalsIgnoreCase(rs.getString("shine_status"));
if (isOfficial && isShining) shining.add(user); if (isOfficial && isShining) shining.add(user);
else if (isOfficial) official.add(user); else if (isOfficial) official.add(user);
@@ -130,26 +130,24 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
sql = outgoing ? """ sql = outgoing ? """
SELECT DISTINCT cs.to_login AS peer FROM connections_state cs SELECT DISTINCT cs.to_login AS peer FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 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 ORDER BY peer
""" : """ """ : """
SELECT DISTINCT cs.login AS peer FROM connections_state cs SELECT DISTINCT cs.login AS peer FROM connections_state cs
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 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 ORDER BY peer
"""; """;
} else { } else {
sql = outgoing ? """ sql = outgoing ? """
SELECT DISTINCT cs.to_login AS peer FROM connections_state cs SELECT DISTINCT cs.to_login AS peer FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=70
AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_can_confirm_shine(cs.login,cs.to_login)
AND shine_target_accepts_shine_confirmation(cs.to_login)
ORDER BY peer ORDER BY peer
""" : """ """ : """
SELECT DISTINCT cs.login AS peer FROM connections_state cs SELECT DISTINCT cs.login AS peer FROM connections_state cs
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 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_can_confirm_shine(cs.login,cs.to_login)
AND shine_target_accepts_shine_confirmation(cs.to_login)
ORDER BY peer ORDER BY peer
"""; """;
} }
@@ -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)
);
}
}
}
@@ -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; }
}
@@ -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; }
}
@@ -54,8 +54,19 @@ public class Net_ListUserParams_Handler implements JsonMessageHandler {
UserParamsDAO dao = UserParamsDAO.getInstance(); UserParamsDAO dao = UserParamsDAO.getInstance();
List<UserParamEntry> entries; List<UserParamEntry> entries;
Integer accountType = null;
List<String> previousAccounts = null;
try (Connection c = db.getConnection()) { try (Connection c = db.getConnection()) {
entries = dao.getByLogin(c, login); 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(); Net_ListUserParams_Response resp = new Net_ListUserParams_Response();
@@ -78,6 +89,8 @@ public class Net_ListUserParams_Handler implements JsonMessageHandler {
items.add(it); items.add(it);
} }
resp.setParams(items); resp.setParams(items);
resp.setAccountType(accountType);
resp.setPreviousAccounts(previousAccounts);
return resp; return resp;
@@ -63,6 +63,10 @@ public class Net_UpsertUserParam_Handler implements JsonMessageHandler {
final String login = req.getLogin().trim(); final String login = req.getLogin().trim();
final String param = req.getParam().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 long timeMs = req.getTime_ms();
final String value = req.getValue(); final String value = req.getValue();
final String clientKeyB64 = req.getClient_key().trim(); final String clientKeyB64 = req.getClient_key().trim();
@@ -31,6 +31,12 @@ import java.util.List;
public class Net_ListUserParams_Response extends Net_Response { public class Net_ListUserParams_Response extends Net_Response {
private String login; 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<>(); private List<Item> params = new ArrayList<>();
public String getLogin() { return login; } public String getLogin() { return login; }
@@ -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;
}
}
}
@@ -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
) {}
}
@@ -4,9 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import shine.db.dao.SyncServersDAO;
import shine.db.dao.UserAccessServersCurrentDAO; import shine.db.dao.UserAccessServersCurrentDAO;
import shine.db.entities.SyncServerEntry;
import shine.db.entities.UserAccessServerRouteEntry; import shine.db.entities.UserAccessServerRouteEntry;
import utils.config.AppConfig; import utils.config.AppConfig;
@@ -136,10 +134,6 @@ public final class ServerConnectionPool implements AutoCloseable {
try { try {
String ownLogin = normalizeLogin(AppConfig.getInstance().getParam(SERVER_LOGIN_CONFIG)); String ownLogin = normalizeLogin(AppConfig.getInstance().getParam(SERVER_LOGIN_CONFIG));
Map<String, String> discovered = new LinkedHashMap<>(); 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()) { for (UserAccessServerRouteEntry entry : UserAccessServersCurrentDAO.getInstance().listDistinctServers()) {
if (entry == null) continue; if (entry == null) continue;
putDiscovered(discovered, ownLogin, entry.getServerLogin(), entry.getServerUrl()); 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.debug.DebugApiConfigurator;
import server.files.DmFileApiConfigurator; import server.files.DmFileApiConfigurator;
import server.files.PublicFileApiConfigurator; import server.files.PublicFileApiConfigurator;
import server.sync.PeriodicBlockchainSyncService;
import server.sync.PeriodicDmDeliveryService; import server.sync.PeriodicDmDeliveryService;
import server.sync.SolanaUsersSyncStartupService; import server.sync.SolanaUsersSyncStartupService;
import server.sync.SyncServersBootstrapService;
import server.sync.ServerConnectionPool; import server.sync.ServerConnectionPool;
import shine.db.DbController; import shine.db.DbController;
import utils.config.AppConfig; import utils.config.AppConfig;
@@ -61,18 +59,6 @@ public final class WsServer {
log.info("Не удалось прочитать параметр server.port, используем порт по умолчанию {}", port); 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. // ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
FreeRegistrationApiBootstrap.startOrThrow(); FreeRegistrationApiBootstrap.startOrThrow();
ArweaveBlockPublisherScheduler.startOrLog(); ArweaveBlockPublisherScheduler.startOrLog();
@@ -89,10 +89,6 @@ public final class AddBlockSender {
int prefix = (type == 3 || type == 4) ? 40 : 44; int prefix = (type == 3 || type == 4) ? 40 : 44;
bodyBytes = Arrays.copyOfRange(bodyBytes, prefix, bodyBytes.length); 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); ContentRecord content = new ContentRecord(type & 0xffff, subType & 0xffff, version & 0xffff, bodyBytes);
Ans104DataItem contentItem = CoreContentTransport.sign(content.toBytes(), List.of(), loginPrivKey); Ans104DataItem contentItem = CoreContentTransport.sign(content.toBytes(), List.of(), loginPrivKey);
CoreRecord core = new CoreRecord(prevHash32, blockNumber, tsSec, content.contentHash32(), contentItem.id32(), line); 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(); ChainState st1 = new ChainState();
AddBlockSender sender1 = new AddBlockSender(ws, st1, u1, bch1, TestConfig.getBlockchainPrivatKey(u1)); 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()); assertTrue(st1.hasHeader());
int u1HeaderBlock = 0; int u1HeaderBlock = 0;
@@ -195,7 +195,7 @@ public class IT_03_AddBlock_NoAuth {
ChainState st2 = new ChainState(); ChainState st2 = new ChainState();
AddBlockSender sender2 = new AddBlockSender(ws, st2, u2, bch2, TestConfig.getBlockchainPrivatKey(u2)); 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()); assertTrue(st2.hasHeader());
int u2HeaderBlock = 0; int u2HeaderBlock = 0;
@@ -267,7 +267,7 @@ public class IT_03_AddBlock_NoAuth {
ChainState st3 = new ChainState(); ChainState st3 = new ChainState();
AddBlockSender sender3 = new AddBlockSender(ws, st3, u3, bch3, TestConfig.getBlockchainPrivatKey(u3)); 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()); assertTrue(st3.hasHeader());
int u3HeaderBlock = 0; int u3HeaderBlock = 0;
@@ -97,6 +97,9 @@ public class IT_04_UserParams_NoAuth {
assertNotNull(lp2.signatureB64); assertNotNull(lp2.signatureB64);
r.ok("ListUserParams OK"); 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) { } catch (Throwable e) {
r.fail("IT_04 упал: " + e.getMessage()); 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) { 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 signatureB64 = signUserParam(clientPrivKey, login, param, timeMs, value);
String reqJson = """ String reqJson = """
@@ -129,7 +136,8 @@ public class IT_04_UserParams_NoAuth {
try (WsSession ws = WsSession.open()) { try (WsSession ws = WsSession.open()) {
String resp = ws.call("UpsertUserParam(" + param + ")", reqJson, timeout); 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"); r.ok("UpsertUserParam(" + param + "): OK");
} }
} }
@@ -51,7 +51,7 @@ public final class SeedDataPopulationHelper {
} }
public void createUsersAndHeaders(List<UserSpec> users) { 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) { 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.address)) upsertProfileParam(user.login, "address", user.address);
if (notBlank(user.web)) upsertProfileParam(user.login, "web", user.web); if (notBlank(user.web)) upsertProfileParam(user.login, "web", user.web);
if (notBlank(user.phone)) upsertProfileParam(user.login, "phone", user.phone); 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 ? "shining" : "unknown");
if (user.shine != null) upsertProfileParam(user.login, "shine", user.shine ? "yes" : "no");
} }
} }
@@ -158,10 +157,10 @@ public final class SeedDataPopulationHelper {
), timeout); ), timeout);
} }
private void initHeader(String login) { private void initHeader(String login, boolean primary) {
ChainState state = new ChainState(); ChainState state = new ChainState();
AddBlockSender sender = new AddBlockSender(ws, state, login, bch(login), keys.blockchainPrivate32); 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); byte[] headerHash = state.getHash32(0);
if (headerHash == null || headerHash.length != 32) { if (headerHash == null || headerHash.length != 32) {
@@ -14,7 +14,7 @@ import static org.junit.jupiter.api.Assertions.fail;
* Заполняет тестовую соц-сеть через API: * Заполняет тестовую соц-сеть через API:
* - пользователи должны уже существовать в актуальном PDA snapshot; * - пользователи должны уже существовать в актуальном PDA snapshot;
* - HEADER и остальные блоки пишутся через AddBlock; * - 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; * - связи (close friend/contact/follow/parent/child/sibling) через AddBlock CONNECTION;
* - посты через AddBlock TEXT_POST. * - посты через AddBlock TEXT_POST.
*/ */
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.20.67 client.version=1.20.71
server.version=1.16.38 server.version=1.16.42
-2
View File
@@ -13,8 +13,6 @@ server.SHiNE.login=
solana.cluster=devnet solana.cluster=devnet
solana.rpcUrl= solana.rpcUrl=
solana.users.sync.enabled=false solana.users.sync.enabled=false
blockchain.sync.enabled=false
sync.importUserProfileFromPartner.enabled=false
arweave.blocks.publish.enabled=false arweave.blocks.publish.enabled=false
arweave.blocks.sync.enabled=false arweave.blocks.sync.enabled=false
@@ -49,3 +49,11 @@
В существующем `blocks_store.block_bytes` хранится контейнер целиком; `block_hash`, `block_signature`, `data_item_id` — hash, подпись, ID CORE. Размер цепочки увеличивается на фактическую длину контейнера. Сохраняются существующая транзакция и очередь; локальный AddBlock ACK не равен Turbo ACK. Публикация CONTENT -> CORE и загрузка пары из Arweave — M4, ещё не реализованы в M3. В существующем `blocks_store.block_bytes` хранится контейнер целиком; `block_hash`, `block_signature`, `data_item_id` — hash, подпись, ID CORE. Размер цепочки увеличивается на фактическую длину контейнера. Сохраняются существующая транзакция и очередь; локальный AddBlock ACK не равен Turbo ACK. Публикация CONTENT -> CORE и загрузка пары из Arweave — M4, ещё не реализованы в M3.
`GetBlockchainBlock` возвращает исходный `blockBytesB64` из одной записи без переупаковки. `GetMyBlockchain` и чтение каналов извлекают смысловое тело CONTENT из пары. Старые JSON-поля и операции сохранены; GetMyBlockchain дополнительно возвращает thisLineNumber из существующей БД. Клиент M3 понимает новый контейнер. `GetBlockchainBlock` возвращает исходный `blockBytesB64` из одной записи без переупаковки. `GetMyBlockchain` и чтение каналов извлекают смысловое тело CONTENT из пары. Старые JSON-поля и операции сохранены; GetMyBlockchain дополнительно возвращает thisLineNumber из существующей БД. Клиент M3 понимает новый контейнер.
### HEADER body v2 (2026-11-27)
Номер CONTENT body v2 допустим только для HEADER (type=0, subType=0, CORE №0). Поле лицензии описано в [TECH-блоках](../Blockchain/10_TECH_Blocks.md). JSON-контракт AddBlock и проверки подписей/хешей не меняются.
### HEADER body v3 (2026-11-27)
Новая прямая запись HEADER требует V3 (`header_v3_required`); предшественники проверяются по каталогу (`previous_account_not_found`), но владение не проверяется. Архивное восстановление допускает V1/V2 и не требует наличия предшественников в локальном каталоге. Новые USER_PARAM `account_role` / `official` запрещены для всех версий (`account_type_immutable`). Новые подтверждения `80/70` проверяются по правилам [Connections](11_Connections_API.md); архивная история принимается без проверки текущих прав голоса. См. [формат TECH](../Blockchain/10_TECH_Blocks.md).
+6 -90
View File
@@ -2,12 +2,11 @@
Этот файл описывает технические WebSocket-запросы, которые нужны для служебной работы клиента с сервером. Часть операций доступна без авторизации, часть требует успешной авторизованной сессии. Этот файл описывает технические WebSocket-запросы, которые нужны для служебной работы клиента с сервером. Часть операций доступна без авторизации, часть требует успешной авторизованной сессии.
Сейчас здесь девять методов: Сейчас здесь восемь методов:
- `Ping` — keep-alive запрос для поддержания живого WebSocket-соединения; - `Ping` — keep-alive запрос для поддержания живого WebSocket-соединения;
- `GetServerInfo` — запрос базовой публичной информации о сервере для выбора узла в децентрализованной сети; - `GetServerInfo` — запрос базовой публичной информации о сервере для выбора узла в децентрализованной сети;
- `ListBlockchainHeads` — краткая сводка по всем локальным блокчейнам сервера для межсерверной синхронизации; - `ListBlockchainHeads` — краткая сводка по всем локальным блокчейнам сервера для диагностики и тестового издателя;
- `GetSyncUserProfile` — межсерверный профиль пользователя для создания локальной цепочки без Solana RPC;
- `SendSignal` — общий межсессионный технический сигнал в одну конкретную сессию или сразу во все активные сессии пользователя; - `SendSignal` — общий межсессионный технический сигнал в одну конкретную сессию или сразу во все активные сессии пользователя;
- `GetCallIceConfig` — выдача STUN/TURN конфигурации для звонков; - `GetCallIceConfig` — выдача STUN/TURN конфигурации для звонков;
- `ClientErrorLog` — отправка клиентской ошибки в серверный лог; - `ClientErrorLog` — отправка клиентской ошибки в серверный лог;
@@ -18,8 +17,7 @@
- `Ping` нужен для регулярной проверки, что соединение всё ещё живо; - `Ping` нужен для регулярной проверки, что соединение всё ещё живо;
- `GetServerInfo` нужен до авторизации и до работы с данными, чтобы клиент понял, что сервер доступен, и показал пользователю краткую карточку этого узла. - `GetServerInfo` нужен до авторизации и до работы с данными, чтобы клиент понял, что сервер доступен, и показал пользователю краткую карточку этого узла.
- `ListBlockchainHeads` нужен для сервер-сервер сверки: партнёр получает список heads по всем цепочкам, сравнивает его со своим состоянием и затем добирает недостающие блоки по диапазону. - `ListBlockchainHeads` — read-only операция для диагностики и тестового издателя, не запускающая репликацию.
- `GetSyncUserProfile` нужен для server-to-server режима, когда принимающий сервер хочет создать у себя локальную runtime-проекцию пользователя и `blockchain_state` без прямого обращения в Solana.
- `SendSignal` нужен для доверенных межсессионных команд одного пользователя. Первое практическое применение — `remote AddBlock via homeserver session`, но формат задуман как общий transport на вырост. - `SendSignal` нужен для доверенных межсессионных команд одного пользователя. Первое практическое применение — `remote AddBlock via homeserver session`, но формат задуман как общий transport на вырост.
Ниже сначала описаны назначение методов, затем точные форматы запросов и ответов. Ниже сначала описаны назначение методов, затем точные форматы запросов и ответов.
@@ -146,12 +144,7 @@
Запрос краткой сводки по всем локальным блокчейнам сервера. Запрос краткой сводки по всем локальным блокчейнам сервера.
Нужен для межсерверной синхронизации. Партнёр может: Используется для диагностики и получения текущей вершины тестовым издателем. Не инициирует синхронизацию.
- получить список всех блокчейнов;
- сравнить `lastBlockNumber` и `lastBlockHash` со своими значениями;
- понять, какие цепочки нужно догонять;
- затем отдельно запросить недостающие блоки по диапазону.
Этот запрос доступен без авторизации. Этот запрос доступен без авторизации.
@@ -201,86 +194,9 @@
--- ---
## 4. `GetSyncUserProfile` ## 4. Удалённый метод
### Назначение `GetSyncUserProfile` удалён вместе с прямой репликацией блоков.
Запрос минимального профиля пользователя для межсерверной синхронизации.
Нужен в сценарии, когда сервер во время periodic sync увидел чужой блокчейн, которого у него локально ещё нет. Вместо обращения в Solana PDA он может запросить у партнёра:
- `login`
- `blockchainName`
- `solanaKey`
- `blockchainKey`
- `clientKey`
- `blockchainSizeLimitBytes`
После этого принимающий сервер может локально создать runtime-проекцию пользователя и запись в `blockchain_state`, а затем уже докачивать блоки через `GetBlockchainBlock`.
Этот запрос доступен без авторизации и предназначен именно для server-to-server sync.
### Запрос
```json
{
"op": "GetSyncUserProfile",
"requestId": "sync-user-001",
"payload": {
"login": "alice"
}
}
```
### Успешный ответ: пользователь не найден
```json
{
"op": "GetSyncUserProfile",
"requestId": "sync-user-001",
"status": 200,
"ok": true,
"payload": {
"exists": false
}
}
```
### Успешный ответ: пользователь найден
```json
{
"op": "GetSyncUserProfile",
"requestId": "sync-user-001",
"status": 200,
"ok": true,
"payload": {
"exists": true,
"login": "alice",
"blockchainName": "alice-001",
"solanaKey": "BASE64_32",
"blockchainKey": "BASE64_32",
"clientKey": "BASE64_32",
"blockchainSizeLimitBytes": 100000
}
}
```
### Поля ответа
- `exists` — найден ли пользователь на сервере-партнёре.
- `login` — канонический login из БД сервера-партнёра.
- `blockchainName` — имя основной цепочки пользователя.
- `solanaKey` — публичный ключ логина.
- `blockchainKey` — публичный ключ блокчейна.
- `clientKey` — публичный клиентский ключ, который в текущей модели используется при создании локальной записи.
- `blockchainSizeLimitBytes` — лимит размера файла блокчейна, который будет записан в локальный `blockchain_state`.
### Специфические коды ошибок `GetSyncUserProfile`
- `400 / BAD_FIELDS` — пустой или некорректный `login`.
- `404 / BLOCKCHAIN_STATE_NOT_FOUND` — пользователь найден, но на сервере-партнёре отсутствует `blockchain_state` для его цепочки.
- При непредвиденной ошибке сервер вернёт общую ошибку из раздела `00`, обычно `500 / INTERNAL_ERROR`.
--- ---
+2 -2
View File
@@ -586,10 +586,10 @@ Channel items contain `ownerLogin`, `slug`, `displayName`, `avatarAr`, `ownerBlo
Channel/message responses expose three counters: Channel/message responses expose three counters:
- `likesCount` — all active likes; - `likesCount` — all active likes;
- `primaryLikesCount` — likes from users whose current `account_role=primary`; - `primaryLikesCount` — likes from accounts whose canonical signed HEADER V3 declares `accountType=1`;
- `shiningLikesCount` — likes from users who are currently both `primary` and `shining`. - `shiningLikesCount` — likes from users who are currently both `primary` and `shining`.
Changing `account_role` or `shine` does not alter the raw reaction. The two qualified counters are recalculated from `reactions_state`; therefore old likes automatically enter or leave qualified counters when the actor's current status changes. The public UI shows only `primaryLikesCount`; details retain all three categories. Alternative accounts can still like. The `account_role` parameter cannot change voting rights. Changes in `shine` or in the canonical HEADER projection recalculate qualified counters from `reactions_state`, without changing raw reactions.
## `SearchChannels` — публичный поиск каналов (v32) ## `SearchChannels` — публичный поиск каналов (v32)
-1
View File
@@ -58,7 +58,6 @@
| `Ping` | `05_Technical_Requests_API.md` | keep-alive | | `Ping` | `05_Technical_Requests_API.md` | keep-alive |
| `GetServerInfo` | `05_Technical_Requests_API.md` | публичная информация о сервере | | `GetServerInfo` | `05_Technical_Requests_API.md` | публичная информация о сервере |
| `ListBlockchainHeads` | `05_Technical_Requests_API.md` | список heads всех локальных блокчейнов | | `ListBlockchainHeads` | `05_Technical_Requests_API.md` | список heads всех локальных блокчейнов |
| `GetSyncUserProfile` | `05_Technical_Requests_API.md` | межсерверный профиль пользователя для синхронизации |
| `SendSignal` | `05_Technical_Requests_API.md` | общий межсессионный технический сигнал в одну или все сессии пользователя | | `SendSignal` | `05_Technical_Requests_API.md` | общий межсессионный технический сигнал в одну или все сессии пользователя |
| `GetCallIceConfig` | `05_Technical_Requests_API.md` | STUN/TURN конфигурация звонков | | `GetCallIceConfig` | `05_Technical_Requests_API.md` | STUN/TURN конфигурация звонков |
| `ClientErrorLog` | `05_Technical_Requests_API.md` | логирование клиентской ошибки | | `ClientErrorLog` | `05_Technical_Requests_API.md` | логирование клиентской ошибки |
+3
View File
@@ -43,6 +43,7 @@
### Типовые ошибки ### Типовые ошибки
- `400 / BAD_FIELDS` — некорректные обязательные поля. - `400 / BAD_FIELDS` — некорректные обязательные поля.
- `400 / account_type_immutable` — попытка записать `account_role` или `official`; тип задаётся только при регистрации.
- `422 / BAD_SIGNATURE` — подпись не прошла проверку. - `422 / BAD_SIGNATURE` — подпись не прошла проверку.
- `501 / DB_ERROR` — ошибка БД. - `501 / DB_ERROR` — ошибка БД.
@@ -127,3 +128,5 @@
## Примечание ## Примечание
Имена JSON-полей `time_ms` и `client_key` сейчас соответствуют Java-модели ответа/запроса и должны передаваться именно в таком виде. Имена JSON-полей `time_ms` и `client_key` сейчас соответствуют Java-модели ответа/запроса и должны передаваться именно в таком виде.
Для HEADER V3 ответ `ListUserParams` дополнительно содержит `accountType` (0/1) и `previousAccounts` (массив логинов). Это производные поля подписанного HEADER, не редактируемые параметры профиля. При V1/V2 тип отсутствует или null: аккаунт не является Primary. Исторический `account_role`/`official` может присутствовать в старых данных, но не определяет статус. Список не меняет статус указанных аккаунтов.
+6 -6
View File
@@ -237,12 +237,12 @@ Effective relation priority is `close_friend > friend > contact > none`. Effecti
### Voting rules ### Voting rules
- new `80` requires the actor to have `account_role=primary`; - New `80` requires two distinct Primary accounts (canonical signed HEADER V3, `accountType=1` on both sides).
- `80` cannot be added to a target with `account_role=non_voting`; - New `70` requires the same pair; the actor must additionally be `shine=shining` (legacy `shine=yes` is normalized), and the target must not be `shine=not_interested`.
- new `70` requires actor `account_role=primary` and `shine=shining` (legacy `shine=yes` is normalized to `shining`); - Alternative, V1/V2 and missing HEADER do not qualify. Self-confirmation does not qualify, regardless of letter case.
- `70` cannot be added to a target with `shine=not_interested`; - Withdrawal (`81/71`) may remove historical declarations; it is not a new confirmation. Ordinary friendship/contact and reactions remain available to everyone.
- a `non_voting` target may still receive `70` if its shine status allows it; - Archive import/replay preserves signed history without checking the current voting rights at import time. Effective graph lists, profile lists and counts all use `shine_can_confirm_primary(actor,target)` / `shine_can_confirm_shine(actor,target)`. Historical ineligible declarations remain in raw history but do not count. A change of the canonical projection or shine status may affect effective confirmations.
- old raw `70/80` remain in `connections_state`, but are excluded from effective lists/counts while either side is ineligible. They become effective again automatically if statuses permit later. - The declared previous accounts do not change anyone's rights or counts. No personhood analyzer is implemented yet.
### `ListContacts` additions (v18) ### `ListContacts` additions (v18)
+24 -6
View File
@@ -1,4 +1,4 @@
# TECH блоки (`type=0`; версия 1, а для HEADER также 2) # TECH блоки (`type=0`; версия 1, а для HEADER также 2 и 3)
TECH-тип покрывает системные записи пользовательской цепочки. Все TECH DataItem имеют подписанный индексный тег: TECH-тип покрывает системные записи пользовательской цепочки. Все TECH DataItem имеют подписанный индексный тег:
@@ -12,7 +12,7 @@ t=tech
### `subType=0` — `HEADER_COMPAT` ### `subType=0` — `HEADER_COMPAT`
Стартовый блок цепочки (`block #0`). Новый клиент создаёт `HEADER v2`, а старые `HEADER v1` продолжают читаться. Стартовый блок цепочки (`block #0`). Новый клиент создаёт `HEADER v3`, а старые `HEADER v1/v2` продолжают читаться.
Формат `HEADER v1`: Формат `HEADER v1`:
@@ -29,13 +29,31 @@ t=tech
[5] ASCII "SHiNE" [5] ASCII "SHiNE"
[1] loginLength (uint8) [1] loginLength (uint8)
[N] login UTF-8 [N] login UTF-8
[15] ASCII "license:CC0-1.0" [1] licenseLength (uint8)
[M] license UTF-8
[32] initialBlockchainKey32 [32] initialBlockchainKey32
``` ```
В `v2` строка `license:CC0-1.0` записывается **буквально**, без отдельного поля длины, и должна полностью совпадать. Наличие префикса `license:` обязательно. Запись является частью подписанного блока. Любые другие строки лицензии и дополнительные байты запрещены. В новом `v2` строка лицензии — произвольный корректный UTF-8 длиной 0–255 **байт**, без обязательного префикса или списка допустимых значений. По умолчанию новый клиент записывает пустую строку до утверждения лицензии. Исторический `v2` с фиксированными 15 байтами ASCII `license:CC0-1.0` без длины по-прежнему читается и сериализуется без изменений. Это отдельное однозначно различимое представление: первый байт `l` (108) не равен длине оставшейся строки (14).
`HEADER v1` остаётся исторически допустимым и не означает автоматически принятую CC0. Существующие блоки #0 не переписываются. Все новые цепочки создаются с `HEADER v2`. `HEADER v1` остаётся исторически допустимым и не означает автоматически принятую CC0. Существующие блоки #0 не переписываются. Все новые цепочки создаются с `HEADER v3`.
Формат `HEADER v3` (BigEndian):
```text
[5] ASCII "SHiNE"
[1] loginLength (uint8)
[N] login UTF-8
[1] accountType (uint8: 0=Alternative, 1=Primary)
если accountType=1:
[2] previousAccountsLength (uint16 BE)
[P] previousAccounts UTF-8, логины через запятую
[1] licenseLength (uint8)
[M] license UTF-8
[32] initialBlockchainKey32
```
Список 0–10 существующих аккаунтов, без повторов и ссылки на себя (сравнение без регистра). Проверка существования выполняется при новой записи через AddBlock, не при архивном восстановлении. Это публичное заявление, не подтверждение владения; оно не изменяет статус, голоса или доступ прежних аккаунтов. Имя и фамилия необязательны. Тип неизменяем. Новые USER_PARAM `account_role` и `official` запрещены; исторические значения не дают Primary. V1/V2 читаются и восстанавливаются, но не считаются Primary. Производные представления `account_identity_state` и `account_predecessors` используют канонический HEADER; отдельного анализатора нет.
Поле `login` хранит **точное неизменяемое написание идентичности при регистрации**: для новой регистрации `login@namespace` соответствует `[A-Za-z0-9_]+@[a-z0-9_]+`, длина не более 30 байт. Регистр локальной части сохраняется побайтно из Solana PDA или сертификата Arweave; `@namespace` остаётся строчным. `AlexSmith@shine` и `alexsmith@shine` идентифицируют одного человека (по lower-case), но только первый вариант допустим в его HEADER, если именно так он зарегистрирован. `@` не меняет бинарную структуру HEADER: `[loginLength:uint8][login UTF-8 bytes]`. При копировании префикса для следующих fork первый HEADER не меняется. Исторические legacy `[A-Za-z0-9_]+` по-прежнему декодируются, но в новую регистрацию не допускаются. Поле `login` хранит **точное неизменяемое написание идентичности при регистрации**: для новой регистрации `login@namespace` соответствует `[A-Za-z0-9_]+@[a-z0-9_]+`, длина не более 30 байт. Регистр локальной части сохраняется побайтно из Solana PDA или сертификата Arweave; `@namespace` остаётся строчным. `AlexSmith@shine` и `alexsmith@shine` идентифицируют одного человека (по lower-case), но только первый вариант допустим в его HEADER, если именно так он зарегистрирован. `@` не меняет бинарную структуру HEADER: `[loginLength:uint8][login UTF-8 bytes]`. При копировании префикса для следующих fork первый HEADER не меняется. Исторические legacy `[A-Za-z0-9_]+` по-прежнему декодируются, но в новую регистрацию не допускаются.
@@ -45,7 +63,7 @@ AddBlock сверяет HEADER #0 с точным именем в `user_identity
HEADER сам не хранит line-prefix, но является root TECH-линии. HEADER сам не хранит line-prefix, но является root TECH-линии.
После успешной регистрации и автоматического входа клиент вызывает `ensureBlockchainHeader(login, storagePwd)` один раз в общем завершении регистрации (как Solana, так и Arweave). При отсутствии блока №0 клиент создаёт и подписывает HEADER и отправляет его через обычный `AddBlock`. Неудачная отправка **не отменяет** уже подтверждённую регистрацию: существующая логика создания первого пользовательского блока проверит и при необходимости создаст HEADER перед ним. Дополнительной проверки при каждом входе нет. Схема `HEADER v2` расширена константой лицензии; сетевой API AddBlock не меняется. После успешной регистрации и автоматического входа клиент вызывает `ensureBlockchainHeader(login, storagePwd)` один раз в общем завершении регистрации (как Solana, так и Arweave). При отсутствии блока №0 клиент создаёт и подписывает HEADER и отправляет его через обычный `AddBlock`. Неудачная отправка **не отменяет** уже подтверждённую регистрацию: существующая логика создания первого пользовательского блока проверит и при необходимости создаст HEADER перед ним. Дополнительной проверки при каждом входе нет. Схема `HEADER v3` допускает произвольную строку лицензии; сетевой API AddBlock не меняется. Выбор типа и списка сохраняется до отправки HEADER, чтобы повтор не изменил заявление.
### `subType=1` — `TECH_CREATE_CHANNEL` ### `subType=1` — `TECH_CREATE_CHANNEL`
+4
View File
@@ -66,3 +66,7 @@ toBlockHash32=SHA-256(Frame HEADER)
```text ```text
t=conn t=conn
``` ```
## Действующие подтверждения (HEADER V3)
`80` — только между разными Primary; `70` — также только между разными Primary, отправитель должен быть сияющим, получатель не должен отказываться от подтверждений (`not_interested`). Старые `70/80` остаются в архиве, но в графе/счётчиках учитываются только при выполнении этих правил. `71/81` могут отзывать старое заявление. Формат CONNECTION не менялся.
+3 -1
View File
@@ -8,7 +8,7 @@
`subType=1` — текстовое поле профиля: `paramKey + paramValue`. `subType=1` — текстовое поле профиля: `paramKey + paramValue`.
Примеры полей: имя, фамилия, `about`, аватар, web, телефон, роль аккаунта и другие свойства профиля, определённые приложением. Примеры полей: имя, фамилия, `about`, аватар, web, телефон, сияние и другие свойства профиля, определённые приложением.
## Линия профиля ## Линия профиля
@@ -43,3 +43,5 @@ Big-endian:
```text ```text
t=prof t=prof
``` ```
`account_role` / `official` — исторические поля. Новая запись запрещена (в том числе через UpsertUserParam); роль определяется HEADER V3. Сияние (`shine`) остаётся изменяемым.
+11
View File
@@ -1,3 +1,14 @@
## 2026-11-27 — HEADER V3, Primary и подтверждения (schema 46–48)
- Выбор Primary/Alternative при регистрации; подписанный HEADER V3 содержит тип и список заявленных прежних аккаунтов. V1/V2 читаются, но не считаются Primary.
- Основной публичный счётчик лайков показывает только Primary; подробности сохраняют все три категории.
- Официальность неизменяема, оба участника подтверждения обязаны быть разными Primary. Сияние остаётся изменяемым; подтверждать сияние может сияющий Primary. Архивная история сохраняется, неэффективные подтверждения не учитываются.
## 2026-11-27 — HEADER v2 и удаление legacy peer-sync
- HEADER v2: длина лицензии uint8 + 0–255 байт UTF-8; исторический v2 и v1 читаются без переписывания. CONTENT body v2 разрешён только для HEADER №0; новый UI записывает пустую лицензию.
- Удалены старые сервисы прямой репликации блоков и `GetSyncUserProfile`; `ListBlockchainHeads` сохранён для test-publisher. Arweave/Turbo, DM и общий пул соединений сохраняются.
## 2026-11-26 — Minimal M2 (промежуточный код, не деплоить) ## 2026-11-26 — Minimal M2 (промежуточный код, не деплоить)
- AddBlock/HEADER и чтение переключены на полную пару CORE/CONTENT в одном `block_bytes`; hash/ID — CORE, порядковый номер линии вычисляет сервер. Старый SQL и транзакция сохраняются. - AddBlock/HEADER и чтение переключены на полную пару CORE/CONTENT в одном `block_bytes`; hash/ID — CORE, порядковый номер линии вычисляет сервер. Старый SQL и транзакция сохраняются.
+4 -51
View File
@@ -1,56 +1,9 @@
# Синхронизация blockchain между SHiNE-серверами # Синхронизация blockchain между SHiNE-серверами
## Локальная модель хранения Прямая репликация пользовательских блоков между серверами удалена 2026-11-27. Параметры `blockchain.sync.enabled` и `sync.importUserProfileFromPartner.enabled` больше не используются. Список `sync_servers` не нужен; существующая таблица в старой БД не удаляется автоматически. Общий ServerConnectionPool и межсерверная доставка DM остаются, адреса берутся из актуальных access-server routes.
PostgreSQL является единственным локальным хранилищем пользовательских блоков. Файлы `<blockchain>.bch`, `.tmp_bch`, `.write_pending`, `.write_check`, `.resync_pending` не используются. ## Действующая модель
`blocks.block_bytes` хранит полный подписанный ANS-104 DataItem. `blockchain_state` хранит текущую вершину цепочки. PostgreSQL хранит полные пары CORE/CONTENT в `blocks.block_bytes`; `blockchain_state` содержит вершину. Публикация и восстановление выполняются через Arweave/Turbo (`arweave.blocks.publish.enabled`, `arweave.blocks.sync.enabled`). Хеш цепочки — SHA-256 бинарного CORE. Подробности: [актуальный протокол](../CORE-CONTENT-MINIMAL/01_PROTOCOL.md).
## Обычный AddBlock `ListBlockchainHeads` сохранён как read-only техническая операция для test-publisher. `GetSyncUserProfile` удалён. Синхронизация Solana, обработка форков и доставка личных сообщений не меняются.
Все проверки и запись выполняются под lock конкретной chain. После проверки Frame v1, подписи и `prevHash` одна SQL-транзакция записывает block + derived state + новую вершину.
Локально созданный пользовательский блок получает `arweave_publish_pending=true`.
## Периодический peer-to-peer sync
Старый межсерверный P2P sync может получать `GetBlockchainBlock` и применять полученный полный DataItem через `AddBlock`. При divergence full-resync:
1. берёт lock chain;
2. очищает derived rows/blocks/state через `BlockchainResyncCleanupDAO`;
3. пересоздаёт state из актуального пользовательского реестра;
4. последовательно проигрывает удалённую цепочку с блока 0;
5. никаких файловых swap/recovery операций нет.
Этот прямой sync включается параметром:
```properties
blockchain.sync.enabled=true
```
Для проверки режима без прямых server-to-server связей его можно выключить в override-конфиге сервера:
```properties
blockchain.sync.enabled=false
```
При выключенном прямом sync сервер по-прежнему может синхронизировать пользователей из Solana и импортировать пользовательские блоки через Arweave, если включён `arweave.blocks.sync.enabled`.
## Arweave sync
Дополнительно каждый сервер может независимо включить `ArweaveBlockSyncScheduler`.
Он ищет child DataItems по тестовому тегу `App=test5592`, проверяет их и импортирует через ту же бизнес-проверку AddBlock. Импортированные блоки не публикуются повторно. Владелец DataItem сверяется либо с актуальным Solana PDA, либо с уже проверенным локальным сертификатом бесплатной регистрации (`FREE_CERT`); для `FREE_CERT` допустима только chain `login-001` с ключом из сертификата.
Если блоки обнаружены не по порядку, persistent queue оставляет более поздние блоки pending до появления предыдущих.
## Источник истины для цепочки
Arweave не участвует в вычислении SHiNE chain hash:
```text
block_hash = SHA256(FrameV1Bytes)
next.prevHash32 = block_hash
```
Поэтому цепочка остаётся проверяемой и переносимой независимо от конкретного storage backend.
+1 -1
View File
@@ -3,7 +3,7 @@
Бинарный протокол не переизобретать. Источник: [PROTOCOL.md первой попытки](../../reference/core-content-attempt-01/handoff-core-content/docs/PROTOCOL.md), с техническими уточнениями формата из [Stage A](../../reference/core-content-attempt-01/docs/Blockchain/20_CORE_CONTENT_STAGE_A.md) и [MASTER_PLAN](../../reference/core-content-attempt-01/handoff-core-content/docs/MASTER_PLAN.md) (только уточнения протокола, не прежний план реализации). Проверочные векторы: [TSV](../../reference/core-content-attempt-01/docs/Blockchain/vectors/core-content-v1.tsv). Бинарный протокол не переизобретать. Источник: [PROTOCOL.md первой попытки](../../reference/core-content-attempt-01/handoff-core-content/docs/PROTOCOL.md), с техническими уточнениями формата из [Stage A](../../reference/core-content-attempt-01/docs/Blockchain/20_CORE_CONTENT_STAGE_A.md) и [MASTER_PLAN](../../reference/core-content-attempt-01/handoff-core-content/docs/MASTER_PLAN.md) (только уточнения протокола, не прежний план реализации). Проверочные векторы: [TSV](../../reference/core-content-attempt-01/docs/Blockchain/vectors/core-content-v1.tsv).
- CORE v2: BigEndian, u8 frameCode=1, prevCoreHash:32, blockNumber:4, timestamp:8, contentHash:32, contentDataItemId:32. 109 байт. При наличии линии lineCode:4, prevLineBlockNumber:4, prevLineCoreHash:32; 149 байт. HEADER №0 без линии, нулевой prevCoreHash. Глобальные номера 0..2147482623. - CORE v2: BigEndian, u8 frameCode=1, prevCoreHash:32, blockNumber:4, timestamp:8, contentHash:32, contentDataItemId:32. 109 байт. При наличии линии lineCode:4, prevLineBlockNumber:4, prevLineCoreHash:32; 149 байт. HEADER №0 без линии, нулевой prevCoreHash. Глобальные номера 0..2147482623.
- CONTENT v1: u8 contentCode=1, type/subType/version по 2 байта, смысловое тело. Без старых структурных префиксов, back32 и подписанного порядкового номера линии. HEADER без CC0; смысловые target-поля сохраняются. Полная матрица типов — в исходной спецификации и ContentBodyParser. - CONTENT v1: u8 contentCode=1, type/subType/version по 2 байта, смысловое тело. Без старых структурных префиксов, back32 и подписанного порядкового номера линии. HEADER body v1 без лицензии или v2 с `[u8 licenseLength][UTF-8 license]` между login и ключом; исторический v2 с фиксированным `license:CC0-1.0` также читается. Новый UI записывает HEADER v3: после login добавляется u8 accountType (0=Alternative, 1=Primary), для Primary — u16 BE длина UTF-8 CSV и список 0–10 прежних аккаунтов, далее лицензия (по умолчанию пустая) и ключ. V1/V2 читаются исторически, но не дают Primary. Только V3 type=1 даёт официальный голос; подтверждения `70/80` действуют только между разными Primary (для `70` также требуется сияющий отправитель и согласие цели). `account_role`/`official` больше не записываются. Смысловые target-поля сохраняются. Полная матрица типов — в исходной спецификации и ContentBodyParser.
- Подписывается CONTENT первым (без поисковых тегов); затем CORE тем же ключом с подписанными App=test5595, n и условным l. Каноническая форма и уникальность тегов проверяются. Сертификат регистрации отдельный DataItem, t=reg; не смешивать с CORE. Namespace Solana/регистрации не менять автоматически. - Подписывается CONTENT первым (без поисковых тегов); затем CORE тем же ключом с подписанными App=test5595, n и условным l. Каноническая форма и уникальность тегов проверяются. Сертификат регистрации отдельный DataItem, t=reg; не смешивать с CORE. Namespace Solana/регистрации не менять автоматически.
- SHA-256 бинарных CORE/CONTENT != ANS-104 ID (SHA-256 подписи). Ссылки глобальной истории и линий используют хеш бинарного CORE. ID контента и хеш из CORE должны совпасть с полученными байтами; обе подписи проверяются и owner совпадает с разрешённым ключом для события/эпохи. Не доверять поисковому индексу. - SHA-256 бинарных CORE/CONTENT != ANS-104 ID (SHA-256 подписи). Ссылки глобальной истории и линий используют хеш бинарного CORE. ID контента и хеш из CORE должны совпасть с полученными байтами; обе подписи проверяются и owner совпадает с разрешённым ключом для события/эпохи. Не доверять поисковому индексу.
- Линии: основной канал 0; пользовательский канал — глобальный номер CREATE_CHANNEL; системные PROFILE=2147483645 (P), CONNECTION=2147483646 (C), TECH=2147483647 (T). Корень системных линий/канала 0 — HEADER; корень пользовательского канала — CREATE_CHANNEL, сам CREATE_CHANNEL находится в TECH. Сервер проверяет актуальный канонический хвост; внутренний индекс линии вычисляется сервером. - Линии: основной канал 0; пользовательский канал — глобальный номер CREATE_CHANNEL; системные PROFILE=2147483645 (P), CONNECTION=2147483646 (C), TECH=2147483647 (T). Корень системных линий/канала 0 — HEADER; корень пользовательского канала — CREATE_CHANNEL, сам CREATE_CHANNEL находится в TECH. Сервер проверяет актуальный канонический хвост; внутренний индекс линии вычисляется сервером.
+1 -1
View File
@@ -3,7 +3,7 @@
- M0: запустить доступные исходные тесты на неизменённом baseline, записать реальные команды, версии и результаты. Не считать прежние отчёты подтверждением новой ветки. - M0: запустить доступные исходные тесты на неизменённом baseline, записать реальные команды, версии и результаты. Не считать прежние отчёты подтверждением новой ветки.
- M1: 109/149 bytes, HEADER, обе подписи/owner, hash/ID/tags, неправильный prev, truncated/oversized envelope, неверный размер, duplicate tags, тип/линия mismatch; Java↔JS↔Python vectors; сырые подписанные bytes сохраняются без изменения. - M1: 109/149 bytes, HEADER, обе подписи/owner, hash/ID/tags, неправильный prev, truncated/oversized envelope, неверный размер, duplicate tags, тип/линия mismatch; Java↔JS↔Python vectors; сырые подписанные bytes сохраняются без изменения.
- M2: одна строка/событие и одна транзакция, duplicate/exact retry, wrong prev/line/target, quota, rollback, root CREATE_CHANNEL, системные линии, канонические индексы, чтение прежними API. Сравнить нормализованное поведение с baseline. M2 автономный ordinal/парсер PASS; настоящая БД, полная компиляция и WS integration ещё NOT RUN (см. M2_REPORT.md). - M2: одна строка/событие и одна транзакция, duplicate/exact retry, wrong prev/line/target, quota, rollback, root CREATE_CHANNEL, системные линии, канонические индексы, чтение прежними API. Сравнить нормализованное поведение с baseline. M2 автономный ordinal/парсер PASS; настоящая БД, полная компиляция и WS integration ещё NOT RUN (см. M2_REPORT.md).
- M3: free и paid registration, HEADER без CC0, login, POST/EDIT/REPLY/LIKE/подписки/профиль, история, backup/proof, unknown-result retry; используемый remote signer не должен подписывать старый Frame. M3: 220 Node PASS, 8 portable C++ vectors PASS; полноценная free/paid registration, firmware build/ESP32 и WS E2E ещё NOT RUN. - M3: free и paid registration, HEADER v2 с произвольной лицензией (по умолчанию пустой), совместимость с v1 и историческим v2, login, POST/EDIT/REPLY/LIKE/подписки/профиль, история, backup/proof, unknown-result retry; используемый remote signer не должен подписывать старый Frame. M3: 220 Node PASS, 8 portable C++ vectors PASS; полноценная free/paid registration, firmware build/ESP32 и WS E2E ещё NOT RUN.
- M4: fake Turbo/gateway без платных операций — правильный порядок, ошибка CONTENT, ошибка CORE после CONTENT, retry точных bytes, restart, duplicate, задержка discovery, MISSING/INVALID, отдельный registration certificate. Сверка цепочки после импорта в чистую тестовую БД. Проверить, что не теряется курсор и не загрязняются социальные индексы. - M4: fake Turbo/gateway без платных операций — правильный порядок, ошибка CONTENT, ошибка CORE после CONTENT, retry точных bytes, restart, duplicate, задержка discovery, MISSING/INVALID, отдельный registration certificate. Сверка цепочки после импорта в чистую тестовую БД. Проверить, что не теряется курсор и не загрязняются социальные индексы.
- M5: начало/отмена/завершение ротации, повтор, FORK назад, новый хвост, канонический старый префикс, отказ неверного ключа, кандидат и его публикация, отметка прочтения clamp, проверка независимых данных по старому сценарию. - M5: начало/отмена/завершение ротации, повтор, FORK назад, новый хвост, канонический старый префикс, отказ неверного ключа, кандидат и его публикация, отметка прочтения clamp, проверка независимых данных по старому сценарию.
- M6: regression auth/DM/звонки/кошельки/уведомления/каналы/профили; smoke и реальные E2E только на разрешённой отдельной среде. Проверка неактивности прямого blockchain sync, активности разрешённого Solana/Arweave sync. Проверить docs и архив. Не путать unit PASS с deployment acceptance. - M6: regression auth/DM/звонки/кошельки/уведомления/каналы/профили; smoke и реальные E2E только на разрешённой отдельной среде. Проверка неактивности прямого blockchain sync, активности разрешённого Solana/Arweave sync. Проверить docs и архив. Не путать unit PASS с deployment acceptance.
@@ -80,5 +80,4 @@ DeleteMessage и DeleteConversation доставляют подписанный
- ACK-флаги synced; - ACK-флаги synced;
- периодический DM-backfill между access-серверами. - периодический DM-backfill между access-серверами.
Блокчейн-синхронизация через server-PDA sync_servers остаётся отдельным Прямая блокчейн-синхронизация через server-PDA sync_servers удалена. Блоки восстанавливаются через Arweave/Turbo; доставка DM независима.
механизмом и продолжает работать.
@@ -200,7 +200,7 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает
- пользовательские подписи; - пользовательские подписи;
- deliveryState и retry-воркер; - deliveryState и retry-воркер;
- read-receipts; - read-receipts;
- синхронизацию пользовательских блокчейнов через server-PDA sync_servers; - восстановление пользовательских блокчейнов через Arweave/Turbo;
- общий постоянный WSS ServerConnectionPool. - общий постоянный WSS ServerConnectionPool.
## UI списка личных чатов — фильтры и отображение времени (2026-08-28) ## UI списка личных чатов — фильтры и отображение времени (2026-08-28)
@@ -1,13 +1,13 @@
import { t } from '../i18n/index.js'; import { t } from '../i18n/index.js';
/** В выборе тарифа счётчик не показываем: он начинается с логина. */ /** В выборе тарифа счётчик не показываем: он начинается с логина. */
export function createRegistrationStepper(step) { export function createRegistrationStepper(step) {
const current = Math.max(1, Math.min(3, Number(step) || 1)); const current = Math.max(1, Math.min(4, Number(step) || 1));
const wrapper = document.createElement('div'); const wrapper = document.createElement('div');
wrapper.className = 'signup-stepper'; wrapper.className = 'signup-stepper';
wrapper.setAttribute('aria-label', t('screens.registration_stepper.text_001', { value1: current })); wrapper.setAttribute('aria-label', t('screens.registration_stepper.text_001', { value1: current }));
const dots = document.createElement('div'); const dots = document.createElement('div');
dots.className = 'signup-stepper__dots'; dots.className = 'signup-stepper__dots';
for (let i = 1; i <= 3; i += 1) { for (let i = 1; i <= 4; i += 1) {
const dot = document.createElement('span'); const dot = document.createElement('span');
dot.className = `signup-stepper__dot${i === current ? ' is-active' : ''}${i < current ? ' is-complete' : ''}`; dot.className = `signup-stepper__dot${i === current ? ' is-active' : ''}${i < current ? ' is-complete' : ''}`;
dots.append(dot); dots.append(dot);
+22 -5
View File
@@ -2545,7 +2545,7 @@
"text_139": "Channel ID's not ready.", "text_139": "Channel ID's not ready.",
"text_140": "Channel ID's not ready.", "text_140": "Channel ID's not ready.",
"text_141": "<span class=\"channel-header-title\">Channel</span><span class=\"channel-header-owner\">&nbsp;</span>", "text_141": "<span class=\"channel-header-title\">Channel</span><span class=\"channel-header-owner\">&nbsp;</span>",
"text_150": "View statistics and list of likes: {value1}", "text_150": "View statistics and list of likes. Primary account likes: {value1}",
"text_151": "Open discussion, answers: {value1}", "text_151": "Open discussion, answers: {value1}",
"text_145": "The interlocutor {value1} has not yet created a personal response chat.", "text_145": "The interlocutor {value1} has not yet created a personal response chat.",
"text_146": "modified by {value1}", "text_146": "modified by {value1}",
@@ -3151,13 +3151,13 @@
"text_115": "{value1} • Record", "text_115": "{value1} • Record",
"text_116": "Comments · {value1}", "text_116": "Comments · {value1}",
"text_119": "Answer {value1}...", "text_119": "Answer {value1}...",
"text_103": "View the statistics of likes: {value1}", "text_103": "View like statistics. Primary account likes: {value1}",
"text_106": "Answer for {value1}. Turn to his comment", "text_106": "Answer for {value1}. Turn to his comment",
"text_092": "Could not create a discussion link.", "text_092": "Could not create a discussion link.",
"text_098": "Message in the {value1} channel", "text_098": "Message in the {value1} channel",
"text_109": "Action with the comment by {value1}", "text_109": "Action with the comment by {value1}",
"text_110": "Responses to this comment · {value1}", "text_110": "Responses to this comment · {value1}",
"text_107": "Likes statistics: {value1}", "text_107": "Like statistics. Primary account likes: {value1}",
"text_108": "Answer {value1}", "text_108": "Answer {value1}",
"text_111": "{value1} {value2}", "text_111": "{value1} {value2}",
"text_112": "Response {value1} · {value2}", "text_112": "Response {value1} · {value2}",
@@ -4226,9 +4226,26 @@
"text_001": "Select \"{value1}\" section", "text_001": "Select \"{value1}\" section",
"text_002": "{value1}: {value2}. Select a section" "text_002": "{value1}: {value2}. Select a section"
}, },
"registration_identity": {
"title": "Choose your account type",
"immutable": "The account type is chosen once at registration and cannot be changed later.",
"primary": "Primary account",
"primary_detail": "SHiNE counts votes from real people. Each person is entitled to only one primary account.",
"alternative": "Alternative account",
"alternative_detail": "You may have any number of alternative accounts. Likes and ratings from alternative accounts are counted separately from votes of real people using primary accounts.",
"previous_detail": "If you previously had primary accounts, list them. Analysis systems can trace your identity history through social connections, for example when friends move from an old account to your new one. This is only your declaration; previous accounts are not blocked and their votes do not change for now.",
"disclosure": "Your declaration will be publicly recorded in the blockchain and preserved in the public blockchain archive. Analysis systems may check the account status in the future. If you provide false information, it will remain in the public blockchain history. Proof of ownership of previous accounts is not required.",
"add": "+ Add account",
"remove": "Remove from list",
"search": "Login or user name",
"find": "Search",
"not_found": "No matching accounts found.",
"search_error": "Search failed.",
"next": "Continue"
},
"registration_stepper": { "registration_stepper": {
"text_001": "Registration: step {value1} out of 3", "text_001": "Registration: step {value1} out of 4",
"text_002": "Step {value1} of 3" "text_002": "Step {value1} of 4"
}, },
"network_version_switcher": { "network_version_switcher": {
"text_001": "<span>Version:</span>", "text_001": "<span>Version:</span>",
+22 -5
View File
@@ -2690,7 +2690,7 @@
"text_147": "История #{value1}", "text_147": "История #{value1}",
"text_148": "Удалённое сообщение от {value1}", "text_148": "Удалённое сообщение от {value1}",
"text_149": "История #{value1}", "text_149": "История #{value1}",
"text_150": "Посмотреть статистику и список лайков: {value1}", "text_150": "Посмотреть статистику и список лайков. Лайки основных аккаунтов: {value1}",
"text_151": "Открыть обсуждение, ответов: {value1}", "text_151": "Открыть обсуждение, ответов: {value1}",
"text_152": "Публикация №{value1} не найдена в канале.", "text_152": "Публикация №{value1} не найдена в канале.",
"text_153": "Не удалось сохранить, сколько сообщений прочитано.{value1}{value2}", "text_153": "Не удалось сохранить, сколько сообщений прочитано.{value1}{value2}",
@@ -3376,11 +3376,11 @@
"text_100": "История #{value1}", "text_100": "История #{value1}",
"text_101": "Удалённое сообщение от {value1}", "text_101": "Удалённое сообщение от {value1}",
"text_102": "История #{value1}", "text_102": "История #{value1}",
"text_103": "Посмотреть статистику лайков: {value1}", "text_103": "Посмотреть статистику лайков. Лайки основных аккаунтов: {value1}",
"text_104": "Открыть обсуждение, ответов: {value1}", "text_104": "Открыть обсуждение, ответов: {value1}",
"text_105": "Профиль {value1}", "text_105": "Профиль {value1}",
"text_106": "Ответ для {value1}. Перейти к его комментарию", "text_106": "Ответ для {value1}. Перейти к его комментарию",
"text_107": "Статистика лайков: {value1}", "text_107": "Статистика лайков. Лайки основных аккаунтов: {value1}",
"text_108": "Ответить {value1}", "text_108": "Ответить {value1}",
"text_109": "Действия с комментарием {value1}", "text_109": "Действия с комментарием {value1}",
"text_110": "Ответы на этот комментарий · {value1}", "text_110": "Ответы на этот комментарий · {value1}",
@@ -4229,9 +4229,26 @@
"dropdown_menu": { "dropdown_menu": {
"text_001": "Назад: {value1}" "text_001": "Назад: {value1}"
}, },
"registration_identity": {
"title": "Выберите тип аккаунта",
"immutable": "Тип аккаунта выбирается один раз при регистрации и впоследствии не может быть изменён.",
"primary": "Основной аккаунт (Primary)",
"primary_detail": "В SHiNE учитываются голоса реальных людей. Каждый человек имеет право иметь только один основной аккаунт.",
"alternative": "Альтернативный аккаунт (Alternative)",
"alternative_detail": "Вы можете иметь любое количество альтернативных аккаунтов. Лайки и рейтинги альтернативных аккаунтов учитываются отдельно от голосов реальных людей с основных аккаунтов.",
"previous_detail": "Если у вас ранее были основные аккаунты, укажите их. Система анализа сможет проследить историю вашей личности по социальным связям, например когда друзья переходят от прежнего аккаунта к новому. Это только ваше заявление: прежние аккаунты не блокируются и их голоса пока не меняются.",
"disclosure": "Ваше заявление будет публично записано в блокчейн и сохранено в публичном блокчейн-архиве. Статус аккаунта в будущем сможет проверять система анализа. Если вы предоставите ложную информацию, она останется в публичной истории блокчейна. Подтверждать владение прежними аккаунтами не требуется.",
"add": "+ Добавить аккаунт",
"remove": "Удалить из списка",
"search": "Логин или имя пользователя",
"find": "Найти",
"not_found": "Подходящие аккаунты не найдены.",
"search_error": "Не удалось выполнить поиск.",
"next": "Продолжить"
},
"registration_stepper": { "registration_stepper": {
"text_001": "Регистрация: шаг {value1} из 3", "text_001": "Регистрация: шаг {value1} из 4",
"text_002": "Шаг {value1} из 3" "text_002": "Шаг {value1} из 4"
}, },
"topbar_filter_title": { "topbar_filter_title": {
"text_001": "Выбрать раздел «{value1}»", "text_001": "Выбрать раздел «{value1}»",
+8 -9
View File
@@ -6,6 +6,7 @@ import { appendShineMessageLinks } from '../services/shine-message-links.js';
import { confirmDialog } from '../components/confirm-dialog.js'; import { confirmDialog } from '../components/confirm-dialog.js';
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js'; import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js'; import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
import { publicLikeCount, hasLikeStatistics } from '../services/public-like-count.js';
import { iconHtml } from '../components/ui-icon.js'; import { iconHtml } from '../components/ui-icon.js';
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js'; import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
import { attachMessageMenu } from '../components/message-menu.js'; import { attachMessageMenu } from '../components/message-menu.js';
@@ -624,9 +625,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
const versions = Array.isArray(node?.versions) ? node.versions : []; const versions = Array.isArray(node?.versions) ? node.versions : [];
const versionsTotal = Number(node?.versionsTotal || versions.length || 1); const versionsTotal = Number(node?.versionsTotal || versions.length || 1);
const text = resolveNodeText(node) || (versionsTotal > 1 ? t('screens.channel_thread_view.text_060') : t('screens.channel_thread_view.text_061')); const text = resolveNodeText(node) || (versionsTotal > 1 ? t('screens.channel_thread_view.text_060') : t('screens.channel_thread_view.text_061'));
const likes = Number(node?.likesCount || 0); const likes = publicLikeCount(node);
const primaryLikes = Number(node?.primaryLikesCount || 0);
const shiningLikes = Number(node?.shiningLikesCount || 0);
const replies = replyCountOf(node); const replies = replyCountOf(node);
const ratings = Number(node?.ratingsCount || 0); const ratings = Number(node?.ratingsCount || 0);
const isOwnMessage = Boolean(state.session.isAuthorized && state.session.login) && String(node?.authorLogin || '').trim().toLowerCase() === String(state.session.login).trim().toLowerCase(); const isOwnMessage = Boolean(state.session.isAuthorized && state.session.login) && String(node?.authorLogin || '').trim().toLowerCase() === String(state.session.login).trim().toLowerCase();
@@ -836,7 +835,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
const likesStatsButton = document.createElement('button'); const likesStatsButton = document.createElement('button');
likesStatsButton.type = 'button'; likesStatsButton.type = 'button';
likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats'; likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats';
likesStatsButton.textContent = String(Number(likes) || ''); likesStatsButton.textContent = String(likes);
likesStatsButton.setAttribute('aria-label', t('screens.channel_thread_view.text_103', { value1: likes })); likesStatsButton.setAttribute('aria-label', t('screens.channel_thread_view.text_103', { value1: likes }));
likesStatsButton.addEventListener('click', (event) => { likesStatsButton.addEventListener('click', (event) => {
event.stopPropagation(); event.stopPropagation();
@@ -920,8 +919,8 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; } if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; }
void handlers.onRepost?.(target); void handlers.onRepost?.(target);
}); });
if (threadsLayout) actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton); if (threadsLayout) actions.append(likeButton, ...(hasLikeStatistics(node) ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
else actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), shareButton, discussionButton); else actions.append(likeButton, ...(hasLikeStatistics(node) ? [likesStatsButton] : []), shareButton, discussionButton);
const supportBtn = document.createElement('button'); const supportBtn = document.createElement('button');
supportBtn.type = 'button'; supportBtn.type = 'button';
supportBtn.className = 'ui-button channel-action-item channel-action-support'; supportBtn.className = 'ui-button channel-action-item channel-action-support';
@@ -1169,7 +1168,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
setMessageReactionState(target, node?.likedByMe === true ? 'liked' : 'unliked'); setMessageReactionState(target, node?.likedByMe === true ? 'liked' : 'unliked');
const liked = getMessageReactionState(target) === 'liked'; const liked = getMessageReactionState(target) === 'liked';
const likes = Number(node?.likesCount || 0); const likes = publicLikeCount(node);
const like = document.createElement('button'); const like = document.createElement('button');
like.type = 'button'; like.type = 'button';
like.className = `channel-action-item thread-comment__like${liked ? ' is-liked' : ''}`; like.className = `channel-action-item thread-comment__like${liked ? ' is-liked' : ''}`;
@@ -1186,7 +1185,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
const commentLikeStats = document.createElement('button'); const commentLikeStats = document.createElement('button');
commentLikeStats.type = 'button'; commentLikeStats.type = 'button';
commentLikeStats.className = 'channel-action-item thread-comment__like-count'; commentLikeStats.className = 'channel-action-item thread-comment__like-count';
commentLikeStats.textContent = String(likes || ''); commentLikeStats.textContent = String(likes);
commentLikeStats.setAttribute('aria-label', t('screens.channel_thread_view.text_107', { value1: likes })); commentLikeStats.setAttribute('aria-label', t('screens.channel_thread_view.text_107', { value1: likes }));
commentLikeStats.addEventListener('click', () => { void showLikeStatistics({ counts: node }); }); commentLikeStats.addEventListener('click', () => { void showLikeStatistics({ counts: node }); });
@@ -1247,7 +1246,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
repost.addEventListener('click', () => (REPOSTS_ENABLED ? handlers.onRepost?.(target) : notifyRepostSoon())); repost.addEventListener('click', () => (REPOSTS_ENABLED ? handlers.onRepost?.(target) : notifyRepostSoon()));
// Ряд действий как у записи канала: лайк, ответы, репост, поделиться. // Ряд действий как у записи канала: лайк, ответы, репост, поделиться.
actions.append(like, ...(likes > 0 ? [commentLikeStats] : []), reply, repost, share); actions.append(like, ...(hasLikeStatistics(node) ? [commentLikeStats] : []), reply, repost, share);
const supportBtn = document.createElement('button'); const supportBtn = document.createElement('button');
supportBtn.type = 'button'; supportBtn.type = 'button';
supportBtn.className = 'channel-action-item thread-comment__support'; supportBtn.className = 'channel-action-item thread-comment__support';
+6 -5
View File
@@ -7,6 +7,7 @@ import { appendShineMessageLinks } from '../services/shine-message-links.js';
import { confirmDialog } from '../components/confirm-dialog.js'; import { confirmDialog } from '../components/confirm-dialog.js';
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js'; import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js'; import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
import { publicLikeCount, hasLikeStatistics } from '../services/public-like-count.js';
import { iconHtml } from '../components/ui-icon.js'; import { iconHtml } from '../components/ui-icon.js';
import { createOverflowDots } from '../components/overflow-dots.js'; import { createOverflowDots } from '../components/overflow-dots.js';
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js'; import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
@@ -1990,7 +1991,7 @@ function renderPostCard(post, {
<span class="channel-action-label">${isPending ? t('screens.channel_view.text_096') : t('screens.channel_view.text_097')}</span> <span class="channel-action-label">${isPending ? t('screens.channel_view.text_096') : t('screens.channel_view.text_097')}</span>
`; `;
likeButton.setAttribute('aria-pressed', String(isLiked)); likeButton.setAttribute('aria-pressed', String(isLiked));
setActionTitle(likeButton, isPending ? t('screens.channel_view.text_098') : `${isLiked ? t('screens.channel_view.text_099') : t('screens.channel_view.text_100')}, ${post.likesCount || 0}`); setActionTitle(likeButton, isPending ? t('screens.channel_view.text_098') : `${isLiked ? t('screens.channel_view.text_099') : t('screens.channel_view.text_100')}, ${publicLikeCount(post)}`);
likeButton.disabled = isPending; likeButton.disabled = isPending;
likeButton.addEventListener('click', async (event) => { likeButton.addEventListener('click', async (event) => {
event.stopPropagation(); event.stopPropagation();
@@ -2009,8 +2010,8 @@ function renderPostCard(post, {
const likesStatsButton = document.createElement('button'); const likesStatsButton = document.createElement('button');
likesStatsButton.type = 'button'; likesStatsButton.type = 'button';
likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats'; likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats';
likesStatsButton.textContent = String(Number(post.likesCount) || ''); likesStatsButton.textContent = String(publicLikeCount(post));
likesStatsButton.setAttribute('aria-label', t('screens.channel_view.text_150', { value1: Number(post.likesCount) || 0 })); likesStatsButton.setAttribute('aria-label', t('screens.channel_view.text_150', { value1: publicLikeCount(post) }));
likesStatsButton.addEventListener('click', (event) => { likesStatsButton.addEventListener('click', (event) => {
event.stopPropagation(); event.stopPropagation();
void showLikeStatistics({ void showLikeStatistics({
@@ -2158,8 +2159,8 @@ function renderPostCard(post, {
} }); } });
}); });
// Четыре кнопки как в Threads: лайк, ответы, репост, поделиться. // Четыре кнопки как в Threads: лайк, ответы, репост, поделиться.
if (threadsLayout) actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton); if (threadsLayout) actions.append(likeButton, ...(hasLikeStatistics(post) ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
else actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), shareButton, discussionButton); else actions.append(likeButton, ...(hasLikeStatistics(post) ? [likesStatsButton] : []), shareButton, discussionButton);
actions.append(supportButton); actions.append(supportButton);
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) { if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
const streamRoute = makeShineChannelStreamRoute({ const streamRoute = makeShineChannelStreamRoute({
+19 -65
View File
@@ -12,7 +12,6 @@ import {
PROFILE_GENDER_MALE, PROFILE_GENDER_MALE,
PROFILE_GENDER_UNKNOWN, PROFILE_GENDER_UNKNOWN,
PROFILE_ACCOUNT_ROLE_PRIMARY, PROFILE_ACCOUNT_ROLE_PRIMARY,
PROFILE_ACCOUNT_ROLE_NON_VOTING,
PROFILE_SHINE_SHINING, PROFILE_SHINE_SHINING,
PROFILE_SHINE_UNKNOWN, PROFILE_SHINE_UNKNOWN,
loadProfileSnapshot, loadProfileSnapshot,
@@ -36,18 +35,6 @@ function shineStatusLabel(value) {
function officialSteps(firstName, lastName) {
const name = `${firstName} ${lastName}`.trim();
return [
{ title: t('dialogs.final.consent.official_steps.odin_chelovek_odin_ofitsialnyy_akkaunt'), text: t('dialogs.final.consent.official_steps.ofitsialnyy_akkaunt_vashe_zayavlenie_chto_eto_vash') },
{ title: t('dialogs.final.consent.official_steps.priznanie_zavisit_ot_drugih_lyudey'), text: t('dialogs.final.consent.official_steps.samo_zayavlenie_ne_delaet_lichnost_proverennoy_dru') },
{ title: t('dialogs.final.consent.official_steps.istoriya_perezhivaet_akkaunt'), text: t('dialogs.final.consent.official_steps.esli_vy_poteryaete_dostup_mozhno_zaregistrirovat_n') },
{ title: t('dialogs.final.consent.official_steps.eto_deystvitelno_vy'), text: t('dialogs.final.consent.official_steps.v_profile_ukazano_value1_podtverzhdayte_tolko_esli', { value1: name }), accept: t('dialogs.final.consent.official_steps.podtverzhdayu_chto_value1_moi_nastoyaschie_imya_i', { value1: name }) },
{ title: t('dialogs.final.consent.official_steps.podtverzhdaya_drugih_otvechayte_za_svoi_slova'), text: t('dialogs.final.consent.official_steps.ofitsialnyy_akkaunt_mozhet_podtverzhdat_osnovnye_a'), accept: t('dialogs.final.consent.official_steps.ponimayu_otvetstvennost_za_svoi_podtverzhdeniya') },
{ title: t('dialogs.final.consent.official_steps.publichnaya_zapis'), text: t('dialogs.final.consent.official_steps.zayavlenie_i_buduschie_podtverzhdeniya_popadayut_v'), accept: t('dialogs.final.consent.official_steps.ya_ponimayu_publichnost_i_dolgovremennoe_hranenie'), button: t('dialogs.final.consent.official_steps.stat_ofitsialnym') },
];
}
function shiningSteps() { return [ function shiningSteps() { return [
{ title: t('dialogs.final.consent.shining_steps.siyayuschiy_ofitsialnyy'), text: t('dialogs.final.consent.shining_steps.otmetit_sebya_siyayuschim_mozhno_i_s_neofitsialnog') }, { title: t('dialogs.final.consent.shining_steps.siyayuschiy_ofitsialnyy'), text: t('dialogs.final.consent.shining_steps.otmetit_sebya_siyayuschim_mozhno_i_s_neofitsialnog') },
{ title: t('dialogs.final.consent.shining_steps.chto_znachit_siyayuschiy'), text: t('dialogs.final.consent.shining_steps.v_shine_eto_chelovek_kotoryy_zanimaetsya_vnutrenni') }, { title: t('dialogs.final.consent.shining_steps.chto_znachit_siyayuschiy'), text: t('dialogs.final.consent.shining_steps.v_shine_eto_chelovek_kotoryy_zanimaetsya_vnutrenni') },
@@ -120,7 +107,7 @@ export function render({ navigate, chrome }) {
const badgesRow = document.createElement('div'); const badgesRow = document.createElement('div');
badgesRow.className = 'chip-row profile-edit-statuses'; badgesRow.className = 'chip-row profile-edit-statuses';
badgesRow.innerHTML = ` badgesRow.innerHTML = `
<button class="chip profile-toggle-btn is-no" type="button" data-status="account_role">${th('screens.profile_edit_view.text_029')}</button> <span class="badge is-no" data-status="account_role">${th('screens.profile_edit_view.text_029')}</span>
<button class="chip profile-toggle-btn is-no" type="button" data-status="shine">${th('screens.profile_edit_view.text_030')}</button> <button class="chip profile-toggle-btn is-no" type="button" data-status="shine">${th('screens.profile_edit_view.text_030')}</button>
`; `;
@@ -138,6 +125,7 @@ export function render({ navigate, chrome }) {
let currentFields = []; let currentFields = [];
let currentAccountRole = ''; let currentAccountRole = '';
let currentAccountType = null;
let currentShineStatus = ''; let currentShineStatus = '';
let currentGender = PROFILE_GENDER_UNKNOWN; let currentGender = PROFILE_GENDER_UNKNOWN;
let statusFlowOpen = false; let statusFlowOpen = false;
@@ -229,7 +217,9 @@ export function render({ navigate, chrome }) {
function updateStatusesUi() { function updateStatusesUi() {
if (accountRoleBtn) { if (accountRoleBtn) {
accountRoleBtn.textContent = t('screens.profile_edit_view.text_020', { value1: accountRoleLabel(currentAccountRole) }); accountRoleBtn.textContent = currentAccountType === 1 ? t('screens.profile_edit_view.text_009')
: currentAccountType === 0 ? t('screens.registration_identity.alternative')
: t('screens.profile_edit_view.text_020', { value1: accountRoleLabel(currentAccountRole) });
accountRoleBtn.classList.remove('is-no', 'is-yes-official', 'is-yes-shine', 'is-not-interested'); accountRoleBtn.classList.remove('is-no', 'is-yes-official', 'is-yes-shine', 'is-not-interested');
accountRoleBtn.classList.add(currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY ? 'is-yes-official' : 'is-no'); accountRoleBtn.classList.add(currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY ? 'is-yes-official' : 'is-no');
} }
@@ -341,13 +331,13 @@ export function render({ navigate, chrome }) {
status.className = 'status-line'; status.className = 'status-line';
status.textContent = t('dialogs.modals.profile_edit_view.label_003'); status.textContent = t('dialogs.modals.profile_edit_view.label_003');
reloadBtn.disabled = true; reloadBtn.disabled = true;
accountRoleBtn.disabled = true;
shineBtn.disabled = true; shineBtn.disabled = true;
try { try {
const snapshot = await loadProfileSnapshot(login); const snapshot = await loadProfileSnapshot(login);
currentFields = snapshot.fields; currentFields = snapshot.fields;
currentAccountRole = snapshot.accountRole || ''; currentAccountRole = snapshot.accountRole || '';
currentAccountType = snapshot.accountType;
currentShineStatus = snapshot.shineStatus || ''; currentShineStatus = snapshot.shineStatus || '';
currentGender = snapshot.gender || PROFILE_GENDER_UNKNOWN; currentGender = snapshot.gender || PROFILE_GENDER_UNKNOWN;
currentAvatar = snapshot.avatar || { value: '', source: '', txId: '', pr: '', timeMs: 0 }; currentAvatar = snapshot.avatar || { value: '', source: '', txId: '', pr: '', timeMs: 0 };
@@ -366,7 +356,6 @@ export function render({ navigate, chrome }) {
showLocalErrorAlert(t('screens.profile_edit_view.text_007'), error); showLocalErrorAlert(t('screens.profile_edit_view.text_007'), error);
} finally { } finally {
reloadBtn.disabled = false; reloadBtn.disabled = false;
accountRoleBtn.disabled = false;
shineBtn.disabled = false; shineBtn.disabled = false;
} }
} }
@@ -409,63 +398,28 @@ export function render({ navigate, chrome }) {
} }
async function onStatusClick(statusKey) { async function onStatusClick(statusKey) {
if (statusFlowOpen) return; if (statusKey !== 'shine' || statusFlowOpen) return;
statusFlowOpen = true; statusFlowOpen = true;
try { try {
const isAccountRole = statusKey === 'account_role'; const alreadyOn = currentShineStatus === PROFILE_SHINE_SHINING;
const alreadyOn = isAccountRole const accepted = alreadyOn ? await confirmDialog({
? currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY title: t('dialogs.final.consent.remove_shining'), text: t('dialogs.pages.profile_edit_view.text_001'),
: currentShineStatus === PROFILE_SHINE_SHINING; confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_002'),
let accepted = false; }) : await confirmConsentSteps({ title: t('dialogs.final.consent.shining_title'), steps: shiningSteps() });
if (alreadyOn) {
accepted = await confirmDialog({
title: isAccountRole ? t('dialogs.final.consent.remove_official') : t('dialogs.final.consent.remove_shining'),
text: t('dialogs.pages.profile_edit_view.text_001'),
confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_002'),
});
} else if (isAccountRole) {
const firstName = String(currentFields.find((field) => field.key === 'first_name')?.value || '').trim();
const lastName = String(currentFields.find((field) => field.key === 'last_name')?.value || '').trim();
if (!firstName || !lastName) {
await confirmDialog({
title: t('dialogs.pages.profile_edit_view.title_003'),
text: t('dialogs.pages.profile_edit_view.text_004'),
confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_005'),
cancelLabel: t('dialogs.pages.profile_edit_view.cancelLabel_006'),
});
return;
}
accepted = await confirmConsentSteps({ title: t('dialogs.final.consent.official_title'), steps: officialSteps(firstName, lastName) });
} else {
accepted = await confirmConsentSteps({ title: t('dialogs.final.consent.shining_title'), steps: shiningSteps() });
}
if (!accepted || !screen.isConnected) return; if (!accepted || !screen.isConnected) return;
const nextValue = isAccountRole status.className = 'status-line'; status.textContent = t('dialogs.modals.profile_edit_view.label_009');
? (alreadyOn ? PROFILE_ACCOUNT_ROLE_NON_VOTING : PROFILE_ACCOUNT_ROLE_PRIMARY)
: (alreadyOn ? PROFILE_SHINE_UNKNOWN : PROFILE_SHINE_SHINING);
status.className = 'status-line';
status.textContent = t('dialogs.modals.profile_edit_view.label_009');
accountRoleBtn.disabled = true;
shineBtn.disabled = true; shineBtn.disabled = true;
try { try {
await saveProfileStatus(login, statusKey, nextValue); await saveProfileStatus(login, 'shine', alreadyOn ? PROFILE_SHINE_UNKNOWN : PROFILE_SHINE_SHINING);
if (!screen.isConnected) return; if (screen.isConnected) await refreshProfileSnapshot();
await refreshProfileSnapshot();
} catch (error) { } catch (error) {
if (!screen.isConnected) return; if (!screen.isConnected) return;
status.className = 'status-line is-unavailable'; status.className = 'status-line is-unavailable';
const what = isAccountRole ? t('screens.profile_edit_view.text_017') : t('screens.profile_edit_view.text_018'); const what = t('screens.profile_edit_view.text_018');
status.textContent = t('screens.profile_edit_view.text_022', { value1: what, value2: toUserMessage(error, t('dialogs.modals.profile_edit_view.label_010')) }); status.textContent = t('screens.profile_edit_view.text_022', { value1: what, value2: toUserMessage(error, t('dialogs.modals.profile_edit_view.label_010')) });
showLocalErrorAlert(t('screens.profile_edit_view.text_023', { value1: what }), error); showLocalErrorAlert(t('screens.profile_edit_view.text_023', { value1: what }), error);
} finally { } finally { if (screen.isConnected) shineBtn.disabled = false; }
if (screen.isConnected) { } finally { statusFlowOpen = false; }
accountRoleBtn.disabled = false;
shineBtn.disabled = false;
}
}
} finally {
statusFlowOpen = false;
}
} }
async function onEditFieldClick(fieldKey) { async function onEditFieldClick(fieldKey) {
@@ -547,7 +501,7 @@ export function render({ navigate, chrome }) {
}); });
reloadBtn.addEventListener('click', refreshProfileSnapshot); reloadBtn.addEventListener('click', refreshProfileSnapshot);
accountRoleBtn.addEventListener('click', () => onStatusClick('account_role')); accountRoleBtn.title = t('screens.registration_identity.immutable');
shineBtn.addEventListener('click', () => onStatusClick('shine')); shineBtn.addEventListener('click', () => onStatusClick('shine'));
avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); }); avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); });
+89 -2
View File
@@ -7,6 +7,7 @@ import { createRegistrationStepper } from '../components/registration-stepper.js
import { authService, clearAuthMessages, clearRegistrationDraft, state } from '../state.js'; import { authService, clearAuthMessages, clearRegistrationDraft, state } from '../state.js';
import { PASSWORD_MAX_LENGTH } from '../services/password-words.js'; import { PASSWORD_MAX_LENGTH } from '../services/password-words.js';
import { getRegistrationNamespaces, checkRegistrationLogin } from '../services/registration-v2-api.js'; import { getRegistrationNamespaces, checkRegistrationLogin } from '../services/registration-v2-api.js';
import { savePendingHeaderIdentity } from '../services/pending-header-identity.js';
import { normalizeFullLogin } from '../services/shine-namespace-service.js'; import { normalizeFullLogin } from '../services/shine-namespace-service.js';
export const pageMeta = { id: 'register-view', get title() { return t('screens.register_view.text_001'); }, showAppChrome: false }; export const pageMeta = { id: 'register-view', get title() { return t('screens.register_view.text_001'); }, showAppChrome: false };
@@ -36,6 +37,10 @@ export function render({ navigate }) {
return window.confirm(t('screens.register_view.text_039')); return window.confirm(t('screens.register_view.text_039'));
} }
function goBack() { function goBack() {
if (Number(draft.uiStep) === 3) {
showPassword();
return;
}
if (Number(draft.uiStep) === 2) { if (Number(draft.uiStep) === 2) {
draft.uiStep = 1; draft.uiStep = 1;
showLogin(); showLogin();
@@ -220,7 +225,7 @@ export function render({ navigate }) {
// Hide the password before navigation to prevent a visible flash. // Hide the password before navigation to prevent a visible flash.
input.clearPasswordField(); input.clearPasswordField();
refreshPasswordCount(); refreshPasswordCount();
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view'); showAccountType();
} catch (error) { } catch (error) {
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || t('screens.register_view.text_028'); if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || t('screens.register_view.text_028');
} finally { } finally {
@@ -231,11 +236,93 @@ export function render({ navigate }) {
body.append(heading, description, label, guidance, status, next); body.append(heading, description, label, guidance, status, next);
} }
function showAccountType() {
draft.uiStep = 3;
body.replaceChildren(createRegistrationStepper(3));
const tr = key => t(`screens.registration_identity.${key}`);
const [heading, description] = title(tr('title'), tr('immutable'));
const choices = document.createElement('div'); choices.className = 'stack';
const option = (type, name, detail) => {
const label = document.createElement('label'); label.className = 'stack signup-guidance';
const radio = document.createElement('input'); radio.type = 'radio'; radio.name = 'registration-account-type';
radio.checked = draft.accountType === type;
const titleRow = document.createElement('strong'); titleRow.append(radio, ' ' + tr(name));
const p = document.createElement('p'); p.textContent = tr(detail);
label.append(titleRow, p); choices.append(label);
radio.addEventListener('change', () => { draft.accountType = type; refresh(); });
};
option(1, 'primary', 'primary_detail');
option(0, 'alternative', 'alternative_detail');
const previous = document.createElement('div'); previous.className = 'stack';
const explanation = document.createElement('p'); explanation.textContent = tr('previous_detail');
const disclosure = document.createElement('p'); disclosure.className = 'signup-guidance'; disclosure.textContent = tr('disclosure');
const list = document.createElement('div'); list.className = 'stack';
const add = document.createElement('button'); add.type = 'button'; add.className = 'secondary-btn'; add.textContent = tr('add');
const searchBox = document.createElement('div'); searchBox.className = 'stack'; searchBox.hidden = true;
const input = document.createElement('input'); input.className = 'input'; input.placeholder = tr('search'); input.autocomplete = 'off';
const search = document.createElement('button'); search.type = 'button'; search.className = 'secondary-btn'; search.textContent = tr('find');
const results = document.createElement('div'); results.className = 'stack';
const status = statusLine();
searchBox.append(input, search, results);
previous.append(explanation, list, add, searchBox, disclosure);
const next = document.createElement('button'); next.type = 'button'; next.className = 'primary-btn signup-next'; next.textContent = tr('next');
let queryRevision = 0;
function refresh() {
previous.hidden = draft.accountType !== 1;
next.disabled = draft.accountType === null;
list.replaceChildren();
for (const login of draft.previousAccounts) {
const row = document.createElement('div'); row.className = 'signup-full-login';
const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'secondary-btn'; remove.textContent = '×';
remove.setAttribute('aria-label', `${tr('remove')} ${login}`);
remove.addEventListener('click', () => { draft.previousAccounts = draft.previousAccounts.filter(v => v !== login); refresh(); });
row.append(login, ' ', remove); list.append(row);
}
add.disabled = draft.previousAccounts.length >= 10;
if (add.disabled || draft.accountType !== 1) { searchBox.hidden = true; results.replaceChildren(); queryRevision++; }
}
add.addEventListener('click', () => { searchBox.hidden = false; input.focus(); });
input.addEventListener('input', () => { queryRevision++; results.replaceChildren(); });
input.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); search.click(); } });
search.addEventListener('click', async () => {
const query = input.value.trim(); if (!query) return;
const revision = ++queryRevision; results.replaceChildren(); status.textContent = '';
try {
const users = await authService.searchPeople(query, { limit: 20 });
if (!screen.isConnected || draft.uiStep !== 3 || revision !== queryRevision || draft.accountType !== 1) return;
const seen = new Set([draft.login, ...draft.previousAccounts].map(v => v.toLowerCase()));
for (const user of users) {
const login = String(user?.login || '');
if (!login || seen.has(login.toLowerCase())) continue;
seen.add(login.toLowerCase());
const choose = document.createElement('button'); choose.type = 'button'; choose.className = 'secondary-btn';
choose.textContent = login;
choose.addEventListener('click', () => {
if (draft.previousAccounts.length >= 10 || draft.accountType !== 1 || draft.previousAccounts.some(v => v.toLowerCase() === login.toLowerCase())) return;
draft.previousAccounts.push(login); input.value = ''; searchBox.hidden = true; results.replaceChildren(); queryRevision++; refresh();
});
results.append(choose);
}
if (!results.childElementCount) status.textContent = tr('not_found');
} catch (error) { if (screen.isConnected && revision === queryRevision) status.textContent = error.message || tr('search_error'); }
});
next.addEventListener('click', () => {
if (![0, 1].includes(draft.accountType)) return;
try {
if (draft.accountType === 0) draft.previousAccounts = [];
savePendingHeaderIdentity(draft.login, draft.preGeneratedKeyBundle?.blockchainPair?.publicKeyB64, draft);
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
} catch (error) { status.textContent = error.message; }
});
body.append(heading, description, choices, previous, status, next); refresh();
}
if (flowType !== 'free' && flowType !== 'paid') { if (flowType !== 'free' && flowType !== 'paid') {
queueMicrotask(() => navigate('registration-choice-view')); queueMicrotask(() => navigate('registration-choice-view'));
return screen; return screen;
} }
if (Number(draft.uiStep) === 2 && draft.login) showPassword(); if (Number(draft.uiStep) === 3 && draft.login && draft.preGeneratedKeyBundle) showAccountType();
else if (Number(draft.uiStep) === 2 && draft.login) showPassword();
else showLogin(); else showLogin();
void getRegistrationNamespaces().then(data => { void getRegistrationNamespaces().then(data => {
+5 -2
View File
@@ -12,6 +12,9 @@ export function render({ navigate }) {
const form = document.createElement('div'); const form = document.createElement('div');
form.className = 'card stack registration-form signup-wizard__body'; form.className = 'card stack registration-form signup-wizard__body';
const draft = state.registrationDraft; const draft = state.registrationDraft;
if (![0, 1].includes(draft.accountType) || !draft.preGeneratedKeyBundle) {
queueMicrotask(() => navigate('register-view')); return screen;
}
const title = document.createElement('h1'); const title = document.createElement('h1');
title.className = 'signup-title'; title.className = 'signup-title';
@@ -75,7 +78,7 @@ export function render({ navigate }) {
edit.className = 'ghost-btn'; edit.className = 'ghost-btn';
edit.textContent = t('screens.registration_email_view.text_011'); edit.textContent = t('screens.registration_email_view.text_011');
form.append(createRegistrationStepper(3), title, lead, inputLabel, info, status, next, codeLabel, codeInfo, confirm, resend, edit); form.append(createRegistrationStepper(4), title, lead, inputLabel, info, status, next, codeLabel, codeInfo, confirm, resend, edit);
let disposed = false; let disposed = false;
let emailRequestId = 0; let emailRequestId = 0;
let confirming = false; let confirming = false;
@@ -204,6 +207,6 @@ export function render({ navigate }) {
} else { } else {
showEmail(); showEmail();
} }
screen.append(createTopBar({ title: t('screens.registration_email_view.text_025'), back: { label: '←', onClick: () => { draft.uiStep = 2; navigate('register-view'); } } }), form); screen.append(createTopBar({ title: t('screens.registration_email_view.text_025'), back: { label: '←', onClick: () => { draft.uiStep = 3; navigate('register-view'); } } }), form);
return screen; return screen;
} }
+11 -3
View File
@@ -91,6 +91,8 @@ function clamp(value, min, max) {
} }
export async function completeRegistrationLogin({ navigate, keyBundle }) { export async function completeRegistrationLogin({ navigate, keyBundle }) {
const draft = state.registrationDraft;
if (![0, 1].includes(draft.accountType)) throw new Error('Missing registration account type');
// Финальный вход регистрации нельзя повторять на сокете, который мог // Финальный вход регистрации нельзя повторять на сокете, который мог
// стать авторизованным после частично успешной предыдущей попытки. // стать авторизованным после частично успешной предыдущей попытки.
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true }); authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
@@ -115,7 +117,10 @@ export async function completeRegistrationLogin({ navigate, keyBundle }) {
// После регистрации оба рабочих ключа сохраняются автоматически. // После регистрации оба рабочих ключа сохраняются автоматически.
// Приватный Recovery/root key не записывается на устройство. // Приватный Recovery/root key не записывается на устройство.
try { try {
await authService.persistSelectedKeys(result.login, result.storagePwd, keyBundle); await authService.persistSelectedKeys(result.login, result.storagePwd, keyBundle, {
saveRoot: true, saveBlockchain: true,
headerIdentity: { accountType: draft.accountType, previousAccounts: [...draft.previousAccounts] },
});
} catch (error) { } catch (error) {
console.warn('Не удалось сохранить рабочие ключи после регистрации; текущая сессия продолжает работать', error); console.warn('Не удалось сохранить рабочие ключи после регистрации; текущая сессия продолжает работать', error);
} }
@@ -163,6 +168,9 @@ export async function completeRegistrationLogin({ navigate, keyBundle }) {
export function render({ navigate }) { export function render({ navigate }) {
const screen = document.createElement('section'); const screen = document.createElement('section');
screen.className = 'stack'; screen.className = 'stack';
if (![0, 1].includes(state.registrationDraft.accountType) || !state.registrationDraft.preGeneratedKeyBundle) {
queueMicrotask(() => navigate('register-view')); return screen;
}
const card = document.createElement('div'); const card = document.createElement('div');
card.className = 'card stack registration-payment-card'; card.className = 'card stack registration-payment-card';
@@ -438,14 +446,14 @@ export function render({ navigate }) {
card.append(testHint); card.append(testHint);
} }
card.append(submitButton, status); card.append(submitButton, status);
card.prepend(createRegistrationStepper(3)); card.prepend(createRegistrationStepper(4));
screen.append( screen.append(
createTopBar({ createTopBar({
title: t('screens.registration_payment_view.text_022'), title: t('screens.registration_payment_view.text_022'),
back: { label: '←', onClick: () => { back: { label: '←', onClick: () => {
if (parseBalanceSol(state.registrationPayment.balanceSOL) > 0 && !window.confirm(t('screens.registration_payment_view.text_071'))) return; if (parseBalanceSol(state.registrationPayment.balanceSOL) > 0 && !window.confirm(t('screens.registration_payment_view.text_071'))) return;
state.registrationDraft.uiStep = 2; navigate('register-view'); state.registrationDraft.uiStep = 3; navigate('register-view');
} }, } },
}), }),
card, card,
@@ -1,3 +1,4 @@
import { confirmationRights } from '../services/account-voting.js';
import { t, th } from '../i18n/index.js'; import { t, th } from '../i18n/index.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { confirmDialog } from '../components/confirm-dialog.js'; import { confirmDialog } from '../components/confirm-dialog.js';
@@ -158,11 +159,8 @@ export function render({ route, chrome }) {
} }
function renderBody() { function renderBody() {
// Те же правила, что проверяет сервер (validateConnectionVotingRights): голосует официальный аккаунт, // Совпадает с серверными предикатами; отсутствие HEADER не даёт прав.
// за сияние – основной и сам сияющий; цель не должна отказываться от подтверждений. const { primary: canPrimary, shine: canShine } = confirmationRights(selfCard, targetCard);
const selfPrimary = selfCard?.accountRole === 'primary';
const canPrimary = selfPrimary && targetCard?.accountRole !== 'non_voting';
const canShine = selfPrimary && selfCard?.shineStatus === 'shining' && targetCard?.shineStatus !== 'not_interested';
body.innerHTML = ` body.innerHTML = `
<section class="card stack relation-manage-card relation-manage-card--social"> <section class="card stack relation-manage-card relation-manage-card--social">
@@ -212,6 +210,9 @@ export function render({ route, chrome }) {
const social = button.dataset.socialKind; const social = button.dataset.socialKind;
const confirm = button.dataset.confirm; const confirm = button.dataset.confirm;
if (!social && !confirm) return; if (!social && !confirm) return;
const rights = confirmationRights(selfCard, targetCard);
if (confirm === 'official_account' && !rights.primary) return;
if (confirm === 'shine_confirmed' && !rights.shine) return;
if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; } if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; }
const isAttestation = confirm === 'official_account' || confirm === 'shine_confirmed'; const isAttestation = confirm === 'official_account' || confirm === 'shine_confirmed';
+9 -2
View File
@@ -495,7 +495,14 @@ export function parseRouteFromPath(pathname = '') {
} }
export function getRoute() { export function getRoute() {
return parseRouteFromPath(window.location.pathname || ''); const path = window.location.pathname || '';
// Нормализуем старые ссылки чатов также при прямом входе и Back/Forward.
const pretty = path.replace(/^(\/(?:chat|chat-view)\/)([^/]+)/i, (_, prefix, id) => prefix + id.replace(/%40/gi, '@'));
if (pretty !== path) {
window.history.replaceState(window.history.state, '', pretty + window.location.search + window.location.hash);
if (currentTrackedPath === path) currentTrackedPath = pretty;
}
return parseRouteFromPath(pretty);
} }
export function navigate(path) { export function navigate(path) {
@@ -557,7 +564,7 @@ export function toPrettyPath(path) {
const prettyHead = PRETTY_PATHS.get(head) || head; const prettyHead = PRETTY_PATHS.get(head) || head;
// Старые вызовы навигации могут передавать %40 через encodeURIComponent. // Старые вызовы навигации могут передавать %40 через encodeURIComponent.
// Для публичных SHiNE-путей оставляем @ видимым, сохраняя остальные escape-коды. // Для публичных SHiNE-путей оставляем @ видимым, сохраняя остальные escape-коды.
if (prettyHead.toLowerCase() === 'shine') { if (['shine', 'chat'].includes(prettyHead.toLowerCase())) {
return [prettyHead, ...tail.map((segment) => segment.replace(/%40/gi, '@'))].join('/'); return [prettyHead, ...tail.map((segment) => segment.replace(/%40/gi, '@'))].join('/');
} }
return [prettyHead, ...tail].join('/'); return [prettyHead, ...tail].join('/');
+11
View File
@@ -0,0 +1,11 @@
// Только явно заявленный Primary может участвовать в официальных подтверждениях.
export function accountRoleFromHeader(accountType) {
return accountType === 1 ? 'primary' : accountType === 0 ? 'non_voting' : '';
}
export function confirmationRights(actor, target) {
const a = String(actor?.login || '').trim().toLowerCase();
const b = String(target?.login || '').trim().toLowerCase();
const primary = Boolean(a && b && a !== b && actor?.accountRole === 'primary' && target?.accountRole === 'primary');
return { primary, shine: primary && actor?.shineStatus === 'shining' && target?.shineStatus !== 'not_interested' };
}
+29 -3
View File
@@ -41,6 +41,7 @@ import {
} from './key-vault.js'; } from './key-vault.js';
import { signEventContainer, submitSignedEvent, readStoredLineMeta } from './core-content.js'; import { signEventContainer, submitSignedEvent, readStoredLineMeta } from './core-content.js';
import { defaultServerWs } from '../deploy-config.js'; import { defaultServerWs } from '../deploy-config.js';
import { readPendingHeaderIdentity, clearPendingHeaderIdentity } from './pending-header-identity.js';
const BCH_SUFFIX = '001'; const BCH_SUFFIX = '001';
const ZERO64 = '0'.repeat(64); const ZERO64 = '0'.repeat(64);
@@ -540,11 +541,15 @@ function extractContactsFromDialogs(dialogs) {
return out; return out;
} }
export const HEADER_VERSION = 1; export const HEADER_VERSION = 3;
// Временное значение до утверждения лицензии проекта.
export const HEADER_DEFAULT_LICENSE = '';
function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) { function makeHeaderBodyBytes({ login, initialBlockchainKey32, license = '', accountType = null, previousAccounts = [] }) {
const cleanLogin = String(login || '').trim(); const cleanLogin = String(login || '').trim();
const loginBytes = utf8Bytes(cleanLogin); const loginBytes = utf8Bytes(cleanLogin);
const licenseBytes = utf8Bytes(license);
if (licenseBytes.length > 255) throw new Error('HEADER license must be 0..255 UTF-8 bytes');
const keyBytes = initialBlockchainKey32 instanceof Uint8Array const keyBytes = initialBlockchainKey32 instanceof Uint8Array
? initialBlockchainKey32 ? initialBlockchainKey32
: new Uint8Array(initialBlockchainKey32 || []); : new Uint8Array(initialBlockchainKey32 || []);
@@ -552,10 +557,25 @@ function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
if (keyBytes.length !== 32 || keyBytes.every((value) => value === 0)) { if (keyBytes.length !== 32 || keyBytes.every((value) => value === 0)) {
throw new Error('HEADER initialBlockchainKey32 must be a non-zero 32-byte key'); throw new Error('HEADER initialBlockchainKey32 must be a non-zero 32-byte key');
} }
let identityBytes = new Uint8Array(0);
if (accountType !== null) {
if (accountType !== 0 && accountType !== 1) throw new Error('Invalid HEADER account type');
if (!Array.isArray(previousAccounts) || previousAccounts.length > 10 || (accountType === 0 && previousAccounts.length)) throw new Error('Invalid HEADER previous accounts');
const seen = new Set([cleanLogin.toLowerCase()]);
for (const previous of previousAccounts) {
if (typeof previous !== 'string' || !(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid or duplicate previous account');
seen.add(previous.toLowerCase());
}
const csv = utf8Bytes(previousAccounts.join(','));
identityBytes = accountType === 1 ? concatBytes(int8Byte(1), Uint8Array.of(csv.length >> 8, csv.length & 255), csv) : int8Byte(0);
}
return concatBytes( return concatBytes(
utf8Bytes('SHiNE'), utf8Bytes('SHiNE'),
int8Byte(loginBytes.length), int8Byte(loginBytes.length),
loginBytes, loginBytes,
identityBytes,
int8Byte(licenseBytes.length),
licenseBytes,
keyBytes, keyBytes,
); );
} }
@@ -1270,6 +1290,7 @@ export class AuthService {
...currentSecrets, ...currentSecrets,
clientKey: keyBundle.clientPair.privatePkcs8B64, clientKey: keyBundle.clientPair.privatePkcs8B64,
}; };
if (saveOptions.headerIdentity) secrets.headerIdentity = saveOptions.headerIdentity;
if (saveOptions.saveRoot) secrets.rootKey = keyBundle.rootPair.privatePkcs8B64; if (saveOptions.saveRoot) secrets.rootKey = keyBundle.rootPair.privatePkcs8B64;
if (saveOptions.saveBlockchain) secrets.blockchainKey = keyBundle.blockchainPair.privatePkcs8B64; if (saveOptions.saveBlockchain) secrets.blockchainKey = keyBundle.blockchainPair.privatePkcs8B64;
await saveEncryptedUserSecrets(login, storagePwd, secrets); await saveEncryptedUserSecrets(login, storagePwd, secrets);
@@ -1774,6 +1795,9 @@ export class AuthService {
} }
const registeredLogin = await this.requireRegisteredDisplayLogin(cleanLogin); const registeredLogin = await this.requireRegisteredDisplayLogin(cleanLogin);
// Never invent an account type after a lost registration draft.
const identity = keyBundle?.headerIdentity || readPendingHeaderIdentity(registeredLogin, publicKeyB64);
if (!identity || ![0, 1].includes(identity.accountType)) throw new Error('HEADER identity declaration is missing; resume registration on the original device');
await this.addBlockSigned({ await this.addBlockSigned({
login: cleanLogin, login: cleanLogin,
storagePwd, storagePwd,
@@ -1782,9 +1806,10 @@ export class AuthService {
msgVersion: HEADER_VERSION, msgVersion: HEADER_VERSION,
// HEADER хранит исходный регистр неизменяемого имени из Solana/Arweave. // HEADER хранит исходный регистр неизменяемого имени из Solana/Arweave.
// Нормализация нужна только для уникальности и имени самой цепочки. // Нормализация нужна только для уникальности и имени самой цепочки.
bodyBytes: makeHeaderBodyBytes({ login: registeredLogin, initialBlockchainKey32 }), bodyBytes: makeHeaderBodyBytes({ login: registeredLogin, initialBlockchainKey32, license: HEADER_DEFAULT_LICENSE, accountType: identity.accountType, previousAccounts: identity.previousAccounts }),
_skipHeaderEnsure: true, _skipHeaderEnsure: true,
}); });
clearPendingHeaderIdentity(registeredLogin, publicKeyB64);
return this.getUser(cleanLogin); return this.getUser(cleanLogin);
} }
@@ -3268,6 +3293,7 @@ export class AuthService {
const cleanParam = (param || '').trim(); const cleanParam = (param || '').trim();
const cleanValue = String(value ?? '').trim(); const cleanValue = String(value ?? '').trim();
if (!cleanLogin || !cleanParam) throw new Error('Не переданы login/param.'); if (!cleanLogin || !cleanParam) throw new Error('Не переданы login/param.');
if (['account_role', 'official'].includes(cleanParam.toLowerCase())) throw new Error('account_type_immutable');
if (!cleanValue) throw new Error('Значение параметра не может быть пустым.'); if (!cleanValue) throw new Error('Значение параметра не может быть пустым.');
if (!storagePwd) throw new Error('Не передан storagePwd для подписи AddBlock.'); if (!storagePwd) throw new Error('Не передан storagePwd для подписи AddBlock.');
@@ -125,14 +125,35 @@ function parseTechBody(subType, body, frame) {
if (magic !== 'SHiNE') throw new Error('Неправильная сигнатура HEADER'); if (magic !== 'SHiNE') throw new Error('Неправильная сигнатура HEADER');
const login = reader.textU8('HEADER login'); const login = reader.textU8('HEADER login');
let license = null; let license = null;
if (frame.version === 2) { let accountType = null;
const marker = reader.text(15, 'HEADER license'); let previousAccounts = [];
if (marker !== 'license:CC0-1.0') throw new Error('Неподдерживаемая лицензия HEADER'); if (frame.version === 3) {
license = 'CC0-1.0'; accountType = reader.u8('HEADER account type');
if (accountType !== 0 && accountType !== 1) throw new Error('Invalid HEADER account type');
if (accountType === 1) {
const csv = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(reader.u16('HEADER previous accounts length'), 'HEADER previous accounts'));
previousAccounts = csv ? csv.split(',') : [];
const seen = new Set([login.toLowerCase()]);
if (previousAccounts.length > 10) throw new Error('Too many previous accounts');
for (const previous of previousAccounts) {
if (!(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid previous account');
seen.add(previous.toLowerCase());
}
}
license = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(reader.u8('HEADER license length'), 'HEADER license'));
} else if (frame.version === 2) {
const field = reader.raw(reader.remaining() - 32, 'HEADER license');
const marker = 'license:CC0-1.0';
if (field.length === marker.length && field.every((b, i) => b === marker.charCodeAt(i))) {
license = 'CC0-1.0'; // исторический HEADER v2
} else {
if (!field.length || field[0] !== field.length - 1) throw new Error('Некорректная длина лицензии HEADER');
license = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(field.slice(1));
}
} }
const initialBlockchainKey = bytesToBase64Url(reader.raw(32, 'initialBlockchainKey32')); const initialBlockchainKey = bytesToBase64Url(reader.raw(32, 'initialBlockchainKey32'));
if (reader.remaining() !== 0) throw new Error('Неожиданные данные после HEADER'); if (reader.remaining() !== 0) throw new Error('Неожиданные данные после HEADER');
return { kind: 'header', magic, login, license, initialBlockchainKey }; return { kind: 'header', magic, login, license, accountType, previousAccounts, initialBlockchainKey };
} }
if (subType === 1) { if (subType === 1) {
const line = frame.signedLine ?? parseLinePrefix(reader); const line = frame.signedLine ?? parseLinePrefix(reader);
@@ -240,7 +261,7 @@ function parseStatusBody(subType, body) {
function parseBody(type, subType, version, body, frame) { function parseBody(type, subType, version, body, frame) {
// Only TECH HEADER subtype 0 has a second version; all other records stay v1. // Only TECH HEADER subtype 0 has a second version; all other records stay v1.
if (version !== 1 && !(type === 0 && subType === 0 && version === 2)) { if (version !== 1 && !(type === 0 && subType === 0 && (version === 2 || version === 3))) {
return { kind: 'unsupported_version', rawBodyLength: body.length }; return { kind: 'unsupported_version', rawBodyLength: body.length };
} }
if (type === 0) return parseTechBody(subType, body, frame); if (type === 0) return parseTechBody(subType, body, frame);
+1 -1
View File
@@ -79,8 +79,8 @@ export function coreTags(core) {
} }
function checkEventLine(content, core) { function checkEventLine(content, core) {
const { type, subType, version } = content; const { type, subType, version } = content;
if (version !== 1) throw new Error('Unsupported CONTENT version for creation');
const header = type === 0 && subType === 0; const header = type === 0 && subType === 0;
if (version !== 1 && !(header && (version === 2 || version === 3))) throw new Error('Unsupported CONTENT version for creation');
if (header !== (core.blockNumber === 0)) throw new Error('HEADER must be CORE #0'); if (header !== (core.blockNumber === 0)) throw new Error('HEADER must be CORE #0');
const code = core.line?.lineCode; const code = core.line?.lineCode;
if (type === 0 && !header) { if (code !== SHINE_CORE_LINE_TECH) throw new Error('Wrong TECH line'); } if (type === 0 && !header) { if (code !== SHINE_CORE_LINE_TECH) throw new Error('Wrong TECH line'); }
@@ -0,0 +1,21 @@
// Только будущие публичные поля HEADER; никаких паролей или приватных ключей.
const prefix = 'shine-pending-header-v3:';
const memory = new Map();
const key = (login, publicKey) => `${prefix}${String(login).trim().toLowerCase()}:${String(publicKey).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`;
export function savePendingHeaderIdentity(login, publicKey, identity) {
if (!publicKey || ![0, 1].includes(identity.accountType)) throw new Error('Missing HEADER identity');
const k = key(login, publicKey);
const data = JSON.stringify({ accountType: identity.accountType, previousAccounts: [...identity.previousAccounts] });
memory.set(k, data);
try { localStorage.setItem(k, data); } catch { /* encrypted vault is a second persistence path */ }
}
export function readPendingHeaderIdentity(login, publicKey) {
const k = key(login, publicKey);
let value = memory.get(k);
try { value = value || localStorage.getItem(k); } catch {}
try { return value ? JSON.parse(value) : null; } catch { return null; }
}
export function clearPendingHeaderIdentity(login, publicKey) {
const k = key(login, publicKey); memory.delete(k);
try { localStorage.removeItem(k); } catch {}
}
+13
View File
@@ -0,0 +1,13 @@
// Public counter represents declared Primary accounts, not verified unique people.
function safeCount(raw) {
const n = Number(raw);
return Number.isFinite(n) ? Math.max(0, Math.trunc(n)) : 0;
}
export function publicLikeCount(message) {
return safeCount(message?.primaryLikesCount);
}
export function hasLikeStatistics(message) {
return publicLikeCount(message) > 0 || safeCount(message?.likesCount) > 0;
}
+7 -7
View File
@@ -1,3 +1,4 @@
import { accountRoleFromHeader } from './account-voting.js';
import { t } from '../i18n/index.js'; import { t } from '../i18n/index.js';
import { authService, state } from '../state.js'; import { authService, state } from '../state.js';
import { validateArweaveTxId } from './arweave-file-service.js'; import { validateArweaveTxId } from './arweave-file-service.js';
@@ -119,10 +120,7 @@ export async function loadProfileSnapshot(login) {
} }
const latestAccountRole = loadLatestByAliasesFromItems(items, ['account_role']); const latestAccountRole = loadLatestByAliasesFromItems(items, ['account_role']);
const rawAccountRole = String(latestAccountRole?.value || '').trim().toLowerCase(); const accountRole = accountRoleFromHeader(payload?.accountType);
const accountRole = rawAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY || rawAccountRole === PROFILE_ACCOUNT_ROLE_NON_VOTING
? rawAccountRole
: '';
const latestShine = loadLatestByAliasesFromItems(items, ['shine']); const latestShine = loadLatestByAliasesFromItems(items, ['shine']);
const rawShine = String(latestShine?.value || '').trim().toLowerCase(); const rawShine = String(latestShine?.value || '').trim().toLowerCase();
@@ -165,6 +163,8 @@ export async function loadProfileSnapshot(login) {
fields, fields,
toggles, toggles,
accountRole, accountRole,
accountType: payload?.accountType ?? null,
previousAccounts: Array.isArray(payload?.previousAccounts) ? payload.previousAccounts : [],
accountRoleTimeMs: latestAccountRole?.timeMs || 0, accountRoleTimeMs: latestAccountRole?.timeMs || 0,
shineStatus, shineStatus,
shineTimeMs: latestShine?.timeMs || 0, shineTimeMs: latestShine?.timeMs || 0,
@@ -193,8 +193,8 @@ export async function saveProfileParamBlock(login, key, value) {
export async function saveProfileStatus(login, key, value) { export async function saveProfileStatus(login, key, value) {
const cleanKey = String(key || '').trim(); const cleanKey = String(key || '').trim();
const cleanValue = String(value || '').trim().toLowerCase(); const cleanValue = String(value || '').trim().toLowerCase();
if (cleanKey === 'account_role' && ![PROFILE_ACCOUNT_ROLE_PRIMARY, PROFILE_ACCOUNT_ROLE_NON_VOTING].includes(cleanValue)) { if (['account_role', 'official'].includes(cleanKey.toLowerCase())) {
throw new Error(t('remaining.profile_errors.invalid_account_role_value')); throw new Error(t('screens.registration_identity.immutable'));
} }
if (cleanKey === 'shine' && ![PROFILE_SHINE_SHINING, PROFILE_SHINE_UNKNOWN, PROFILE_SHINE_NOT_INTERESTED].includes(cleanValue)) { if (cleanKey === 'shine' && ![PROFILE_SHINE_SHINING, PROFILE_SHINE_UNKNOWN, PROFILE_SHINE_NOT_INTERESTED].includes(cleanValue)) {
throw new Error(t('remaining.profile_errors.invalid_shine_value')); throw new Error(t('remaining.profile_errors.invalid_shine_value'));
@@ -206,7 +206,7 @@ export async function saveProfileStatus(login, key, value) {
// Kept only for old callers outside the current UI. New code must use saveProfileStatus(). // Kept only for old callers outside the current UI. New code must use saveProfileStatus().
export async function saveProfileToggle(login, key, enabled) { export async function saveProfileToggle(login, key, enabled) {
if (key === 'shine') return saveProfileStatus(login, 'shine', enabled ? PROFILE_SHINE_SHINING : PROFILE_SHINE_UNKNOWN); if (key === 'shine') return saveProfileStatus(login, 'shine', enabled ? PROFILE_SHINE_SHINING : PROFILE_SHINE_UNKNOWN);
if (key === 'official') throw new Error(t('remaining.profile_errors.the_official_parameter_is_deprecated_use_account_role')); if (key === 'official') throw new Error(t('screens.registration_identity.immutable'));
throw new Error(`Неизвестный legacy toggle: ${key}`); throw new Error(`Неизвестный legacy toggle: ${key}`);
} }
+2
View File
@@ -32,6 +32,8 @@ const INVALID_SESSION_CODES = new Set([
function createEmptyRegistrationDraft() { function createEmptyRegistrationDraft() {
return { return {
uiStep: 1, uiStep: 1,
accountType: null,
previousAccounts: [],
flowType: '', flowType: '',
namespaceFeeLamports: '', namespaceFeeLamports: '',
namespaceServerLogin: '', namespaceServerLogin: '',
@@ -1930,16 +1930,41 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
}; };
} }
function parseHeaderBody(bodyBytes) { function parseHeaderBody(bodyBytes, version) {
const reader = makeBigEndianReader(bodyBytes, 'HEADER'); const reader = makeBigEndianReader(bodyBytes, 'HEADER');
const tag = readUtf8(reader.readBytes(5)); const tag = readUtf8(reader.readBytes(5));
if (tag !== MAGIC) { if (tag !== MAGIC) {
throw new Error(`HEADER: неожиданный tag ${tag}`); throw new Error(`HEADER: неожиданный tag ${tag}`);
} }
const login = reader.readUtf8U8(); const login = reader.readUtf8U8();
let accountType = null, previousAccounts = [], license = null;
const strict = bytes => new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
if (version === 3) {
accountType = reader.readU8();
if (![0,1].includes(accountType)) throw new Error('Invalid HEADER account type');
if (accountType === 1) {
const csv = strict(reader.readBytes(reader.readU16()));
previousAccounts = csv ? csv.split(',') : [];
const seen = new Set([login.toLowerCase()]);
if (previousAccounts.length > 10) throw new Error('Too many previous accounts');
for (const previous of previousAccounts) {
if (!(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid previous account');
seen.add(previous.toLowerCase());
}
}
license = strict(reader.readBytes(reader.readU8()));
} else if (version === 2) {
const field = bodyBytes.slice(6 + bodyBytes[5], -32);
if (field.length === 15 && field.every((b,i) => b === 'license:CC0-1.0'.charCodeAt(i))) {
reader.readBytes(15); license = 'CC0-1.0';
} else {
if (!field.length || field[0] !== field.length - 1) throw new Error('Invalid HEADER license length');
license = strict(reader.readBytes(reader.readU8()));
}
}
const initialBlockchainKey = base64Url(reader.readBytes(32)); const initialBlockchainKey = base64Url(reader.readBytes(32));
reader.ensureDone(); reader.ensureDone();
return { kind: 'header', login, tag, initialBlockchainKey }; return { kind: 'header', login, tag, initialBlockchainKey, accountType, previousAccounts, license };
} }
function parseCreateChannelBody(bodyBytes, line) { function parseCreateChannelBody(bodyBytes, line) {
@@ -2026,11 +2051,11 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
} }
function parseBlockchainBody(type, subType, version, bodyBytes, line) { function parseBlockchainBody(type, subType, version, bodyBytes, line) {
if (version !== 1) { if (version !== 1 && !(type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER && [2,3].includes(version))) {
return { kind: 'unsupported', reason: `Неподдерживаемая версия body ${version}` }; return { kind: 'unsupported', reason: `Неподдерживаемая версия body ${version}` };
} }
if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER) { if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER) {
return parseHeaderBody(bodyBytes); return parseHeaderBody(bodyBytes, version);
} }
if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_CREATE_CHANNEL) { if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_CREATE_CHANNEL) {
return parseCreateChannelBody(bodyBytes, line); return parseCreateChannelBody(bodyBytes, line);
@@ -2069,7 +2094,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
const core = parseCorePayload(coreBytes); const core = parseCorePayload(coreBytes);
if (contentBytes.length < 7 || contentBytes.length > 8*1024*1024-117 || contentBytes[0] !== 1 || bytesToHex(await digestSha256(contentBytes)) !== core.contentHashHex) throw new Error('CONTENT hash/format mismatch'); if (contentBytes.length < 7 || contentBytes.length > 8*1024*1024-117 || contentBytes[0] !== 1 || bytesToHex(await digestSha256(contentBytes)) !== core.contentHashHex) throw new Error('CONTENT hash/format mismatch');
const type=readUint16BE(contentBytes,1),subType=readUint16BE(contentBytes,3),version=readUint16BE(contentBytes,5); const type=readUint16BE(contentBytes,1),subType=readUint16BE(contentBytes,3),version=readUint16BE(contentBytes,5);
if (version !== 1 || (type===0 && subType===0)!==(core.blockNumber===0)) throw new Error('Invalid CONTENT version/HEADER'); if ((version !== 1 && !(type===0 && subType===0 && [2,3].includes(version))) || (type===0 && subType===0)!==(core.blockNumber===0)) throw new Error('Invalid CONTENT version/HEADER');
const channelText=type===1 && [10,11,50,90,92,100,110,120,130].includes(subType); const channelText=type===1 && [10,11,50,90,92,100,110,120,130].includes(subType);
const expectedLine=type===0&&subType!==0?2147483647:type===3?2147483646:type===4?2147483645:null; const expectedLine=type===0&&subType!==0?2147483647:type===3?2147483646:type===4?2147483645:null;
if (channelText ? !core.line||core.line.lineCode>CORE_MAX_NUMBER : expectedLine===null ? !!core.line : core.line?.lineCode!==expectedLine) throw new Error('CONTENT/CORE line mismatch'); if (channelText ? !core.line||core.line.lineCode>CORE_MAX_NUMBER : expectedLine===null ? !!core.line : core.line?.lineCode!==expectedLine) throw new Error('CONTENT/CORE line mismatch');
+31
View File
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { accountRoleFromHeader, confirmationRights } from '../js/services/account-voting.js';
test('only explicit HEADER V3 type 1 is Primary; no legacy fallbacks', () => {
assert.equal(accountRoleFromHeader(1), 'primary');
assert.equal(accountRoleFromHeader(0), 'non_voting');
for (const x of [undefined, null, '1', 2, true]) assert.equal(accountRoleFromHeader(x), '');
});
test('confirmation permissions match all actor and target categories', () => {
const types = [null, 0, 1];
const statuses = ['', 'shining', 'unknown', 'not_interested'];
for (const a of types) for (const b of types) for (const as of statuses) for (const bs of statuses) {
const actor = { login: 'A@free', accountRole: accountRoleFromHeader(a), shineStatus: as };
const target = { login: 'B@free', accountRole: accountRoleFromHeader(b), shineStatus: bs };
assert.deepEqual(confirmationRights(actor, target), { primary: a === 1 && b === 1, shine: a === 1 && b === 1 && as === 'shining' && bs !== 'not_interested' });
assert.deepEqual(confirmationRights(actor, { ...target, login: 'a@FREE' }), { primary: false, shine: false });
}
assert.deepEqual(confirmationRights(null, null), {primary:false,shine:false});
});
test('profile has no official toggle; both confirmation actions enforce shared rules', () => {
const src = name => readFileSync(new URL(`../js/pages/${name}`, import.meta.url), 'utf8');
const profile = src('profile-edit-view.js');
assert.match(profile, /<span class="badge is-no" data-status="account_role">/);
assert.doesNotMatch(profile, /accountRoleBtn\.addEventListener/);
const relations = src('user-relation-manage-view.js');
assert.match(relations, /confirmationRights\(selfCard, targetCard\)/);
assert.match(relations, /!rights\.primary/);
assert.match(relations, /!rights\.shine/);
});
@@ -55,7 +55,7 @@ test('при навигации старые вручную закодирова
const { toPrettyPath } = await import('../js/router.js'); const { toPrettyPath } = await import('../js/router.js');
assert.equal(toPrettyPath('SHiNE/innaa%40free/news/3'), 'SHiNE/innaa@free/news/3'); assert.equal(toPrettyPath('SHiNE/innaa%40free/news/3'), 'SHiNE/innaa@free/news/3');
assert.equal(toPrettyPath('SHiNE/Prof/innaa%40free'), 'SHiNE/Prof/innaa@free'); assert.equal(toPrettyPath('SHiNE/Prof/innaa%40free'), 'SHiNE/Prof/innaa@free');
assert.equal(toPrettyPath('chat/innaa%40free'), 'chat/innaa%40free'); assert.equal(toPrettyPath('chat/innaa%40free'), 'chat/innaa@free');
} finally { } finally {
globalThis.window = previousWindow; globalThis.window = previousWindow;
} }
+32
View File
@@ -0,0 +1,32 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const source = fs.readFileSync(new URL('../js/router.js', import.meta.url), 'utf8').replace(/^import .*$/gm, '').replace(/^export /gm, '');
function setup(path) {
const url = new URL(path, 'https://t2.shineup.me');
const calls = [];
const window = { location: url, history: { state: { shineFrom: '/messages' }, replaceState(state, _, value) { calls.push([state, value]); url.href = new URL(value, url).href; }, pushState(state, _, value) { url.href = new URL(value, url).href; } }, dispatchEvent() {} };
const router = vm.runInNewContext(source + '\n({toPrettyPath,getRoute,navigate})', { window, PopStateEvent: class {}, parseShineRouteParts: () => null });
return { router, window, calls };
}
test('chat navigation keeps @ visible; other escapes unchanged', () => {
const {router, window} = setup('/messages');
assert.equal(router.toPrettyPath('chat-view/qwer1%40free'), 'chat/qwer1@free');
assert.equal(router.toPrettyPath('chat/qwer1%40free/media'), 'chat/qwer1@free/media');
assert.equal(router.toPrettyPath('chat/a%40b%2Fc'), 'chat/a@b%2Fc');
assert.equal(router.toPrettyPath('settings/a%40b'), 'settings/a%40b');
router.navigate('chat-view/qwer1%40free');
assert.equal(window.location.pathname, '/chat/qwer1@free');
assert.equal(router.getRoute().params.chatId, 'qwer1@free');
});
test('direct legacy URL canonicalizes without new history entry and retains query/hash', () => {
const {router, window, calls} = setup('/chat/qwer1%40free/media?x=1#anchor');
const route = router.getRoute();
assert.equal(route.pageId, 'chat-media-view');
assert.equal(route.params.chatId, 'qwer1@free');
assert.equal(window.location.pathname, '/chat/qwer1@free/media');
assert.deepEqual(calls, [[{shineFrom:'/messages'}, '/chat/qwer1@free/media?x=1#anchor']]);
router.getRoute();
assert.equal(calls.length, 1);
});
@@ -89,3 +89,23 @@ test('Minimal pair codec and container: exact vectors, tampering, unsigned lengt
} }
assert.throws(()=>unpackCoreContent(new Uint8Array(CORE_MAX_CONTAINER_BYTES+1))); assert.throws(()=>unpackCoreContent(new Uint8Array(CORE_MAX_CONTAINER_BYTES+1)));
}); });
import { inspectBlockchainDataItem } from '../js/services/blockchain-entry-inspector.js';
test('HEADER v2 signed CORE/CONTENT and inspector accept arbitrary UTF-8 license', async () => {
const pkcs8=Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]);
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
const owner=unhex(rows[0][1]);
const login=Buffer.from('Alice@shine');
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', '\ufeffx', 'x'.repeat(255)]) {
const bytes=Buffer.from(license);
const body=Buffer.concat([Buffer.from('SHiNE'),Buffer.of(login.length),login,Buffer.of(bytes.length),bytes,owner]);
const content={type:0,subType:0,version:2,body};
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content,prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null});
const raw=packCoreContent(signed.coreDataItem,signed.contentDataItem);
const result=await inspectBlockchainDataItem(Buffer.from(raw).toString('base64'));
assert.equal(result.frame.body.license,license);
assert.equal(result.frame.version,2);
await assert.rejects(signCoreContentPair({owner32:owner,privateKey:key,content:{...content,version:4},prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null}));
}
});
+35 -5
View File
@@ -16,21 +16,22 @@ const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeH
Uint8Array, Uint8Array,
}); });
test('client writes new HEADER v1 as SHiNE → login → key', () => { test('client writes HEADER v2 as SHiNE → login → length + license → key', () => {
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1); const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = 'Alice@shine'; const login = 'Alice@shine';
const body = encode({ login, initialBlockchainKey32: key }); const license = 'Лицензия 🌞';
const body = encode({ login, initialBlockchainKey32: key, license });
const loginBytes = utf8(login); const loginBytes = utf8(login);
const expected = Uint8Array.from([ const expected = Uint8Array.from([
...utf8('SHiNE'), loginBytes.length, ...loginBytes, ...utf8('SHiNE'), loginBytes.length, ...loginBytes,
...key, utf8(license).length, ...utf8(license), ...key,
]); ]);
assert.deepEqual(Array.from(body), Array.from(expected)); assert.deepEqual(Array.from(body), Array.from(expected));
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/); assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
assert.match(auth, /export const HEADER_VERSION = 1/); assert.match(auth, /export const HEADER_VERSION = 3/);
}); });
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => { test('inspector decodes both v1 and v2 and supports arbitrary license and rejects malformed v2', () => {
const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, ''); const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, '');
const inspect = vm.runInNewContext(`${stripped}\nparseShineFrame`, { const inspect = vm.runInNewContext(`${stripped}\nparseShineFrame`, {
TextDecoder, DataView, Uint8Array, BigInt, TextDecoder, DataView, Uint8Array, BigInt,
@@ -66,5 +67,34 @@ test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', ()
const invalid = bodyV2.slice(); const invalid = bodyV2.slice();
invalid[prefix.length + 8] = 'X'.charCodeAt(0); invalid[prefix.length + 8] = 'X'.charCodeAt(0);
assert.throws(() => inspect(frameFor(2, invalid))); assert.throws(() => inspect(frameFor(2, invalid)));
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', 'x'.repeat(255)]) {
const body = encode({ login: 'Alice@shine', initialBlockchainKey32: key, license });
assert.equal(inspect(frameFor(2, body)).body.license, license);
assert.throws(() => inspect(frameFor(2, body.slice(0, -1))));
}
assert.throws(() => encode({ login: 'Alice@shine', initialBlockchainKey32: key, license: 'x'.repeat(256) }));
assert.throws(() => inspect(frameFor(2, Uint8Array.from([...prefix, 1, 255, ...key]))));
assert.throws(() => inspect(frameFor(2, new Uint8Array(0)))); assert.throws(() => inspect(frameFor(2, new Uint8Array(0))));
}); });
test('HEADER v3: actual serializer and inspector agree on identity and reject malformed declarations', () => {
const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, '');
const inspect = vm.runInNewContext(`${stripped}\nparseShineFrame`, {TextDecoder, DataView, Uint8Array, BigInt, bytesToBase64Url: b => Buffer.from(b).toString('base64url'), Buffer});
const login = 'Alice@shine', key = Uint8Array.from({length:32}, (_,i)=>i+1);
const prefix = [...utf8('SHiNE'), utf8(login).length, ...utf8(login)];
const frame = body => {const a=new Uint8Array(88+body.length), v=new DataView(a.buffer);v.setUint16(0,1);v.setInt32(66,a.length);v.setUint16(86,3);a.set(body,88);return a;};
const make = (accountType,previousAccounts=[],license='')=>encode({login,initialBlockchainKey32:key,accountType,previousAccounts,license});
assert.deepEqual([...make(0)], [...prefix,0,0,...key]);
assert.deepEqual([...make(1)], [...prefix,1,0,0,0,...key]);
for(const previousAccounts of [[],['Bob@free','Older'],Array.from({length:10},(_,i)=>'old'+i+'@free')]) {
const body=make(1,previousAccounts,'Лицензия');
const parsed=inspect(frame(body)).body;
assert.equal(parsed.accountType,1);assert.deepEqual(Array.from(parsed.previousAccounts),previousAccounts);assert.equal(parsed.license,'Лицензия');
assert.throws(()=>inspect(frame(body.slice(0,-1))));
}
assert.equal(inspect(frame(make(0))).body.accountType,0);
for(const list of [['ALICE@shine'],['Bob@free','bob@free'],['a,b'],Array.from({length:11},(_,i)=>'old'+i)]) assert.throws(()=>make(1,list));
assert.throws(()=>make(0,['Bob@free']));assert.throws(()=>make(2));
const bad=make(1);bad[prefix.length]=2;assert.throws(()=>inspect(frame(bad)));
const csv=utf8('Bob@free,bob@free');assert.throws(()=>inspect(frame(Uint8Array.from([...prefix,1,0,csv.length,...csv,0,...key]))));
});
@@ -68,7 +68,7 @@ test('HEADER и PostgreSQL требуют неизменяемого регис
const handler = readFileSync(new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/blockchain/Net_AddBlock_Handler.java', import.meta.url), 'utf8'); const handler = readFileSync(new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/blockchain/Net_AddBlock_Handler.java', import.meta.url), 'utf8');
const header = readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/body/HeaderBody.java', import.meta.url), 'utf8'); const header = readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/body/HeaderBody.java', import.meta.url), 'utf8');
const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v37.sql', import.meta.url), 'utf8'); const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v37.sql', import.meta.url), 'utf8');
assert.match(client, /bodyBytes: makeHeaderBodyBytes\(\{ login: registeredLogin, initialBlockchainKey32 \}\)/); assert.match(client, /bodyBytes: makeHeaderBodyBytes\(\{ login: registeredLogin, initialBlockchainKey32, license: HEADER_DEFAULT_LICENSE, accountType: identity\.accountType, previousAccounts: identity\.previousAccounts \}\)/);
assert.doesNotMatch(client, /makeHeaderBodyBytes\(\{ login: cleanLogin\.toLowerCase\(\)/); assert.doesNotMatch(client, /makeHeaderBodyBytes\(\{ login: cleanLogin\.toLowerCase\(\)/);
assert.match(handler, /headerBody\.login\.equals\(registeredOwner\.getLogin\(\)\)/); assert.match(handler, /headerBody\.login\.equals\(registeredOwner\.getLogin\(\)\)/);
assert.match(header, /\[A-Za-z0-9_\]\+@\[a-z0-9_\]\+/); assert.match(header, /\[A-Za-z0-9_\]\+@\[a-z0-9_\]\+/);
+11
View File
@@ -35,3 +35,14 @@ test('viewer: requests CORE then CONTENT by ID and never claims signature verifi
ctx.fetch=async url=>url.endsWith(cid)?{ok:false,status:404}:{ok:true,arrayBuffer:async()=>bytes(f.core).buffer}; ctx.fetch=async url=>url.endsWith(cid)?{ok:false,status:404}:{ok:true,arrayBuffer:async()=>bytes(f.core).buffer};
await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5595'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/); await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5595'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/);
}); });
test('viewer: parses historical v2 and v3 primary declaration',async()=>{
const f=find('header'), old=bytes(f.content), key=old.slice(-32), prefix=old.slice(7,-32);
const csv=new TextEncoder().encode('Bob@free,Older');
for(const [version,body,role] of [[2,[...prefix,0,...key],null],[3,[...prefix,0,0,...key],0],[3,[...prefix,1,0,csv.length,...csv,0,...key],1]]){
const content=Uint8Array.from([1,0,0,0,0,0,version,...body]),core=bytes(f.core);
core.set(new Uint8Array(await webcrypto.subtle.digest('SHA-256',content)),45);
const result=await v.parseBlockchainBlock(core,content);
assert.equal(result.body.accountType,role);assert.equal(result.body.license,'');
assert.deepEqual(Array.from(result.body.previousAccounts),role===1?['Bob@free','Older']:[]);
}
});
@@ -0,0 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {savePendingHeaderIdentity,readPendingHeaderIdentity,clearPendingHeaderIdentity} from '../js/services/pending-header-identity.js';
test('pending HEADER declaration survives module reload and remains bound to login and key',async()=>{
const m=new Map();globalThis.localStorage={setItem:(k,v)=>m.set(k,v),getItem:k=>m.get(k),removeItem:k=>m.delete(k)};
const declaration={accountType:1,previousAccounts:['Bob@free']};
savePendingHeaderIdentity('Alice@shine','a+/=',declaration);
const fresh=await import('../js/services/pending-header-identity.js?reload');
assert.deepEqual(fresh.readPendingHeaderIdentity('alice@shine','a-_'),declaration);
assert.equal(fresh.readPendingHeaderIdentity('alice@shine','other'),null);
assert.equal(fresh.readPendingHeaderIdentity('bob@shine','a-_'),null);
clearPendingHeaderIdentity('Alice@shine','a+/=');
assert.equal(fresh.readPendingHeaderIdentity('alice@shine','a-_'),null);
delete globalThis.localStorage;
});
+29
View File
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { publicLikeCount, hasLikeStatistics } from '../js/services/public-like-count.js';
test('public likes only count declared Primary accounts', () => {
const post = { likesCount: 20, primaryLikesCount: 5, shiningLikesCount: 2 };
assert.equal(publicLikeCount(post), 5);
assert.equal(hasLikeStatistics(post), true);
assert.equal(publicLikeCount({ likesCount: 20, primaryLikesCount: 0 }), 0);
assert.equal(hasLikeStatistics({ likesCount: 20, primaryLikesCount: 0 }), true);
assert.equal(publicLikeCount({ likesCount: 20 }), 0);
assert.equal(publicLikeCount({ primaryLikesCount: -1 }), 0);
assert.equal(publicLikeCount({ primaryLikesCount: 'invalid' }), 0);
assert.equal(hasLikeStatistics({ likesCount: 0, primaryLikesCount: 0 }), false);
});
test('feed and both thread layouts use the public count and keep stats accessible', () => {
const src = name => readFileSync(new URL(`../js/pages/${name}`, import.meta.url), 'utf8');
const feed = src('channel-view.js');
const thread = src('channel-thread-view.js');
assert.match(feed, /likesStatsButton\.textContent = String\(publicLikeCount\(post\)\)/);
assert.equal((feed.match(/hasLikeStatistics\(post\) \? \[likesStatsButton\]/g) || []).length, 2);
assert.equal((thread.match(/const likes = publicLikeCount\(node\);/g) || []).length, 2);
assert.match(thread, /commentLikeStats\.textContent = String\(likes\)/);
assert.equal((thread.match(/hasLikeStatistics\(node\)/g) || []).length, 3);
assert.match(feed, /counts: post/);
assert.match(thread, /showLikeStatistics\(\{ counts: node \}\)/);
});
@@ -24,17 +24,18 @@ const context = {
}; };
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context); const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
test('CORE/CONTENT HEADER v1 contains login and initial key without CC0', () => { test('CORE/CONTENT HEADER v2 contains login, empty license and initial key', () => {
const key = Uint8Array.from({ length: 32 }, (_, n) => n + 1); const key = Uint8Array.from({ length: 32 }, (_, n) => n + 1);
const result = makeHeaderBodyBytes({ login: 'Alice@shine', initialBlockchainKey32: key }); const result = makeHeaderBodyBytes({ login: 'Alice@shine', initialBlockchainKey32: key });
const login = new TextEncoder().encode('Alice@shine'); const login = new TextEncoder().encode('Alice@shine');
assert.equal(new TextDecoder().decode(result.slice(0,5)), 'SHiNE'); assert.equal(new TextDecoder().decode(result.slice(0,5)), 'SHiNE');
assert.equal(result[5], login.length); assert.equal(result[5], login.length);
assert.deepEqual(Array.from(result.slice(6, 6+login.length)), Array.from(login)); assert.deepEqual(Array.from(result.slice(6, 6+login.length)), Array.from(login));
assert.deepEqual(Array.from(result.slice(6+login.length)), Array.from(key)); assert.deepEqual(Array.from(result.slice(7+login.length)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 32); assert.equal(result[6+login.length], 0);
assert.equal(result.length, 5 + 1 + login.length + 1 + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/); assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
assert.match(auth, /export const HEADER_VERSION = 1/); assert.match(auth, /export const HEADER_VERSION = 3/);
}); });
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => { test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {
@@ -53,7 +53,7 @@ async function simulateCompletion({ headerFails = false } = {}) {
const calls = []; const calls = [];
const state = { const state = {
entrySettings: { shineServer: 'wss://test.invalid' }, entrySettings: { shineServer: 'wss://test.invalid' },
registrationDraft: { login: 'AlexSmith@shine', password: 'secret' }, registrationDraft: { login: 'AlexSmith@shine', password: 'secret', accountType: 1, previousAccounts: ['old@free'] },
loginDraft: {}, loginDraft: {},
registrationPayment: {}, registrationPayment: {},
authReturnHash: '', authReturnHash: '',
@@ -64,7 +64,10 @@ async function simulateCompletion({ headerFails = false } = {}) {
async createSessionForExistingUser() { async createSessionForExistingUser() {
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session', sessionMaterial: {} }; return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session', sessionMaterial: {} };
}, },
async persistSelectedKeys() {}, async persistSelectedKeys(login, pwd, bundle, options) {
assert.equal(options.headerIdentity.accountType, 1);
assert.deepEqual(Array.from(options.headerIdentity.previousAccounts), ['old@free']);
},
async persistSessionMaterial() {}, async persistSessionMaterial() {},
async resumeSession() { async resumeSession() {
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session' }; return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session' };
@@ -3,7 +3,7 @@ import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import fs from 'node:fs'; import fs from 'node:fs';
const read = relative => expandRussian(fs.readFileSync(new URL(relative, import.meta.url), 'utf8')); const read = relative => expandRussian(fs.readFileSync(new URL(relative, import.meta.url), 'utf8'));
test('выбор аккаунта перед шагом 1, всего три шага', () => { test('выбор тарифа перед шагом 1, всего четыре шага', () => {
const choice = read('../js/pages/registration-choice-view.js'); const choice = read('../js/pages/registration-choice-view.js');
const login = read('../js/pages/register-view.js'); const login = read('../js/pages/register-view.js');
const email = read('../js/pages/registration-email-view.js'); const email = read('../js/pages/registration-email-view.js');
@@ -11,8 +11,9 @@ test('выбор аккаунта перед шагом 1, всего три ш
assert.doesNotMatch(choice, /createRegistrationStepper\(/); assert.doesNotMatch(choice, /createRegistrationStepper\(/);
assert.match(login, /createRegistrationStepper\(1\)/); assert.match(login, /createRegistrationStepper\(1\)/);
assert.match(login, /createRegistrationStepper\(2\)/); assert.match(login, /createRegistrationStepper\(2\)/);
assert.match(email, /createRegistrationStepper\(3\)/); assert.match(login, /createRegistrationStepper\(3\)/);
assert.match(payment, /createRegistrationStepper\(3\)/); assert.match(email, /createRegistrationStepper\(4\)/);
assert.match(payment, /createRegistrationStepper\(4\)/);
}); });
test('реальная почта и 256-символьный лимит сохранены', () => { test('реальная почта и 256-символьный лимит сохранены', () => {
const email = read('../js/pages/registration-email-view.js'); const email = read('../js/pages/registration-email-view.js');