Разделить среды и закрепить лицензии в HEADER 1.0

This commit is contained in:
AidarKC
2026-12-05 11:42:20 +03:00
parent a64168a748
commit 77c7021aed
89 changed files with 4204 additions and 211 deletions
@@ -677,7 +677,7 @@ public final class ArweaveBlockSyncService {
private JsonNode graphQlPage(long minHeight, String cursor, boolean registrationsOnly) throws Exception {
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\",\"test5599\"]}" +
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
+ cfg.syncPageSize() + ", after:" + after
@@ -49,6 +49,8 @@ public final class FreeRegistrationApiBootstrap {
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
throw new IllegalStateException("Free registration requires Turbo transport");
String mode=cfg.getStringOrEmpty("freeRegistration.signerMode").trim();
if (utils.config.ServerEnvironment.TEST_MODE && "external".equals(mode))
throw new IllegalStateException("Test registration requires local signer; ESP32 is production only");
if ("external".equals(mode)) {
newExternal = new ExternalRegistrar(dbSource(), freeNamespace, cfg.getStringOrEmpty("server.SHiNE.login"));
issuer = new FreeRegistrationIssuer(dbSource(), newExternal, allowEmailReuse);
@@ -18,5 +18,5 @@ class ExternalRegistrarVectorTest {
}
}
// Synthetic public test vector; never use its seed for a real namespace.
private static final String EXPECTED = "02003830de5c252e8d4da7dab6de28fdc2f8693dc709f4688895c2e92e2092113f4172cd21a1c7e9842c4cac6fd0cb0537c958d8ad22a00f0297082275df4edf730e03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b800000300000000000000390000000000000006064170701074657374353539390274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d56310001000c4578616d706c654066726565202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f779d957dfe14d4d4097cfcb567944a1a3b4ee04024b71c189d95cfe15ed1bba8a5cf7b7a314e264437a0361f7422c287da24e70d785a0e7c2b1f8cc7073e6d05808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f";
private static final String EXPECTED = "02003db465c55d7fe21c9dac184333d65066dc317bfc5e7e2ab25a06c0d9c8dad2bdc153141ea724629e1388dccc2fe4427c0a71c638e6bb3245f3758f8268e5a80503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b800000300000000000000360000000000000006064170700a5348694e450274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d56310001000c4578616d706c654066726565202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f779d957dfe14d4d4097cfcb567944a1a3b4ee04024b71c189d95cfe15ed1bba8a5cf7b7a314e264437a0361f7422c287da24e70d785a0e7c2b1f8cc7073e6d05808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f";
}
@@ -19,7 +19,7 @@ public final class BodyRecordParser {
// TECH accepts only the current 1.0 body format.
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
&& (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.LEGACY_VER & 0xFFFF))) {
&& v == (HeaderBody.VER & 0xFFFF)) {
return new HeaderBody(subType, version, bodyBytes).check();
}
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
@@ -32,14 +32,23 @@ public final class CoreContentTransport {
require(Arrays.equals(item.id32(), ProtocolHash.copy32(expectedId)), "DataItem ID не совпадает");
require(item.verifySignature(), "Неверная подпись ANS-104");
}
public static final class WrongAppNamespace extends IllegalArgumentException {
public WrongAppNamespace() { super("WRONG_APP_NAMESPACE"); }
}
public static void requireApp(Ans104DataItem item) {
if (!item.tags().stream().filter(t -> t.name().equals("App")).toList().equals(
List.of(new Ans104DataItem.Tag("App", ShineProtocolTags.CORE_NAMESPACE))))
throw new WrongAppNamespace();
}
public static CoreRecord verifyCore(Ans104DataItem item, byte[] authorizedOwner, byte[] expectedId, long nowSeconds) {
requireApp(item);
verify(item, authorizedOwner, expectedId);
CoreRecord core = CoreRecord.parse(item.data()); core.checkTimestamp(nowSeconds);
List<Ans104DataItem.Tag> expected = coreTags(core);
for (String name : List.of("App", "n", "l")) {
var actual = item.tags().stream().filter(t -> t.name().equals(name)).toList();
var wanted = expected.stream().filter(t -> t.name().equals(name)).toList();
require(actual.equals(wanted) || (name.equals("App") && actual.equals(List.of(new Ans104DataItem.Tag("App", "test5599")))), "Некорректный тег CORE: " + name);
require(actual.equals(wanted), "Некорректный тег CORE: " + name);
}
require(item.tags().stream().noneMatch(t -> t.name().equals("t") || t.name().equals("c")), "Legacy теги CORE запрещены");
return core;
@@ -3,13 +3,12 @@ package blockchain;
/**
* Канонические ANS-104 tag names/value текущего SHiNE transport namespace на сервере.
*
* При смене тестовой эпохи namespace меняется отдельно в трёх рабочих местах:
* сервер, UI и актуальный Arweave Viewer.
* Namespace runtime определяется единственным серверным режимом.
*/
public final class ShineProtocolTags {
private ShineProtocolTags() {}
public static final String CORE_NAMESPACE = "SHiNE";
public static final String CORE_NAMESPACE = utils.config.ServerEnvironment.ARWEAVE_APP_TAG;
/** Новый регистрационный сертификат остаётся отдельным объектом; используется при переключении эпохи. */
public static final java.util.List<Ans104DataItem.Tag> CORE_REGISTRATION_TAGS = java.util.List.of(
new Ans104DataItem.Tag("App", CORE_NAMESPACE),
@@ -17,7 +16,7 @@ public final class ShineProtocolTags {
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
public static final String CORE_NUMBER_TAG_NAME = "n";
public static final String CORE_LINE_TAG_NAME = "l";
public static final String NAMESPACE = "test5592";
public static final String NAMESPACE = CORE_NAMESPACE;
public static final String APP_TAG_NAME = "App";
public static final String APP_TAG_VALUE = NAMESPACE;
public static final String CHANNEL_TAG_NAME = "c";
@@ -17,13 +17,12 @@ import java.util.Objects;
* [TAG_LEN] tag ASCII; [1] login length; [N] login UTF-8;
* [1] accountType (0 alternative / 1 primary);
* [2+N] previous accounts CSV for Primary only;
* [2] license length for v2 (v1: [1]); [M] arbitrary license UTF-8; [32] initial blockchain key.
* [2] license length (uint16 BE); [M] license UTF-8; [32] initial blockchain key.
*/
public final class HeaderBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 2;
public static final short LEGACY_VER = 1;
public static final String DEFAULT_LICENSE = "CC0-1.0";
public static final short VER = 1;
public static final String DEFAULT_LICENSE = "licenses:CC-BY-NC-4.0/sha256:41003d4a74749c0220e33dd415042164b5a1093ed401f36277234f772d22d3d0/arweave:Xtym3vUAyt7OgFBINBh1ene-5360Ah76c6D-O9ywxVE;SCDL-1.0/sha256:696454cb26c7ecb9e8b66812996b37733dc532307a3584718edd442b291870af/arweave:NPckIo-nQUP2-ZM6PIoDYnx-6wwLeErH39jXCddOxPE";
public static final int ALTERNATIVE = 0, PRIMARY = 1;
public static final short SUBTYPE_COMPAT = 0;
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
@@ -45,7 +44,7 @@ public final class HeaderBody implements BodyRecord {
this.subType = subType;
this.version = version;
if ((subType & 0xFFFF) != SUBTYPE_COMPAT) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (version != VER && version != LEGACY_VER) throw new IllegalArgumentException("Bad HEADER version");
if (version != VER) throw new IllegalArgumentException("Bad HEADER version");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
@@ -55,7 +54,7 @@ public final class HeaderBody implements BodyRecord {
if (!TAG.equals(tag)) throw new IllegalArgumentException("Bad tag: " + tag);
int loginLen = Byte.toUnsignedInt(bb.get());
if (loginLen == 0 || bb.remaining() < loginLen + (version == VER ? 35 : 34)) throw new IllegalArgumentException("Bad HEADER login length");
if (loginLen == 0 || bb.remaining() < loginLen + 35) throw new IllegalArgumentException("Bad HEADER login length");
byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes);
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HEADER login");
@@ -63,9 +62,9 @@ public final class HeaderBody implements BodyRecord {
this.accountType = Byte.toUnsignedInt(bb.get());
List<String> parsedPrevious;
if (accountType == PRIMARY) {
if (bb.remaining() < (version == VER ? 36 : 35)) throw new IllegalArgumentException("Truncated HEADER previous accounts");
if (bb.remaining() < 36) throw new IllegalArgumentException("Truncated HEADER previous accounts");
int size = Short.toUnsignedInt(bb.getShort());
if (size > bb.remaining() - (version == VER ? 34 : 33)) throw new IllegalArgumentException("Bad HEADER previous accounts length");
if (size > bb.remaining() - 34) throw new IllegalArgumentException("Bad HEADER previous accounts length");
byte[] previous = new byte[size];
bb.get(previous);
String csv = BodyTargetSupport.decodeStrictUtf8(previous, "HEADER previous accounts");
@@ -77,7 +76,7 @@ public final class HeaderBody implements BodyRecord {
}
this.previousAccounts = parsedPrevious;
int licenseSize = version == VER ? Short.toUnsignedInt(bb.getShort()) : Byte.toUnsignedInt(bb.get());
int licenseSize = Short.toUnsignedInt(bb.getShort());
if (bb.remaining() != licenseSize + 32) throw new IllegalArgumentException("Bad HEADER license length");
byte[] licenseBytes = new byte[licenseSize];
bb.get(licenseBytes);
@@ -117,8 +116,8 @@ public final class HeaderBody implements BodyRecord {
@Override
public HeaderBody check() {
if ((subType & 0xFFFF) != SUBTYPE_COMPAT || (version != VER && version != LEGACY_VER)) throw new IllegalArgumentException("Bad HeaderBody version");
if (!StandardCharsets.UTF_8.newEncoder().canEncode(license) || license.getBytes(StandardCharsets.UTF_8).length > (version == VER ? 65535 : 255))
if ((subType & 0xFFFF) != SUBTYPE_COMPAT || version != VER) throw new IllegalArgumentException("Bad HeaderBody version");
if (!StandardCharsets.UTF_8.newEncoder().canEncode(license) || license.getBytes(StandardCharsets.UTF_8).length > 65535)
throw new IllegalArgumentException("HEADER license exceeds version byte limit");
if (login.isBlank()) throw new IllegalArgumentException("Login is blank");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
@@ -149,11 +148,10 @@ public final class HeaderBody implements BodyRecord {
byte[] licenseUtf8 = license.getBytes(StandardCharsets.UTF_8);
byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
int identitySize = 1 + (accountType == PRIMARY ? 2 + previous.length : 0);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + identitySize + (version == VER ? 2 : 1) + licenseUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + identitySize + 2 + licenseUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
bb.put(TAG_ASCII).put((byte) loginUtf8.length).put(loginUtf8).put((byte) accountType);
if (accountType == PRIMARY) bb.putShort((short) previous.length).put(previous);
if (version == VER) bb.putShort((short) licenseUtf8.length);
else bb.put((byte) licenseUtf8.length);
bb.putShort((short) licenseUtf8.length);
bb.put(licenseUtf8).put(initialBlockchainKey32);
return bb.array();
}
@@ -41,8 +41,8 @@ public final class StageAProtocolChecks {
private static void checkBodies() throws Exception {
var header = HeaderBody.forCoreContent("Alice@shine", OWNER);
testBody(0,HEADER_COMPAT,header,null,0);
ok(header.license.equals("CC0-1.0") && header.accountType == HeaderBody.PRIMARY,"canonical HEADER 1.0");
for (String license : new String[]{"", "CC0-1.0", "CC-BY-NC-4.0", "Лицензия 🌞", "x".repeat(255)}) {
ok(header.license.equals(HeaderBody.DEFAULT_LICENSE) && header.accountType == HeaderBody.PRIMARY,"canonical HEADER 1.0");
for (String license : new String[]{"", "CC0-1.0", "CC-BY-NC-4.0", "Лицензия 🌞", "x".repeat(300)}) {
var h = HeaderBody.identity("Alice@shine", OWNER, license, HeaderBody.PRIMARY, List.of());
var c = new ContentRecord(0,0,HeaderBody.VER,h.toBytes());
var parsed = (HeaderBody) parseSemantic(c);
@@ -207,21 +207,23 @@ public final class StageAProtocolChecks {
var foreignCore=core(128,line(0),content,other.id32()); var foreign=sign(foreignCore,CoreContentTransport.coreTags(foreignCore));
bad(() -> CoreContentTransport.verifyPair(foreign,foreign.id32(),other,OWNER,NOW),"different owner with matching content ID");
bad(() -> CoreContentTransport.verifyContent(c,other,other.owner32()),"wrong content ID");
var tagged=CoreContentTransport.sign(content.toBytes(),List.of(tag("App","test5599"),tag("n","128")),SEED);
var tagged=CoreContentTransport.sign(content.toBytes(),List.of(tag("App","test5570"),tag("n","128")),SEED);
bad(() -> CoreContentTransport.verifyContent(core(128,line(0),content,tagged.id32()),tagged,OWNER),"tagged CONTENT");
rejectTags(c,List.of(tag("App","test5592"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","0128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","129"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","P")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128")));
rejectTags(c,List.of(tag("App","test5599"),tag("App","test5599"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","0"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","0"),tag("c","news")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","0"),tag("t","tech")));
rejectTags(core(128,null,content,item.id32()),List.of(tag("App","test5599"),tag("n","128"),tag("l","0")));
rejectTags(core(128,line(CoreRecord.TECH),content,item.id32()),List.of(tag("App","test5599"),tag("n","128"),tag("l",Integer.toString(CoreRecord.TECH))));
ok(ShineProtocolTags.CORE_REGISTRATION_TAGS.equals(List.of(tag("App","SHiNE"), tag("t","reg"), tag("Protocol","SHiNE-Free-Registration-V1"))), "separate registration tags");
rejectTags(c,List.of(tag("App","SHiNE"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","0128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","129"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","128"),tag("l","P")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","128")));
rejectTags(c,List.of(tag("App","test5570"),tag("App","test5570"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","128"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","128"),tag("l","0"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","128"),tag("l","0"),tag("c","news")));
rejectTags(c,List.of(tag("App","test5570"),tag("n","128"),tag("l","0"),tag("t","tech")));
rejectTags(core(128,null,content,item.id32()),List.of(tag("App","test5570"),tag("n","128"),tag("l","0")));
rejectTags(core(128,line(CoreRecord.TECH),content,item.id32()),List.of(tag("App","test5570"),tag("n","128"),tag("l",Integer.toString(CoreRecord.TECH))));
ok(ShineProtocolTags.CORE_REGISTRATION_TAGS.equals(List.of(tag("App",ShineProtocolTags.CORE_NAMESPACE), tag("t","reg"), tag("Protocol","SHiNE-Free-Registration-V1"))), "separate registration tags");
rejectTags(core(128,null,content,item.id32()),ShineProtocolTags.CORE_REGISTRATION_TAGS);
var oldFrame=new byte[109]; oldFrame[1]=1;
bad(() -> CoreRecord.parse(oldFrame),"old Frame v1");
@@ -240,7 +242,7 @@ public final class StageAProtocolChecks {
return result;
}
private static void checkRawTagSignatures() {
var original = CoreContentTransport.sign(new byte[]{7},List.of(tag("App","test5599")),SEED);
var original = CoreContentTransport.sign(new byte[]{7},List.of(tag("App","test5570")),SEED);
byte[] raw = original.rawTags();
// Эквивалентный Avro-массив с отрицательным count и явным размером блока.
byte[] alternative = new byte[raw.length+1];
@@ -61,6 +61,9 @@ public final class AppConfig {
}
}
/** Значение из конфигурационного файла без системных/env переопределений. */
public String getFileParam(String name) { return properties.getProperty(name); }
/** Вернёт значение строки или null, если параметр не найден */
public String getParam(String name) {
String fromSystem = System.getProperty(name);
@@ -0,0 +1,19 @@
package utils.config;
/** Единый неизменяемый режим процесса. Только точное false включает production. */
public final class ServerEnvironment {
private ServerEnvironment() {}
public static final String PRODUCTION_APP = "SHiNE";
public static final String TEST_APP = "test5570";
public static boolean isTestMode(String value) { return !"false".equals(value); }
private static String configuredMode() {
// Чистые protocol-тесты не требуют серверного application.properties.
if (!java.nio.file.Files.exists(java.nio.file.Path.of("application.properties"))
&& ServerEnvironment.class.getClassLoader().getResource("application.properties") == null) return null;
return AppConfig.getInstance().getFileParam("server.testMode");
}
public static final boolean TEST_MODE = isTestMode(configuredMode());
public static final String ARWEAVE_APP_TAG = TEST_MODE ? TEST_APP : PRODUCTION_APP;
public static final String SOLANA_CLUSTER = TEST_MODE ? "devnet" : "mainnet-beta";
public static final String DEFAULT_RPC_URL = "https://api." + SOLANA_CLUSTER + ".solana.com";
}
@@ -2,8 +2,8 @@ package utils.config;
/**
* Публичные адреса Solana-программ SHiNE.
* Program ID одинаковые для mainnet/devnet, а cluster/RPC должны
* переопределяться через application.properties конкретного инстанса.
* Program ID одинаковые для mainnet/devnet; кластер определяется ServerEnvironment.
* RPC можно переопределять в application.properties.
*/
public final class SolanaProgramsConfig {
@@ -11,8 +11,8 @@ public final class SolanaProgramsConfig {
private static final AppConfig CONFIG = AppConfig.getInstance();
public static final String SOLANA_CLUSTER = getParam("solana.cluster", "mainnet-beta");
public static final String SOLANA_RPC_URL = getParam("solana.rpcUrl", "https://api.mainnet-beta.solana.com");
public static final String SOLANA_CLUSTER = ServerEnvironment.SOLANA_CLUSTER;
public static final String SOLANA_RPC_URL = getParam("solana.rpcUrl", ServerEnvironment.DEFAULT_RPC_URL);
// Программа регистрации пользователей (shine_users), задеплоена в mainnet.
public static final String SHINE_USERS_PROGRAM_ID = "SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6";
@@ -100,6 +100,13 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
if (blockchainName == null || blockchainName.isBlank()) {
return error(req, WireCodes.Status.BAD_REQUEST, "empty_blockchain_name", 0, "");
}
try {
blockchain.CoreContentTransport.requireApp(CoreContentContainer.unpack(decodeBase64(req.getBlockBytesB64())).core());
} catch (blockchain.CoreContentTransport.WrongAppNamespace e) {
return error(req, 422, "WRONG_APP_NAMESPACE", -1, "");
} catch (IllegalArgumentException e) {
return error(req, 400, "bad_block_format", -1, "");
}
if (BlockchainResyncGuard.isBlockedForExternalAddBlock(blockchainName)) {
BlockchainStateEntry currentState = null;
try {
@@ -236,6 +243,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "pending_publication_limit" -> "Слишком много блоков ожидают публикации в Turbo";
case "block_number_conflict" -> "Номер блока уже занят другой подписанной парой";
case "limit_check_failed" -> "Ошибка проверки лимита размера";
case "WRONG_APP_NAMESPACE" -> "Блок принадлежит другой сети SHiNE";
case "bad_block_format" -> "Некорректный формат блока";
case "bad_block_body" -> "Некорректное тело блока";
case "header_v1_required" -> "Для нового блокчейна требуется HEADER 1.0 с типом аккаунта";
@@ -366,6 +374,13 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
login, blockchainName, globalNumberFromReq, e);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_base64", serverLastNum, serverLastHashHex);
}
try {
blockchain.CoreContentTransport.requireApp(CoreContentContainer.unpack(blockBytes).core());
} catch (blockchain.CoreContentTransport.WrongAppNamespace e) {
return new AddBlockResult(422, "WRONG_APP_NAMESPACE", serverLastNum, serverLastHashHex);
} catch (IllegalArgumentException e) {
return new AddBlockResult(400, "bad_block_format", serverLastNum, serverLastHashHex);
}
if (publishToArweave && !replayMode && globalNumberFromReq >= 0 && globalNumberFromReq <= serverLastNum) {
try {
BlockEntry existing = blocksDAO.getByNumber(blockchainName, globalNumberFromReq);
@@ -49,6 +49,13 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "blockNumber и blockBytesB64 обязательны");
}
try {
blockchain.CoreContentTransport.requireApp(blockchain.CoreContentContainer.unpack(Base64Ws.decode(req.getBlockBytesB64())).core());
} catch (blockchain.CoreContentTransport.WrongAppNamespace e) {
return NetExceptionResponseFactory.error(req, 422, "WRONG_APP_NAMESPACE", "Блок принадлежит другой сети SHiNE");
} catch (IllegalArgumentException e) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "Некорректный формат блока");
}
String login = ctx.getLogin().trim();
KeyRotationSessionEntry initial;
try {
@@ -32,7 +32,9 @@ public class Net_GetServerInfo_Handler implements JsonMessageHandler {
resp.setDescription(CONFIG.getStringOrEmpty("server.info.description"));
resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin"));
resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo"));
resp.setSolanaCluster(CONFIG.getStringOrEmpty("solana.cluster"));
resp.setTestMode(utils.config.ServerEnvironment.TEST_MODE);
resp.setArweaveAppTag(utils.config.ServerEnvironment.ARWEAVE_APP_TAG);
resp.setSolanaCluster(utils.config.ServerEnvironment.SOLANA_CLUSTER);
resp.setAboutText(ServerAboutText.readServerAbout(java.nio.file.Path.of(".")));
return resp;
@@ -27,6 +27,12 @@ public class Net_GetServerInfo_Response extends Net_Response {
private String origin;
private String extraInfo;
private String solanaCluster;
private boolean testMode;
private String arweaveAppTag;
public boolean isTestMode() { return testMode; }
public void setTestMode(boolean value) { testMode = value; }
public String getArweaveAppTag() { return arweaveAppTag; }
public void setArweaveAppTag(String value) { arweaveAppTag = value; }
private String aboutText;
public String getAboutText() { return aboutText; }
@@ -57,13 +57,8 @@ public record AppConfig(
utils.config.AppConfig serverConfig
) {
String rpcUrl =
firstRequired(
serverConfig,
"Solana users sync RPC URL",
RPC_URL_KEY,
LEGACY_SOLANA_RPC_URL_KEY
);
String rpcUrl = optionalParam(serverConfig, RPC_URL_KEY);
if (rpcUrl == null) rpcUrl = utils.config.SolanaProgramsConfig.SOLANA_RPC_URL;
String websocketUrl =
requireParam(
@@ -0,0 +1,108 @@
package server.ws;
import blockchain.Ans104DataItem;
import blockchain.CoreContentContainer;
import blockchain.CoreContentTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import shine.db.DbController;
import utils.config.AppConfig;
import utils.config.ServerEnvironment;
import utils.config.SolanaProgramsConfig;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.sql.Connection;
import java.time.Duration;
import java.util.List;
/** Проверки до запуска сетевого сервера и фоновых задач. Не удаляет пользовательские данные. */
final class ServerEnvironmentGuard {
private static final AppConfig CFG = AppConfig.getInstance();
private static final String APP = ServerEnvironment.ARWEAVE_APP_TAG;
private static final String GENESIS = ServerEnvironment.TEST_MODE
? "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG"
: "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d";
private ServerEnvironmentGuard() {}
static void verifyConfiguration() throws Exception {
// Не даём устаревшему параметру выбрать другую сеть незаметно.
String legacy = CFG.getStringOrEmpty("solana.cluster");
if (!legacy.isEmpty() && !legacy.equals(ServerEnvironment.SOLANA_CLUSTER))
throw new IllegalStateException("Remove obsolete solana.cluster or set server.testMode correctly");
String rpc = CFG.getStringOrEmpty("solana.rpcUrl");
if (!rpc.isEmpty()) verifyRpc(rpc, "solana.rpcUrl");
if (sync.config.AppConfig.isEnabled(CFG)) {
var syncConfig = sync.config.AppConfig.fromServerConfig(CFG);
if (!syncConfig.databaseUrl().equals(CFG.getStringOrEmpty("db.url")))
throw new IllegalStateException("Solana users sync must use the same runtime database");
if (!syncConfig.rpcUrl().equals(rpc)) verifyRpc(syncConfig.rpcUrl(), "solana.users.sync.rpcUrl");
// HTTP equivalent of the WS endpoint must also belong to the same cluster.
String ws = syncConfig.websocketUrl();
String http = ws.startsWith("wss://") ? "https://" + ws.substring(6)
: ws.startsWith("ws://") ? "http://" + ws.substring(5) : "";
if (http.isEmpty()) throw new IllegalStateException("Invalid Solana users sync WS URL");
if (!http.equals(syncConfig.rpcUrl()) && !http.equals(rpc)) verifyRpc(http, "solana.users.sync.wsUrl");
}
if (!ServerEnvironment.TEST_MODE && CFG.getBoolean("arweave.blocks.sync.enabled", false)
&& CFG.getStringOrEmpty("arweave.blocks.sync.startBlockHeight").matches("[1-9][0-9]*") == false)
throw new IllegalStateException("Production Arweave sync requires an explicit positive startBlockHeight after legacy test publications");
}
private static void verifyRpc(String url, String key) throws Exception {
// Не выводить URL: он может содержать API key.
try {
URI uri = URI.create(url);
var http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(8)).build();
var request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(15))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"getGenesisHash\",\"params\":[]}" )).build();
var response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200 || !GENESIS.equals(new ObjectMapper().readTree(response.body()).path("result").asText()))
throw new IllegalStateException("Wrong Solana genesis hash");
} catch (Exception e) {
throw new IllegalStateException("Cannot verify Solana cluster for " + key + "; expected " + ServerEnvironment.SOLANA_CLUSTER);
}
}
static void bindDatabase() throws Exception {
try (Connection c = DbController.getInstance().getConnection()) {
c.setAutoCommit(false);
try (var s = c.createStatement()) {
// Advisory transaction lock serializes first start of two server processes.
s.execute("SELECT pg_advisory_xact_lock(5570010)");
s.execute("CREATE TABLE IF NOT EXISTS shine_runtime_environment (id INTEGER PRIMARY KEY CHECK(id=1), arweave_app_tag TEXT NOT NULL)");
String bound = null;
try (var rs = s.executeQuery("SELECT arweave_app_tag FROM shine_runtime_environment WHERE id=1")) {
if (rs.next()) bound = rs.getString(1);
}
if (bound != null && !APP.equals(bound)) throw new IllegalStateException("Database belongs to another SHiNE environment: " + bound);
if (bound == null) {
boolean populated;
try (var rs = s.executeQuery("SELECT EXISTS(SELECT 1 FROM user_identity_current) OR EXISTS(SELECT 1 FROM blocks_store) OR EXISTS(SELECT 1 FROM solana_user_pda_current) OR EXISTS(SELECT 1 FROM shine_namespace_current) OR EXISTS(SELECT 1 FROM arweave_block_import_queue)")) {
rs.next(); populated = rs.getBoolean(1);
}
if (populated && !"true".equals(CFG.getParam("server.adoptExistingDatabase")))
throw new IllegalStateException("Unmarked populated database: use a new database or explicitly audit and adopt it with server.adoptExistingDatabase=true");
// Audit signed tags in existing history and staging before recording the environment.
for (String table : List.of("blocks_store", "key_rotation_candidate_blocks", "key_rotation_rebuild_staging", "canonical_rebuild_staging")) {
try (var rows = s.executeQuery("SELECT block_bytes FROM " + table)) {
while (rows.next()) CoreContentTransport.requireApp(CoreContentContainer.unpack(rows.getBytes(1)).core());
}
}
try (var rows = s.executeQuery("SELECT raw_signed_data_item FROM free_registration_certificate")) {
while (rows.next()) CoreContentTransport.requireApp(new Ans104DataItem(rows.getBytes(1)));
}
// Old queue may contain legacy App values and old checkpoints; do not adopt silently.
try (var rows = s.executeQuery("SELECT 1 FROM arweave_block_import_queue WHERE status='PENDING' LIMIT 1")) {
if (rows.next()) throw new IllegalStateException("Unmarked database has pending Arweave imports; audit queue or use a clean database");
}
try (var ins = c.prepareStatement("INSERT INTO shine_runtime_environment(id, arweave_app_tag) VALUES (1, ?)")) {
ins.setString(1, APP); ins.executeUpdate();
}
}
c.commit();
} catch (Exception e) { c.rollback(); throw e; }
}
}
}
@@ -68,7 +68,7 @@ public final class SolanaRpcGateway extends HttpServlet {
Window window = LIMITS.compute(key, (k, old) -> old == null || old.minute != minute
? new Window(minute, 1) : new Window(minute, old.count + 1));
if (window.count > (write ? 6 : 180)) { fail(resp, 429, "RPC request limit exceeded"); return; }
String rpc = AppConfig.getInstance().getStringOrEmpty("solana.rpcUrl");
String rpc = utils.config.SolanaProgramsConfig.SOLANA_RPC_URL;
if (!rpc.startsWith("https://") && !rpc.startsWith("http://")) {
fail(resp, 503, "Solana RPC is not configured"); return;
}
@@ -39,7 +39,9 @@ public final class WsServer {
// Solana sync использует ту же БД и создаёт собственные таблицы;
// без этого порядка чистая БД ошибочно выглядит для runtime как legacy.
// ============================================================
ServerEnvironmentGuard.verifyConfiguration();
DbController.getInstance();
ServerEnvironmentGuard.bindDatabase();
// ============================================================
// 1.1) Синхронизация пользовательских Solana PDA