SHA256
Compare commits
18
Commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
5db3ad8a3e | ||
|
|
e556615fa9 | ||
|
|
790740cd56 | ||
|
|
d91e4a32df | ||
|
|
9e7526fd81 | ||
|
|
d3a84dd451 | ||
|
|
653015b2e7 | ||
|
|
8ac8f04128 | ||
|
|
80c70ebcdc | ||
|
|
792f368175 | ||
|
|
859dbee1f1 | ||
|
|
8f3b81c368 | ||
|
|
0274183730 | ||
|
|
c9f54224bb | ||
|
|
02c705d41e | ||
|
|
76bbc9d023 | ||
|
|
780ca53931 | ||
|
|
fc86c6190e |
+66
-9
@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
|
||||
import server.sync.BlockchainResyncGuard;
|
||||
import shine.db.DbController;
|
||||
import shine.db.KeyEncodingUtil;
|
||||
import utils.config.AppConfig;
|
||||
import shine.db.dao.ArweaveBlockImportDAO;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
@@ -19,6 +20,7 @@ import shine.db.dao.CanonicalChainResolver;
|
||||
import shine.db.dao.ChannelReadStateDAO;
|
||||
import shine.db.dao.BlockchainResyncCleanupDAO;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.dao.RegistrationIdentityDAO;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
|
||||
@@ -225,7 +227,7 @@ public final class ArweaveBlockSyncService {
|
||||
if (pending.isEmpty()) break;
|
||||
for (ArweaveBlockImportDAO.QueueItem q : pending) {
|
||||
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
|
||||
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin());
|
||||
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
|
||||
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
|
||||
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
|
||||
continue;
|
||||
@@ -257,7 +259,7 @@ public final class ArweaveBlockSyncService {
|
||||
progress = true;
|
||||
continue;
|
||||
}
|
||||
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32());
|
||||
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (physicalUser == null || physicalUser.getBlockchainName() == null
|
||||
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|
||||
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
|
||||
@@ -335,7 +337,7 @@ public final class ArweaveBlockSyncService {
|
||||
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
|
||||
BchBlockEntry b = new BchBlockEntry(raw);
|
||||
|
||||
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32());
|
||||
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
|
||||
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
|
||||
continue;
|
||||
@@ -352,7 +354,7 @@ public final class ArweaveBlockSyncService {
|
||||
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
|
||||
if (b.blockNumber != fb.forkPointBlockNumber + 1)
|
||||
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
|
||||
SolanaUserPdaCurrentEntry parent = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32);
|
||||
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
|
||||
if (parent == null || parent.getBlockchainName() == null
|
||||
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
|
||||
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
|
||||
@@ -388,9 +390,64 @@ public final class ArweaveBlockSyncService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обычный пользователь подтверждается текущим Solana PDA. У бесплатной регистрации PDA
|
||||
* намеренно отсутствует: её проверяемая идентичность хранится в сертификате. Для обеих
|
||||
* моделей импортёр должен сопоставить ANS-104 owner с уже проверенной локальной записью,
|
||||
* иначе блоки FREE_CERT никогда не смогут попасть на другой сервер.
|
||||
*/
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByLogin(String login) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByLogin(login);
|
||||
if (solana != null) return solana;
|
||||
|
||||
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
|
||||
if (identity == null || !identity.isFree() || identity.blockchainKey() == null || identity.blockchainKey().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return freeCertificateOwner(identity.fullLogin(), identity.blockchainKey());
|
||||
}
|
||||
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainKey(byte[] owner32) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainKey(owner32);
|
||||
if (solana != null) return solana;
|
||||
if (owner32 == null || owner32.length != 32) return null;
|
||||
|
||||
String blockchainKey = KeyEncodingUtil.encodeBase58(owner32);
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT login, blockchain_key
|
||||
FROM user_identity_current
|
||||
WHERE registration_status='FREE_CERT' AND blockchain_key=?
|
||||
LIMIT 1
|
||||
""")) {
|
||||
ps.setString(1, blockchainKey);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? freeCertificateOwner(rs.getString("login"), rs.getString("blockchain_key")) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainName(String blockchainName) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainName(blockchainName);
|
||||
if (solana != null) return solana;
|
||||
if (blockchainName == null || !blockchainName.endsWith("-001")) return null;
|
||||
String login = blockchainName.substring(0, blockchainName.length() - 4);
|
||||
SolanaUserPdaCurrentEntry free = resolveChainOwnerByLogin(login);
|
||||
return free != null && blockchainName.equalsIgnoreCase(free.getBlockchainName()) ? free : null;
|
||||
}
|
||||
|
||||
private static SolanaUserPdaCurrentEntry freeCertificateOwner(String login, String blockchainKey) {
|
||||
SolanaUserPdaCurrentEntry owner = new SolanaUserPdaCurrentEntry();
|
||||
owner.setLogin(login);
|
||||
owner.setBlockchainName(login.toLowerCase(Locale.ROOT) + "-001");
|
||||
owner.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(blockchainKey));
|
||||
owner.setPaidLimitBytes(0L);
|
||||
return owner;
|
||||
}
|
||||
|
||||
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
|
||||
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
|
||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L);
|
||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
|
||||
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
|
||||
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
|
||||
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
|
||||
@@ -414,7 +471,7 @@ public final class ArweaveBlockSyncService {
|
||||
while(rs.next())logins.add(rs.getString(1));
|
||||
}
|
||||
for(String login:logins){
|
||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);
|
||||
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
|
||||
if(u==null||u.getBlockchainName()==null)continue;
|
||||
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
|
||||
}
|
||||
@@ -477,17 +534,17 @@ public final class ArweaveBlockSyncService {
|
||||
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
|
||||
}
|
||||
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
|
||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
||||
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
||||
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
|
||||
try{
|
||||
validateGenericStaging(login);
|
||||
cleanupDAO.cleanupLoginForCanonicalReplay(login);
|
||||
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
|
||||
String bch=login+"-"+String.format("%03d",f);
|
||||
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
|
||||
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
||||
}}
|
||||
|
||||
+7
-2
@@ -33,7 +33,9 @@ public final class FreeRegistrationApiBootstrap {
|
||||
FreeRegistrationPublisher publisher=null;
|
||||
RegistrationEmailSender emailSender=null;
|
||||
AllowedEmailDomains allowedEmailDomains=null;
|
||||
if (cfg.getBoolean("freeRegistration.enabled",false)) {
|
||||
String freeNamespace=cfg.getStringOrEmpty("freeRegistration.namespace").trim();
|
||||
boolean freeRegistrationEnabled=cfg.getBoolean("freeRegistration.enabled",false) && !freeNamespace.isEmpty();
|
||||
if (freeRegistrationEnabled) {
|
||||
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
|
||||
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
|
||||
// Относительный путь — от WorkingDirectory процесса Java.
|
||||
@@ -44,6 +46,8 @@ public final class FreeRegistrationApiBootstrap {
|
||||
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
|
||||
throw new IllegalStateException("Free registration requires Turbo transport");
|
||||
newSigner=LocalRegistrarSigner.fromConfig(cfg);
|
||||
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
|
||||
cfg.getStringOrEmpty("server.SHiNE.login"));
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
|
||||
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
|
||||
new VerifiedFreeRegistrationImporter(allowEmailReuse));
|
||||
@@ -58,7 +62,8 @@ public final class FreeRegistrationApiBootstrap {
|
||||
}
|
||||
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
|
||||
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains);
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
|
||||
freeRegistrationEnabled ? freeNamespace : "");
|
||||
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||
signer=newSigner; workflow=newWorkflow;
|
||||
}
|
||||
|
||||
+24
@@ -24,6 +24,30 @@ public final class FreeRegistrationIssuer {
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
}
|
||||
|
||||
/** Проверяет привязку локального ключа и сервера до открытия бесплатной регистрации. */
|
||||
static void validateConfiguredNamespace(DataSource db, RegistrarSigner signer, String namespace,
|
||||
String localServerLogin) throws Exception {
|
||||
if (localServerLogin == null || localServerLogin.isBlank())
|
||||
throw new IllegalStateException("server.SHiNE.login is required for free registration");
|
||||
try (Connection conn = db.getConnection();
|
||||
PreparedStatement statement = conn.prepareStatement("""
|
||||
SELECT namespace_type, registrar_pubkey, default_server_login
|
||||
FROM shine_namespace_current WHERE namespace = ?
|
||||
""")) {
|
||||
statement.setString(1, namespace);
|
||||
try (ResultSet rs = statement.executeQuery()) {
|
||||
if (!rs.next() || rs.getInt("namespace_type") != 2)
|
||||
throw new IllegalStateException("Configured free registration namespace is unavailable");
|
||||
byte[] namespaceKey = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||
if (!Arrays.equals(namespaceKey, signer.publicKey32()))
|
||||
throw new IllegalStateException("Registrar public key does not match configured namespace");
|
||||
String namespaceServer = rs.getString("default_server_login");
|
||||
if (namespaceServer == null || !namespaceServer.equalsIgnoreCase(localServerLogin.trim()))
|
||||
throw new IllegalStateException("Configured free namespace belongs to another access server");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */
|
||||
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email) throws Exception {
|
||||
|
||||
+28
-6
@@ -51,10 +51,12 @@ public final class FreeRegistrationWorkflow {
|
||||
private final boolean allowTestCode;
|
||||
private final boolean allowEmailReuse;
|
||||
private final AllowedEmailDomains allowedEmailDomains;
|
||||
/** Единственный type-2 namespace, для которого этот сервер является регистратором. */
|
||||
private final String freeRegistrationNamespace;
|
||||
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains) {
|
||||
AllowedEmailDomains allowedEmailDomains, String freeRegistrationNamespace) {
|
||||
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
|
||||
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
|
||||
if (emailSender != null && allowedEmailDomains == null)
|
||||
@@ -65,11 +67,24 @@ public final class FreeRegistrationWorkflow {
|
||||
this.emailSender = emailSender;
|
||||
this.allowTestCode = allowTestCode;
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
this.freeRegistrationNamespace = normalizeConfiguredNamespace(freeRegistrationNamespace);
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, allowedEmailDomains, "");
|
||||
}
|
||||
private static String normalizeConfiguredNamespace(String value) {
|
||||
String namespace = value == null ? "" : value.trim();
|
||||
if (namespace.isEmpty()) return "";
|
||||
if (!namespace.matches("[a-z0-9_]+"))
|
||||
throw new IllegalArgumentException("Free registration namespace must use lowercase ASCII letters, digits or _");
|
||||
return namespace;
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
|
||||
emailSender == null ? null : loadDefaultEmailDomains());
|
||||
emailSender == null ? null : loadDefaultEmailDomains(), "");
|
||||
}
|
||||
private static AllowedEmailDomains loadDefaultEmailDomains() {
|
||||
try {
|
||||
@@ -94,10 +109,15 @@ public final class FreeRegistrationWorkflow {
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login
|
||||
FROM shine_namespace_current ORDER BY namespace
|
||||
"""); ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
|
||||
rs.getString(4),rs.getInt(5),rs.getString(6)));
|
||||
FROM shine_namespace_current
|
||||
WHERE namespace_type = 1 OR (namespace_type = 2 AND namespace = ?)
|
||||
ORDER BY namespace
|
||||
""")) {
|
||||
ps.setString(1, freeRegistrationNamespace);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
|
||||
rs.getString(4),rs.getInt(5),rs.getString(6)));
|
||||
}
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
@@ -111,6 +131,8 @@ public final class FreeRegistrationWorkflow {
|
||||
try (ResultSet rs=p.executeQuery()) {
|
||||
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
|
||||
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4);
|
||||
if (type == 2 && !namespace.equals(freeRegistrationNamespace))
|
||||
throw new IllegalArgumentException("Free registration is unavailable for this namespace");
|
||||
if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
|
||||
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||
}
|
||||
|
||||
+5
-2
@@ -122,9 +122,12 @@ public final class VerifiedFreeRegistrationImporter {
|
||||
INSERT INTO blockchain_state_store (
|
||||
login, fork_number, blockchain_key, size_limit, file_size_bytes,
|
||||
last_block_number, last_block_hash, updated_at_ms)
|
||||
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
|
||||
VALUES (?, 1, ?, 0, 0, -1, ?, ?)
|
||||
""")) {
|
||||
insert.setString(1, login);
|
||||
// blockchain_state — техническая проекция chain: её ключ
|
||||
// совпадает с normalized_login и blockchain_name, а не с
|
||||
// отображаемым написанием login в сертификате.
|
||||
insert.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
|
||||
// как и у пользователей, импортированных из Solana PDA.
|
||||
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class FreeRegistrationNamespaceConfigurationTest {
|
||||
@Test
|
||||
void acceptsLowercaseNamespaceForLocalFreeRegistration() {
|
||||
assertDoesNotThrow(() -> new FreeRegistrationWorkflow(
|
||||
null, null, null, false, false, null, "testfree"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMixedCaseNamespaceInsteadOfSilentlyServingAnotherNamespace() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new FreeRegistrationWorkflow(
|
||||
null, null, null, false, false, null, "TestFree"));
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,9 @@ public final class DatabaseInitializer {
|
||||
public static final int SCHEMA_VERSION_40 = 40;
|
||||
public static final int SCHEMA_VERSION_41 = 41;
|
||||
public static final int SCHEMA_VERSION_42 = 42;
|
||||
public static final int SCHEMA_VERSION_43 = 43;
|
||||
public static final int SCHEMA_VERSION_44 = 44;
|
||||
public static final int SCHEMA_VERSION_45 = 45;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||
@@ -46,6 +49,9 @@ public final class DatabaseInitializer {
|
||||
public static final String POSTGRES_MIGRATION_V40_RESOURCE = "postgres/migration_v40.sql";
|
||||
public static final String POSTGRES_MIGRATION_V41_RESOURCE = "postgres/migration_v41.sql";
|
||||
public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.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_V45_RESOURCE = "postgres/migration_v45.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -185,9 +191,21 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V42_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_42) {
|
||||
if (currentVersion == SCHEMA_VERSION_42) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V43_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion == SCHEMA_VERSION_43) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion == SCHEMA_VERSION_44) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_45) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 42, found " + currentVersion);
|
||||
"Unsupported SHiNE DB v2 schema version: expected 45, found " + currentVersion);
|
||||
}
|
||||
normalizeBlockchainStateKeysToBase64(conn);
|
||||
}
|
||||
|
||||
@@ -187,10 +187,27 @@ public final class BlockchainStateDAO {
|
||||
}
|
||||
}
|
||||
|
||||
/** Change ONLY the quota projection; 0 means unbounded. */
|
||||
public void updateSizeLimit(String blockchainName, long limit) throws SQLException {
|
||||
if (limit < 0L) throw new IllegalArgumentException("limit must be nonnegative");
|
||||
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
|
||||
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
""")) {
|
||||
ChainRef r = chainRef(blockchainName);
|
||||
ps.setLong(1, limit);
|
||||
ps.setLong(2, System.currentTimeMillis());
|
||||
ps.setString(3, r.login());
|
||||
ps.setInt(4, r.fork());
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit.
|
||||
*/
|
||||
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
|
||||
if (deltaBytes < 0L) throw new IllegalArgumentException("deltaBytes must be nonnegative");
|
||||
String sql = """
|
||||
UPDATE blockchain_state_store
|
||||
SET
|
||||
@@ -198,7 +215,8 @@ public final class BlockchainStateDAO {
|
||||
updated_at_ms = ?
|
||||
WHERE
|
||||
LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
AND (file_size_bytes + ?) <= size_limit
|
||||
AND file_size_bytes <= 9223372036854775807 - ?
|
||||
AND (size_limit = 0 OR (file_size_bytes + ?) <= size_limit)
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -208,6 +226,7 @@ public final class BlockchainStateDAO {
|
||||
ps.setString(3, r.login());
|
||||
ps.setInt(4, r.fork());
|
||||
ps.setLong(5, deltaBytes);
|
||||
ps.setLong(6, deltaBytes);
|
||||
return ps.executeUpdate() > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,24 +73,63 @@ public final class ChannelNameStateDAO {
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, entry.getSlug());
|
||||
ps.setString(2, entry.getDisplayName());
|
||||
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
||||
ps.setString(4, entry.getOwnerLogin());
|
||||
ps.setString(5, entry.getOwnerBlockchainName());
|
||||
ps.setInt(6, entry.getChannelTypeCode());
|
||||
ps.setInt(7, entry.getChannelTypeVersion());
|
||||
ps.setInt(8, entry.getChannelRootBlockNumber());
|
||||
ps.setBytes(9, entry.getChannelRootBlockHash());
|
||||
ps.setLong(10, entry.getCreatedAtMs());
|
||||
ps.setString(11, entry.getAvaAr() == null ? "" : entry.getAvaAr());
|
||||
ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr());
|
||||
ps.setLong(13, Math.max(0L, entry.getAvaSize()));
|
||||
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
||||
bindInsert(ps, entry);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Используется только при воспроизведении уже подписанной истории. В live AddBlock
|
||||
* дубликат имени запрещён; при replay блок всё же нужно сохранить, иначе цепочка
|
||||
* после него останется разорванной.
|
||||
*/
|
||||
public void insertOrReplaceWithNewerRoot(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
||||
String sql = """
|
||||
INSERT INTO channel_names_state (
|
||||
slug, display_name, channel_description, owner_login, owner_bch_name,
|
||||
channel_type_code, channel_type_version, channel_root_block_number,
|
||||
channel_root_block_hash, created_at_ms, ava_ar, ava_pr, ava_size, meta_updated_at_ms
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (owner_bch_name, channel_type_code, slug) DO UPDATE SET
|
||||
display_name = EXCLUDED.display_name,
|
||||
channel_description = EXCLUDED.channel_description,
|
||||
owner_login = EXCLUDED.owner_login,
|
||||
channel_type_version = EXCLUDED.channel_type_version,
|
||||
channel_root_block_number = EXCLUDED.channel_root_block_number,
|
||||
channel_root_block_hash = EXCLUDED.channel_root_block_hash,
|
||||
created_at_ms = EXCLUDED.created_at_ms,
|
||||
ava_ar = EXCLUDED.ava_ar,
|
||||
ava_pr = EXCLUDED.ava_pr,
|
||||
ava_size = EXCLUDED.ava_size,
|
||||
meta_updated_at_ms = EXCLUDED.meta_updated_at_ms,
|
||||
is_deleted = FALSE,
|
||||
deleted_at_ms = 0,
|
||||
deleted_block_number = NULL
|
||||
WHERE EXCLUDED.channel_root_block_number > channel_names_state.channel_root_block_number
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
bindInsert(ps, entry);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
private static void bindInsert(PreparedStatement ps, ChannelNameStateEntry entry) throws SQLException {
|
||||
ps.setString(1, entry.getSlug());
|
||||
ps.setString(2, entry.getDisplayName());
|
||||
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
||||
ps.setString(4, entry.getOwnerLogin());
|
||||
ps.setString(5, entry.getOwnerBlockchainName());
|
||||
ps.setInt(6, entry.getChannelTypeCode());
|
||||
ps.setInt(7, entry.getChannelTypeVersion());
|
||||
ps.setInt(8, entry.getChannelRootBlockNumber());
|
||||
ps.setBytes(9, entry.getChannelRootBlockHash());
|
||||
ps.setLong(10, entry.getCreatedAtMs());
|
||||
ps.setString(11, entry.getAvaAr() == null ? "" : entry.getAvaAr());
|
||||
ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr());
|
||||
ps.setLong(13, Math.max(0L, entry.getAvaSize()));
|
||||
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
||||
}
|
||||
|
||||
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
||||
String sql = """
|
||||
UPDATE channel_names_state
|
||||
|
||||
+20
-4
@@ -73,10 +73,26 @@ public final class SolanaUserPdaCurrentDAO {
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, blockchainName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) {
|
||||
return null;
|
||||
}
|
||||
return mapRow(rs);
|
||||
if (rs.next()) return mapRow(rs);
|
||||
}
|
||||
}
|
||||
// Old forks remain valid separate blockchains even after root rotation.
|
||||
String forkSql = """
|
||||
SELECT u.login,
|
||||
u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0') AS blockchain_name,
|
||||
f.value ->> 'blockchainKey' AS blockchain_key,
|
||||
(f.value ->> 'paidLimitBytes')::bigint AS paid_limit_bytes
|
||||
FROM solana_user_pda_current u
|
||||
CROSS JOIN LATERAL jsonb_array_elements(
|
||||
COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb
|
||||
) AS f(value)
|
||||
WHERE LOWER(u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0')) = LOWER(?)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(forkSql)) {
|
||||
ps.setString(1, blockchainName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-4
@@ -10,6 +10,7 @@ import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public final class UserNotificationsStateDAO {
|
||||
private static volatile UserNotificationsStateDAO instance;
|
||||
@@ -45,7 +46,7 @@ public final class UserNotificationsStateDAO {
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
ps.setString(i++, e.getOwnerLogin());
|
||||
ps.setString(i++, normalizedLogin(e.getOwnerLogin()));
|
||||
ps.setString(i++, e.getNotificationKind());
|
||||
ps.setLong(i++, e.getCreatedAtMs());
|
||||
ps.setString(i++, e.getSourceLogin());
|
||||
@@ -74,7 +75,7 @@ public final class UserNotificationsStateDAO {
|
||||
""";
|
||||
List<UserNotificationEntry> out = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, ownerLogin);
|
||||
ps.setString(1, normalizedLogin(ownerLogin));
|
||||
ps.setString(2, kind);
|
||||
ps.setInt(3, Math.max(1, limit));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
@@ -96,7 +97,7 @@ public final class UserNotificationsStateDAO {
|
||||
""";
|
||||
List<UserNotificationEntry> out = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
|
||||
ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
|
||||
ps.setLong(4, Math.max(0, cutoffMs));
|
||||
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); }
|
||||
}
|
||||
@@ -106,7 +107,7 @@ public final class UserNotificationsStateDAO {
|
||||
public long countUnseen(Connection c, String ownerLogin, String kind, long seenAtMs) throws SQLException {
|
||||
String sql = "SELECT COUNT(*) FROM user_notifications_state WHERE owner_login = ? AND notification_kind = ? AND created_at_ms > ?";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
|
||||
ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
|
||||
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getLong(1) : 0L; }
|
||||
}
|
||||
}
|
||||
@@ -129,4 +130,12 @@ public final class UserNotificationsStateDAO {
|
||||
e.setSourceText(rs.getString("source_text"));
|
||||
return e;
|
||||
}
|
||||
|
||||
/**
|
||||
* owner_login — технический FK на normalized_login. Исходный регистр остаётся
|
||||
* в полях подписанного блока и в отображаемых source/target login.
|
||||
*/
|
||||
private static String normalizedLogin(String login) {
|
||||
return login == null ? null : login.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
||||
+8
-3
@@ -1,6 +1,7 @@
|
||||
package shine.db.entities;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Агрегатная сущность текущего состояния блокчейна.
|
||||
@@ -42,14 +43,18 @@ public final class BlockchainStateEntry {
|
||||
if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName);
|
||||
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
|
||||
if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999");
|
||||
this.login=blockchainName.substring(0,dash);
|
||||
// Runtime-ключ цепочки всегда нормализован. Исходное написание
|
||||
// зарегистрированного login хранится отдельно в user_identity_current.
|
||||
this.login=blockchainName.substring(0,dash).trim().toLowerCase(Locale.ROOT);
|
||||
this.forkNumber=parsedFork;
|
||||
}
|
||||
public int getForkNumber() { return forkNumber; }
|
||||
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
|
||||
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
public void setLogin(String login) {
|
||||
this.login = login == null ? null : login.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public String getBlockchainKey() { return blockchainKey; }
|
||||
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
|
||||
@@ -80,4 +85,4 @@ public final class BlockchainStateEntry {
|
||||
|
||||
public long getUpdatedAtMs() { return updatedAtMs; }
|
||||
public void setUpdatedAtMs(long updatedAtMs) { this.updatedAtMs = updatedAtMs; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
-- v43: runtime-идентичность blockchain_state совпадает с normalized_login.
|
||||
-- Исходный регистр зарегистрированного имени остаётся в user_identity_current.login
|
||||
-- и никогда не переписывает подписанные сертификаты или блоки.
|
||||
BEGIN;
|
||||
|
||||
-- blocks_store уже использует normalized_login. Временно снимаем составной FK,
|
||||
-- чтобы привести родительские строки blockchain_state к тому же ключу.
|
||||
ALTER TABLE blocks_store DROP CONSTRAINT IF EXISTS fk_blocks_physical_fork;
|
||||
ALTER TABLE blockchain_state_store DROP CONSTRAINT IF EXISTS blockchain_state_login_fkey;
|
||||
|
||||
-- v36-совместимость подставляла display login, что несовместимо с blocks_store.
|
||||
DROP TRIGGER IF EXISTS trg_canonical_identity_blockchain_state_store_login
|
||||
ON blockchain_state_store;
|
||||
|
||||
UPDATE blockchain_state_store
|
||||
SET login = LOWER(BTRIM(login))
|
||||
WHERE login IS DISTINCT FROM LOWER(BTRIM(login));
|
||||
|
||||
ALTER TABLE blockchain_state_store
|
||||
ADD CONSTRAINT blockchain_state_login_fkey
|
||||
FOREIGN KEY (login) REFERENCES user_identity_current(normalized_login);
|
||||
|
||||
ALTER TABLE blocks_store
|
||||
ADD CONSTRAINT fk_blocks_physical_fork
|
||||
FOREIGN KEY (login, fork_number)
|
||||
REFERENCES blockchain_state_store(login, fork_number);
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_normalize_blockchain_state_login()
|
||||
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
NEW.login := LOWER(BTRIM(NEW.login));
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
CREATE TRIGGER trg_normalize_blockchain_state_login
|
||||
BEFORE INSERT OR UPDATE OF login ON blockchain_state_store
|
||||
FOR EACH ROW EXECUTE FUNCTION shine_normalize_blockchain_state_login();
|
||||
|
||||
UPDATE db_schema_version
|
||||
SET schema_version = 43,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
WHERE id = 1;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,29 @@
|
||||
-- v44: owner_login уведомлений — технический ключ normalized_login.
|
||||
-- Исходный регистр остаётся в содержимом подписанных блоков и полях source/target.
|
||||
BEGIN;
|
||||
|
||||
UPDATE user_notifications_state
|
||||
SET owner_login = LOWER(BTRIM(owner_login))
|
||||
WHERE owner_login IS DISTINCT FROM LOWER(BTRIM(owner_login));
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_canonical_identity_user_notifications_state_owner_login
|
||||
ON user_notifications_state;
|
||||
DROP TRIGGER IF EXISTS trg_normalize_user_notifications_state_owner_login
|
||||
ON user_notifications_state;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_normalize_user_notification_owner_login()
|
||||
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
NEW.owner_login := LOWER(BTRIM(NEW.owner_login));
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
CREATE TRIGGER trg_normalize_user_notifications_state_owner_login
|
||||
BEFORE INSERT OR UPDATE OF owner_login ON user_notifications_state
|
||||
FOR EACH ROW EXECUTE FUNCTION shine_normalize_user_notification_owner_login();
|
||||
|
||||
UPDATE db_schema_version
|
||||
SET schema_version = 44,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
WHERE id = 1;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,68 @@
|
||||
-- v45: FREE_CERT — полноценная identity без фиктивной Solana PDA.
|
||||
-- Обычные проекции и чтение blockchain выбирают ветку по user_identity_current;
|
||||
-- Solana PDA остаётся источником только Solana-специфичных данных.
|
||||
BEGIN;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_identity_active_fork(p_login TEXT)
|
||||
RETURNS INTEGER
|
||||
LANGUAGE plpgsql
|
||||
STABLE
|
||||
AS $$
|
||||
DECLARE
|
||||
v_fork INTEGER;
|
||||
BEGIN
|
||||
SELECT substring(blockchain_name FROM '([0-9]{3})$')::INTEGER
|
||||
INTO v_fork
|
||||
FROM user_identity_current
|
||||
WHERE LOWER(login) = LOWER(BTRIM(p_login))
|
||||
LIMIT 1;
|
||||
|
||||
IF v_fork BETWEEN 1 AND 999 THEN
|
||||
RETURN v_fork;
|
||||
END IF;
|
||||
|
||||
SELECT fork_number
|
||||
INTO v_fork
|
||||
FROM blockchain_state_store
|
||||
WHERE LOWER(login) = LOWER(BTRIM(p_login))
|
||||
ORDER BY updated_at_ms DESC, fork_number DESC
|
||||
LIMIT 1;
|
||||
|
||||
RETURN COALESCE(v_fork, 1);
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_active_fork(p_login TEXT, p_block_number INTEGER)
|
||||
RETURNS INTEGER
|
||||
LANGUAGE sql
|
||||
STABLE
|
||||
AS $$
|
||||
SELECT shine_canonical_fork(p_login, shine_identity_active_fork(p_login), p_block_number)
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_channel_names_state_refresh_owner_stats()
|
||||
RETURNS TRIGGER
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
PERFORM shine_refresh_user_stats(OLD.owner_login);
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
PERFORM shine_refresh_user_stats(NEW.owner_login);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_channel_names_state_refresh_owner_stats ON channel_names_state;
|
||||
CREATE TRIGGER trg_channel_names_state_refresh_owner_stats
|
||||
AFTER INSERT OR UPDATE OF owner_login, channel_type_code, is_deleted OR DELETE
|
||||
ON channel_names_state
|
||||
FOR EACH ROW EXECUTE FUNCTION shine_channel_names_state_refresh_owner_stats();
|
||||
|
||||
-- Исправить уже записанные FREE_CERT и paid identity одним пересчётом.
|
||||
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
|
||||
|
||||
UPDATE db_schema_version
|
||||
SET schema_version = 45,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
WHERE id = 1;
|
||||
COMMIT;
|
||||
@@ -34,9 +34,14 @@ dependencies {
|
||||
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
|
||||
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
|
||||
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
|
||||
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
|
||||
+2
-2
@@ -143,7 +143,7 @@ public final class SolanaUserPdaImportService {
|
||||
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
|
||||
int major = u8(raw, 5);
|
||||
int minor = u8(raw, 6);
|
||||
if (major != 1 || minor != 2) return null;
|
||||
if (major != 1 || (minor != 2 && minor != 3)) return null;
|
||||
return parseUserPdaV12(raw);
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ public final class SolanaUserPdaImportService {
|
||||
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
|
||||
int major = u8(raw, 5);
|
||||
int minor = u8(raw, 6);
|
||||
if (major != 1 || minor != 2) return null;
|
||||
if (major != 1 || (minor != 2 && minor != 3)) return null;
|
||||
return parseServerProfileV12(raw);
|
||||
}
|
||||
|
||||
|
||||
+16
-3
@@ -38,6 +38,8 @@ import shine.db.dao.BlocksDAO;
|
||||
import shine.db.dao.CanonicalChainResolver;
|
||||
import shine.db.dao.ChannelNameStateDAO;
|
||||
import shine.db.dao.CurrentUsersDAO;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
import shine.db.dao.UserNotificationsStateDAO;
|
||||
import shine.db.dao.UserParamsDAO;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
@@ -53,6 +55,7 @@ import java.util.List;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/**
|
||||
@@ -67,6 +70,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_AddBlock_Handler.class);
|
||||
|
||||
private static long resolveChainLimit(String blockchainName) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
|
||||
return current == null ? 0L : current.getPaidLimitBytes();
|
||||
}
|
||||
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
|
||||
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
|
||||
@@ -281,7 +289,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
recovered.setBlockchainName(user.getBlockchainName());
|
||||
recovered.setLogin(user.getLogin());
|
||||
recovered.setBlockchainKey(user.getBlockchainKey());
|
||||
recovered.setSizeLimit(100_000L);
|
||||
recovered.setSizeLimit(Math.max(0L, resolveChainLimit(user.getBlockchainName())));
|
||||
recovered.setFileSizeBytes(0L);
|
||||
recovered.setLastBlockNumber(-1);
|
||||
recovered.setLastBlockHash(new byte[32]);
|
||||
@@ -335,7 +343,12 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
// 3) лимит (оставляем как было)
|
||||
try {
|
||||
long oldSize = st.getFileSizeBytes();
|
||||
long limit = st.getSizeLimit();
|
||||
// Current synced Solana PDA is authoritative; free users have no PDA.
|
||||
long limit = resolveChainLimit(blockchainName);
|
||||
if (limit != st.getSizeLimit()) {
|
||||
stateDAO.updateSizeLimit(blockchainName, limit);
|
||||
st.setSizeLimit(limit);
|
||||
}
|
||||
long newSize = safeAdd(oldSize, blockBytes.length);
|
||||
|
||||
if (limit > 0 && newSize > limit) {
|
||||
@@ -440,7 +453,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
}
|
||||
|
||||
try {
|
||||
if (channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) {
|
||||
if (!replayMode && channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) {
|
||||
return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
+4
-1
@@ -79,7 +79,10 @@ public final class BlockchainWriter {
|
||||
blocksDAO.insert(c, be);
|
||||
|
||||
if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
|
||||
if (channelNameStateEntry != null) channelNameStateDAO.insert(c, channelNameStateEntry);
|
||||
if (channelNameStateEntry != null) {
|
||||
if (replayMode) channelNameStateDAO.insertOrReplaceWithNewerRoot(c, channelNameStateEntry);
|
||||
else channelNameStateDAO.insert(c, channelNameStateEntry);
|
||||
}
|
||||
if (channelMetaUpdateEntry != null) channelNameStateDAO.updateMeta(c, channelMetaUpdateEntry);
|
||||
if (notificationEntry != null) userNotificationsStateDAO.upsert(c, notificationEntry);
|
||||
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Только проверка небезопасных входящих маркеров v=2. Исходный TEXT не переписывается. */
|
||||
final class AttachmentMarkerValidator {
|
||||
private static final Pattern ROOT = Pattern.compile("[1-9A-HJ-NP-Za-km-z]{32,44}");
|
||||
private static final Pattern SHA = Pattern.compile("[0-9a-f]{64}");
|
||||
private static final Pattern TX_ID = Pattern.compile("[A-Za-z0-9_-]{43}");
|
||||
private static final Pattern MIME = Pattern.compile("(?i)[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+");
|
||||
private static final Set<String> ALLOWED = Set.of("v", "nm", "sz", "pr", "sha256", "mm", "ar");
|
||||
|
||||
private AttachmentMarkerValidator() { }
|
||||
|
||||
static boolean validateLeadingV2Markers(String raw) {
|
||||
String text = raw == null ? "" : raw;
|
||||
int offset = 0;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
String prefix;
|
||||
if (text.startsWith("<S:att;", offset)) prefix = "<S:att;";
|
||||
else if (text.startsWith("<S:attach;", offset)) prefix = "<S:attach;";
|
||||
else if (text.startsWith("<SHiNE:attach;", offset)) prefix = "<SHiNE:attach;";
|
||||
else return true;
|
||||
int start = offset + prefix.length();
|
||||
int end = text.indexOf('>', start);
|
||||
if (end < 0 || end - start > 2048 || text.substring(start, end).contains("\n")) return false;
|
||||
String fields = text.substring(start, end);
|
||||
if (java.util.Arrays.stream(fields.split(";", -1)).anyMatch(field -> field.matches("v\\s*=\\s*0*2"))) {
|
||||
if (!validateV2(fields)) return false;
|
||||
}
|
||||
offset = end + 1;
|
||||
if (offset >= text.length()) return true;
|
||||
if (text.charAt(offset) != '\n') return false;
|
||||
offset++;
|
||||
}
|
||||
// Больше десяти технических тегов трактуем как недопустимые метаданные.
|
||||
return !text.startsWith("<S:att;", offset) && !text.startsWith("<S:attach;", offset)
|
||||
&& !text.startsWith("<SHiNE:attach;", offset);
|
||||
}
|
||||
|
||||
private static boolean validateV2(String rawFields) {
|
||||
String[] fields = rawFields.split(";", -1);
|
||||
if (fields.length < 4 || !fields[0].equals("v=2")) return false;
|
||||
Set<String> seen = new HashSet<>();
|
||||
String name = null, size = null, root = null, sha = null, mime = null, ar = null;
|
||||
for (String part : fields) {
|
||||
int index = part.indexOf('=');
|
||||
if (index <= 0 || part.indexOf('=', index + 1) >= 0) return false;
|
||||
String key = part.substring(0, index);
|
||||
String value = part.substring(index + 1);
|
||||
if (!ALLOWED.contains(key) || !seen.add(key) || value.isEmpty()) return false;
|
||||
switch (key) {
|
||||
case "v": if (!value.equals("2")) return false; break;
|
||||
case "nm": name = value; break;
|
||||
case "sz": size = value; break;
|
||||
case "pr": root = value; break;
|
||||
case "sha256": sha = value; break;
|
||||
case "mm": mime = value; break;
|
||||
case "ar": ar = value; break;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
if (name == null || size == null || !seen.contains("v") || (root == null) == (sha == null)) return false;
|
||||
if (!size.matches("[1-9][0-9]{0,18}")) return false;
|
||||
try { if (Long.parseLong(size) < 1) return false; } catch (NumberFormatException e) { return false; }
|
||||
if (root != null && !ROOT.matcher(root).matches()) return false;
|
||||
if (sha != null && !SHA.matcher(sha).matches()) return false;
|
||||
if (mime != null && (mime.length() > 127 || !MIME.matcher(mime).matches())) return false;
|
||||
if (ar != null && !TX_ID.matcher(ar).matches()) return false;
|
||||
|
||||
StringBuilder decoded = new StringBuilder();
|
||||
for (int i = 0; i < name.length(); i++) {
|
||||
char ch = name.charAt(i);
|
||||
if (ch == '%') {
|
||||
if (i + 2 >= name.length()) return false;
|
||||
String code = name.substring(i + 1, i + 3).toUpperCase(java.util.Locale.ROOT);
|
||||
ch = switch (code) {
|
||||
case "25" -> '%'; case "3B" -> ';'; case "3D" -> '=';
|
||||
case "3C" -> '<'; case "3E" -> '>'; default -> 0;
|
||||
};
|
||||
if (ch == 0) return false;
|
||||
i += 2;
|
||||
} else if (ch == '<' || ch == '>' || ch == '=' || ch == ';') return false;
|
||||
if (ch < 32 || ch == 127) return false;
|
||||
decoded.append(ch);
|
||||
}
|
||||
return decoded.toString().getBytes(StandardCharsets.UTF_8).length <= 255;
|
||||
}
|
||||
}
|
||||
+45
-36
@@ -41,7 +41,8 @@ public final class ChannelNamesStateBootstrapper {
|
||||
private static void rebuildFromBlocksOrThrow() {
|
||||
ChannelNameStateDAO dao = ChannelNameStateDAO.getInstance();
|
||||
List<ChannelNameStateEntry> entries = new ArrayList<>();
|
||||
Map<String, String> slugToIdentity = new LinkedHashMap<>();
|
||||
Map<String, ChannelNameStateEntry> entriesByOwnerTypeSlug = new LinkedHashMap<>();
|
||||
Map<ChannelRoot, ChannelNameStateEntry> replacedRoots = new LinkedHashMap<>();
|
||||
List<String> conflicts = new ArrayList<>();
|
||||
List<String> skipped = new ArrayList<>();
|
||||
|
||||
@@ -49,14 +50,7 @@ public final class ChannelNamesStateBootstrapper {
|
||||
SELECT login, bch_name, block_number, block_hash, block_bytes
|
||||
FROM blocks
|
||||
WHERE msg_type = ? AND msg_sub_type = ?
|
||||
AND fork_number=shine_canonical_fork(
|
||||
login,
|
||||
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
|
||||
FROM solana_user_pda_current
|
||||
WHERE LOWER(login)=LOWER(blocks.login)
|
||||
LIMIT 1),
|
||||
block_number
|
||||
)
|
||||
AND fork_number=shine_active_fork(login, block_number)
|
||||
ORDER BY LOWER(login), block_number
|
||||
""";
|
||||
|
||||
@@ -115,14 +109,6 @@ public final class ChannelNamesStateBootstrapper {
|
||||
continue;
|
||||
}
|
||||
|
||||
String identity = ownerBch + "#" + blockNumber;
|
||||
String ownerTypeSlug = ownerLogin.toLowerCase(Locale.ROOT) + "|" + channelTypeCode + "|" + slug;
|
||||
String existing = slugToIdentity.putIfAbsent(ownerTypeSlug, identity);
|
||||
if (existing != null && !existing.equals(identity)) {
|
||||
conflicts.add("owner/type/slug=\"" + ownerTypeSlug + "\" conflicts: " + existing + " vs " + identity);
|
||||
continue;
|
||||
}
|
||||
|
||||
ChannelNameStateEntry entry = new ChannelNameStateEntry();
|
||||
entry.setSlug(slug);
|
||||
entry.setDisplayName(displayName);
|
||||
@@ -138,18 +124,28 @@ public final class ChannelNamesStateBootstrapper {
|
||||
entry.setChannelRootBlockNumber(blockNumber);
|
||||
entry.setChannelRootBlockHash(blockHash);
|
||||
entry.setCreatedAtMs(parsed.timestamp * 1000L);
|
||||
entries.add(entry);
|
||||
String ownerTypeSlug = ownerLogin.toLowerCase(Locale.ROOT) + "|" + channelTypeCode + "|" + slug;
|
||||
ChannelNameStateEntry previous = entriesByOwnerTypeSlug.put(ownerTypeSlug, entry);
|
||||
if (previous != null) {
|
||||
replacedRoots.put(new ChannelRoot(previous.getOwnerBlockchainName(), previous.getChannelRootBlockNumber(), previous.getChannelRootBlockHash()), entry);
|
||||
conflicts.add("owner/type/slug=\"" + ownerTypeSlug + "\" conflicts: "
|
||||
+ previous.getOwnerBlockchainName() + "#" + previous.getChannelRootBlockNumber()
|
||||
+ " vs " + ownerBch + "#" + blockNumber + "; kept newest root");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
entries.addAll(entriesByOwnerTypeSlug.values());
|
||||
|
||||
dao.clearAll(c);
|
||||
dao.insertAll(c, entries);
|
||||
redirectFollowedChannelRoots(c, replacedRoots);
|
||||
|
||||
applyMetaUpdates(c, dao, entries, skipped);
|
||||
applyDeletionStates(c, dao, skipped);
|
||||
// v18: counters are a projection, so rebuild them from current state after a full channel-name bootstrap.
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) {
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM user_identity_current")) {
|
||||
ps.execute();
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
@@ -162,7 +158,7 @@ public final class ChannelNamesStateBootstrapper {
|
||||
c.commit();
|
||||
log.info("channel_names_state bootstrapped: {}", entries.size());
|
||||
if (!conflicts.isEmpty()) {
|
||||
log.warn("channel_names_state bootstrap detected {} slug conflicts (kept first occurrence)", conflicts.size());
|
||||
log.warn("channel_names_state bootstrap detected {} slug conflicts (kept newest root)", conflicts.size());
|
||||
int preview = Math.min(conflicts.size(), 10);
|
||||
for (int i = 0; i < preview; i++) {
|
||||
log.warn("channel_names_state conflict: {}", conflicts.get(i));
|
||||
@@ -192,19 +188,37 @@ public final class ChannelNamesStateBootstrapper {
|
||||
}
|
||||
}
|
||||
|
||||
/** Connections are a mutable projection. Keep follows on the current root when a legacy duplicate is replaced. */
|
||||
private static void redirectFollowedChannelRoots(Connection c,
|
||||
Map<ChannelRoot, ChannelNameStateEntry> replacedRoots) throws Exception {
|
||||
String sql = """
|
||||
UPDATE connections_state
|
||||
SET to_block_number = ?, to_block_hash = ?
|
||||
WHERE LOWER(to_login) = LOWER(?)
|
||||
AND to_block_number = ?
|
||||
AND to_block_hash = ?
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
for (Map.Entry<ChannelRoot, ChannelNameStateEntry> replacement : replacedRoots.entrySet()) {
|
||||
ChannelRoot oldRoot = replacement.getKey();
|
||||
ChannelNameStateEntry current = replacement.getValue();
|
||||
ps.setInt(1, current.getChannelRootBlockNumber());
|
||||
ps.setBytes(2, current.getChannelRootBlockHash());
|
||||
ps.setString(3, current.getOwnerLogin());
|
||||
ps.setInt(4, oldRoot.blockNumber());
|
||||
ps.setBytes(5, oldRoot.blockHash());
|
||||
ps.addBatch();
|
||||
}
|
||||
ps.executeBatch();
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyDeletionStates(Connection c, ChannelNameStateDAO dao, List<String> skipped) throws Exception {
|
||||
String sql = """
|
||||
SELECT bch_name, block_number, block_bytes, msg_sub_type
|
||||
FROM blocks
|
||||
WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?)
|
||||
AND fork_number=shine_canonical_fork(
|
||||
login,
|
||||
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
|
||||
FROM solana_user_pda_current
|
||||
WHERE LOWER(login)=LOWER(blocks.login)
|
||||
LIMIT 1),
|
||||
block_number
|
||||
)
|
||||
AND fork_number=shine_active_fork(login, block_number)
|
||||
ORDER BY LOWER(login), block_number
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -233,6 +247,8 @@ public final class ChannelNamesStateBootstrapper {
|
||||
}
|
||||
}
|
||||
|
||||
private record ChannelRoot(String ownerBlockchainName, int blockNumber, byte[] blockHash) {}
|
||||
|
||||
private static void applyMetaUpdates(Connection c,
|
||||
ChannelNameStateDAO dao,
|
||||
List<ChannelNameStateEntry> entries,
|
||||
@@ -246,14 +262,7 @@ public final class ChannelNamesStateBootstrapper {
|
||||
SELECT login, bch_name, block_number, block_bytes
|
||||
FROM blocks
|
||||
WHERE msg_type = ? AND msg_sub_type = ?
|
||||
AND fork_number=shine_canonical_fork(
|
||||
login,
|
||||
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
|
||||
FROM solana_user_pda_current
|
||||
WHERE LOWER(login)=LOWER(blocks.login)
|
||||
LIMIT 1),
|
||||
block_number
|
||||
)
|
||||
AND fork_number=shine_active_fork(login, block_number)
|
||||
ORDER BY LOWER(login), block_number
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
|
||||
+26
-2
@@ -5,6 +5,7 @@ import blockchain.body.BodyRecord;
|
||||
import blockchain.body.CreateChannelBody;
|
||||
import blockchain.body.TextLineBody;
|
||||
import blockchain.body.TextReplyBody;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelMessages_Response;
|
||||
import shine.db.channels.ChannelNameRules;
|
||||
import shine.db.MsgSubType;
|
||||
import shine.db.sql.CurrentUsersSql;
|
||||
@@ -226,6 +227,7 @@ final class ChannelsReadSupport {
|
||||
} else if (e.body instanceof blockchain.body.StatusActionBody sab) {
|
||||
ti.text = sab.message;
|
||||
}
|
||||
ti.attachmentMetadataValid = AttachmentMarkerValidator.validateLeadingV2Markers(ti.text);
|
||||
return ti;
|
||||
} catch (Exception ex) {
|
||||
return new TextInfo();
|
||||
@@ -236,7 +238,7 @@ final class ChannelsReadSupport {
|
||||
String order = asc ? "ASC" : "DESC";
|
||||
boolean bounded = limit > 0;
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
@@ -263,6 +265,9 @@ final class ChannelsReadSupport {
|
||||
pb.blockNumber = rs.getInt("block_number");
|
||||
pb.blockHash = rs.getBytes("block_hash");
|
||||
pb.blockBytes = rs.getBytes("block_bytes");
|
||||
pb.dataItemId = rs.getBytes("data_item_id");
|
||||
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
|
||||
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
|
||||
pb.toBchName = rs.getString("to_bch_name");
|
||||
pb.toBlockNumber = (Integer) rs.getObject("to_block_number");
|
||||
pb.toBlockHash = rs.getBytes("to_block_hash");
|
||||
@@ -286,7 +291,7 @@ final class ChannelsReadSupport {
|
||||
|
||||
static List<PostBlock> versionsForPost(Connection c, String ownerBch, int originalBlock, byte[] originalHash) throws SQLException {
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
|
||||
AND to_block_number=? AND to_block_hash=?
|
||||
@@ -309,6 +314,9 @@ final class ChannelsReadSupport {
|
||||
pb.blockNumber = rs.getInt("block_number");
|
||||
pb.blockHash = rs.getBytes("block_hash");
|
||||
pb.blockBytes = rs.getBytes("block_bytes");
|
||||
pb.dataItemId = rs.getBytes("data_item_id");
|
||||
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
|
||||
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
|
||||
out.add(pb);
|
||||
}
|
||||
return out;
|
||||
@@ -703,12 +711,27 @@ final class ChannelsReadSupport {
|
||||
|| subType == MsgSubType.TEXT_COURSE;
|
||||
}
|
||||
|
||||
static String dataItemIdBase64Url(byte[] bytes) {
|
||||
return bytes != null && bytes.length == 32
|
||||
? java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) : null;
|
||||
}
|
||||
|
||||
static void setStorageInfo(Net_GetChannelMessages_Response.VersionItem out, byte[] id, boolean pending, Long publishedAt, byte[] raw) {
|
||||
out.setArweaveDataItemId(dataItemIdBase64Url(id));
|
||||
out.setArweavePublishPending(pending);
|
||||
out.setArweavePublishedAtMs(publishedAt);
|
||||
out.setSignedDataItemBytes(raw == null ? null : raw.length);
|
||||
}
|
||||
|
||||
static final class PostBlock {
|
||||
String login;
|
||||
String bchName;
|
||||
int blockNumber;
|
||||
byte[] blockHash;
|
||||
byte[] blockBytes;
|
||||
byte[] dataItemId;
|
||||
boolean arweavePublishPending;
|
||||
Long arweavePublishedAtMs;
|
||||
String toBchName;
|
||||
Integer toBlockNumber;
|
||||
byte[] toBlockHash;
|
||||
@@ -717,6 +740,7 @@ final class ChannelsReadSupport {
|
||||
}
|
||||
|
||||
static final class TextInfo {
|
||||
boolean attachmentMetadataValid = true;
|
||||
String text = "";
|
||||
long createdAtMs = 0L;
|
||||
}
|
||||
|
||||
+9
@@ -152,7 +152,9 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||
v1.setBlockNumber(post.blockNumber);
|
||||
v1.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
|
||||
v1.setText(postText.text);
|
||||
v1.setAttachmentMetadataValid(postText.attachmentMetadataValid);
|
||||
v1.setCreatedAtMs(postText.createdAtMs);
|
||||
ChannelsReadSupport.setStorageInfo(v1, post.dataItemId, post.arweavePublishPending, post.arweavePublishedAtMs, post.blockBytes);
|
||||
versionsOut.add(v1);
|
||||
|
||||
if (ChannelsReadSupport.supportsEditPostVersions(post.msgSubType)) {
|
||||
@@ -164,13 +166,20 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||
ve.setBlockNumber(edit.blockNumber);
|
||||
ve.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
|
||||
ve.setText(editText.text);
|
||||
ve.setAttachmentMetadataValid(editText.attachmentMetadataValid);
|
||||
ve.setCreatedAtMs(editText.createdAtMs);
|
||||
ChannelsReadSupport.setStorageInfo(ve, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
|
||||
versionsOut.add(ve);
|
||||
}
|
||||
}
|
||||
|
||||
item.setVersions(versionsOut);
|
||||
item.setVersionsTotal(versionsOut.size());
|
||||
item.setAttachmentMetadataValid(v1.isAttachmentMetadataValid());
|
||||
item.setArweaveDataItemId(v1.getArweaveDataItemId());
|
||||
item.setArweavePublishPending(v1.getArweavePublishPending());
|
||||
item.setArweavePublishedAtMs(v1.getArweavePublishedAtMs());
|
||||
item.setSignedDataItemBytes(v1.getSignedDataItemBytes());
|
||||
|
||||
Net_GetChannelMessages_Response.VersionItem lastV = versionsOut.get(versionsOut.size() - 1);
|
||||
item.setText(lastV.getText());
|
||||
|
||||
+1
-2
@@ -158,14 +158,13 @@ public class Net_GetGroupDialog_Handler implements JsonMessageHandler {
|
||||
String sql = """
|
||||
SELECT login, bch_name, block_number, block_hash, block_bytes
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND line_code=? AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND line_code=? AND fork_number=shine_active_fork(login,block_number)
|
||||
ORDER BY block_number ASC
|
||||
""";
|
||||
List<MsgRow> out = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
|
||||
ps.setInt(2, line);
|
||||
ps.setString(3, ChannelsReadSupport.loginFromChainName(ownerBch));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
MsgRow row = new MsgRow();
|
||||
|
||||
+25
-19
@@ -19,7 +19,6 @@ import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.Comparator;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
@@ -116,7 +115,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
private List<PostRow> findRepliesAndRatings(Connection c, String toBchName, int toBlockNumber, byte[] toBlockHash, int limit) throws Exception {
|
||||
String targetLogin = ChannelsReadSupport.loginFromChainName(toBchName);
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
FROM blocks
|
||||
WHERE msg_type=1
|
||||
AND to_block_number=? AND to_block_hash=?
|
||||
@@ -124,7 +123,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
(msg_sub_type=? AND (LOWER(to_login)=LOWER(?) OR to_bch_name=?))
|
||||
OR (msg_sub_type=? AND LOWER(to_login)=LOWER(?))
|
||||
)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(blocks.login) LIMIT 1),block_number)
|
||||
AND fork_number=shine_active_fork(login,block_number)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setInt(1, toBlockNumber);
|
||||
@@ -153,17 +152,16 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
|
||||
private PostRow findByLogicalTarget(Connection c, String login, int blockNumber, byte[] blockHash) throws Exception {
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_active_fork(login,block_number)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, login);
|
||||
ps.setInt(2, blockNumber);
|
||||
ps.setBytes(3, blockHash);
|
||||
ps.setString(4, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
@@ -172,17 +170,16 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
|
||||
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND block_number=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_active_fork(login,block_number)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
String login=ChannelsReadSupport.loginFromChainName(bchName);
|
||||
ps.setString(1, login);
|
||||
ps.setInt(2, blockNumber);
|
||||
ps.setString(3, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
@@ -191,10 +188,10 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
|
||||
private PostRow findByNumberAndHash(Connection c, String bchName, int blockNumber, byte[] blockHash) throws Exception {
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_active_fork(login,block_number)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -202,7 +199,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
ps.setString(1, login);
|
||||
ps.setInt(2, blockNumber);
|
||||
ps.setBytes(3, blockHash);
|
||||
ps.setString(4, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
@@ -226,6 +222,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
row.blockNumber = rs.getInt("block_number");
|
||||
row.blockHash = rs.getBytes("block_hash");
|
||||
row.blockBytes = rs.getBytes("block_bytes");
|
||||
row.dataItemId = rs.getBytes("data_item_id");
|
||||
row.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
|
||||
row.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
|
||||
row.toLogin = rs.getString("to_login");
|
||||
row.toBchName = rs.getString("to_bch_name");
|
||||
row.toBlockNumber = (Integer) rs.getObject("to_block_number");
|
||||
@@ -259,7 +258,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
first.setBlockNumber(row.blockNumber);
|
||||
first.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
|
||||
first.setText(base.text);
|
||||
first.setAttachmentMetadataValid(base.attachmentMetadataValid);
|
||||
first.setCreatedAtMs(base.createdAtMs);
|
||||
ChannelsReadSupport.setStorageInfo(first, row.dataItemId, row.arweavePublishPending, row.arweavePublishedAtMs, row.blockBytes);
|
||||
node.setArweaveDataItemId(first.getArweaveDataItemId());
|
||||
node.setArweavePublishPending(first.getArweavePublishPending());
|
||||
node.setArweavePublishedAtMs(first.getArweavePublishedAtMs());
|
||||
node.setSignedDataItemBytes(first.getSignedDataItemBytes());
|
||||
versions.add(first);
|
||||
|
||||
if (row.msgSubType == MsgSubType.TEXT_REPLY
|
||||
@@ -275,19 +280,18 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
v.setBlockNumber(edit.blockNumber);
|
||||
v.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
|
||||
v.setText(et.text);
|
||||
v.setAttachmentMetadataValid(et.attachmentMetadataValid);
|
||||
v.setCreatedAtMs(et.createdAtMs);
|
||||
ChannelsReadSupport.setStorageInfo(v, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
|
||||
versions.add(v);
|
||||
}
|
||||
}
|
||||
|
||||
node.setVersions(versions);
|
||||
node.setVersionsTotal(versions.size());
|
||||
node.setAttachmentMetadataValid(first.isAttachmentMetadataValid());
|
||||
node.setText(versions.get(versions.size() - 1).getText());
|
||||
|
||||
if (row.blockBytes != null) {
|
||||
node.setRawBlockB64(Base64.getEncoder().encodeToString(row.blockBytes));
|
||||
}
|
||||
|
||||
int[] stats = ChannelsReadSupport.loadStats(c, row.bchName, row.blockNumber, row.blockHash);
|
||||
node.setLikesCount(stats[0]);
|
||||
node.setPrimaryLikesCount(stats[3]);
|
||||
@@ -310,11 +314,11 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
|
||||
private List<PostRow> findEdits(Connection c, String bch, int targetBlock, byte[] targetHash, int subType) throws Exception {
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
|
||||
AND to_block_number=? AND to_block_hash=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_active_fork(login,block_number)
|
||||
ORDER BY block_number ASC
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -323,7 +327,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
ps.setInt(2, subType);
|
||||
ps.setInt(3, targetBlock);
|
||||
ps.setBytes(4, targetHash);
|
||||
ps.setString(5, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
List<PostRow> out = new ArrayList<>();
|
||||
while (rs.next()) out.add(mapRow(rs));
|
||||
@@ -338,6 +341,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
int blockNumber;
|
||||
byte[] blockHash;
|
||||
byte[] blockBytes;
|
||||
byte[] dataItemId;
|
||||
boolean arweavePublishPending;
|
||||
Long arweavePublishedAtMs;
|
||||
String toLogin;
|
||||
String toBchName;
|
||||
Integer toBlockNumber;
|
||||
|
||||
+2
-3
@@ -89,7 +89,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
|
||||
private String loadPrimaryBlockchainName(Connection c, String canonicalLogin) throws Exception {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT blockchain_name
|
||||
FROM solana_user_pda_current
|
||||
FROM user_identity_current
|
||||
WHERE LOWER(login)=LOWER(?)
|
||||
LIMIT 1
|
||||
""")) {
|
||||
@@ -181,7 +181,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
|
||||
AND msg_sub_type = ?
|
||||
AND to_block_number = ?
|
||||
AND to_block_hash = ?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_active_fork(login,block_number)
|
||||
ORDER BY block_number ASC
|
||||
""")) {
|
||||
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
|
||||
@@ -189,7 +189,6 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
|
||||
ps.setInt(3, shine.db.MsgSubType.TEXT_EDIT_REPLY);
|
||||
ps.setInt(4, originalBlockNumber);
|
||||
ps.setBytes(5, originalBlockHash);
|
||||
ps.setString(6, ChannelsReadSupport.loginFromChainName(ownerBch));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
ChannelsReadSupport.TextInfo editText = ChannelsReadSupport.parseTextAndTime(rs.getBytes("block_bytes"));
|
||||
|
||||
+32
@@ -159,6 +159,11 @@ public class Net_GetChannelMessages_Response extends Net_Response {
|
||||
private int repliesCount;
|
||||
private int ratingsCount;
|
||||
private int versionsTotal;
|
||||
private boolean attachmentMetadataValid = true;
|
||||
private String arweaveDataItemId;
|
||||
private Boolean arweavePublishPending;
|
||||
private Long arweavePublishedAtMs;
|
||||
private Integer signedDataItemBytes;
|
||||
private List<VersionItem> versions = new ArrayList<>();
|
||||
|
||||
public BlockRef getMessageRef() { return messageRef; }
|
||||
@@ -221,6 +226,17 @@ public class Net_GetChannelMessages_Response extends Net_Response {
|
||||
public int getRatingsCount() { return ratingsCount; }
|
||||
public void setRatingsCount(int ratingsCount) { this.ratingsCount = ratingsCount; }
|
||||
|
||||
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
|
||||
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
|
||||
public String getArweaveDataItemId() { return arweaveDataItemId; }
|
||||
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
|
||||
public Boolean getArweavePublishPending() { return arweavePublishPending; }
|
||||
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
|
||||
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
|
||||
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
|
||||
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
|
||||
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
|
||||
|
||||
public int getVersionsTotal() { return versionsTotal; }
|
||||
public void setVersionsTotal(int versionsTotal) { this.versionsTotal = versionsTotal; }
|
||||
|
||||
@@ -234,6 +250,22 @@ public class Net_GetChannelMessages_Response extends Net_Response {
|
||||
private String blockHash;
|
||||
private String text;
|
||||
private long createdAtMs;
|
||||
private boolean attachmentMetadataValid = true;
|
||||
private String arweaveDataItemId;
|
||||
private Boolean arweavePublishPending;
|
||||
private Long arweavePublishedAtMs;
|
||||
private Integer signedDataItemBytes;
|
||||
|
||||
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
|
||||
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
|
||||
public String getArweaveDataItemId() { return arweaveDataItemId; }
|
||||
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
|
||||
public Boolean getArweavePublishPending() { return arweavePublishPending; }
|
||||
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
|
||||
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
|
||||
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
|
||||
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
|
||||
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
|
||||
|
||||
public int getVersionIndex() { return versionIndex; }
|
||||
public void setVersionIndex(int versionIndex) { this.versionIndex = versionIndex; }
|
||||
|
||||
-3
@@ -21,13 +21,10 @@ public class Net_GetMessageThread_Response extends Net_Response {
|
||||
|
||||
public static class MessageNode extends Net_GetChannelMessages_Response.MessageItem {
|
||||
private ChannelInfo channelInfo;
|
||||
private String rawBlockB64;
|
||||
|
||||
public ChannelInfo getChannelInfo() { return channelInfo; }
|
||||
public void setChannelInfo(ChannelInfo channelInfo) { this.channelInfo = channelInfo; }
|
||||
|
||||
public String getRawBlockB64() { return rawBlockB64; }
|
||||
public void setRawBlockB64(String rawBlockB64) { this.rawBlockB64 = rawBlockB64; }
|
||||
}
|
||||
|
||||
public static class ChannelInfo {
|
||||
|
||||
+8
-1
@@ -13,6 +13,8 @@ import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.DbController;
|
||||
import shine.db.dao.CurrentUsersDAO;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.CurrentUserEntry;
|
||||
|
||||
@@ -26,6 +28,11 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetUser_Handler.class);
|
||||
|
||||
private static long resolveChainLimit(String blockchainName) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
|
||||
return current == null ? 0L : current.getPaidLimitBytes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
Net_GetUser_Request req = (Net_GetUser_Request) baseRequest;
|
||||
@@ -80,7 +87,7 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
|
||||
st.setLastBlockNumber(-1);
|
||||
st.setLastBlockHash(new byte[32]);
|
||||
st.setFileSizeBytes(0);
|
||||
st.setSizeLimit(1_000_000L);
|
||||
st.setSizeLimit(Math.max(0L, resolveChainLimit(u.getBlockchainName())));
|
||||
st.setUpdatedAtMs(System.currentTimeMillis());
|
||||
stateDAO.upsert(st);
|
||||
log.warn("GetUser: восстановлена запись blockchain_state для login={}, blockchainName={}",
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AttachmentMarkerValidatorTest {
|
||||
private static final String PR = "4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi";
|
||||
private static String marker(String fields) { return "<S:att;" + fields + ">\nтекст"; }
|
||||
|
||||
@Test void validUnicodeAndEscapes() {
|
||||
assertTrue(AttachmentMarkerValidator.validateLeadingV2Markers(marker("v=2;nm=Водопад%3Bлето%3D2026.mp4;sz=1837243;pr=" + PR + ";mm=video/mp4")));
|
||||
assertTrue(AttachmentMarkerValidator.validateLeadingV2Markers("Обычный текст"));
|
||||
}
|
||||
|
||||
@Test void rejectsMalformedV2WithoutChangingBlock() {
|
||||
for (String fields : new String[]{
|
||||
"v=2;nm=abc;sz=10;sz=20;pr=" + PR,
|
||||
"v=2;nm=abc%ZZ;sz=10;pr=" + PR,
|
||||
"v=2;nm=abc;unknown=x;sz=10;pr=" + PR,
|
||||
"v=2;nm=abc;sz=-1;pr=" + PR,
|
||||
"v=2;nm=abc;sz=10;pr=bad",
|
||||
"nm=abc;v=2;sz=10;pr=" + PR
|
||||
}) assertFalse(AttachmentMarkerValidator.validateLeadingV2Markers(marker(fields)), fields);
|
||||
}
|
||||
}
|
||||
+17
-24
@@ -142,20 +142,17 @@ public final class ShineUsersCodec {
|
||||
null
|
||||
);
|
||||
|
||||
case IX_UPDATE_USERS_ECONOMY_CONFIG ->
|
||||
new ParsedInstruction(
|
||||
TxKind.UPDATE_USERS_ECONOMY_CONFIG,
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
new EconomyConfigState(
|
||||
1,
|
||||
reader.readU64(),
|
||||
reader.readU64(),
|
||||
reader.readU64()
|
||||
),
|
||||
null
|
||||
);
|
||||
case IX_UPDATE_USERS_ECONOMY_CONFIG -> {
|
||||
// Historical v1 transactions contain three u64s, v2 only update fee.
|
||||
int payloadBytes = reader.remaining();
|
||||
EconomyConfigState economy = switch (payloadBytes) {
|
||||
case 8 -> new EconomyConfigState(2, 0L, 0L, 0L, reader.readU64());
|
||||
case 24 -> new EconomyConfigState(1, reader.readU64(), reader.readU64(), reader.readU64(), 20_000L);
|
||||
default -> throw new IllegalArgumentException("Invalid economy config instruction length");
|
||||
};
|
||||
yield new ParsedInstruction(TxKind.UPDATE_USERS_ECONOMY_CONFIG,
|
||||
false, null, null, economy, null);
|
||||
}
|
||||
|
||||
case IX_UPDATE_NAMESPACE_PRICE ->
|
||||
new ParsedInstruction(
|
||||
@@ -260,7 +257,7 @@ public final class ShineUsersCodec {
|
||||
if (formatMajor != 1) {
|
||||
throw new IllegalArgumentException("Unsupported PDA format " + formatMajor + "." + formatMinor);
|
||||
}
|
||||
if (formatMinor == 2) {
|
||||
if (formatMinor == 2 || formatMinor == 3) {
|
||||
return parseUserPdaAccountV12(pdaAddress, slot, rawDataBase64, lastTxSignature, raw);
|
||||
}
|
||||
if (formatMinor == 0) {
|
||||
@@ -862,17 +859,13 @@ public final class ShineUsersCodec {
|
||||
|
||||
public record EconomyConfigState(
|
||||
int version,
|
||||
long registrationFeeLamports,
|
||||
long lamportsPerLimitStep,
|
||||
long startBonusLimit
|
||||
long registrationFeeLamports, // legacy v1 only
|
||||
long lamportsPerLimitStep, // legacy v1 only
|
||||
long startBonusLimit, // legacy v1 only
|
||||
long updateFeeLamports // v2 (v1 fallback 20_000)
|
||||
) {
|
||||
public static EconomyConfigState initial() {
|
||||
return new EconomyConfigState(
|
||||
1,
|
||||
START_REGISTRATION_FEE_LAMPORTS,
|
||||
START_LAMPORTS_PER_LIMIT_STEP,
|
||||
START_BONUS_LIMIT
|
||||
);
|
||||
return new EconomyConfigState(2, 0L, 0L, 0L, 20_000L);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+44
-5
@@ -63,7 +63,7 @@ public final class PostgresStorageRepository
|
||||
"last_error, economy_config_version, " +
|
||||
"registration_fee_lamports, " +
|
||||
"lamports_per_limit_step, " +
|
||||
"start_bonus_limit, updated_at_ms " +
|
||||
"start_bonus_limit, update_fee_lamports, updated_at_ms " +
|
||||
"FROM solana_sync_state WHERE id = 1"
|
||||
);
|
||||
ResultSet resultSet =
|
||||
@@ -106,7 +106,8 @@ public final class PostgresStorageRepository
|
||||
),
|
||||
resultSet.getLong(
|
||||
"start_bonus_limit"
|
||||
)
|
||||
),
|
||||
resultSet.getLong("update_fee_lamports")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -274,6 +275,7 @@ public final class PostgresStorageRepository
|
||||
connection,
|
||||
snapshots
|
||||
);
|
||||
syncBlockchainStateLimits(connection, snapshots);
|
||||
|
||||
reconcileConfirmedKeyRotations(
|
||||
connection,
|
||||
@@ -314,6 +316,7 @@ public final class PostgresStorageRepository
|
||||
connection,
|
||||
snapshots
|
||||
);
|
||||
syncBlockchainStateLimits(connection, snapshots);
|
||||
|
||||
reconcileConfirmedKeyRotations(
|
||||
connection,
|
||||
@@ -337,6 +340,36 @@ public final class PostgresStorageRepository
|
||||
}
|
||||
}
|
||||
|
||||
/** Copy on-chain fork limits into the server's runtime state. 0 = unbounded.
|
||||
* Never touch block tips, used bytes, or keys. Works after PDA updates even
|
||||
* when record_number remains unchanged (future system-only limit mutation).
|
||||
*/
|
||||
private void syncBlockchainStateLimits(Connection connection,
|
||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots) throws SQLException {
|
||||
if (snapshots == null || snapshots.isEmpty()) return;
|
||||
try (PreparedStatement exists = connection.prepareStatement("SELECT to_regclass('public.blockchain_state_store')")) {
|
||||
try (ResultSet rs = exists.executeQuery()) {
|
||||
if (!rs.next() || rs.getString(1) == null) return;
|
||||
}
|
||||
}
|
||||
try (PreparedStatement stmt = connection.prepareStatement("""
|
||||
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
|
||||
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
""")) {
|
||||
for (ShineUsersCodec.UserPdaSnapshot snapshot : snapshots) {
|
||||
if (snapshot == null || snapshot.blockchainForks() == null) continue;
|
||||
for (ShineUsersCodec.BlockchainForkSnapshot fork : snapshot.blockchainForks()) {
|
||||
stmt.setLong(1, fork.paidLimitBytes());
|
||||
stmt.setLong(2, System.currentTimeMillis());
|
||||
stmt.setString(3, snapshot.login());
|
||||
stmt.setInt(4, fork.forkIndex() + 1);
|
||||
stmt.addBatch();
|
||||
}
|
||||
}
|
||||
stmt.executeBatch();
|
||||
}
|
||||
}
|
||||
|
||||
private void upsertTxHistory(
|
||||
Connection connection,
|
||||
List<TxHistoryEntry> txEntries
|
||||
@@ -862,8 +895,8 @@ public final class PostgresStorageRepository
|
||||
"last_seen_slot, last_relevant_signature, " +
|
||||
"last_relevant_slot, last_error, economy_config_version, " +
|
||||
"registration_fee_lamports, lamports_per_limit_step, " +
|
||||
"start_bonus_limit, updated_at_ms" +
|
||||
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
||||
"start_bonus_limit, update_fee_lamports, updated_at_ms" +
|
||||
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
||||
"ON CONFLICT (id) DO UPDATE SET " +
|
||||
"status = EXCLUDED.status, " +
|
||||
"ready = EXCLUDED.ready, " +
|
||||
@@ -878,6 +911,7 @@ public final class PostgresStorageRepository
|
||||
"registration_fee_lamports = EXCLUDED.registration_fee_lamports, " +
|
||||
"lamports_per_limit_step = EXCLUDED.lamports_per_limit_step, " +
|
||||
"start_bonus_limit = EXCLUDED.start_bonus_limit, " +
|
||||
"update_fee_lamports = EXCLUDED.update_fee_lamports, " +
|
||||
"updated_at_ms = EXCLUDED.updated_at_ms";
|
||||
|
||||
try (PreparedStatement statement =
|
||||
@@ -898,14 +932,16 @@ public final class PostgresStorageRepository
|
||||
statement.setNull(11, Types.BIGINT);
|
||||
statement.setNull(12, Types.BIGINT);
|
||||
statement.setNull(13, Types.BIGINT);
|
||||
statement.setNull(14, Types.BIGINT);
|
||||
} else {
|
||||
statement.setInt(10, snapshot.economyConfigState().version());
|
||||
statement.setLong(11, snapshot.economyConfigState().registrationFeeLamports());
|
||||
statement.setLong(12, snapshot.economyConfigState().lamportsPerLimitStep());
|
||||
statement.setLong(13, snapshot.economyConfigState().startBonusLimit());
|
||||
statement.setLong(14, snapshot.economyConfigState().updateFeeLamports());
|
||||
}
|
||||
|
||||
bindNullableLong(statement, 14, snapshot.updatedAtMs());
|
||||
bindNullableLong(statement, 15, snapshot.updatedAtMs());
|
||||
statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
@@ -934,10 +970,13 @@ public final class PostgresStorageRepository
|
||||
"registration_fee_lamports BIGINT, " +
|
||||
"lamports_per_limit_step BIGINT, " +
|
||||
"start_bonus_limit BIGINT, " +
|
||||
"update_fee_lamports BIGINT, " +
|
||||
"updated_at_ms BIGINT" +
|
||||
")"
|
||||
);
|
||||
|
||||
statement.executeUpdate("ALTER TABLE solana_sync_state ADD COLUMN IF NOT EXISTS update_fee_lamports BIGINT");
|
||||
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO solana_sync_state (id, status, ready) " +
|
||||
"VALUES (1, 'EMPTY', FALSE) " +
|
||||
|
||||
@@ -58,10 +58,10 @@ public final class KeyRotationRebuildService {
|
||||
}
|
||||
private void registerCandidateSegment(KeyRotationSessionEntry s)throws Exception{try(Connection c=DbController.getInstance().getConnection()){segments.upsert(c,new BlockchainForkSegmentsDAO.Segment(s.getLogin(),forkOf(s.getCandidateBlockchainName()),forkOf(s.getSourceBlockchainName()),s.getForkFromBlock(),s.getForkFromHash(),s.getForkFromBlock()+1,System.currentTimeMillis()));}}
|
||||
private void replayStaging(KeyRotationSessionEntry s)throws Exception{
|
||||
SolanaUserPdaCurrentEntry u=users.getByLogin(s.getLogin());long limit=u!=null&&u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L;long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
|
||||
long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,blockchain_key,block_bytes,block_hash FROM key_rotation_rebuild_staging WHERE rotation_session_id=? ORDER BY logical_block_number ASC")){ps.setLong(1,s.getId());try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1),f=rs.getInt(2);String key=rs.getString(3);byte[] raw=rs.getBytes(4),hash=rs.getBytes(5);String bch=s.getLogin()+"-"+String.format("%03d",f);
|
||||
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
|
||||
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=users.getByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
|
||||
String target=bch;BlockchainResyncGuard.withBypass(target,()->{Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(target,raw);if(!r.ok())throw new IllegalStateException("canonical replay rejected #"+n+": "+r.reasonCode());});
|
||||
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
||||
}}}
|
||||
|
||||
@@ -370,7 +370,7 @@ public final class PeriodicBlockchainSyncService {
|
||||
state.setBlockchainName(currentUser.getBlockchainName());
|
||||
state.setLogin(currentUser.getLogin());
|
||||
state.setBlockchainKey(currentUser.getBlockchainKey());
|
||||
state.setSizeLimit(currentUser.getPaidLimitBytes() > 0 ? currentUser.getPaidLimitBytes() : 100_000L);
|
||||
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());
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# TODO — DM-вложения: один объект Cloudflare R2 на один файл
|
||||
|
||||
**Статус:** отложено, **не реализовано**. 17.11.2026. Не вносить изменения в рабочий код без отдельного решения.
|
||||
|
||||
## Что хотим
|
||||
|
||||
Перейти от хранения DM-вложения как набора отдельных зашифрованных объектов и отдельного манифеста к схеме **«одно вложение пользователя = один зашифрованный объект R2»** (корзина `shine-dm`). Это касается и голосовых вложений, если они используют тот же механизм.
|
||||
|
||||
Сейчас (после патча DM 64 МиБ): исходный файл до 500 МиБ шифруется клиентом по 64 МиБ с AES-256-GCM; каждый блок записывается отдельным объектом в R2, плюс зашифрованный манифест. Например, 500 МиБ = 8 блоков + 1 манифест = 9 объектов.
|
||||
|
||||
## Предполагаемая будущая схема (обсудить до реализации)
|
||||
|
||||
1. **Оставить логическое шифрование частями**, например по 64 МиБ, чтобы не держать исходный файл на 500 МиБ целиком в памяти. Каждый блок шифруется/аутентифицируется независимо, как и сейчас; соблюдать уникальность nonce/IV и корректную аутентификацию метаданных.
|
||||
2. **Небольшой файл:** обычный `PutObject` (один объект). **Крупный файл:** S3 Multipart Upload в R2 (`CreateMultipartUpload` → `UploadPart` → `CompleteMultipartUpload`; при сбое `AbortMultipartUpload`). При Multipart каждый зашифрованный блок может стать частью *одного* конечного объекта. Java-сервер только управляет разрешениями и завершением загрузки, байты файла по-прежнему идут из браузера напрямую в R2.
|
||||
3. **Убрать отдельный объект-манифест для нового формата.** Сведения для расшифровки и границ блоков положить в защищённые метаданные E2EE DM либо в аутентифицированный заголовок единого объекта. Определить строгую версию формата (условно DM-file v4), смещения блоков, размер последнего блока, формат nonce/тегов и правила проверки целостности. Старые форматы не менять.
|
||||
4. **ID объекта:** рассмотреть `Base58(32 криптографически случайных байт)`, чтобы знать имя до начала загрузки, вместо `Base58(SHA-256(ciphertext))`. 32 *байта*, не 32 бита. Случайный ID не является проверкой целостности: AES-GCM и аутентифицированные метаданные обязаны обеспечивать целостность каждого блока и файла в целом. Не допускать перезаписи существующего ID.
|
||||
5. **Получение:** по возможности один GET с потоковой обработкой и расшифровкой по 64 МиБ; либо HTTP Range. Обязательно проверить Firefox, Safari, Android/iOS PWA, CORS и память при скачивании/сохранении большого файла. Несколько Range-запросов остаются несколькими платными операциями чтения, даже когда объект один.
|
||||
6. **Сохранить:** E2EE (ключи не поступают на сервер/R2), прямую загрузку, федерацию/access-server отправителя, лимит 500 МиБ на первом этапе, срок хранения 14 дней, работу старых DM v1/v2/v3 (включая v3 по 8 и по 64 МиБ), существующие пользовательские сценарии. Не менять бинарный контейнер обычного DM без отдельной необходимости.
|
||||
7. **Сервер/API и устойчивость:** нужны новые подписанные операции Multipart, привязка `uploadId` к пользователю/файлу/лимитам, валидация частей и `ETag`, запрет чужого `Complete`/`Abort`, ограничение числа операций, очистка незавершённых загрузок, повтор неудачной части, тесты ошибок и документация. Проверить, что штатное удаление через 14 дней распространяется на итоговый объект.
|
||||
|
||||
## Экономика R2 — не обещать экономии заранее
|
||||
|
||||
Для **Standard** на 17.11.2026: Class A (записи) — $4,50/млн, Class B (чтения) — $0,36/млн, хранение — $0,015/ГБ-месяц; бесплатный месячный лимит — 1 млн A, 10 млн B, 10 ГБ-месяц. Стоимость определяется операциями и объёмом, а не непосредственно числом объектов.
|
||||
|
||||
Пример для **500 МиБ**, без повторов/HEAD/дополнительных операций:
|
||||
|
||||
| Вариант | Class A при загрузке | Class B при одном полном скачивании |
|
||||
| --- | ---: | ---: |
|
||||
| Отдельные 8 блоков по 64 МиБ + манифест (текущее) | 9 PUT | 9 GET |
|
||||
| Один объект через Multipart: 8 частей + start + complete | 10 | 1 GET при едином запросе; до 8–9 при Range |
|
||||
| Один обычный PUT целого объекта | 1 | 1 GET; но потоковая загрузка прямо из PWA требует отдельной проверки совместимости |
|
||||
|
||||
Multipart **не гарантирует снижение платы за запись**, хотя уменьшает число конечных объектов. Один потоковый PUT теоретически сокращает операции записи, но нельзя считать его надёжно работающим в браузерах без прототипа и тестов совместимости. Общий объём хранения почти тот же. Сначала собрать реальные метрики числа вложений/размеров/чтений и расходов, затем сравнить стоимость, сложность и устойчивость.
|
||||
|
||||
**Документы для будущего изменения:** `docs/Personal_Messages/Файлы_DM_v3_R2.md`, `docs/Personal_Messages/README.md`, `docs/API/18_DM_File_Storage_API.md`, клиент `shine-UI/js/services/dm-file-service.js`, серверный API и тесты. Этот TODO — план, **не описание текущей реализации**.
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
client.version=1.20.57
|
||||
server.version=1.16.29
|
||||
client.version=1.20.67
|
||||
server.version=1.16.38
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@
|
||||
- Все вопросы деплоя SHiNE решать через эту папку `deploy/`.
|
||||
- Скрипты лежат в `deploy/scripts/`.
|
||||
- Production-серверы: `shineup.me` и `server2.shineup.me`.
|
||||
- Test/devnet серверы: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`, `t4.shineup.me`.
|
||||
- Test/devnet серверы: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`.
|
||||
- Отдельный общий тестовый сервер: `test.shineup.me`. На нём уже работают тестовые пользователи; не использовать его для очистки, пересоздания или экспериментального деплоя без отдельного подтверждения.
|
||||
- TURN-серверы: `turn1.shineup.me`, `turn2.shineup.me`, `turn3.shineup.me`.
|
||||
- В deploy-документах и скриптах использовать домены, а не IP.
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ Production:
|
||||
- `t1.shineup.me`;
|
||||
- `t2.shineup.me`;
|
||||
- `t3.shineup.me`;
|
||||
- `t4.shineup.me`.
|
||||
- `test.shineup.me` — общий рабочий тестовый сервер с тестовыми пользователями; не очищать и не пересоздавать без отдельного подтверждения.
|
||||
|
||||
В документации и скриптах использовать домены, а не IP. SSH-пользователь — `player`.
|
||||
|
||||
@@ -46,8 +46,6 @@ bash deploy/scripts/test_t2_server.sh
|
||||
bash deploy/scripts/test_t2_ui.sh
|
||||
bash deploy/scripts/test_t3_server.sh
|
||||
bash deploy/scripts/test_t3_ui.sh
|
||||
bash deploy/scripts/test_t4_server.sh
|
||||
bash deploy/scripts/test_t4_ui.sh
|
||||
```
|
||||
|
||||
Не путать `server2.shineup.me` и `t2.shineup.me`.
|
||||
@@ -65,6 +63,6 @@ bash deploy/scripts/test_t4_ui.sh
|
||||
| `t1.shineup.me` | `player@t1.shineup.me` | `/home/player/t1/server` | `shine-t1` | 7101 |
|
||||
| `t2.shineup.me` | `player@t2.shineup.me` | `/home/player/t2/server` | `shine-t2` | 7102 |
|
||||
| `t3.shineup.me` | `player@t3.shineup.me` | `/home/player/t3/server` | `shine-t3` | 7103 |
|
||||
| `t4.shineup.me` | `player@t4.shineup.me` | `/home/player/t4/server` | `shine-t4` | 7104 |
|
||||
| `test.shineup.me` | `player@t4.shineup.me` | `/home/player/t4/server` | `shine-test` | 7104 |
|
||||
|
||||
Источники истины для деталей и backup: `deploy/AGENTS.md`, `deploy/README.md`, `deploy/backup/README.md` и сами скрипты `deploy/scripts/`.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
- целевой стандарт для SHiNE: `PostgreSQL 18.x`;
|
||||
- текущий факт на production `shineup.me` и `server2.shineup.me` на дату `2026-07-28`: `PostgreSQL 18.4`;
|
||||
- текущий факт на test/devnet `t1` / `t2` / `t3` / `t4` на дату `2026-07-28`: `PostgreSQL 18.4`.
|
||||
- текущий факт на test/devnet `t1` / `t2` / `t3` / `test.shineup.me` на дату `2026-07-28`: `PostgreSQL 18.4`.
|
||||
|
||||
## Цель
|
||||
|
||||
|
||||
+3
-4
@@ -13,12 +13,13 @@
|
||||
|
||||
- Основной production: `shineup.me`.
|
||||
- Второй production: `server2.shineup.me`.
|
||||
- Test/devnet стенд: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`, `t4.shineup.me`.
|
||||
- Test/devnet стенд: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`.
|
||||
- Общий рабочий тестовый сервер: `test.shineup.me`. На нём уже работают тестовые пользователи; не очищать и не пересоздавать без отдельного подтверждения.
|
||||
|
||||
Краткое текущее состояние на `2026-07-28`:
|
||||
|
||||
- оба production уже на `PostgreSQL 18.4` в отдельных Docker-контейнерах `shine-postgres`;
|
||||
- весь test/devnet стенд `t1`-`t4` тоже уже на `PostgreSQL 18.4`;
|
||||
- test/devnet стенд `t1`-`t3` и общий `test.shineup.me` уже на `PostgreSQL 18.4`;
|
||||
- тестовые контуры используют общий Docker-контейнер `shine-test-postgres`;
|
||||
- production использует Helius mainnet, test/devnet использует Helius devnet;
|
||||
- актуальные подробности по всем шести серверам смотреть в `PRODUCTION_SERVERS.md` и `TEST_SERVERS.md`.
|
||||
@@ -82,8 +83,6 @@ Test/devnet wrappers:
|
||||
- `scripts/test_t2_ui.sh`
|
||||
- `scripts/test_t3_server.sh`
|
||||
- `scripts/test_t3_ui.sh`
|
||||
- `scripts/test_t4_server.sh`
|
||||
- `scripts/test_t4_ui.sh`
|
||||
|
||||
## Примеры
|
||||
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
Создать DNS-запись домена:
|
||||
|
||||
- production: `shineup.me` или `server2.shineup.me`;
|
||||
- test/devnet: `t1.shineup.me` ... `t4.shineup.me`.
|
||||
- test/devnet: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`.
|
||||
- общий рабочий тестовый сервер: `test.shineup.me`; не очищать и не пересоздавать без отдельного подтверждения.
|
||||
|
||||
После смены физического сервера достаточно обновить DNS.
|
||||
|
||||
|
||||
@@ -9,6 +9,6 @@ handle @solana_rpc {
|
||||
}
|
||||
```
|
||||
|
||||
Порт `7070` приведён для основного сервера из резервной конфигурации. У t1/t2/t3/t4 используйте фактический локальный Java-порт (например, 7102). Не заменяйте существующие настройки сервера целиком этой вставкой.
|
||||
Порт `7070` приведён для основного сервера из резервной конфигурации. У t1/t2/t3 и `test.shineup.me` используйте фактический локальный Java-порт (например, 7102). Не заменяйте существующие настройки сервера целиком этой вставкой.
|
||||
|
||||
Далее: `caddy validate --config /etc/caddy/Caddyfile`, перезагрузите Caddy и проверьте `POST https://<ваш-сервер>/solana-rpc` с JSON-RPC `getVersion`.
|
||||
|
||||
+14
-11
@@ -1,17 +1,20 @@
|
||||
# Test/devnet серверы SHiNE
|
||||
|
||||
Отдельный test/devnet стенд состоит из четырёх независимых SHiNE-инстансов:
|
||||
Основной test/devnet стенд состоит из трёх независимых SHiNE-инстансов:
|
||||
|
||||
- `t1.shineup.me`
|
||||
- `t2.shineup.me`
|
||||
- `t3.shineup.me`
|
||||
- `t4.shineup.me`
|
||||
|
||||
Отдельно работает общий тестовый сервер:
|
||||
|
||||
- `test.shineup.me` — бывший T4, с уже работающими тестовыми пользователями. Не очищать и не пересоздавать без отдельного подтверждения.
|
||||
|
||||
Это не production. Все deploy-цели задаются через домены.
|
||||
|
||||
Текущее фактическое состояние на `2026-07-28`:
|
||||
|
||||
- все четыре тестовых контура `t1` / `t2` / `t3` / `t4` уже работают без `SQLite`;
|
||||
- `t1`, `t2`, `t3` и `test.shineup.me` работают без `SQLite`;
|
||||
- все четыре контура используют `PostgreSQL 18.4`;
|
||||
- PostgreSQL на test-хосте общий для всех четырёх контуров и запущен в Docker-контейнере `shine-test-postgres`;
|
||||
- все четыре контура используют один и тот же Helius devnet RPC/WS endpoint;
|
||||
@@ -44,7 +47,7 @@
|
||||
| `t1.shineup.me` | `server_t1` | `/home/player/t1/server` | `/home/player/t1/UI` | `7101` | `shine-t1.service` | `shine_t1_db` | `shine_t1` |
|
||||
| `t2.shineup.me` | `server_t2` | `/home/player/t2/server` | `/home/player/t2/UI` | `7102` | `shine-t2.service` | `shine_t2_db` | `shine_t2` |
|
||||
| `t3.shineup.me` | `server_t3` | `/home/player/t3/server` | `/home/player/t3/UI` | `7103` | `shine-t3.service` | `shine_t3_db` | `shine_t3` |
|
||||
| `t4.shineup.me` | `server_t4` | `/home/player/t4/server` | `/home/player/t4/UI` | `7104` | `shine-t4.service` | `shine_t4_db` | `shine_t4` |
|
||||
| `test.shineup.me` | `test_server@shine` | `/home/player/t4/server` | `/home/player/t4/UI` | `7104` | `shine-test.service` | `shine_test_db` | `shine_t2` |
|
||||
|
||||
## Deploy
|
||||
|
||||
@@ -58,7 +61,7 @@
|
||||
DEPLOY_SOLANA_ENDPOINT="https://t1.shineup.me/solana-rpc" bash deploy/scripts/test_t1_ui.sh
|
||||
```
|
||||
|
||||
Для остальных стендов замените `t1` на `t2`, `t3`, `t4`. Не вставляйте URL с личным ключом Helius в `DEPLOY_SOLANA_ENDPOINT`: значение будет опубликовано в `shine-UI/js/deploy-config.js` на сайте.
|
||||
Для остальных стендов замените `t1` на `t2` или `t3`. Для общего тестового сервера используйте `test.shineup.me`; не выполняйте на нём очистку или пересоздание. Не вставляйте URL с личным ключом Helius в `DEPLOY_SOLANA_ENDPOINT`: значение будет опубликовано в `shine-UI/js/deploy-config.js` на сайте.
|
||||
|
||||
```bash
|
||||
bash deploy/scripts/test_t1_server.sh
|
||||
@@ -70,8 +73,8 @@ DEPLOY_SOLANA_ENDPOINT="https://t2.shineup.me/solana-rpc" bash deploy/scripts/te
|
||||
bash deploy/scripts/test_t3_server.sh
|
||||
DEPLOY_SOLANA_ENDPOINT="https://t3.shineup.me/solana-rpc" bash deploy/scripts/test_t3_ui.sh
|
||||
|
||||
bash deploy/scripts/test_t4_server.sh
|
||||
DEPLOY_SOLANA_ENDPOINT="https://t4.shineup.me/solana-rpc" bash deploy/scripts/test_t4_ui.sh
|
||||
bash deploy/scripts/test_shineupme_server.sh
|
||||
DEPLOY_SOLANA_ENDPOINT="https://test.shineup.me/solana-rpc" bash deploy/scripts/test_shineupme_ui.sh
|
||||
```
|
||||
|
||||
## Проверка
|
||||
@@ -80,13 +83,13 @@ DEPLOY_SOLANA_ENDPOINT="https://t4.shineup.me/solana-rpc" bash deploy/scripts/te
|
||||
curl -I https://t1.shineup.me
|
||||
curl -I https://t2.shineup.me
|
||||
curl -I https://t3.shineup.me
|
||||
curl -I https://t4.shineup.me
|
||||
curl -I https://test.shineup.me
|
||||
```
|
||||
|
||||
На сервере:
|
||||
|
||||
```bash
|
||||
sudo systemctl --no-pager --full status caddy shine-t1 shine-t2 shine-t3 shine-t4
|
||||
sudo systemctl --no-pager --full status caddy shine-t1 shine-t2 shine-t3 shine-test
|
||||
sudo docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
|
||||
```
|
||||
|
||||
@@ -96,6 +99,6 @@ sudo docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
|
||||
|
||||
Отдельный нюанс по web push:
|
||||
|
||||
- у `t1`, `t2`, `t3`, `t4` в UI уже есть одинаковый встроенный `VAPID` public key;
|
||||
- то есть `t3` и `t4` используют тот же web push клиентский код, что и `t1` / `t2`;
|
||||
- у `t1`, `t2`, `t3` и `test.shineup.me` в UI уже есть одинаковый встроенный `VAPID` public key;
|
||||
- то есть `t3` и `test.shineup.me` используют тот же web push клиентский код, что и `t1` / `t2`;
|
||||
- если позже понадобится разделить push-ключи по тестовым контурам, это нужно делать отдельным UI deploy с новым `DEPLOY_WEBPUSH_VAPID_PUBLIC`.
|
||||
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# test.shineup.me использует /etc/shine/shine-test.env. Не вызываем
|
||||
# deploy_server.sh: тот пересоздаёт unit без EnvironmentFile.
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||
REMOTE_HOST="player@t4.shineup.me"
|
||||
REMOTE_SERVER_DIR="/home/player/t4/server"
|
||||
REMOTE_SERVICE_NAME="shine-test"
|
||||
LOCAL_JAR="$ROOT_DIR/SHiNE-server/build/libs/shine-server.jar"
|
||||
|
||||
echo "==> Building server jar"
|
||||
(cd "$ROOT_DIR" && ./gradlew shadowJar)
|
||||
|
||||
if [[ ! -s "$LOCAL_JAR" ]]; then
|
||||
echo "ERROR: server jar not found: $LOCAL_JAR" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> Deploy server to test.shineup.me ($REMOTE_HOST)"
|
||||
ssh -o BatchMode=yes -o ConnectTimeout=20 "$REMOTE_HOST" "echo SSH OK" >/dev/null
|
||||
rsync -az --timeout=120 "$LOCAL_JAR" "$ROOT_DIR/allowed-email-domains.txt" \
|
||||
"$REMOTE_HOST:$REMOTE_SERVER_DIR/"
|
||||
ssh "$REMOTE_HOST" "sudo systemctl restart '$REMOTE_SERVICE_NAME'; sudo systemctl --no-pager --full status '$REMOTE_SERVICE_NAME'"
|
||||
|
||||
echo "Всё хорошо: сервер test.shineup.me обновлён и сервис $REMOTE_SERVICE_NAME перезапущен"
|
||||
Regular → Executable
+6
-7
@@ -2,20 +2,19 @@
|
||||
set -euo pipefail
|
||||
|
||||
# Use an explicit public RPC gateway URL. Never commit an Helius API key.
|
||||
# Recommended: https://t4.shineup.me/solana-rpc (only if the proxy is configured).
|
||||
if [[ -z "${DEPLOY_SOLANA_ENDPOINT:-}" ]]; then
|
||||
echo "ERROR: DEPLOY_SOLANA_ENDPOINT is required for t4 UI deploy." >&2
|
||||
echo "Set it to a working public RPC gateway (prefer your /solana-rpc proxy)." >&2
|
||||
echo "ERROR: DEPLOY_SOLANA_ENDPOINT is required for test.shineup.me UI deploy." >&2
|
||||
echo "Set it to a working public RPC gateway (prefer https://test.shineup.me/solana-rpc)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
REMOTE_HOST="player@t4.shineup.me" \
|
||||
REMOTE_UI_DIR="/home/player/t4/UI" \
|
||||
EXPECTED_CADDY_UI_ROOT="/home/player/t4/UI" \
|
||||
EXPECTED_CADDY_SITE="t4.shineup.me" \
|
||||
DEPLOY_SERVER_LOGIN="server_t4" \
|
||||
DEPLOY_SERVER_ADDRESS="t4.shineup.me" \
|
||||
EXPECTED_CADDY_SITE="test.shineup.me" \
|
||||
DEPLOY_SERVER_LOGIN="test_server@shine" \
|
||||
DEPLOY_SERVER_ADDRESS="test.shineup.me" \
|
||||
DEPLOY_SOLANA_CLUSTER="devnet" \
|
||||
DEPLOY_SOLANA_ENDPOINT="$DEPLOY_SOLANA_ENDPOINT" \
|
||||
TARGET_URL="https://t4.shineup.me" \
|
||||
TARGET_URL="https://test.shineup.me" \
|
||||
bash "$(dirname "$0")/deploy_ui.sh"
|
||||
@@ -1,11 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
REMOTE_HOST="player@t2.shineup.me" \
|
||||
TARGET_DOMAIN="t2.shineup.me" \
|
||||
REMOTE_SERVER_DIR="/home/player/t2/server" \
|
||||
REMOTE_DM_FILES_DIR="/home/player/test-dm-files" \
|
||||
REMOTE_PUBLIC_FILES_DIR="/home/player/test-public-files" \
|
||||
REMOTE_SERVICE_NAME="shine-t2" \
|
||||
SERVER_PORT="7102" \
|
||||
bash "$(dirname "$0")/deploy_server.sh"
|
||||
# t2.shineup.me использует /etc/shine/shine-t2.env. Не вызываем
|
||||
# deploy_server.sh: тот пересоздаёт unit без EnvironmentFile.
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||
REMOTE_HOST="player@t2.shineup.me"
|
||||
REMOTE_SERVER_DIR="/home/player/t2/server"
|
||||
REMOTE_SERVICE_NAME="shine-t2"
|
||||
LOCAL_JAR="$ROOT_DIR/SHiNE-server/build/libs/shine-server.jar"
|
||||
|
||||
echo "==> Building server jar"
|
||||
(cd "$ROOT_DIR" && ./gradlew shadowJar)
|
||||
|
||||
if [[ ! -s "$LOCAL_JAR" ]]; then
|
||||
echo "ERROR: server jar not found: $LOCAL_JAR" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> Deploy server to t2.shineup.me ($REMOTE_HOST)"
|
||||
ssh -o BatchMode=yes -o ConnectTimeout=20 "$REMOTE_HOST" "echo SSH OK" >/dev/null
|
||||
rsync -az --timeout=120 "$LOCAL_JAR" "$ROOT_DIR/allowed-email-domains.txt" \
|
||||
"$REMOTE_HOST:$REMOTE_SERVER_DIR/"
|
||||
ssh "$REMOTE_HOST" "sudo systemctl restart '$REMOTE_SERVICE_NAME'; sudo systemctl --no-pager --full status '$REMOTE_SERVICE_NAME'"
|
||||
|
||||
echo "Всё хорошо: сервер t2.shineup.me обновлён и сервис $REMOTE_SERVICE_NAME перезапущен"
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
REMOTE_HOST="player@t4.shineup.me" \
|
||||
TARGET_DOMAIN="t4.shineup.me" \
|
||||
REMOTE_SERVER_DIR="/home/player/t4/server" \
|
||||
REMOTE_DM_FILES_DIR="/home/player/test-dm-files" \
|
||||
REMOTE_PUBLIC_FILES_DIR="/home/player/test-public-files" \
|
||||
REMOTE_SERVICE_NAME="shine-t4" \
|
||||
SERVER_PORT="7104" \
|
||||
bash "$(dirname "$0")/deploy_server.sh"
|
||||
@@ -35,6 +35,7 @@
|
||||
- обязательный тестовый tag `App=test5592`;
|
||||
- для channel block — `c=<canonical_channel_slug>`;
|
||||
- новый `CreateChannelBody`: техническое имя `channelName` должно быть длиной 4–32 символа (`A-Z`, `a-z`, `0-9`, `_`, `-`); для длины 1–3 возвращается `bad_channel_name`. Проверка выполняется на уровне body (`checkForCreate`) и бизнес-валидации `AddBlock`. Ранее подписанные блоки с именами короче 4 символов по-прежнему читаются и могут быть воспроизведены в архивном `replayMode` (но обычный `AddBlock` их отклоняет); бинарный формат v1 не изменён;
|
||||
- новый `CreateChannelBody` с тем же владельцем, типом и canonical slug отклоняется обычным `AddBlock` с `409 channel_name_already_exists`. При архивном `replayMode` исторический дубликат сохраняется только для непрерывности уже подписанной цепочки, а проекция выбирает корень с большим номером;
|
||||
- `TEXT_CHANNEL_DELETE (type=1/subType=92/version=1)` является обычным line-based channel block с пустым text и тем же обязательным `c=<slug>`; отдельной операции API для удаления канала нет;
|
||||
- `data` содержит SHiNE Frame v1 (`frameCode=1`).
|
||||
|
||||
|
||||
@@ -275,9 +275,10 @@
|
||||
### MessageNode (дополнение)
|
||||
- `MessageNode` расширяет формат сообщения из `GetChannelMessages` и дополнительно содержит:
|
||||
- `channelInfo` — мета-информация о канале (если применимо);
|
||||
- `rawBlockB64` — сырой `block_bytes` текущего блока в Base64.
|
||||
- Поле `rawBlockB64` присутствует у узлов во всех частях ответа `GetMessageThread`: `focus`, `ancestors[]`, `descendants[]`.
|
||||
- В `GetChannelMessages` поле `rawBlockB64` **не добавляется** (лента канала без сырого блока, чтобы не раздувать ответ).
|
||||
- `channelInfo` не содержит бинарной записи. Для полного оригинала используется существующая публичная операция `GetBlockchainBlock` (поля `blockchainName`, `blockNumber`, ответ `blockBytesB64`).
|
||||
- `rawBlockB64` больше **не отправляется** в обычном `GetMessageThread` — ни для focus, ни для ancestors/descendants, что экономит трафик.
|
||||
- В `GetChannelMessages` полный бинарный блок также не передаётся.
|
||||
- В обоих ответах `MessageItem` содержит `arweaveDataItemId` (Base64URL SHA-256 подписи, 43 символа), `arweavePublishPending`, `arweavePublishedAtMs`, `signedDataItemBytes`, `attachmentMetadataValid` (серверная проверка синтаксиса маркеров `v=2`; исходный текст остаётся неизменным). Эти же поля возвращаются **для каждого элемента `versions[]`**, поскольку каждая редакция — отдельный DataItem. `arweavePublishedAtMs` означает регистрацию отправки сервисом, а не независимую проверку шлюза. Поля могут быть `null`, если metadata отсутствует. URL полезных данных: `https://arweave.net/raw/<arweaveDataItemId>`; полный подписанный ANS-104 возвращается по `GetBlockchainBlock`, но это ответ сервера SHiNE, не доказательство извлечения оболочки из Arweave.
|
||||
- И в `GetChannelMessages`, и в `GetMessageThread` каждое сообщение теперь содержит:
|
||||
- `repliesCount` — число дочерних сообщений типа `TEXT_REPLY`;
|
||||
- `ratingsCount` — число дочерних сообщений типа `TEXT_RATING`.
|
||||
|
||||
@@ -103,7 +103,7 @@ Login/fork для edit не подписываются: edit может ссыл
|
||||
- Такой edit трактуется как логическое удаление содержимого сообщения.
|
||||
- Для удаления отдельного сообщения используется именно edit-блок; отдельного `DELETE`-подтипа сообщения нет. `TEXT_CHANNEL_DELETE=92` относится только к soft-delete всего канала.
|
||||
|
||||
## Вложения в текстовых сообщениях (`S:att v=1`)
|
||||
## Вложения в текстовых сообщениях (`S:att v=1` и `v=2`)
|
||||
|
||||
Для `TEXT_POST`, `TEXT_REPLY`, `TEXT_EDIT_POST` и `TEXT_EDIT_REPLY` клиент может хранить вложения как технические строки в начале обычного `text`.
|
||||
|
||||
@@ -127,8 +127,8 @@ Arweave-вложение:
|
||||
|
||||
Обязательные поля:
|
||||
|
||||
- `v=1`
|
||||
- `nm` - имя файла, закодированное через `encodeURIComponent`
|
||||
- `v=1` для исторических записей, `v=2` для новых
|
||||
- `nm` - имя файла: для `v=1` старое `encodeURIComponent`, для `v=2` UTF-8 с экранированием только `%`, `<`, `>`, `=`, `;`
|
||||
- `sz` - размер файла в байтах
|
||||
- `sha256` - SHA-256 исходного файла в hex
|
||||
|
||||
@@ -151,4 +151,6 @@ Arweave-вложение:
|
||||
- старые клиенты без поддержки вложений могут показывать технические строки как обычный текст;
|
||||
- пустой пользовательский текст допустим, если перед ним есть хотя бы один валидный attach-блок.
|
||||
|
||||
В `v=2` при структурированном чтении проверяется уникальность полей, допустимость кодирования и значений. Безопасное текстовое представление и файловые URL должны дополнительно валидироваться на клиенте и сервере.
|
||||
|
||||
Сам файл всегда хранится вне блокчейна. В блокчейне остаются имя, размер, SHA-256 и, только для Arweave-вложения, `ar`.
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
# Вложения в TEXT-сообщениях (`S:att;v=1`)
|
||||
# Вложения в TEXT-сообщениях (`S:att;v=1` и `v=2`)
|
||||
|
||||
Технический префикс в UTF-8 `text` для `TEXT_POST`, `TEXT_REPLY`, `TEXT_EDIT_POST`, `TEXT_EDIT_REPLY`. Бинарный формат TEXT не меняется. До 10 вложений в начале сообщения, затем обычный текст; порядок сохраняется.
|
||||
|
||||
## Канонический формат (2026-11)
|
||||
## Канонический формат (2026-11, v=2)
|
||||
|
||||
```text
|
||||
<S:att;v=1;nm=photo.jpg;sz=248193;pr=BASE58_ROOT;mm=image/jpeg>
|
||||
<S:att;v=1;nm=video.mp4;sz=15000000;pr=BASE58_ROOT;mm=video/mp4;ar=TXID>
|
||||
<S:att;v=2;nm=photo.jpg;sz=248193;pr=BASE58_ROOT;mm=image/jpeg>
|
||||
<S:att;v=2;nm=video.mp4;sz=15000000;pr=BASE58_ROOT;mm=video/mp4;ar=TXID>
|
||||
Текст публикации
|
||||
```
|
||||
|
||||
- `v` — версия (1).
|
||||
- `nm` — имя файла в `encodeURIComponent`.
|
||||
- `v` — версия: **2** для новых публикаций, старые `v=1` остаются читаемыми.
|
||||
- `nm` — UTF-8 имя файла без массового URL-кодирования. В `v=2` только служебные символы кодируются однобайтовыми ASCII-последовательностями: `%`→`%25`, `;`→`%3B`, `=`→`%3D`, `<`→`%3C`, `>`→`%3E`. Управляющие символы в именах не допускаются. Фактическая нормализация клиента заменяет `\` и `/` на `_` (старое правило).
|
||||
- Пример: `Водопад.mp4` записывается как `Водопад.mp4`; `Лето;фильм=1.mp4` — как `Лето%3Bфильм%3D1.mp4`.
|
||||
- Парсер v=2 отвергает неизвестные и повторные ключи, неверное экранирование, ошибочный MIME, некорректную длину/идентификатор. Сервер/импортёр не должны доверять метаданным клиента и обязаны проверять формат при структурированном чтении. Блокчейн и исходный `text` хранятся побайтово неизменными.
|
||||
- `sz` — размер подготовленных байтов в десятичном виде.
|
||||
- `pr` — **BitTorrent v2 Pieces Root (32 байта), Base58**, не SHA-256 целого файла; текущий стандарт новых вложений.
|
||||
- `mm` — необязательный MIME, в формате `type/subtype`; неизвестный — `application/octet-stream`.
|
||||
@@ -32,4 +34,4 @@ HTML, SVG, XHTML, JavaScript, XML по расширению или MIME выво
|
||||
|
||||
## Совместимость
|
||||
|
||||
Парсер терпимо читает старое поле `sha256` и префиксы `<SHiNE:attach>`/`<S:attach>`, если данные сохранились. Массовая миграция не выполняется. Экспериментальные `preAr`, `preSha256`, `previewAr`, `previewSha256`, `width`, `duration`, `thumbnail` не входят в протокол.
|
||||
Существующий `v=1` использует `encodeURIComponent`/`decodeURIComponent`. Новые записи создаются в `v=2`, уже записанные блоки не переписываются. Парсер терпимо читает старое поле `sha256` и префиксы `<SHiNE:attach>`/`<S:attach>`, если данные сохранились. Массовая миграция не выполняется. Экспериментальные `preAr`, `preSha256`, `previewAr`, `previewSha256`, `width`, `duration`, `thumbnail` не входят в протокол.
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
## 2026-11-19 — Компактные имена вложений в `S:att v=2`
|
||||
|
||||
- `S:att;v=2` записывает UTF-8 имена непосредственно и %-кодирует только служебные символы; `v=1` остаётся читаемым, бинарный Frame не изменён.
|
||||
- Парсер клиента проверяет имена, повторные поля, MIME и идентификаторы. Сервер передаёт исходный текст неизменным и не считает маркеры вложений достоверными без их разбора.
|
||||
|
||||
## 2026-11-08 — Минимальная длина имени нового канала в TECH_CREATE_CHANNEL
|
||||
|
||||
- Для создания блока `TECH_CREATE_CHANNEL (type=0/subType=1/version=1)` введён протокольный минимум `channelName`: **4 символа**; максимум остаётся 32.
|
||||
|
||||
@@ -40,7 +40,7 @@ blockchain.sync.enabled=false
|
||||
|
||||
Дополнительно каждый сервер может независимо включить `ArweaveBlockSyncScheduler`.
|
||||
|
||||
Он ищет child DataItems по тестовому тегу `App=test5592`, проверяет их и импортирует через ту же бизнес-проверку AddBlock. Импортированные блоки не публикуются повторно.
|
||||
Он ищет child DataItems по тестовому тегу `App=test5592`, проверяет их и импортирует через ту же бизнес-проверку AddBlock. Импортированные блоки не публикуются повторно. Владелец DataItem сверяется либо с актуальным Solana PDA, либо с уже проверенным локальным сертификатом бесплатной регистрации (`FREE_CERT`); для `FREE_CERT` допустима только chain `login-001` с ключом из сертификата.
|
||||
|
||||
Если блоки обнаружены не по порядку, persistent queue оставляет более поздние блоки pending до появления предыдущих.
|
||||
|
||||
|
||||
@@ -41,6 +41,23 @@
|
||||
|
||||
Обычный `Enter` в поле ввода личного сообщения отправляет непустой текст через существующий обработчик формы (включая ответы и редактирование); `Shift+Enter`, `Ctrl+Enter`, `Alt+Enter` и `Meta+Enter` вставляют перенос строки. Во время композиции IME отправка по Enter отключена. Это изменение относится только к UI; формат контейнера `SHiNE_DM` и серверный API не изменяются.
|
||||
|
||||
### Внешние ссылки и уведомления о переводах
|
||||
|
||||
Обычные `http://`, `https://` и `www.` ссылки в тексте DM остаются частью обычного
|
||||
текста и не меняют формат `SHiNE_DM`. При обычном нажатии UI предлагает скопировать
|
||||
ссылку или открыть её во внешнем браузере; внутренние ссылки SHiNE продолжают
|
||||
обрабатываться роутером приложения.
|
||||
|
||||
При переводе SOL/USDT собеседнику отправляется уведомление с подписью транзакции и
|
||||
ссылкой на Solana Explorer. Ссылка строится с текущим кластером (`devnet` или
|
||||
`mainnet-beta`), поэтому проверка открывает правильную сеть. Это также только UI-текст
|
||||
DM: серверный API, подпись и бинарный контейнер не изменяются.
|
||||
|
||||
При открытии личного чата UI прокручивает ленту к линии непрочитанных сообщений,
|
||||
если такие сообщения есть; при отсутствии непрочитанных — к последнему сообщению.
|
||||
При первичной загрузке истории это правило применяется после ответа сервера, а не
|
||||
только к сообщениям, уже находящимся в локальном кэше.
|
||||
|
||||
## Информационное сообщение о шифровании в начале DM (13.11.2026)
|
||||
|
||||
Экран `shine-UI/js/pages/chat-view.js` добавляет в самое начало визуальной ленты каждого личного диалога серое пояснение по центру о сквозном шифровании, ключах, открытом коде и последствиях потери пароля. Текст локализован для RU/EN через `screens.chat_view.security_notice.*`, стили — в `shine-UI/styles/features/chat.css`.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# SHiNE User PDA 1.3 — Root-signature, system limits, economy v2
|
||||
|
||||
## Canonical binary record
|
||||
|
||||
* Outer record layout and fork size **remain unchanged** from PDA 1.2; `paid_limit_bytes` remains `u32` (4 bytes) in **every fork**.
|
||||
* The new `format_minor = 3`. On create every fork limit is `0`. No `additional_limit` instruction argument or paid top-up.
|
||||
* `0` means **unlimited total blockchain bytes**, positive `N` means maximum `N` bytes. This does not remove per-block/request limits.
|
||||
* Canonical signing preimage = **exact serialized unsigned PDA bytes**, omitting **only four quota bytes in each fork**. Keep original physical `record_len` and variable-block `payload_len` fields unchanged in the canonical preimage; changing length values would change hashes.
|
||||
* `SHA256(canonical signing bytes)` is verified by an Ed25519 instruction from the Root Key. The 64-byte signature stored in PDA is **Root Key's signature**. The contract verifies signatures; it never signs for the user.
|
||||
* Normal update: one root Ed25519 instruction. Full key rotation: old root Ed25519 followed by new root Ed25519; stored signature is from new root. New root/client/blockchain keys must be rotated together. Blockchain Key remains for signing user-blockchain content, not User PDA.
|
||||
* Changes to on-chain limits are **not implemented** in this patch. Future privileged instruction must mutate ONLY the 4 bytes and have explicit authorization/audit. It must not permit untrusted PDA input to override the limit.
|
||||
* Every new fork starts with `paid_limit_bytes = 0` (unlimited), regardless of the previous fork's limit. Historical forks retain their own values. The existing fork cooldown is retained for ordinary forks.
|
||||
* `prev_record_hash` for a predecessor v1.2 is SHA256(physical v1.2 unsigned bytes). For v1.3 it is SHA256(canonical unsigned bytes without limit bytes). The first signed update migrates v1.2 -> 1.3 at the same PDA address.
|
||||
* Old v1.2 accounts remain readable and usable for Stars support operations. Their record signatures follow the old v1.2 rule until the first root-authorized migration to 1.3.
|
||||
|
||||
## Economy PDA v2
|
||||
|
||||
The on-chain state contains **only** `version=2:u8` and `update_fee_lamports:u64` (9 useful bytes; old allocated space may remain padded). No registration fee or quota price in this PDA. Registration fee lives in the namespace PDA. User PDA update fee comes from this economy PDA.
|
||||
|
||||
For existing v1 economy PDA, the program temporarily reads the legacy state and uses the previous fixed update fee 20,000 lamports; submit the authorized `IX_UPDATE_USERS_ECONOMY_CONFIG` with **only** 8-byte LE `update_fee_lamports` to migrate the existing economy PDA to v2. Its PDA address does not change.
|
||||
|
||||
## Wire changes
|
||||
|
||||
* `IX_CREATE_USER_PDA(3)`: removed `additional_limit:u64` after `created_at_ms`.
|
||||
* `IX_UPDATE_USER_PDA(4)`: removed `additional_limit:u64` after `updated_at_ms`; retained `auth_mode:u8` with **only 1 (root)** supported. The normal update requires the old root; rotation requires both old/new root signatures.
|
||||
* `IX_UPDATE_USERS_ECONOMY_CONFIG(2)`: now **only** `update_fee_lamports:u64`; same authority and account list as v1.
|
||||
|
||||
## Server
|
||||
|
||||
* Keep `size_limit=0` in runtime `blockchain_state_store` as unlimited, and `size_limit>0` as the active block-size total quota.
|
||||
* Both the optimistic handler check and the atomic SQL file-size update must treat zero as unlimited.
|
||||
* Synchronize limits for all historical forks from `solana_user_pda_current` into existing runtime blockchain states without resetting tips, size, or key material; use current fork value when accepting a block. If a valid free user has no Solana PDA yet, default to 0.
|
||||
* Limit mutation is not yet exposed; future change will require sync by slot/signature even without a changed `record_number`.
|
||||
|
||||
## Deployment order
|
||||
|
||||
1. Deploy server and client handling v1.2 + 1.3, economy v2 and zero-unlimited semantics together.
|
||||
2. Upgrade Solana `shine_users` program with the existing Program ID using authorized upgrade procedures; do **not** rotate seeds or PDA addresses.
|
||||
3. Migrate economy PDA v1 -> v2 through the authorized update instruction (default 20,000 lamports or chosen value).
|
||||
4. Create a new v1.3 account and verify stored root signature, first zero quota, added blocks >100 KB, Stars support, old v1.2 read, first v1.2 -> v1.3 root migration.
|
||||
5. Test full root/client/blockchain rotation requiring signatures from **both roots**, old fork read, and paid namespace creation.
|
||||
|
||||
Deployment and live signed chain transactions have **not** been performed by this source patch.
|
||||
@@ -139,7 +139,9 @@
|
||||
|
||||
Исходное сообщение остаётся наверху, ниже — счётчик и ответы в последовательном порядке. Не предлагать «Популярные» до подтверждения алгоритма и источника данных.
|
||||
|
||||
Для вложенных ответов показывать «В ответ …» и короткий контекст. Не уменьшать ширину текстовой колонки бесконечными отступами: после одного уровня показывать связь подписью или открывать подветку, используя имеющуюся маршрутизацию. Тонкая линия допустима только для обозначения реальной связи, не вокруг каждого комментария. Плотность ответов сохраняется близкой к Ночному SHiNE; выбор полноэкранного редактора из Клуба не означает переноса всей его плотности.
|
||||
Шапка автора — отдельная компактная полоса: фотография, отображаемые имя и фамилия, затем логин и относительное время без знака минус. Нажатие на шапку не уводит со страницы сразу, а открывает меню с действием «Показать профиль».
|
||||
|
||||
Прямые ответы исходному сообщению показываются отдельными блоками, разделёнными тонкой линией. Внутри блока виден только один вложенный уровень: не более двух комментариев сразу, остальные раскрываются кнопкой «Показать ещё». Более глубокие ответы не добавляются в этот блок; их можно открыть как отдельную подветку выбранного комментария. На карточке комментария счётчик означает только число его прямых ответов. Для вложенных ответов показывать «В ответ …» и короткий контекст. Не уменьшать ширину текстовой колонки бесконечными отступами. Тонкая линия допустима только для обозначения реальной связи, не вокруг каждого комментария. Плотность ответов сохраняется близкой к Ночному SHiNE; выбор полноэкранного редактора из Клуба не означает переноса всей его плотности.
|
||||
|
||||
Возврат ведёт в тот же канал и на прежнюю позицию. После отправки новый ответ появляется в ветке; при ошибке остаются текст и вложения. Длинные ветки потребуют отдельной проверки пагинации, состояния загрузки и перехода к конкретному ответу.
|
||||
|
||||
|
||||
@@ -103,3 +103,10 @@ await confirmDialog({
|
||||
Английские формулировки являются первым черновым переводом и требуют редакторской вычитки. Часть русских строк в служебном коде и отдельных нестандартных сценариях остаётся вне словарей; данные пользователей и протокольные значения переводить нельзя. При отсутствии ключа сохраняется русский fallback.
|
||||
|
||||
Проверка `node --test shine-UI/tests/i18n-completeness.test.mjs` требует одинаковых ключей и параметров в двух словарях и проверяет статические обращения `t()`/`th()` в JavaScript. После правок запускать также весь набор `node --test shine-UI/tests/*.test.mjs`, проверку синтаксиса JS и `python3 scripts/check_docs.py`.
|
||||
|
||||
## Пароль и генерация ключей в регистрации и входе (21.11.2026)
|
||||
|
||||
- На экране регистрации показывается разъяснение, что логин и пароль используются для локальной генерации криптографических ключей, а сервер не хранит пароль или приватные ключи. Пользователю рекомендуются 12–16+ символов или длинная парольная фраза. В тестовом периоде обязательный минимум **1 символ**, максимум **256**. Счётчик символов (`N / 256`) находится **только на регистрации**.
|
||||
- Для ввода пароля и при регистрации, и при входе используется расширяющееся поле до **трёх строк** (дальше прокрутка), по умолчанию видимое. В каждой строке на достаточно широком экране помещается **32 моноширинных символа**, на узких экранах длина строки адаптивна (приоритет — читаемость и отсутствие горизонтального выхода за экран). Автоматический перенос визуальный и не вставляет `\n` в пароль. Кнопка-глаз скрывает содержимое даже в многострочном поле; обычный Enter отправляет форму, Shift+Enter вставляет перенос строки. Перенос строки, введённый вручную, является частью пароля и влияет на ключи. После успешной генерации ключей при регистрации и после успешной авторизации при входе видимое поле сразу очищается, включая маску (секрет для следующих шагов регистрации остаётся в оперативном состоянии до окончания процесса). При возврате на шаг пароля ранее введённое значение не подставляется обратно.
|
||||
- Пока вычисляются ключи, оба экрана используют один экран ожидания с анимацией и подписями «Генерируем ваши цифровые ключи…» / «Генерируем их из вашего логина и пароля непосредственно на этом устройстве.». Проценты и индикатор хода работы **не показываются**; алгоритмы получения ключей и запросы API не изменены.
|
||||
- Подписи находятся в словарях `ru.json` и `en.json` (`components.secret_generation_overlay.*`, `screens.register_view.*`).
|
||||
|
||||
@@ -45,13 +45,16 @@
|
||||
`shine-network-explorer-v3`. Запись хранит ответ `getUserConnectionsGraph`,
|
||||
идентификатор сервера/аккаунта/логина и отметку времени. Время жизни — 24 часа;
|
||||
просроченное повторно запрашивается при обращении, а просроченные рёбра исключаются
|
||||
из исследованного графа. При открытии страницы до 1000 свежих изученных графов
|
||||
из исследованного графа. При переключении версий внутри уже открытой вкладки до 1000 свежих изученных графов
|
||||
восстанавливаются без сетевых запросов; память ограничена 800 горячими записями.
|
||||
Если IndexedDB недоступен, работает временное кэширование в памяти.
|
||||
|
||||
Пока вкладка V3 открыта, раз в пять минут проверяется актуальность выбранного центра.
|
||||
Подтверждённое изменение дружеских связей через UI также сбрасывает кэш V3, если
|
||||
этот экран открыт. Операция очистки инвалидирует незавершённые загрузки.
|
||||
этот экран открыт. Операция очистки инвалидирует незавершённые загрузки. **При каждом нажатии нижней
|
||||
кнопки «Связи»** исследованный граф V3/V4, координаты и IndexedDB-кэш графа
|
||||
сбрасываются, центр снова — собственный пользователь; X2 и фильтры выключены.
|
||||
При смене V3 ↔ V4 внутри открытого экрана сброса нет. Кэш изображений не затрагивается.
|
||||
|
||||
## Проверка
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Связи V4 — статический Canvas 2D
|
||||
|
||||
Вводится отдельный вариант **V4 · Canvas** в селекторе версий «Связи». V1, V2 и V3 остаются доступны.
|
||||
Ни сервер, ни API, ни блокчейн не меняются.
|
||||
|
||||
## Данные и управление
|
||||
|
||||
V4 использует ту же страницу `network-explorer/network-view.js` через `renderExplorer(context, { canvas: true })`:
|
||||
передача `graph-model.js`, кэш IndexedDB, загрузка X2, глубина 0–4, фильтры «Близкие»/«Сияющие»,
|
||||
поиск, сброс кэша и хранение координат являются общими для V3 и V4. Если пользователь перемещает
|
||||
узел, координаты сохраняются точно так же, как в V3. Разрешено перерисовать весь граф при приходе
|
||||
новых данных; перерасчёт модели не превращается в бесконечную анимацию.
|
||||
|
||||
V4 поддерживает мышь/сенсорный экран: перетаскивание сцены и узлов, масштабирование колесом
|
||||
и щипком, короткое и долгое нажатие, контекстное меню правой кнопкой. Групповое перетаскивание
|
||||
исторических центров из общего движка V1 для модели V3 не применяется.
|
||||
|
||||
`ZOOM_MIN = 0.55`, `ZOOM_MAX = 2.2`, `DIVE_ZOOM = 1.7`. Параметр `DIVE_ZOOM`
|
||||
используется в методе `recenter` движка; обычный выбор пользователя, как и V3, обрабатывается
|
||||
страницей с обновлением центра исследуемой сети.
|
||||
|
||||
## Рисование
|
||||
|
||||
- Слой №1 Canvas — связи; слой №2 — сияние, аватары, значки официальных пользователей, подписи.
|
||||
- Для каждой вершины изображение собирается в спрайт: внешняя стеклянная кромка V3
|
||||
(`/assets/glass_overlay_faithful.png`) рисуется под круглой **непрозрачной** фотографией/инициалами.
|
||||
Дополнительных цветных ободков V2 нет. Непрозрачная подложка под кромкой закрывает концы линий.
|
||||
- У сияющих есть **статическая** аура. Фотография остаётся поверх стекла и сияния;
|
||||
типы отношений кодируются цветами самих связей.
|
||||
- Подписи V2: округлая полупрозрачная плашка, компактное «Имя Ф.» (кроме центра),
|
||||
приоритет важных узлов, проверка пересечений и перенос плашки над узлом при необходимости.
|
||||
- Взаимная связь со встречными разными типами получает градиент от первого цвета ко второму.
|
||||
Для односторонней связи яркость плавно падает в сторону адресата.
|
||||
- Между двумя сияющими пользователями рисуется трёхслойный неон V3 на кривой:
|
||||
размытое поле, размытая трубка и светлая сердцевина. Для остальных пар — тонкая
|
||||
двухпроходная цветная линия. Односторонние сияющие линии сохраняют статичный пунктир V3.
|
||||
Пульсация и бегущие штрихи отсутствуют.
|
||||
- **Все вершины направляются на отрисовку**, даже если они за кадром. Для читабельности
|
||||
пересекающиеся текстовые плашки могут пропускаться. Связи также не отсекаются по viewport.
|
||||
- Спрайты повторно используются при движении карты и пересоздаются только при изменении фото,
|
||||
вида/разрешения или темы. Размер кэшированных спрайтов подстраивается под zoom и DPR,
|
||||
а общий расчётный бюджет изображений ограничен примерно 96 МБ.
|
||||
- После завершения ввода, загрузки изображений и пакетного построения спрайтов `requestAnimationFrame`
|
||||
больше не запрашивается; в состоянии покоя расхода кадров на эффекты нет.
|
||||
- В V4 старый анимированный псевдо-фон `.fg-stage::before` отключён; фон остаётся статичным.
|
||||
|
||||
## Повторное открытие вкладки «Связи»
|
||||
|
||||
Каждое нажатие **нижней кнопки «Связи»** сбрасывает исследованный граф V3/V4:
|
||||
очищает графы в памяти и в IndexedDB, забывает раскрытые ветви и координаты, возвращает
|
||||
к собственному профилю, отключает X2 и дополнительные фильтры. После окончания
|
||||
очистки загружаются собственные непосредственные связи. Новый запрос ждёт завершения
|
||||
очистки — старые данные не восстанавливаются наперегонки из IndexedDB.
|
||||
Переключение версий V1/V2/V3/V4 в селекторе внутри открытого экрана **не** сбрасывает
|
||||
исследованный граф. Кэш изображений браузера, фотографии и другие данные приложения не стираются.
|
||||
Верхнее меню «Очистить кэш» остаётся отдельным действием внутри уже открытой карты.
|
||||
|
||||
## Файлы
|
||||
|
||||
- `shine-UI/js/pages/network-canvas-v4/graph-renderer.js` — рендер и жесты.
|
||||
- `shine-UI/js/pages/network-canvas-v4/graph-style.js` — палитры и геометрия направленных линий.
|
||||
- `shine-UI/js/pages/network-canvas-v4/network-view.js` — адаптер страницы V4.
|
||||
- `shine-UI/js/pages/network-explorer/network-view.js` — общая страница V3/V4.
|
||||
- `shine-UI/js/pages/network-version-switcher.js` — выбор V4 и обработчик входа во вкладку.
|
||||
- `shine-UI/js/components/toolbar.js` — сигнал повторного входа по нижней кнопке.
|
||||
- `shine-UI/index.html` — обновлённый build hash загрузки UI.
|
||||
- `shine-UI/styles/features/network.css` — Canvas-слои, выключение старой анимации.
|
||||
- `shine-UI/tests/network-explorer-v4.test.mjs` — проверки градиентов, затухания, геометрии и модели.
|
||||
|
||||
## Проверка и ограничения
|
||||
|
||||
Команды в корне репозитория:
|
||||
|
||||
```bash
|
||||
node --test shine-UI/tests/network-explorer-v3.test.mjs shine-UI/tests/network-explorer-v4.test.mjs
|
||||
```
|
||||
|
||||
Базовые тесты проверяют градиенты и затухание линий, геометрию и BFS-модель, а также
|
||||
инварианты порядка рисования стекла/фото, стиля неона/подписей и механизма сброса вкладки.
|
||||
Они не заменяют полноценный браузерный тест страницы с авторизацией и реальными запросами к серверу.
|
||||
Для финальной проверки на устройстве стоит сравнить FPS/память V3 и V4 на одном исследованном графе,
|
||||
проверить фото из Arweave и R2, долгий тап и пересечения подписей на узком экране.
|
||||
|
||||
|
||||
### Canvas V4c — стекло и неон как в V3 (19.11.2026)
|
||||
|
||||
- Цветные красно-синие кольца аватаров удалены. Возвращена стеклянная PNG-кромка V3 (`glass_overlay_faithful.png`, 119% размера узла).
|
||||
- Фото/инициалы рисуются **после** стекла, непрозрачно, поверх бликов; диск под стеклом закрывает окончания линий нижнего Canvas. Сияющие ауры остались статичными.
|
||||
- Сияющие связи рисуются в стиле V3: поле 16px с размытием 6px, трубка 6px с размытием 2px и тонкое светлое ядро 2px, всё с `screen`-композитингом. Blur выполняется один раз для слоя всех связей. Сине-красные градиенты и затухание односторонних связей сохранены.
|
||||
- Система подписей V2, масштаб 0.55–2.2 и сброс исследованной карты при входе в «Связи» без изменений. Никаких пульсаций и фоновых циклов рендера.
|
||||
@@ -10,6 +10,7 @@
|
||||
- [Поддержка SHiNE в меню кошельков](WALLET_SHINE_SUPPORT.md) — отдельный пункт пожертвования, старые экраны кошельков и билетов.
|
||||
- [Локализация UI (этап 1)](I18N.md) — языковой движок, приоритет системного языка и глобальные настройки.
|
||||
- [Связи V3: исследование графа](NETWORK_EXPLORER_V3.md) — BFS-глубина, X2, размеры аватарок, кэш 24 часа.
|
||||
- [Связи V4: Canvas](NETWORK_EXPLORER_V4.md) — та же логика V3, аватары и подписи V2, статичная аура и неоновые линии.
|
||||
- [PWA: масштабирование и аватар профиля](PWA_VIEWPORT_AND_AVATAR_PREVIEW.md) — поведение полноэкранного интерфейса и просмотра фотографии.
|
||||
- [Заявления о статусах и предупреждения о блокчейне](PROFILE_DECLARATIONS_AND_CONSENT.md) — действующие сценарии профиля, лайков и подтверждений на 06.11.2026.
|
||||
|
||||
|
||||
@@ -16,3 +16,39 @@
|
||||
Название и подсказка пункта локализованы в RU/EN; словарь `screens.support_phase2` управляет уже существующим окном пожертвования.
|
||||
|
||||
Проверка: `node --test shine-UI/tests/support-phase2.test.mjs shine-UI/tests/wallet-donate-menu.test.mjs`.
|
||||
|
||||
## Мультивалютный кошелёк и прямые переводы (17.11.2026)
|
||||
|
||||
Добавлен отдельный маршрут `wallet/transfer` и `wallet/transfer/<login>`: форма с валютой SOL/USDT, балансами и подтверждением суммы. Из чата получатель фиксирован (логин + найденный blockchainKey), из кошелька вводится только произвольный адрес Base58. Опциональное DM-уведомление доступно только при переводе из чата.
|
||||
|
||||
- Старая кнопка SOL перевода по `window.prompt` заменена переходом на полноэкранный `wallet-transfer-view.js`.
|
||||
- Из меню переписки (вертикальное троеточие) пункт «Перевести деньги» открывает ту же страницу с предвыбранным собеседником.
|
||||
- Адрес контакта берётся **из последнего blockchainKey** Solana PDA; для бесплатных аккаунтов без PDA — из `GetUser.blockchainKey`. Не использовать `clientKey` (DM) и `rootKey`.
|
||||
- Для пользовательского перевода SOL применяется прямой `SystemProgram.transfer` (lamports), для USDT — `TransferChecked` обычной SPL Token Program. Токеновые счета ATA определяются по owner + mint; при отсутствии получательского ATA создаётся (аренду платит отправитель в SOL).
|
||||
- В Mainnet допустим исключительно официальный USDT-mint `Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB`; в Devnet **настоящего USDT нет** и без тестового mint USDT выключен. Для отдельного тестового SPL-актива с 6 знаками можно заполнить `devnetTestUsdtMint` в `js/deploy-config.js`. Такой актив всегда подписывается в UI «Тестовый USDT».
|
||||
- Прямые переводы не являются пожертвованиями, не вызывают `shine_users` и не обновляют Stars/DAO. Существующие формы донатов не менялись.
|
||||
- При запросе получателя-кошелька запрещены программные и токеновые счета (а также невалидные ed25519 адреса). Пользователь подтверждает адрес перед подписью.
|
||||
- Опциональное сообщение в DM отправляется **после подтверждённой** Solana-транзакции; неуспех доставки DM не отменяет перевод и не инициирует повторную отправку. Нельзя показывать такой перевод как неуспешный из-за сбоя DM.
|
||||
- Кнопка Jupiter из кошелька открывает внутреннюю страницу `/wallet/swap` (бета); внешнего кошелька не требуется. Прямые переводы и Stars остаются отдельными операциями.
|
||||
|
||||
Тесты: `node --test shine-UI/tests/wallet-multicurrency-transfer.test.mjs` и полный набор `shine-UI/tests/*.test.mjs`.
|
||||
|
||||
|
||||
## Обмен Jupiter через API (17.11.2026, β)
|
||||
|
||||
- `wallet/swap` открывается из экрана Solana. Направления: **SOL → USDT**, **USDT → SOL**; только Mainnet. На Devnet обмен отключён. Пары зафиксированы по canonical mint, подстановка неизвестного токена невозможна.
|
||||
- Используется **Jupiter Swap API V2 `GET /swap/v2/build`**, Metis Router, без стороннего JS/Phantom. Клиент получает сырые инструкции, валидирует mint/сумму/проскальзывание (не более 0,5%), разрешённые программы и signer accounts; проверяет Address Lookup Tables по Solana RPC.
|
||||
- Формируется v0-транзакция через локальный `@solana/web3.js`. Перед подписью выполняется `simulateTransaction` и сверяются USDT/SOL балансы после операции. Подписывает **только пользовательский `blockchainKey`**; приватный ключ не отправляется Jupiter и не предоставляется серверу SHiNE. SHiNE RPC используется для чтения Solana и передачи подписанной транзакции.
|
||||
- В бета-функции пользователь видит предупреждение и должен дважды подтвердить намерение: чекбокс принятия рисков и финальное `confirm` с суммами. Лимиты: **0,02 SOL** или **5 USDT** за обмен, и 0,01 SOL остатка на комиссии. При неизвестной инструкции, устаревшей котировке (>30 c), ошибке симуляции или несовпадении балансов выполнение запрещено.
|
||||
- Если после отправки статус неопределён, идентификатор подписанной транзакции сохраняется в `sessionStorage`. Нельзя автоматически повторять обмен, пока статус не выяснен. Ошибка сети не означает, что операция не прошла.
|
||||
- Без изменения Java-сервера, PostgreSQL, `shine_users`, Stars и донатов. Используется существующий шлюз `/solana-rpc`. Бета-обмен не тестировался реальными средствами в Mainnet: **не является подтверждённо безопасным финансовым релизом**. Не все маршруты Jupiter могут пройти консервативную проверку; такие маршруты отклоняются. Jupiter Keyless API ограничен по частоте.
|
||||
|
||||
Для проверки: `node --test shine-UI/tests/wallet-jupiter-swap-beta.test.mjs shine-UI/tests/wallet-multicurrency-transfer.test.mjs`. Тесты покрывают политику валидации, но не эквивалентны end-to-end тесту реального обмена.
|
||||
|
||||
### Упрощение переводов (18.11.2026)
|
||||
|
||||
- Меню чата: «Перевести деньги» перенесено после пункта «Добавить в контакты» (если пункт показан), непосредственно перед разделителем, за которым расположены «Очистить историю» и «Удалить чат».
|
||||
- Переход из чата `wallet/transfer/<login>`: единственный получатель — собеседник. Показываются логин и вычисленный `blockchainKey` (Solana), адрес нельзя редактировать. Никакого переключения получателя или поиска контактов. Перед подписанием ключ повторно сверяется.
|
||||
- Переход из кошелька `wallet/transfer`: пустое поле для ввода любого обычного адреса Solana; выбора контактов и галочки DM нет.
|
||||
- Выбор SOL/USDT, балансы, проверка адреса, транзакция и защита от повторной отправки без изменений. Путь Jupiter Swap β и его предупреждения не изменены.
|
||||
- В Mainnet интерфейс автоматически использует официальный mint USDT и может показывать нулевой баланс, если токенов нет. Devnet не имеет настоящего USDT; обмен Jupiter на Devnet отключён.
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
## Конфигурация
|
||||
|
||||
- `freeRegistration.enabled=false` по умолчанию. Включается только на тестовом сервере после проверки соответствия namespace.
|
||||
- `freeRegistration.enabled=false` по умолчанию. Для включения обязательно одновременно задать `freeRegistration.namespace=<namespace>`: это единственный type-2 namespace, в котором данный сервер выдаёт бесплатные аккаунты. Если namespace не задан или `enabled=false`, сервер публикует только платные namespace и не показывает в UI вариант бесплатной регистрации.
|
||||
- При включении сервер до начала работы сверяет, что указанный namespace имеет type 2, его `default_server_login` совпадает с `server.SHiNE.login`, а `registrar_pubkey` — с публичным ключом из seed. При несовпадении запуск прекращается; чужой namespace нельзя случайно обслужить.
|
||||
- `freeRegistration.registrarSeedFile` — абсолютный путь к файлу вне Git, внутри одна Base64-строка **32-byte Ed25519 seed**. Пример имени `/var/lib/shine/secrets/registrar-seed.b64`; не создавать файл с тестовым ключом внутри репозитория.
|
||||
- `LocalRegistrarSigner.fromConfig(AppConfig)` проверяет enabled и наличие пути, не печатает секрет или bytes в лог.
|
||||
- Публичный ключ signer должен совпадать с `shine_namespace_current.registrar_pubkey` (из on-chain namespace), иначе `FreeRegistrationIssuer.issue` отказывает.
|
||||
|
||||
@@ -48,9 +48,15 @@
|
||||
- `SolanaUsersSyncService` + `PostgresStorageRepository` создают/перезаписывают snapshots; не допустить, чтобы sync очищал доверенные free-сертификаты или создавал дубль при Solana upgrade.
|
||||
- `ArweaveBlockSyncService` читает `solana_user_pda_current` и blockchain-данные: восстановление free должно оставаться независимым от факта существования реального Solana PDA.
|
||||
|
||||
## Решение для этапа 5 — пока НЕ принято
|
||||
## Принятое решение: единая identity без фиктивной PDA
|
||||
|
||||
Требование мастер-плана: одна логическая личность для `FREE_CERT` и `PAID_UPGRADED`; при free **нет on-chain PDA**, но сохраняются FK/индексы/функциональность сообщений, каналов, связей и сессий. Не вставлять фиктивный Solana snapshot со slot/signature только ради удовлетворения FK. Выбрать единый identity-index после проверки реальной схемы и протестировать:
|
||||
Одна логическая личность существует для `FREE_CERT` и `PAID_UPGRADED`; при free **нет on-chain PDA**, но сохраняются FK/индексы/функциональность сообщений, каналов, связей и сессий. Не вставлять фиктивный Solana snapshot со slot/signature только ради удовлетворения FK.
|
||||
|
||||
Обычные серверные операции обязаны использовать `user_identity_current`: он содержит подтверждённые сертификатом Arweave login, blockchain name и публичные ключи free-пользователя. `solana_user_pda_current` допустимо использовать только для функций, которым действительно нужны on-chain сведения: платежи, Solana-ротация ключей, PDA и маршруты из Solana.
|
||||
|
||||
Для чтения блокчейна SQL-функции `shine_identity_active_fork(login)` и `shine_active_fork(login, block_number)` выбирают ветку по общей identity; при отсутствии PDA используется актуальная запись `blockchain_state_store`, а последним fallback служит fork `1`. Это обеспечивает одинаковую работу каналов и обсуждений у free и paid пользователей.
|
||||
|
||||
После миграции статистика free-пользователей пересчитывается из `channel_names_state` и `connections_state`. Проверить:
|
||||
|
||||
1. создание free до появления в Solana, работа всех 15 зависимых таблиц;
|
||||
2. транзакционный upgrade без перегенерации root/blockchain/client и без переименования логина;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
| `ConfirmFreeRegistration` | `challengeId,code` (случайный шестизначный код из письма) | `fullLogin,dataItemId,publicationStatus,chainConfirmed:false` | выпуск+Turbo ACK+локальный импорт |
|
||||
| `GetRegistrationStatus` | `fullLogin` | `registrationStatus,dataItemId,publicationStatus`; для FREE_CERT дополнительно `innerSignature64B64,rootPublicKey,blockchainPublicKey,clientPublicKey,defaultServerLogin` | retry/upgrade |
|
||||
|
||||
`registrationFeeLamports` — строка десятичного целого u64. `currencyCode` — числовой код: `1` = SOL; `2` зарезервирован, сервер не принимает его до реализации USDT. Сервер отдаёт актуальный кэш namespace после sync Solana, UI перед платной транзакцией дополнительно читает значение напрямую из Solana. Публичные ключи запроса — Base64 от ровно 32 байт (не PKCS#8). `innerSignature64B64` — Base64 внутренней подписи Ed25519, публичная информация сертификата; PRIVATE-ключ регистратора никогда не отдаётся.
|
||||
`registrationFeeLamports` — строка десятичного целого u64. `currencyCode` — числовой код: `1` = SOL; `2` зарезервирован, сервер не принимает его до реализации USDT. Сервер отдаёт актуальный кэш namespace после sync Solana, UI перед платной транзакцией дополнительно читает значение напрямую из Solana. `GetNamespaces` всегда содержит платные namespace и содержит type-2 namespace только когда на этом access-сервере явно включён и проверен `freeRegistration.namespace`; другие type-2 namespace не возвращаются и не принимаются в `CheckRegistrationLogin`. Публичные ключи запроса — Base64 от ровно 32 байт (не PKCS#8). `innerSignature64B64` — Base64 внутренней подписи Ed25519, публичная информация сертификата; PRIVATE-ключ регистратора никогда не отдаётся.
|
||||
|
||||
**Ошибки:** `REGISTRATION_UNAVAILABLE` 503, `INVALID_REGISTRATION_INPUT` 400, `REGISTRATION_CONFLICT` 409, `RATE_LIMITED` 429, прочие 500 требуют анализа логов без раскрытия секретов. Проверка логина и email *не резервирует* их; перед подписью и перед импортом делается повторная проверка.
|
||||
|
||||
|
||||
@@ -35,3 +35,9 @@ payload = identity_fields || inner_signature64 || email_sha256:32
|
||||
Детерминированные фикстуры: `shine-solana/shine/tests/fixtures/registration-v2.json` (в том числе ранее подписанный ANS-104 DataItem с историческим `App=test5591`, его ID и подписи). Этот вектор сохранён **исключительно для проверки криптографического формата**, он НЕ является актуальным тегом выпуска. Актуальный `App=test5592` проверяется выпуском нового сертификата через Java `FreeRegistrationCertificateV1Check`. Векторные ключи предназначены только для тестов. Java-подписание и проверка сертификата присутствуют в этапе 7; загрузка через Turbo и доверенный импорт — этап 8.
|
||||
|
||||
Адрес PDA при upgrade вычисляется от **ASCII lowercase** полного логина, но строка логина в сертификате, его подпись и поле `login` в PDA остаются в исходном регистре. Пароль/Argon2id также используют lowercase полного логина.
|
||||
|
||||
Исходное написание — это отображаемое зарегистрированное имя. Runtime-идентификаторы
|
||||
(`normalized_login`, `blockchain_name`, ключи `blocks_store` и `blockchain_state_store`)
|
||||
используют ASCII lowercase. Поэтому уже выпущенные сертификаты с заглавными буквами
|
||||
остаются валидными: сервер не меняет их подписанные байты, а приводит к lowercase
|
||||
только несигнатурные ключи хранения и поиска.
|
||||
|
||||
+2
-2
@@ -39,13 +39,13 @@
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
window.__SHINE_BUILD_HASH__ = '20261116-boot-error-ui-v1';
|
||||
window.__SHINE_BUILD_HASH__ = '20261119-graph-v4c';
|
||||
window.__SHINE_CLIENT_VERSION__ = '1.20.9';
|
||||
</script>
|
||||
<script>
|
||||
(function attachStylesWithBuildHash() {
|
||||
const v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
|
||||
const cssFiles = ['./styles/main.css', './styles/layout.css', './styles/app-shell.css', './styles/buttons-white.css', './styles/components/topbar.css', './styles/components/dropdown-menu.css', './styles/components/primitives.css', './styles/components/feedback.css', './styles/components/tabs.css', './styles/components/chips.css', './styles/components/nav-list.css', './styles/components/palette-editor.css', './styles/components/avatar.css', './styles/components/modal.css', './styles/components/person-note.css', './styles/components/person-row.css', './styles/components/compose.css', './styles/components/attachments.css', './styles/components/media-viewer.css', './styles/components/channel-editor.css', './styles/components/emoji-picker.css', './styles/components/call-ui.css', './styles/components/scroll-to-bottom.css', './styles/components/overflow-dots.css', './styles/components/toolbar.css', './styles/features/preauth.css', './styles/features/messages.css', './styles/features/chat.css', './styles/features/channels-common.css', './styles/features/channels-list.css', './styles/features/channel.css', './styles/features/channel-thread.css', './styles/features/notifications.css', './styles/features/network.css', './styles/features/profile.css', './styles/features/profile-page.css', './styles/features/settings.css', './styles/features/devices.css', './styles/features/developer-tools.css', './styles/network-graph.css', './styles/network-legacy.css'];
|
||||
const cssFiles = ['./styles/main.css', './styles/layout.css', './styles/app-shell.css', './styles/buttons-white.css', './styles/components/topbar.css', './styles/components/dropdown-menu.css', './styles/components/primitives.css', './styles/components/feedback.css', './styles/components/tabs.css', './styles/components/chips.css', './styles/components/nav-list.css', './styles/components/palette-editor.css', './styles/components/avatar.css', './styles/components/modal.css', './styles/components/person-note.css', './styles/components/person-row.css', './styles/components/compose.css', './styles/components/attachments.css', './styles/components/media-viewer.css', './styles/components/channel-editor.css', './styles/components/emoji-picker.css', './styles/components/call-ui.css', './styles/components/scroll-to-bottom.css', './styles/components/overflow-dots.css', './styles/components/toolbar.css', './styles/features/preauth.css', './styles/features/messages.css', './styles/features/chat.css', './styles/features/channels-common.css', './styles/features/channels-list.css', './styles/features/channel.css', './styles/features/channel-thread.css', './styles/features/notifications.css', './styles/features/network.css', './styles/features/profile.css', './styles/features/profile-page.css', './styles/features/settings.css', './styles/features/devices.css', './styles/features/developer-tools.css', './styles/features/wallet-transfer.css', './styles/features/wallet-swap.css', './styles/network-graph.css', './styles/network-legacy.css'];
|
||||
// Стили, добавленные скриптом, браузер не ждёт перед первой отрисовкой: без этого
|
||||
// на долю секунды виден экран без CSS (логотип 640×640), а потом он «прыгает» на место.
|
||||
const root = document.documentElement;
|
||||
|
||||
+7
-3
@@ -86,7 +86,9 @@ import * as publicSupportQueueView from './pages/public-support-queue-view.js';
|
||||
import * as profileView from './pages/profile-view.js?v=20261110-pwa-avatar';
|
||||
import * as profileEditView from './pages/profile-edit-view.js';
|
||||
import * as profilesView from './pages/profiles-view.js';
|
||||
import * as walletView from './pages/wallet-view.js?v=202609260900';
|
||||
import * as walletView from './pages/wallet-view.js?v=202611170124';
|
||||
import * as walletTransferView from './pages/wallet-transfer-view.js';
|
||||
import * as walletSwapView from './pages/wallet-swap-view.js';
|
||||
import * as settingsView from './pages/settings-view.js';
|
||||
import * as accessKeysView from './pages/access-keys-view.js';
|
||||
import * as myBlockchainView from './pages/my-blockchain-view.js';
|
||||
@@ -118,7 +120,7 @@ import * as solanaUsersInitView from './pages/solana-users-init-view.js';
|
||||
import * as solanaRpcCheckView from './pages/solana-rpc-check-view.js';
|
||||
import * as messagesList from './pages/messages-list.js?v=202610130400';
|
||||
import * as contactSearchView from './pages/contact-search-view.js';
|
||||
import * as chatView from './pages/chat-view.js?v=202610130200';
|
||||
import * as chatView from './pages/chat-view.js?v=202611170124';
|
||||
import * as chatMediaView from './pages/chat-media-view.js';
|
||||
import { isDmChatMuted } from './services/dm-chat-prefs.js';
|
||||
import { getDevicePref } from './services/device-prefs.js';
|
||||
@@ -135,7 +137,7 @@ import * as channelDonateView from './pages/channel-donate-view.js';
|
||||
import * as channelThreadView from './pages/channel-thread-view.js';
|
||||
import * as addChannelView from './pages/add-channel-view.js';
|
||||
import * as addPersonalPublicChatView from './pages/add-personal-public-chat-view.js';
|
||||
import * as networkView from './pages/network-version-switcher.js?v=202610170100';
|
||||
import * as networkView from './pages/network-version-switcher.js?v=20261119-graph-v4b';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
||||
|
||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||
@@ -173,6 +175,8 @@ const routes = {
|
||||
'profile-edit-view': profileEditView,
|
||||
'profiles-view': profilesView,
|
||||
'wallet-view': walletView,
|
||||
'wallet-transfer-view': walletTransferView,
|
||||
'wallet-swap-view': walletSwapView,
|
||||
'settings-view': settingsView,
|
||||
'access-keys-view': accessKeysView,
|
||||
'my-blockchain-view': myBlockchainView,
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { formatDateTime } from '../i18n/format.js';
|
||||
import { escapeHtml } from '../services/attachment-format.js';
|
||||
import { arweaveBlockUrl, checkArweavePayload, checkSolanaAuthor, readSignedBlock, signedDataItemFilename } from '../services/blockchain-proof-service.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
const validHash = (value) => /^[0-9a-f]{64}$/iu.test(String(value || ''));
|
||||
const label = (key) => t(`blockchain_details.${key}`);
|
||||
const safe = (value) => escapeHtml(String(value ?? ''));
|
||||
const shortened = (value) => String(value || '').length > 24
|
||||
? `${String(value).slice(0, 12)}…${String(value).slice(-8)}` : String(value || '');
|
||||
|
||||
function asVersions(details) {
|
||||
const raw = Array.isArray(details?.raw?.versions) ? details.raw.versions : [];
|
||||
if (raw.length) return raw.map((v, i) => ({ ...v, versionIndex: Number(v.versionIndex || i + 1) }));
|
||||
return [{ versionIndex: 1, blockNumber: details.blockNumber, blockHash: details.blockHash,
|
||||
createdAtMs: details.createdAtMs, arweaveDataItemId: details.raw?.arweaveDataItemId || '',
|
||||
arweavePublishPending: details.raw?.arweavePublishPending,
|
||||
arweavePublishedAtMs: details.raw?.arweavePublishedAtMs,
|
||||
signedDataItemBytes: details.raw?.signedDataItemBytes }];
|
||||
}
|
||||
function field(title, value, { code = false } = {}) {
|
||||
const valueHtml = code ? `<code title="${safe(value)}">${safe(value)}</code>` : `<strong>${safe(value)}</strong>`;
|
||||
return `<div class="block-proof-row"><span>${safe(title)}</span>${valueHtml}</div>`;
|
||||
}
|
||||
function statusFor(version) {
|
||||
if (version?.arweavePublishedAtMs > 0) return { color: 'success', text: label('published') };
|
||||
if (version?.arweavePublishPending === true) return { color: 'pending', text: label('pending') };
|
||||
return { color: 'unknown', text: label('unknown') };
|
||||
}
|
||||
async function copy(value) {
|
||||
const text = String(value || '');
|
||||
if (!text) return;
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
const input = document.createElement('textarea');
|
||||
input.value = text; input.style.position = 'fixed'; input.style.opacity = '0';
|
||||
document.body.append(input); input.select(); document.execCommand('copy'); input.remove();
|
||||
}
|
||||
showToast(label('copied'));
|
||||
}
|
||||
function resultRow(name, status, reason = '') {
|
||||
const mark = status === 'valid' ? '✓' : status === 'invalid' ? '✕' : '—';
|
||||
const description = status === 'valid' ? label('verified') : status === 'invalid' ? label('failed') : label('not_verified');
|
||||
return `<div class="block-proof-check block-proof-check--${status}"><span aria-hidden="true">${mark}</span><div><strong>${safe(name)}: ${safe(description)}</strong>${reason ? `<small>${safe(reason)}</small>` : ''}</div></div>`;
|
||||
}
|
||||
|
||||
/** Единый диалог для ленты канала и страницы обсуждения. */
|
||||
export function openBlockchainDetailsModal(details, { authService, solanaEndpoint, isActive = () => true } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
const versions = asVersions(details);
|
||||
let current = versions.length - 1;
|
||||
let busy = false;
|
||||
const rawText = JSON.stringify(details.raw || {}, null, 2);
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="blockchain-details-modal">
|
||||
<section class="modal-card stack blockchain-details-card block-proof-card" role="dialog" aria-modal="true" aria-label="${safe(label('title'))}">
|
||||
<header class="block-proof-header">
|
||||
<span class="block-proof-icon" aria-hidden="true">⛓</span>
|
||||
<div><h3 class="modal-title">${safe(label('title'))}</h3><p class="meta-muted">${safe(label('description'))}</p></div>
|
||||
</header>
|
||||
${versions.length > 1 ? `<label class="field-label" for="block-proof-version">${safe(label('version'))}</label>
|
||||
<select class="input" id="block-proof-version">${versions.map((v, i) => `<option value="${i}" ${i === current ? 'selected' : ''}>${safe(label('version'))} ${i + 1} · #${safe(v.blockNumber)}</option>`).join('')}</select>` : ''}
|
||||
<div id="block-proof-content"></div>
|
||||
<div class="block-proof-actions">
|
||||
<a class="secondary-btn block-proof-link" id="block-proof-open" target="_blank" rel="noopener noreferrer">↗ ${safe(label('open_arweave'))}</a>
|
||||
<button class="secondary-btn" type="button" id="block-proof-copy-url">${safe(label('copy_url'))}</button>
|
||||
<button class="secondary-btn" type="button" id="block-proof-download">↓ ${safe(label('download_signed'))}</button>
|
||||
<button class="secondary-btn block-proof-verify" type="button" id="block-proof-verify">🛡 ${safe(label('verify'))}</button>
|
||||
</div>
|
||||
<div id="block-proof-results" class="block-proof-results" hidden aria-live="polite"></div>
|
||||
<details class="block-proof-raw"><summary>${safe(label('technical'))}</summary>
|
||||
<pre class="blockchain-raw-block">${safe(rawText)}</pre>
|
||||
<button class="secondary-btn" id="block-proof-copy-raw" type="button">${safe(label('copy_raw'))}</button>
|
||||
</details>
|
||||
<button class="secondary-btn" id="block-proof-close" type="button">${safe(label('close'))}</button>
|
||||
</section>
|
||||
</div>`;
|
||||
const get = (id) => root.querySelector(`#${id}`);
|
||||
const currentVersion = () => versions[current];
|
||||
const content = get('block-proof-content');
|
||||
const results = get('block-proof-results');
|
||||
const button = get('block-proof-download');
|
||||
const verify = get('block-proof-verify');
|
||||
const close = () => { if (get('blockchain-details-modal')) root.innerHTML = ''; };
|
||||
function renderVersion() {
|
||||
const v = currentVersion();
|
||||
const archive = statusFor(v);
|
||||
const hash = validHash(v.blockHash) ? v.blockHash : '';
|
||||
const url = arweaveBlockUrl(v.arweaveDataItemId);
|
||||
const date = Number(v.createdAtMs || details.createdAtMs);
|
||||
content.innerHTML = `
|
||||
<div class="block-proof-facts">
|
||||
${field(label('author'), details.authorLogin || '—')}
|
||||
${field(label('blockchain'), details.authorBlockchainName || '—', { code: true })}
|
||||
${field(label('block_number'), v.blockNumber)}
|
||||
${field(label('created'), date > 0 ? formatDateTime(new Date(date)) : '—')}
|
||||
${field(label('storage'), 'Arweave')}
|
||||
${field(label('signed_size'), Number.isInteger(v.signedDataItemBytes) ? `${v.signedDataItemBytes} ${label('bytes')}` : '—')}
|
||||
</div>
|
||||
${v.attachmentMetadataValid === false ? `<p class="block-proof-warning">${safe(label('invalid_attachment'))}</p>` : ''}
|
||||
<div class="block-proof-status block-proof-status--${archive.color}"><span class="block-proof-dot"></span>${safe(archive.text)}</div>
|
||||
<div class="block-proof-hash"><span>${safe(label('hash'))}</span><div><code title="${safe(hash)}">${safe(shortened(hash) || '—')}</code><button type="button" class="block-proof-copy-icon" id="block-proof-copy-hash" ${hash ? '' : 'disabled'} aria-label="${safe(label('copy_hash'))}" title="${safe(label('copy_hash'))}">⧉</button></div></div>
|
||||
${url ? `<div class="block-proof-hash"><span>Arweave DataItem ID</span><div><code title="${safe(v.arweaveDataItemId)}">${safe(shortened(v.arweaveDataItemId))}</code><button type="button" class="block-proof-copy-icon" id="block-proof-copy-id" aria-label="${safe(label('copy_id'))}" title="${safe(label('copy_id'))}">⧉</button></div></div>` : ''}`;
|
||||
get('block-proof-open').href = url || '#';
|
||||
get('block-proof-open').hidden = !url;
|
||||
get('block-proof-copy-url').disabled = !url;
|
||||
get('block-proof-copy-hash')?.addEventListener('click', () => { void copy(hash); });
|
||||
get('block-proof-copy-id')?.addEventListener('click', () => { void copy(v.arweaveDataItemId); });
|
||||
results.hidden = true;
|
||||
results.replaceChildren();
|
||||
}
|
||||
async function signedBlock() {
|
||||
const v = currentVersion();
|
||||
if (!validHash(v.blockHash)) throw new Error(label('missing_hash'));
|
||||
return readSignedBlock({ authService, blockchainName: details.authorBlockchainName,
|
||||
blockNumber: v.blockNumber, blockHash: v.blockHash, dataItemId: v.arweaveDataItemId });
|
||||
}
|
||||
get('block-proof-version')?.addEventListener('change', (event) => {
|
||||
if (busy) { event.target.value = String(current); return; }
|
||||
current = Number(event.target.value); renderVersion();
|
||||
});
|
||||
get('block-proof-copy-url')?.addEventListener('click', () => { void copy(arweaveBlockUrl(currentVersion().arweaveDataItemId)); });
|
||||
get('block-proof-copy-raw')?.addEventListener('click', () => { void copy(rawText); });
|
||||
get('block-proof-close')?.addEventListener('click', close);
|
||||
button.addEventListener('click', async () => {
|
||||
if (busy) return;
|
||||
busy = true; button.disabled = true; verify.disabled = true;
|
||||
try {
|
||||
const proof = await signedBlock();
|
||||
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||
const blobUrl = URL.createObjectURL(new Blob([proof.bytes], { type: 'application/octet-stream' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = blobUrl;
|
||||
link.download = signedDataItemFilename(details.authorBlockchainName, currentVersion().blockNumber);
|
||||
document.body.append(link); link.click(); link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
|
||||
} catch (error) { if (isActive()) showToast(String(error?.message || error), { kind: 'error' }); }
|
||||
finally { busy = false; button.disabled = false; verify.disabled = false; }
|
||||
});
|
||||
verify.addEventListener('click', async () => {
|
||||
if (busy) return;
|
||||
busy = true; verify.disabled = true; button.disabled = true;
|
||||
const select = get('block-proof-version'); if (select) select.disabled = true;
|
||||
results.hidden = false; results.textContent = label('checking');
|
||||
try {
|
||||
const proof = await signedBlock();
|
||||
const id = currentVersion().arweaveDataItemId || proof.actualId;
|
||||
const [arweave, solana] = await Promise.all([
|
||||
checkArweavePayload(id, proof.data),
|
||||
checkSolanaAuthor({ authorLogin: details.authorLogin, blockchainName: details.authorBlockchainName,
|
||||
owner32: proof.owner32, solanaEndpoint }),
|
||||
]);
|
||||
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||
results.innerHTML = [
|
||||
resultRow(label('signature'), 'valid'),
|
||||
resultRow(label('integrity'), 'valid'),
|
||||
resultRow(label('arweave_check'), arweave.status, arweave.reason),
|
||||
resultRow(label('solana_check'), solana.status, solana.reason),
|
||||
`<p class="meta-muted">${safe(label('proof_note'))}</p>`,
|
||||
].join('');
|
||||
} catch (error) {
|
||||
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||
results.innerHTML = resultRow(label('signed_check'), 'unavailable', String(error?.message || error));
|
||||
} finally {
|
||||
busy = false;
|
||||
if (get('blockchain-details-modal')) { verify.disabled = false; button.disabled = false; if (select) select.disabled = false; }
|
||||
}
|
||||
});
|
||||
renderVersion();
|
||||
}
|
||||
@@ -10,5 +10,9 @@ export function attachMessageMenu(card, head, items) {
|
||||
trigger.setAttribute('aria-label', t('screens.message_menu.text_001'));
|
||||
head.append(trigger);
|
||||
const menu = createDropdownMenu({ anchorEl: trigger, items });
|
||||
card.cleanup = () => menu.destroy();
|
||||
const previousCleanup = card.cleanup;
|
||||
card.cleanup = () => {
|
||||
previousCleanup?.();
|
||||
menu.destroy();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/** Общий экран ожидания локальной генерации ключей. Без ложного процента выполнения. */
|
||||
export function createSecretGenerationOverlay() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'secret-generation-overlay';
|
||||
overlay.hidden = true;
|
||||
overlay.setAttribute('role', 'status');
|
||||
overlay.setAttribute('aria-live', 'polite');
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'secret-generation-card stack';
|
||||
|
||||
const spinner = document.createElement('div');
|
||||
spinner.className = 'secret-generation-spinner';
|
||||
spinner.setAttribute('aria-hidden', 'true');
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'secret-generation-title';
|
||||
title.textContent = t('components.secret_generation_overlay.title');
|
||||
|
||||
const description = document.createElement('p');
|
||||
description.className = 'secret-generation-description';
|
||||
description.textContent = t('components.secret_generation_overlay.description');
|
||||
|
||||
card.append(spinner, title, description);
|
||||
overlay.append(card);
|
||||
return {
|
||||
overlay,
|
||||
show() { overlay.hidden = false; },
|
||||
hide() { overlay.hidden = true; },
|
||||
};
|
||||
}
|
||||
@@ -154,6 +154,13 @@ export function renderToolbar(currentPageId, navigate) {
|
||||
if (isNotifications) renderBadge(btn, counters.notificationsUnreadCount, t('screens.toolbar.text_014'), 'notification-toolbar-badge');
|
||||
if (item.pageId === 'channels-list') {
|
||||
btn.addEventListener('click', () => navigate('channels-list'));
|
||||
} else if (isNetwork) {
|
||||
btn.addEventListener('click', () => {
|
||||
// Каждый вход через основную вкладку начинает новое исследование сети.
|
||||
// Переключение между V1–V4 внутри вкладки этот сброс не вызывает.
|
||||
if (state.session.isAuthorized) window.dispatchEvent(new Event('shine:network-tab-enter'));
|
||||
navigateWithGuestRules(item.pageId, navigate);
|
||||
});
|
||||
} else {
|
||||
btn.addEventListener('click', () => navigateWithGuestRules(item.pageId, navigate));
|
||||
}
|
||||
|
||||
@@ -1,30 +1,101 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
/** The password is intentionally visible initially on both auth screens. */
|
||||
/**
|
||||
* Native password inputs are single-line only. A textarea allows long phrases to
|
||||
* wrap across up to three lines. Masking uses a non-interactive bullet mirror so
|
||||
* it also works in browsers without CSS text-security support.
|
||||
*/
|
||||
export function createExpandablePasswordTextarea() {
|
||||
const input = document.createElement('textarea');
|
||||
input.className = 'input auth-password-field__textarea';
|
||||
input.rows = 1;
|
||||
// 32 visible monospace characters per line on screens wide enough.
|
||||
// Soft wrap only: never add newline characters to the actual password.
|
||||
input.cols = 32;
|
||||
input.wrap = 'soft';
|
||||
input.autocapitalize = 'off';
|
||||
input.spellcheck = false;
|
||||
input.setAttribute('autocorrect', 'off');
|
||||
|
||||
const resize = () => {
|
||||
const computed = window.getComputedStyle(input);
|
||||
const lineHeight = Number.parseFloat(computed.lineHeight) || 24;
|
||||
const extras = (Number.parseFloat(computed.paddingTop) || 0)
|
||||
+ (Number.parseFloat(computed.paddingBottom) || 0)
|
||||
+ (Number.parseFloat(computed.borderTopWidth) || 0)
|
||||
+ (Number.parseFloat(computed.borderBottomWidth) || 0);
|
||||
input.style.height = `${lineHeight + extras}px`;
|
||||
input.style.height = `${Math.min(input.scrollHeight, 3 * lineHeight + extras)}px`;
|
||||
};
|
||||
input.addEventListener('input', resize);
|
||||
// Initial value may be restored from a registration draft before mounting.
|
||||
input.resizePasswordField = resize;
|
||||
input.clearPasswordField = () => {
|
||||
input.value = '';
|
||||
input.updatePasswordMask?.();
|
||||
resize();
|
||||
};
|
||||
return input;
|
||||
}
|
||||
|
||||
/** Passwords are deliberately visible initially on registration and sign-in. */
|
||||
export function createVisiblePasswordField(input) {
|
||||
input.type = 'text';
|
||||
const multiline = input.tagName === 'TEXTAREA';
|
||||
if (!multiline) input.type = 'text';
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'auth-password-field';
|
||||
wrap.className = multiline ? 'auth-password-field auth-password-field--multiline' : 'auth-password-field';
|
||||
|
||||
let mask = null;
|
||||
let visible = true;
|
||||
if (multiline) {
|
||||
mask = document.createElement('div');
|
||||
mask.className = 'auth-password-field__mask';
|
||||
mask.setAttribute('aria-hidden', 'true');
|
||||
mask.hidden = true;
|
||||
const updateMask = () => {
|
||||
// Preserve explicit line breaks while not copying actual password text.
|
||||
mask.textContent = Array.from(input.value, char => char === '\n' ? '\n' : '•').join('');
|
||||
mask.scrollTop = input.scrollTop;
|
||||
mask.scrollLeft = input.scrollLeft;
|
||||
};
|
||||
input.addEventListener('input', updateMask);
|
||||
input.addEventListener('scroll', () => {
|
||||
mask.scrollTop = input.scrollTop;
|
||||
mask.scrollLeft = input.scrollLeft;
|
||||
});
|
||||
input.updatePasswordMask = updateMask;
|
||||
}
|
||||
|
||||
const toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'auth-password-field__toggle';
|
||||
function updateToggle() {
|
||||
const visible = input.type !== 'password';
|
||||
toggle.innerHTML = iconHtml(visible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
|
||||
toggle.setAttribute('aria-label', visible ? t('screens.visible_password_field.text_001') : t('screens.visible_password_field.text_002'));
|
||||
toggle.setAttribute('title', visible ? t('screens.visible_password_field.text_003') : t('screens.visible_password_field.text_004'));
|
||||
toggle.setAttribute('aria-pressed', String(!visible));
|
||||
const isVisible = multiline ? visible : input.type !== 'password';
|
||||
toggle.innerHTML = iconHtml(isVisible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
|
||||
toggle.setAttribute('aria-label', isVisible ? t('screens.visible_password_field.text_001') : t('screens.visible_password_field.text_002'));
|
||||
toggle.setAttribute('title', isVisible ? t('screens.visible_password_field.text_003') : t('screens.visible_password_field.text_004'));
|
||||
toggle.setAttribute('aria-pressed', String(!isVisible));
|
||||
}
|
||||
toggle.addEventListener('click', () => {
|
||||
const start = input.selectionStart;
|
||||
const end = input.selectionEnd;
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
if (multiline) {
|
||||
visible = !visible;
|
||||
wrap.classList.toggle('auth-password-field--masked', !visible);
|
||||
mask.hidden = visible;
|
||||
input.updatePasswordMask();
|
||||
input.resizePasswordField();
|
||||
} else {
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
}
|
||||
updateToggle();
|
||||
input.focus();
|
||||
try { if (start !== null && end !== null) input.setSelectionRange(start, end); } catch { /* unsupported input method */ }
|
||||
});
|
||||
updateToggle();
|
||||
wrap.append(input, toggle);
|
||||
wrap.append(input);
|
||||
if (mask) wrap.append(mask);
|
||||
wrap.append(toggle);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
@@ -7,3 +7,7 @@ export const defaultServerHttp = `https://${defaultServerAddress}`;
|
||||
export const defaultServerWs = `wss://${defaultServerAddress}/ws`;
|
||||
export const defaultSolanaCluster = 'mainnet-beta';
|
||||
export const defaultSolanaEndpoint = `${defaultServerHttp}/solana-rpc`;
|
||||
|
||||
// Devnet ONLY: optional 6-decimal SPL test token representing USDT for UI/transfer tests.
|
||||
// Do not use this in Mainnet; official USDT mint is pinned by solana-usdt-service.js.
|
||||
export const devnetTestUsdtMint = '';
|
||||
|
||||
@@ -1,7 +1,50 @@
|
||||
{
|
||||
"wallet_multi": {
|
||||
"transfer_title": "Send funds",
|
||||
"transfer_to_contact": "Send funds",
|
||||
"asset": "Asset",
|
||||
"amount": "Amount",
|
||||
"recipient": "Recipient Solana address",
|
||||
"contacts": "SHiNE contacts",
|
||||
"search_contacts": "Search by login",
|
||||
"notify": "Send a message after the transfer is confirmed",
|
||||
"other_address": "Use another address",
|
||||
"contact": "Recipient",
|
||||
"resolving": "Looking up blockchainKey…",
|
||||
"no_contacts": "No matching contacts",
|
||||
"no_stars": "Direct transfer: no Stars or DAO fee.",
|
||||
"send": "Send",
|
||||
"sending": "Awaiting Solana confirmation…",
|
||||
"sent": "Transfer completed",
|
||||
"confirm": "Confirm transfer? Check the address and amount:",
|
||||
"success": "Transfer confirmed on Solana",
|
||||
"notice_sent": "Message sent to recipient.",
|
||||
"notice_failed": "Transfer succeeded, but notification failed",
|
||||
"dm_prefix": "💸 You have received a transfer:",
|
||||
"dm_signature": "Solana transaction",
|
||||
"dm_explorer": "Check in Solana Explorer",
|
||||
"balance_unavailable": "USDT balance unavailable",
|
||||
"test_mint_missing": "Token is not configured on Devnet",
|
||||
"devnet_disclaimer": "Official USDT does not exist on Devnet. Testing requires a separate 6-decimal SPL token.",
|
||||
"jupiter_external": "Swap on Jupiter ↗",
|
||||
"jupiter_warning": "Jupiter opens externally. Your built-in SHiNE wallet is not automatically connected; swapping requires an external compatible wallet. Real USDT swaps are unavailable on Devnet.",
|
||||
"uncertain": "Transfer status is uncertain; it may have succeeded. Check Solana history before sending again.",
|
||||
"receive_hint": "This address receives SOL and USDT on Solana. Do not send tokens from other blockchains."
|
||||
},
|
||||
"chat_links": {
|
||||
"title": "External link",
|
||||
"description": "Choose what to do with this internet link.",
|
||||
"copy": "Copy link",
|
||||
"open": "Open in browser",
|
||||
"cancel": "Cancel",
|
||||
"copied": "Link copied",
|
||||
"copy_failed": "Could not copy the link"
|
||||
},
|
||||
"language": {
|
||||
"menu": "Language / Language",
|
||||
"selector": "Interface language / Language"
|
||||
"selector": "Interface language / Language",
|
||||
"uncertain": "Transfer status is uncertain; it may have succeeded. Check Solana history before sending again.",
|
||||
"receive_hint": "This address receives SOL and USDT on Solana. Do not send tokens from other blockchains."
|
||||
},
|
||||
"dialogs": {
|
||||
"app": {
|
||||
@@ -968,6 +1011,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"secret_generation_overlay": {"title": "Generating your digital keys…", "description": "Generating them from your login and password directly on this device."}
|
||||
},
|
||||
"screens": {
|
||||
"dm_attachments": {
|
||||
"text_001": "Download",
|
||||
@@ -977,10 +1023,7 @@
|
||||
"text_005": "File downloaded",
|
||||
"text_006": "file",
|
||||
"text_007": "Download {value1}",
|
||||
"file_expired": "File no longer available: encrypted attachments are kept for up to 14 days.",
|
||||
"file_expired_short": "Attachment has expired",
|
||||
"remaining_less_day": "Attachment available for less than a day",
|
||||
"remaining_days": "Attachment available for {value1} more days"
|
||||
"file_expired": "File no longer available: encrypted attachments are kept for up to 14 days."
|
||||
},
|
||||
"palette_editor": {
|
||||
"text_001": "Failed to read palette, please make sure the whole text is copied.",
|
||||
@@ -1503,7 +1546,7 @@
|
||||
"text_018": "There's no namespace available yet.",
|
||||
"text_019": "In a free account, password change is not available. After switching to a full account, it will be possible to change it.",
|
||||
"text_016": "Create a password",
|
||||
"text_017": "On your device, cryptographic access keys are created from the username and password. Private keys are not stored on the server.",
|
||||
"text_017": "Your password is the foundation of your digital keys.",
|
||||
"text_022": "Your username changed. Press “Continue” again.",
|
||||
"text_023": "That login's already taken. Try another one.",
|
||||
"text_015": "This name will remain forever and will be displayed exactly as you choose now. You can't change it later.",
|
||||
@@ -1518,11 +1561,12 @@
|
||||
"text_030": "Minimum login length: {value1} characters.",
|
||||
"text_031": "Password (from 1 to {value1} characters)",
|
||||
"text_032": "Enter a password between 1 and {value1} characters.",
|
||||
"text_034": "The best password is the one you remember.",
|
||||
"text_037": "Don't lose your password!",
|
||||
"text_038": "We cannot recover it or your keys. If access to keys on all devices is lost, encrypted personal correspondence may not be available.",
|
||||
"text_035": "Any non-empty password will do. For reliability, it is better to choose your long phrase or random code. Do not use known quotes or obvious sequences.",
|
||||
"text_036": "On a familiar device, you usually do not have to enter a password every time you sign in: work keys are stored locally. To sign in from a new device, the password is your backup access method.",
|
||||
"text_034": "🔐 Your password is your digital key",
|
||||
"text_037": "🔒 Your keys belong to you alone.",
|
||||
"text_038": "Our server does not store your password or private keys and cannot recover them. If you lose your password, access to your keys and encrypted conversations will be lost forever. Keep your password somewhere safe!",
|
||||
"text_035": "Private cryptographic keys are generated from your username and password directly on your device. They are stored only on your devices and provide access to your account, private messages, and digital wallets.",
|
||||
"text_036": "Choose a strong password: we recommend 12–16 characters or more. You can use a long, memorable phrase combining words, numbers, and special characters.",
|
||||
"password_counter": "Characters: {value1} / {value2}",
|
||||
"text_039": "Warning: The wallet is already full. Changing your login or password will create a different wallet! The funds will remain at the old address, and the old password will be required to access them. Continue?"
|
||||
},
|
||||
"network_view": {
|
||||
@@ -2175,7 +2219,9 @@
|
||||
"text_066": "Subscribed",
|
||||
"text_067": "Subscribed.",
|
||||
"text_070": "Signed.",
|
||||
"text_071": "Category of notifications"
|
||||
"text_071": "Category of notifications",
|
||||
"text_072": "Add close friend in return",
|
||||
"text_073": "You are close friends now"
|
||||
},
|
||||
"user_profile_list_view": {
|
||||
"text_002": "Message",
|
||||
@@ -2219,13 +2265,6 @@
|
||||
"text_039": "Who to show"
|
||||
},
|
||||
"chat_view": {
|
||||
"voice_cancel": "Discard recording",
|
||||
"voice_pause": "Pause recording",
|
||||
"voice_resume": "Resume recording",
|
||||
"voice_cancelled": "Recording discarded",
|
||||
"voice_tap_hint": "Tap send or discard the recording",
|
||||
"voice_send": "Send voice message",
|
||||
"file_remove": "Remove file {value1}",
|
||||
"security_notice": {
|
||||
"title": "Private chat security",
|
||||
"encryption": "Messages in this chat are encrypted on the participants' devices.",
|
||||
@@ -2894,7 +2933,8 @@
|
||||
"text_303": "When the current queue limit is filled, a new limit with a lower coefficient will open.",
|
||||
"text_300": "Tickets are tied to queue 1 and the recipient’s address you specify when you purchase.",
|
||||
"text_301": "The payment is considered in USD, and the write-off goes to SOL at the USDT/SOL rate, which is checked at the time of the transaction.",
|
||||
"text_305": "Refresh balance"
|
||||
"text_305": "Refresh balance",
|
||||
"unlimited": "Unlimited"
|
||||
},
|
||||
"device_view": {
|
||||
"text_008": "Are you sure you want to close the other sessions?",
|
||||
@@ -4664,6 +4704,9 @@
|
||||
},
|
||||
"app": {
|
||||
"error_sent_to_server_login_time": "Error sent to server · {login} · {time}",
|
||||
"error_report_pending": "Sending error report…",
|
||||
"error_report_received": "Error report received · {id}",
|
||||
"error_report_not_sent": "Could not send error report",
|
||||
"message_from_login": "Message from {login}",
|
||||
"connecting": "Connecting…",
|
||||
"connecting_tap_to_retry_now": "Connecting… Tap to retry now",
|
||||
@@ -4790,5 +4833,75 @@
|
||||
"attachment_error": {
|
||||
"hash_mismatch": "The downloaded file SHA-256 does not match the blockchain: {actual} != {expected} ({url})"
|
||||
}
|
||||
},
|
||||
"wallet_swap": {
|
||||
"title": "Swap · Jupiter",
|
||||
"beta": "🧪 Beta — still in development",
|
||||
"warning": "Automated SOL ↔ USDT swaps via Jupiter have not been fully tested in SHiNE. We do not recommend using this feature yet. Transactions may fail, behave unexpectedly, or cause a loss of funds. If you choose to experiment, you do so at your own risk and should use only tiny amounts. No outcome is guaranteed.\n\nYour private keys remain inside the SHiNE client. Jupiter finds the route, SHiNE signs locally, and Solana RPC broadcasts the transaction. The SHiNE server does not custody your funds or private keys.",
|
||||
"direction": "Swap direction",
|
||||
"amount": "Amount to sell",
|
||||
"get_quote": "Get Jupiter quote",
|
||||
"expected": "Estimated output",
|
||||
"minimum": "Minimum output (0.5% slippage)",
|
||||
"route": "Route",
|
||||
"quote_note": "Quotes expire quickly. Network fees and the market price can change. A small SOL balance is required for fees.",
|
||||
"accept_risk": "I understand this is experimental and may result in loss of funds. I accept the risk.",
|
||||
"execute": "Confirm experimental swap",
|
||||
"check_status": "Check previous swap status",
|
||||
"fetching": "Fetching Jupiter quote…",
|
||||
"review": "Verify the amount and minimum output before proceeding.",
|
||||
"executing": "Simulating, validating, signing and broadcasting…",
|
||||
"final_warning": "WARNING: EXPERIMENTAL SWAP. We do not recommend using this feature with real funds. No guarantees. Do not use large amounts.",
|
||||
"final_question": "Do you want to proceed at your own risk?",
|
||||
"devnet_unavailable": "Jupiter swaps require Mainnet. Devnet has no real USDT liquidity; swaps are disabled.",
|
||||
"success": "Swap confirmed on Solana. Refreshing balances.",
|
||||
"pending": "A previous swap may have landed. Do not retry until its status is verified on Solana Explorer.",
|
||||
"pending_resolved": "Previous swap status was resolved.",
|
||||
"transaction": "Solana transaction",
|
||||
"session_required": "Sign in to SHiNE to access the wallet.",
|
||||
"stale": "Quote is over 30 seconds old. Please fetch it again.",
|
||||
"wallet_changed": "Wallet changed; the quote has been invalidated.",
|
||||
"sol_limit": "Beta limit: up to 0.02 SOL per swap. Keep 0.01 SOL for fees.",
|
||||
"usdt_limit": "Beta limit: up to 5 USDT per swap. Keep SOL available for fees.",
|
||||
"wallet_hint": "🧪 Experimental SOL ↔ USDT swaps via Jupiter. Not recommended for real funds; please review the warnings before trying.",
|
||||
"wallet_button": "Swap · Jupiter β"
|
||||
},
|
||||
"blockchain_details": {
|
||||
"invalid_attachment": "Attachment metadata is invalid; the original block remains unchanged.",
|
||||
"title": "Blockchain data",
|
||||
"description": "Original record and independent verification",
|
||||
"author": "Author",
|
||||
"blockchain": "Author blockchain",
|
||||
"block_number": "Block number",
|
||||
"created": "Created",
|
||||
"storage": "Storage",
|
||||
"signed_size": "Signed DataItem size",
|
||||
"bytes": "bytes",
|
||||
"published": "Submitted to Arweave",
|
||||
"pending": "Pending upload to Arweave",
|
||||
"unknown": "Arweave status not confirmed",
|
||||
"hash": "SHiNE block SHA-256",
|
||||
"copy_hash": "Copy hash",
|
||||
"copy_id": "Copy DataItem ID",
|
||||
"version": "Version",
|
||||
"open_arweave": "Open in Arweave",
|
||||
"copy_url": "Copy link",
|
||||
"download_signed": "Download signed record",
|
||||
"verify": "Verify authenticity",
|
||||
"technical": "Original server response · technical data",
|
||||
"copy_raw": "Copy JSON",
|
||||
"close": "Close",
|
||||
"copied": "Copied",
|
||||
"missing_hash": "Missing valid block hash",
|
||||
"checking": "Checking the record, Arweave and Solana…",
|
||||
"verified": "verified",
|
||||
"failed": "does not match",
|
||||
"not_verified": "not verified",
|
||||
"signature": "Ed25519 signature",
|
||||
"integrity": "Block integrity and DataItem ID",
|
||||
"arweave_check": "Data in Arweave",
|
||||
"solana_check": "Author key in Solana",
|
||||
"signed_check": "Signed record",
|
||||
"proof_note": "Verification runs in your browser. Unavailable Arweave or Solana data does not mean forgery. Key ownership does not prove an exact publication time. Free users without a PDA cannot be verified through Solana."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,50 @@
|
||||
{
|
||||
"wallet_multi": {
|
||||
"transfer_title": "Перевести деньги",
|
||||
"transfer_to_contact": "Перевести деньги",
|
||||
"asset": "Валюта",
|
||||
"amount": "Сумма",
|
||||
"recipient": "Адрес Solana получателя",
|
||||
"contacts": "Контакты SHiNE",
|
||||
"search_contacts": "Найти контакт по логину",
|
||||
"notify": "Отправить получателю сообщение после успешного перевода",
|
||||
"other_address": "Ввести другой адрес",
|
||||
"contact": "Получатель",
|
||||
"resolving": "Определяем blockchainKey…",
|
||||
"no_contacts": "Контакты не найдены",
|
||||
"no_stars": "Обычный перевод без доната, Stars и комиссии DAO.",
|
||||
"send": "Перевести",
|
||||
"sending": "Проверяем перевод в Solana…",
|
||||
"sent": "Перевод выполнен",
|
||||
"confirm": "Подтвердить перевод? Проверьте адрес и сумму:",
|
||||
"success": "Перевод подтверждён Solana",
|
||||
"notice_sent": "Сообщение получателю отправлено.",
|
||||
"notice_failed": "Перевод выполнен, но сообщение не отправлено",
|
||||
"dm_prefix": "💸 Вам отправлен перевод:",
|
||||
"dm_signature": "Транзакция Solana",
|
||||
"dm_explorer": "Проверить в Solana Explorer",
|
||||
"balance_unavailable": "Баланс USDT недоступен",
|
||||
"test_mint_missing": "Токен не настроен в Devnet",
|
||||
"devnet_disclaimer": "На Devnet настоящий USDT отсутствует. Для тестирования нужен отдельный SPL-токен с 6 знаками.",
|
||||
"jupiter_external": "Обменять на Jupiter ↗",
|
||||
"jupiter_warning": "Jupiter откроется на внешнем сайте. Встроенный кошелёк SHiNE там не подключается автоматически: для обмена потребуется совместимый внешний кошелёк. На Devnet реального обмена USDT нет.",
|
||||
"uncertain": "Не удалось однозначно подтвердить перевод. Он мог пройти! Проверьте историю Solana перед повторной отправкой.",
|
||||
"receive_hint": "Этот адрес используется для SOL и USDT в сети Solana. Не отправляйте сюда токены из других блокчейнов."
|
||||
},
|
||||
"chat_links": {
|
||||
"title": "Внешняя ссылка",
|
||||
"description": "Выберите действие с интернет-ссылкой.",
|
||||
"copy": "Скопировать ссылку",
|
||||
"open": "Открыть в браузере",
|
||||
"cancel": "Отмена",
|
||||
"copied": "Ссылка скопирована",
|
||||
"copy_failed": "Не удалось скопировать ссылку"
|
||||
},
|
||||
"language": {
|
||||
"menu": "Язык / Language",
|
||||
"selector": "Язык интерфейса / Interface language"
|
||||
"selector": "Язык интерфейса / Interface language",
|
||||
"uncertain": "Не удалось однозначно подтвердить перевод. Он мог пройти! Проверьте историю Solana перед повторной отправкой.",
|
||||
"receive_hint": "Этот адрес используется для SOL и USDT в сети Solana. Не отправляйте сюда токены из других блокчейнов."
|
||||
},
|
||||
"dialogs": {
|
||||
"app": {
|
||||
@@ -968,6 +1011,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"secret_generation_overlay": {"title": "Генерируем ваши цифровые ключи…", "description": "Генерируем их из вашего логина и пароля непосредственно на этом устройстве."}
|
||||
},
|
||||
"screens": {
|
||||
"dm_attachments": {
|
||||
"text_001": "Скачать",
|
||||
@@ -977,10 +1023,7 @@
|
||||
"text_005": "Файл скачан",
|
||||
"text_006": "файл",
|
||||
"text_007": "Скачать {value1}",
|
||||
"file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней.",
|
||||
"file_expired_short": "Срок хранения вложения истёк",
|
||||
"remaining_less_day": "Вложение доступно ещё менее дня",
|
||||
"remaining_days": "Вложение доступно ещё {value1} дн."
|
||||
"file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней."
|
||||
},
|
||||
"palette_editor": {
|
||||
"text_001": "Не удалось прочитать палитру: проверьте, что текст скопирован целиком.",
|
||||
@@ -1501,7 +1544,7 @@
|
||||
"text_014": "Введите логин",
|
||||
"text_015": "Это имя навсегда сохранится и будет отображаться именно так, как вы выберете сейчас. Позже изменить его нельзя.",
|
||||
"text_016": "Придумайте пароль",
|
||||
"text_017": "На вашем устройстве из логина и пароля создаются криптографические ключи доступа. Приватные ключи не хранятся на сервере.",
|
||||
"text_017": "Ваш пароль — основа ваших цифровых ключей.",
|
||||
"text_018": "Пока нет доступного пространства имён",
|
||||
"text_019": "В бесплатном аккаунте смена пароля недоступна. После перехода на полноценный аккаунт появится возможность его менять.",
|
||||
"text_020": "Для полноценного аккаунта поддерживается смена пароля: необходимые зашифрованные сообщения перешифровываются на вашем устройстве, а не на сервере.",
|
||||
@@ -1518,11 +1561,12 @@
|
||||
"text_031": "Пароль (от 1 до {value1} символов)",
|
||||
"text_032": "Введите пароль длиной от 1 до {value1} символов.",
|
||||
"text_033": "Не удалось загрузить пространства имён: {value1}",
|
||||
"text_034": "Лучший пароль — тот, который вы точно помните.",
|
||||
"text_035": "Подойдёт любой непустой пароль. Для надёжности лучше выбрать свою длинную фразу или случайный код. Не используйте известные цитаты и очевидные последовательности.",
|
||||
"text_036": "На привычном устройстве обычно не придётся вводить пароль при каждом входе: рабочие ключи сохраняются локально. Для входа с нового устройства пароль — ваш резервный способ доступа.",
|
||||
"text_037": "Не теряйте пароль!",
|
||||
"text_038": "Мы не можем восстановить его или ваши ключи. Если доступ к ключам на всех устройствах утрачен, зашифрованная личная переписка может оказаться недоступна.",
|
||||
"text_034": "🔐 Ваш пароль — ваш цифровой ключ",
|
||||
"text_035": "Из вашего логина и пароля прямо на устройстве генерируются приватные криптографические ключи. Они хранятся только на ваших устройствах и обеспечивают доступ к аккаунту, личной переписке и цифровым кошелькам.",
|
||||
"text_036": "Придумайте надёжный пароль: рекомендуем 12–16 символов или больше. Можно использовать длинную запоминающуюся фразу со словами, цифрами и специальными символами.",
|
||||
"text_037": "🔒 Ваши ключи принадлежат только вам.",
|
||||
"text_038": "Наш сервер не хранит ваш пароль и приватные ключи и не может восстановить их. Если вы потеряете пароль, доступ к вашим ключам и зашифрованной переписке будет утрачен навсегда. Сохраните пароль в надёжном месте!",
|
||||
"password_counter": "Символов: {value1} / {value2}",
|
||||
"text_039": "Внимание: кошелёк уже пополнен. Изменение логина или пароля создаст другой кошелёк! Средства останутся на старом адресе, и для доступа к ним потребуется прежний пароль. Продолжить?"
|
||||
},
|
||||
"network_view": {
|
||||
@@ -2308,7 +2352,9 @@
|
||||
"text_068": "Подписался",
|
||||
"text_069": "Подписалась",
|
||||
"text_070": "Подписался(-ась)",
|
||||
"text_071": "Категория уведомлений"
|
||||
"text_071": "Категория уведомлений",
|
||||
"text_072": "Добавить в близкие друзья в ответ",
|
||||
"text_073": "Теперь вы близкие друзья"
|
||||
},
|
||||
"user_profile_list_view": {
|
||||
"text_001": "Список",
|
||||
@@ -2352,23 +2398,16 @@
|
||||
"text_039": "Кого показать"
|
||||
},
|
||||
"chat_view": {
|
||||
"voice_cancel": "Отменить запись",
|
||||
"voice_pause": "Приостановить запись",
|
||||
"voice_resume": "Продолжить запись",
|
||||
"voice_cancelled": "Запись отменена",
|
||||
"voice_tap_hint": "Нажмите кнопку отправки или отмените запись",
|
||||
"voice_send": "Отправить голосовое",
|
||||
"file_remove": "Убрать файл {value1}",
|
||||
"security_notice": {
|
||||
"title": "Безопасность личной переписки",
|
||||
"encryption": "Сообщения в этом чате шифруются на устройствах участников.",
|
||||
"servers": "Сервер доставляет зашифрованные данные, но не должен видеть содержимое переписки.",
|
||||
"derivation": "Ключи переписки производятся из ключей аккаунта и хранятся на устройствах.",
|
||||
"rotation": "При смене ключей часть сообщений может потребовать повторного получения ключей.",
|
||||
"source": "Перед отправкой проверьте, что вы общаетесь с нужным пользователем и сервером.",
|
||||
"title": "Ваша переписка защищена сквозным шифрованием",
|
||||
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
|
||||
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
|
||||
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля",
|
||||
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
|
||||
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
|
||||
"warning_label": "Важно:",
|
||||
"warning": "не передавайте приватные ключи и пароль аккаунта другим людям.",
|
||||
"recovery": "Восстановление доступа зависит от сохранённых ключей и пароля. Храните их безопасно."
|
||||
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
|
||||
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку"
|
||||
},
|
||||
"text_001": "Чат",
|
||||
"text_002": "Без звука",
|
||||
@@ -2713,8 +2752,8 @@
|
||||
"text_006": "Ваши публикации, сообщения и лайки хранятся вечно.",
|
||||
"text_007": "Начать регистрацию",
|
||||
"text_008": "Сияние",
|
||||
"text_009": "Ваши публикации — надолго",
|
||||
"text_010": "Публичные сообщения сохраняются в децентрализованном хранилище Arweave.",
|
||||
"text_009": "Ваши публикации — навечно",
|
||||
"text_010": "Публичные сообщения сохраняются в децентрализованной сети «Сияние» и хранилище Arweave.",
|
||||
"text_011": "Прозрачные оценки",
|
||||
"text_012": "Публичные реакции и оценки можно проверять, а не просто доверять скрытым счётчикам.",
|
||||
"text_013": "Настоящий социальный граф",
|
||||
@@ -3080,7 +3119,8 @@
|
||||
"text_302": "Если курс уезжает слишком далеко, покупка отклоняется. Для интерфейса заложен допуск 3%.",
|
||||
"text_303": "Когда текущий лимит очереди заполнится, откроется новый лимит с более низким коэффициентом.",
|
||||
"text_304": "Номер билета нужно сохранить отдельно: именно по нему удобно отслеживать, когда он дойдет до выплаты.",
|
||||
"text_305": "Скопировать адрес в буфер обмена"
|
||||
"text_305": "Скопировать адрес в буфер обмена",
|
||||
"unlimited": "Без ограничений"
|
||||
},
|
||||
"solana_users_init_view": {
|
||||
"text_001": "Подключите кошелёк и выполните init_users_economy_config.",
|
||||
@@ -4664,6 +4704,9 @@
|
||||
},
|
||||
"app": {
|
||||
"error_sent_to_server_login_time": "Ошибка отправлена на сервер · {login} · {time}",
|
||||
"error_report_pending": "Отправляем отчёт об ошибке…",
|
||||
"error_report_received": "Отчёт об ошибке получен · {id}",
|
||||
"error_report_not_sent": "Не удалось отправить отчёт об ошибке",
|
||||
"message_from_login": "Сообщение от {login}",
|
||||
"connecting": "Соединяюсь…",
|
||||
"connecting_tap_to_retry_now": "Соединяюсь… Нажмите, чтобы попробовать сразу",
|
||||
@@ -4790,5 +4833,75 @@
|
||||
"attachment_error": {
|
||||
"hash_mismatch": "SHA-256 скачанного файла не совпал с блокчейном: {actual} != {expected} ({url})"
|
||||
}
|
||||
},
|
||||
"wallet_swap": {
|
||||
"title": "Обмен валют · Jupiter",
|
||||
"beta": "🧪 Бета-версия — находится в разработке",
|
||||
"warning": "Обмен SOL ↔ USDT через автоматический обменник Jupiter ещё не прошёл полное тестирование в SHiNE. Мы пока не рекомендуем пользоваться функцией. Возможны ошибки, неудачные транзакции и потеря средств. Если решите попробовать — только на свой риск и на минимальных суммах. Гарантии результата нет.\n\nПриватные ключи остаются в вашем приложении. Jupiter подбирает маршрут обмена, SHiNE подписывает локально, а Solana RPC отправляет транзакцию. Сервер SHiNE не хранит ключи и не принимает средства на свой баланс.",
|
||||
"direction": "Направление обмена",
|
||||
"amount": "Сколько отдать",
|
||||
"get_quote": "Рассчитать через Jupiter",
|
||||
"expected": "Ожидаете получить",
|
||||
"minimum": "Минимум при проскальзывании 0,5%",
|
||||
"route": "Маршрут",
|
||||
"quote_note": "Котировка быстро устаревает. Сумма и комиссии сети могут измениться. Для обмена также нужен SOL на комиссию.",
|
||||
"accept_risk": "Понимаю: функция экспериментальная, возможна потеря средств. Использую на свой риск.",
|
||||
"execute": "Подтвердить тестовый обмен",
|
||||
"check_status": "Проверить статус предыдущего обмена",
|
||||
"fetching": "Запрашиваем котировку Jupiter…",
|
||||
"review": "Проверьте сумму и условия. Прежде чем подтверждать, примите предупреждение.",
|
||||
"executing": "Симулируем, проверяем и отправляем транзакцию в Solana…",
|
||||
"final_warning": "ВНИМАНИЕ: ЭКСПЕРИМЕНТАЛЬНЫЙ ОБМЕН. Мы не рекомендуем использовать его с реальными деньгами, гарантий нет. Не отправляйте большие суммы.",
|
||||
"final_question": "Вы действительно хотите выполнить этот обмен на свой риск?",
|
||||
"devnet_unavailable": "Jupiter Swap работает только в Mainnet. На Devnet нет реальной ликвидности USDT; обмен отключён.",
|
||||
"success": "Обмен подтверждён Solana. Балансы обновляются.",
|
||||
"pending": "У предыдущего обмена неопределённый статус. Не повторяйте операцию, пока не проверите транзакцию в Solana Explorer.",
|
||||
"pending_resolved": "Статус предыдущей транзакции разрешён.",
|
||||
"transaction": "Транзакция в Solana",
|
||||
"session_required": "Для обмена войдите в SHiNE и откройте кошелёк.",
|
||||
"stale": "Котировка старше 30 секунд. Рассчитайте заново.",
|
||||
"wallet_changed": "Ключ кошелька изменился, расчёт отменён.",
|
||||
"sol_limit": "Бета-лимит: до 0,02 SOL за обмен. Оставьте 0,01 SOL на комиссии.",
|
||||
"usdt_limit": "Бета-лимит: до 5 USDT за обмен. Нужен запас SOL на комиссии.",
|
||||
"wallet_hint": "🧪 Тестовый обмен SOL ↔ USDT через Jupiter. Функция не рекомендована для реальных средств: откройте предупреждение перед использованием.",
|
||||
"wallet_button": "Обменять · Jupiter β"
|
||||
},
|
||||
"blockchain_details": {
|
||||
"invalid_attachment": "Вложение содержит некорректные метаданные; исходный блок сохранён без изменений.",
|
||||
"title": "Данные блокчейна",
|
||||
"description": "Исходная запись и её независимая проверка",
|
||||
"author": "Автор",
|
||||
"blockchain": "Блокчейн автора",
|
||||
"block_number": "Номер блока",
|
||||
"created": "Создан",
|
||||
"storage": "Хранилище",
|
||||
"signed_size": "Полный подписанный блок",
|
||||
"bytes": "байт",
|
||||
"published": "Отправлено в Arweave",
|
||||
"pending": "Ожидает отправки в Arweave",
|
||||
"unknown": "Состояние Arweave не подтверждено",
|
||||
"hash": "SHA-256 блока SHiNE",
|
||||
"copy_hash": "Скопировать хеш",
|
||||
"copy_id": "Скопировать DataItem ID",
|
||||
"version": "Версия",
|
||||
"open_arweave": "Открыть в Arweave",
|
||||
"copy_url": "Скопировать ссылку",
|
||||
"download_signed": "Скачать с подписью",
|
||||
"verify": "Проверить подлинность",
|
||||
"technical": "Исходный ответ сервера · технические данные",
|
||||
"copy_raw": "Скопировать JSON",
|
||||
"close": "Закрыть",
|
||||
"copied": "Скопировано",
|
||||
"missing_hash": "Нет корректного хеша блока",
|
||||
"checking": "Проверяем оригинал, Arweave и Solana…",
|
||||
"verified": "подтверждено",
|
||||
"failed": "не совпадает",
|
||||
"not_verified": "не проверено",
|
||||
"signature": "Подпись Ed25519",
|
||||
"integrity": "Целостность блока и DataItem ID",
|
||||
"arweave_check": "Данные в Arweave",
|
||||
"solana_check": "Ключ автора в Solana",
|
||||
"signed_check": "Подписанный блок",
|
||||
"proof_note": "Проверка выполняется в браузере. Отсутствие ответа Arweave или Solana не означает подделку. Действительность ключа не подтверждает точное время публикации. Для бесплатных пользователей без PDA проверка авторства через Solana недоступна."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,10 +482,12 @@ export function render({navigate, chrome}) {
|
||||
saved = null;
|
||||
}
|
||||
|
||||
const savedRoot = String(saved?.rootKey || '').trim();
|
||||
const savedBlockchain = String(saved?.blockchainKey || '').trim();
|
||||
const savedClient = String(saved?.clientKey || '').trim();
|
||||
if (savedBlockchain && savedClient) {
|
||||
if (savedRoot && savedBlockchain && savedClient) {
|
||||
return {
|
||||
rootPrivatePkcs8B64: savedRoot,
|
||||
blockchainPrivatePkcs8B64: savedBlockchain,
|
||||
clientPrivatePkcs8B64: savedClient,
|
||||
payerAddress: await clientAddressFromPrivatePkcs8(savedBlockchain),
|
||||
@@ -513,10 +515,14 @@ export function render({navigate, chrome}) {
|
||||
if (!equalBytes(derivedClientPublic, currentPda.clientKey)) {
|
||||
throw new Error(t('screens.access_servers_view.text_013'));
|
||||
}
|
||||
if (!equalBytes(base64ToBytes(keyBundle.rootPair.publicKeyB64), currentPda.rootKey)) {
|
||||
throw new Error('Root Key не соответствует PDA');
|
||||
}
|
||||
|
||||
await authService.persistSelectedKeys(sessionLogin, storagePwd, keyBundle);
|
||||
|
||||
return {
|
||||
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
payerAddress: clientAddressFromPublicB64(keyBundle.blockchainPair.publicKeyB64),
|
||||
@@ -546,6 +552,7 @@ export function render({navigate, chrome}) {
|
||||
const tx = await updateShineUserPdaOnSolana({
|
||||
login: sessionLogin,
|
||||
solanaEndpoint,
|
||||
rootPrivatePkcs8B64: signingMaterial.rootPrivatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: signingMaterial.blockchainPrivatePkcs8B64,
|
||||
clientPrivatePkcs8B64: signingMaterial.clientPrivatePkcs8B64,
|
||||
accessServers: normalizedList,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { formatDateTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
|
||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
@@ -38,7 +39,7 @@ import {
|
||||
escapeHtml,
|
||||
parseMessageAttachments,
|
||||
} from '../services/attachment-format.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { loadProfileSnapshot, profileDisplayName } from '../services/user-profile-params.js';
|
||||
import { extractLoginFromBlockchainName, formatChannelAddress, makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
import { parsePublicationOrdinal, publicationAtOrdinal, ordinalForPublication } from '../services/channel-message-ordinals.js';
|
||||
import { dropPageData, pageDataAge, readPageData, writePageData } from '../services/page-data-cache.js';
|
||||
@@ -460,56 +461,10 @@ function buildBlockchainDetails({ target, authorLogin, timestampMs, text, raw, l
|
||||
msgSubType: msgSubType ?? source.msgSubType ?? '',
|
||||
createdAtMs: timestampMs || source.createdAtMs || '',
|
||||
text: String(text || ''),
|
||||
signature: source.signature || source.blockSignature || source.authorSignature || t('screens.channel_thread_view.text_080'),
|
||||
publicKey: source.publicKey || source.authorPublicKey || t('screens.channel_thread_view.text_081'),
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
const rawText = JSON.stringify(details.raw || details, null, 2);
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="thread-blockchain-details-modal">
|
||||
<div class="modal-card stack blockchain-details-card">
|
||||
<h3 class="modal-title">${t('dialogs.modals.channel_thread_view.label_001')}</h3>
|
||||
<p class="meta-muted">${t('dialogs.modals.channel_thread_view.label_002')}</p>
|
||||
<div class="blockchain-details-grid">
|
||||
<span>${t('dialogs.modals.channel_thread_view.label_003')}</span><strong>${escapeHtml(details.authorLogin)}</strong>
|
||||
<span>${t('dialogs.modals.channel_thread_view.label_004')}</span><code>${escapeHtml(details.authorBlockchainName)}</code>
|
||||
<span>${t('dialogs.modals.channel_thread_view.label_005')}</span><code>${escapeHtml(details.blockNumber)}</code>
|
||||
<span>${t('dialogs.modals.channel_thread_view.label_006')}</span><code>${escapeHtml(details.blockHash)}</code>
|
||||
<span>${t('dialogs.modals.channel_thread_view.label_007')}</span><code>${escapeHtml(details.msgSubType)}</code>
|
||||
<span>${t('dialogs.modals.channel_thread_view.label_008')}</span><code>${escapeHtml(details.createdAtMs ? formatDateTime(new Date(Number(details.createdAtMs))) : '–')}</code>
|
||||
<span>Public key</span><code>${escapeHtml(details.publicKey)}</code>
|
||||
<span>${t('dialogs.modals.channel_thread_view.label_009')}</span><code>${escapeHtml(details.signature)}</code>
|
||||
</div>
|
||||
<label class="field-label" for="thread-blockchain-details-text">${t('dialogs.modals.channel_thread_view.label_010')}</label>
|
||||
<textarea class="input" id="thread-blockchain-details-text" rows="4" readonly>${escapeHtml(details.text)}</textarea>
|
||||
<pre class="blockchain-raw-block" id="thread-blockchain-raw-block" hidden>${escapeHtml(rawText)}</pre>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="thread-blockchain-details-copy" type="button">${t('dialogs.modals.channel_thread_view.label_011')}</button>
|
||||
<button class="secondary-btn" id="thread-blockchain-details-raw" type="button">${t('dialogs.modals.channel_thread_view.label_012')}</button>
|
||||
</div>
|
||||
<button class="secondary-btn" id="thread-blockchain-details-close" type="button">${t('dialogs.modals.channel_thread_view.label_013')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
root.querySelector('#thread-blockchain-details-close')?.addEventListener('click', () => {
|
||||
root.innerHTML = '';
|
||||
});
|
||||
root.querySelector('#thread-blockchain-details-copy')?.addEventListener('click', async () => {
|
||||
await copyTextToClipboard(rawText);
|
||||
if (!isActive()) return;
|
||||
showToast(t('dialogs.remaining.pages.channel_thread_view.openblockchaindetailsmodal.dannye_blokcheyna_skopirovany'));
|
||||
});
|
||||
root.querySelector('#thread-blockchain-details-raw')?.addEventListener('click', () => {
|
||||
const rawEl = root.querySelector('#thread-blockchain-raw-block');
|
||||
if (!rawEl) return;
|
||||
rawEl.hidden = !rawEl.hidden;
|
||||
});
|
||||
}
|
||||
|
||||
function resolveNodeText(node) {
|
||||
return firstNonEmptyText(
|
||||
latestVersionText(node?.versions),
|
||||
@@ -736,6 +691,17 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
if (node?.createdAtMs) timestamp.title = formatDateTime(new Date(node.createdAtMs));
|
||||
authorBlock.append(title, timestamp);
|
||||
authorTile.append(avatar, authorBlock);
|
||||
const profileMenu = createDropdownMenu({
|
||||
anchorEl: authorTile,
|
||||
minWidth: 190,
|
||||
dimBackground: false,
|
||||
items: [{ label: t('screens.chat_view.text_004'), iconHtml: iconHtml('profile'), action: () => handlers.navigate(makeProfileRoute(author)) }],
|
||||
});
|
||||
authorTile.addEventListener('click', (event) => { event.stopPropagation(); profileMenu.toggle(); });
|
||||
void loadThreadAvatarSnapshot(author).then((snapshot) => {
|
||||
if (!loginEl.isConnected || (threadsLayout && isOwnerPost)) return;
|
||||
loginEl.textContent = profileDisplayName(snapshot, author);
|
||||
});
|
||||
// Запись канала в обсуждении – как открытый пост в Threads: аватар и название канала в шапке, текст на всю ширину.
|
||||
const threadsLayout = focusPost && (!isOwnerPost || Boolean(channel));
|
||||
if (isOwnerPost) authorTile.hidden = !threadsLayout;
|
||||
@@ -1009,7 +975,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
raw: node,
|
||||
localNumber,
|
||||
msgSubType,
|
||||
}), { isActive: handlers.isActive });
|
||||
}), { isActive: handlers.isActive, authService, solanaEndpoint: state.entrySettings.solanaServer });
|
||||
});
|
||||
menuItems.push({ label: t('screens.channel_thread_view.text_012'), action: () => detailsButton.click() });
|
||||
if (isOwnMessage) {
|
||||
@@ -1057,12 +1023,8 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
if (!headRow.querySelector('.channel-message-type-button')) headRow.hidden = true;
|
||||
}
|
||||
card.append(actions);
|
||||
authorTile.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
const login = String(node?.authorLogin || '').trim();
|
||||
if (!login) return;
|
||||
handlers.navigate(makeProfileRoute(login));
|
||||
});
|
||||
const priorCleanup = card.cleanup;
|
||||
card.cleanup = () => { priorCleanup?.(); profileMenu.destroy(); };
|
||||
return card;
|
||||
}
|
||||
|
||||
@@ -1110,6 +1072,10 @@ function replyCountOf(node) {
|
||||
return Number(node?.totalReplies ?? node?.repliesCount ?? 0);
|
||||
}
|
||||
|
||||
function directReplyCountOf(node) {
|
||||
return Number(node?.repliesCount || 0);
|
||||
}
|
||||
|
||||
function nodeKey(node) {
|
||||
return messageRefKey(buildTargetFromNode(node));
|
||||
}
|
||||
@@ -1132,8 +1098,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
who.type = 'button';
|
||||
who.className = 'thread-comment__who';
|
||||
who.setAttribute('aria-label', t('screens.channel_thread_view.text_105', { value1: author }));
|
||||
who.append(identity?.avatar || renderUserAvatar({ login: author, size: nested ? 'xs' : 'sm', className: 'thread-comment__avatar avatar-plain' }));
|
||||
who.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
|
||||
who.append(identity?.avatar || createThreadAvatar(author));
|
||||
|
||||
const main = document.createElement('div');
|
||||
main.className = 'thread-comment__main';
|
||||
@@ -1144,8 +1109,11 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
name.type = 'button';
|
||||
name.className = 'thread-comment__name';
|
||||
name.textContent = identity?.title || author;
|
||||
name.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
|
||||
head.append(name);
|
||||
const login = document.createElement('span');
|
||||
login.className = 'thread-comment__login';
|
||||
login.textContent = `@${author.replace(/^@/, '')}`;
|
||||
head.append(login);
|
||||
if (!identity && channelOwner && author.toLowerCase() === channelOwner.toLowerCase()) {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'thread-comment__badge';
|
||||
@@ -1158,6 +1126,19 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
head.append(time);
|
||||
main.append(head);
|
||||
|
||||
const profileMenu = createDropdownMenu({
|
||||
anchorEl: who,
|
||||
minWidth: 190,
|
||||
dimBackground: false,
|
||||
items: [{ label: t('screens.chat_view.text_004'), iconHtml: iconHtml('profile'), action: () => handlers.navigate(makeProfileRoute(author)) }],
|
||||
});
|
||||
who.addEventListener('click', (event) => { event.stopPropagation(); profileMenu.toggle(); });
|
||||
name.addEventListener('click', (event) => { event.stopPropagation(); profileMenu.toggle(); });
|
||||
void loadThreadAvatarSnapshot(author).then((snapshot) => {
|
||||
if (!name.isConnected || identity) return;
|
||||
name.textContent = profileDisplayName(snapshot, author);
|
||||
});
|
||||
|
||||
if (mention && parent && parent !== focus) {
|
||||
const to = document.createElement('button');
|
||||
to.type = 'button';
|
||||
@@ -1209,7 +1190,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
commentLikeStats.setAttribute('aria-label', t('screens.channel_thread_view.text_107', { value1: likes }));
|
||||
commentLikeStats.addEventListener('click', () => { void showLikeStatistics({ counts: node }); });
|
||||
|
||||
const replies = replyCountOf(node);
|
||||
const replies = directReplyCountOf(node);
|
||||
const reply = document.createElement('button');
|
||||
reply.type = 'button';
|
||||
reply.className = 'channel-action-item thread-comment__reply';
|
||||
@@ -1229,7 +1210,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
try { await navigator.clipboard.writeText(parsed.text); showToast(t('screens.channel_thread_view.text_046')); }
|
||||
catch { showToast(t('screens.channel_thread_view.text_047'), { kind: 'error' }); }
|
||||
} },
|
||||
{ label: t('screens.channel_thread_view.text_020'), iconHtml: iconHtml('info'), action: () => openBlockchainDetailsModal(buildBlockchainDetails({ target, authorLogin: author, timestampMs: node?.createdAtMs, text: resolveNodeText(node), raw: node, localNumber: 0, msgSubType: Number(node?.msgSubType || 0) }), { isActive: handlers.isActive }) },
|
||||
{ label: t('screens.channel_thread_view.text_020'), iconHtml: iconHtml('info'), action: () => openBlockchainDetailsModal(buildBlockchainDetails({ target, authorLogin: author, timestampMs: node?.createdAtMs, text: resolveNodeText(node), raw: node, localNumber: 0, msgSubType: Number(node?.msgSubType || 0) }), { isActive: handlers.isActive, authService, solanaEndpoint: state.entrySettings.solanaServer }) },
|
||||
];
|
||||
if (versions.length > 1) menuItems.push({ label: t('screens.channel_thread_view.text_021'), action: () => openMessageHistoryModal({ versions }) });
|
||||
if (isOwn) {
|
||||
@@ -1248,7 +1229,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
} });
|
||||
}
|
||||
const menu = createDropdownMenu({ anchorEl: more, items: menuItems });
|
||||
item.cleanup = () => menu.destroy();
|
||||
item.cleanup = () => { profileMenu.destroy(); menu.destroy(); };
|
||||
head.append(more);
|
||||
|
||||
const share = document.createElement('button');
|
||||
@@ -1287,46 +1268,27 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
return item;
|
||||
}
|
||||
|
||||
// Сколько ответов внутри ветки видно сразу; остальные – по «Ещё N ответов».
|
||||
// Ветка прямого ответа: сам комментарий и не более одного вложенного уровня.
|
||||
// Ответы глубже открываются как отдельное обсуждение вложенного комментария.
|
||||
const THREAD_GROUP_VISIBLE_REPLIES = 2;
|
||||
|
||||
// Ветка ответа верхнего уровня: сам ответ и всё дерево под ним одной колонкой с линией, как в Threads.
|
||||
// Ответы глубже, чем отдал сервер, открываются отдельным обсуждением этого ответа.
|
||||
function renderReplyGroup(branch, { focus, channelOwner, handlers }) {
|
||||
const group = document.createElement('div');
|
||||
group.className = 'thread-group';
|
||||
group.append(renderComment({ node: branch.node, parent: focus, focus, channelOwner, handlers }));
|
||||
|
||||
const nested = [];
|
||||
const walk = (children, parent) => {
|
||||
(Array.isArray(children) ? children : []).forEach((child) => {
|
||||
if (!child?.node) return;
|
||||
nested.push({ node: child.node, parent, loaded: Array.isArray(child.children) ? child.children.length : 0 });
|
||||
walk(child.children, child.node);
|
||||
});
|
||||
};
|
||||
walk(branch.children, branch.node);
|
||||
const nested = (Array.isArray(branch.children) ? branch.children : [])
|
||||
.filter((child) => child?.node)
|
||||
.map((child) => ({ node: child.node, parent: branch.node }));
|
||||
if (!nested.length) return group;
|
||||
|
||||
group.classList.add('has-replies');
|
||||
const list = document.createElement('div');
|
||||
list.className = 'thread-replies';
|
||||
let previous = branch.node;
|
||||
nested.forEach(({ node, parent, loaded }, index) => {
|
||||
const comment = renderComment({ node, parent, focus, channelOwner, handlers, nested: true, mention: parent !== previous });
|
||||
nested.forEach(({ node, parent }, index) => {
|
||||
const comment = renderComment({ node, parent, focus, channelOwner, handlers, nested: true });
|
||||
if (index >= THREAD_GROUP_VISIBLE_REPLIES) comment.classList.add('is-collapsed');
|
||||
list.append(comment);
|
||||
const unloaded = Number(node?.repliesCount || 0) - loaded;
|
||||
if (unloaded > 0) {
|
||||
const deeper = document.createElement('button');
|
||||
deeper.type = 'button';
|
||||
deeper.className = 'thread-more thread-more--deeper';
|
||||
if (index >= THREAD_GROUP_VISIBLE_REPLIES) deeper.classList.add('is-collapsed');
|
||||
deeper.textContent = t('screens.channel_thread_view.text_110', { value1: unloaded });
|
||||
deeper.addEventListener('click', () => handlers.onOpenThread(buildTargetFromNode(node)));
|
||||
list.append(deeper);
|
||||
}
|
||||
previous = node;
|
||||
});
|
||||
const hidden = nested.length - THREAD_GROUP_VISIBLE_REPLIES;
|
||||
if (hidden > 0) {
|
||||
@@ -1352,7 +1314,6 @@ function pluralRu(n, one, few, many) {
|
||||
return many;
|
||||
}
|
||||
|
||||
|
||||
function renderDescendants(items, handlers, nextNumber, depth = 0, parent = null) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'stack';
|
||||
@@ -1427,8 +1388,8 @@ function setThreadMuted(key, muted) {
|
||||
try { localStorage.setItem(THREAD_MUTE_KEY, JSON.stringify(all)); } catch { /* приватный режим */ }
|
||||
}
|
||||
|
||||
// Глубина дерева ответов за один запрос; что глубже – открывается обсуждением конкретного ответа.
|
||||
const THREAD_LOAD_DEPTH = 8;
|
||||
// Фокус, его прямые ответы и один вложенный уровень для каждой ветки.
|
||||
const THREAD_LOAD_DEPTH = 2;
|
||||
|
||||
// Загрузка обсуждения без привязки к экрану: её же использует подгрузка заранее, по касанию записи.
|
||||
async function loadThreadData(sel, cacheKey, isCurrent) {
|
||||
@@ -1887,7 +1848,7 @@ export function render({ navigate, route, chrome }) {
|
||||
const modalRoot = document.getElementById('modal-root');
|
||||
if (!modalRoot) return;
|
||||
if (modalRoot.querySelector([
|
||||
'#thread-blockchain-details-modal',
|
||||
'#blockchain-details-modal',
|
||||
'#thread-edit-modal',
|
||||
'#thread-history-modal',
|
||||
'#thread-reply-modal',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { formatDateTime, getIntlLocale } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
|
||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
@@ -39,6 +40,7 @@ import {
|
||||
softHaptic,
|
||||
} from '../services/channels-ux.js';
|
||||
import { renderAvatar, renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { avatarReferenceToRenderModel, parseAvatarReference } from '../services/avatar-reference.js';
|
||||
import { openChannelEditor } from '../components/channel-editor.js';
|
||||
import { markArweaveAttachmentPlaced, openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
|
||||
@@ -50,7 +52,7 @@ import {
|
||||
MAX_MESSAGE_ATTACHMENTS,
|
||||
parseMessageAttachments,
|
||||
} from '../services/attachment-format.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { loadProfileSnapshot, profileDisplayName } from '../services/user-profile-params.js';
|
||||
import {
|
||||
extractLoginFromBlockchainName,
|
||||
makeProfileRoute,
|
||||
@@ -849,56 +851,10 @@ function buildBlockchainDetails({ messageRef, authorLogin, timestampMs, text, ra
|
||||
msgSubType: msgSubType ?? source.msgSubType ?? '',
|
||||
createdAtMs: timestampMs || source.createdAtMs || '',
|
||||
text: String(text || ''),
|
||||
signature: source.signature || source.blockSignature || source.authorSignature || t('screens.channel_view.text_114'),
|
||||
publicKey: source.publicKey || source.authorPublicKey || t('screens.channel_view.text_115'),
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
const rawText = JSON.stringify(details.raw || details, null, 2);
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="blockchain-details-modal">
|
||||
<div class="modal-card stack blockchain-details-card">
|
||||
<h3 class="modal-title">${t('dialogs.modals.channel_view.label_011')}</h3>
|
||||
<p class="meta-muted">${t('dialogs.modals.channel_view.label_012')}</p>
|
||||
<div class="blockchain-details-grid">
|
||||
<span>${t('dialogs.modals.channel_view.label_013')}</span><strong>${escapeHtml(details.authorLogin)}</strong>
|
||||
<span>${t('dialogs.modals.channel_view.label_014')}</span><code>${escapeHtml(details.authorBlockchainName)}</code>
|
||||
<span>${t('dialogs.modals.channel_view.label_015')}</span><code>${escapeHtml(details.blockNumber)}</code>
|
||||
<span>${t('dialogs.modals.channel_view.label_016')}</span><code>${escapeHtml(details.blockHash)}</code>
|
||||
<span>${t('dialogs.modals.channel_view.label_017')}</span><code>${escapeHtml(details.msgSubType)}</code>
|
||||
<span>${t('dialogs.modals.channel_view.label_018')}</span><code>${escapeHtml(details.createdAtMs ? formatDateTime(new Date(Number(details.createdAtMs))) : '–')}</code>
|
||||
<span>Public key</span><code>${escapeHtml(details.publicKey)}</code>
|
||||
<span>${t('dialogs.modals.channel_view.label_019')}</span><code>${escapeHtml(details.signature)}</code>
|
||||
</div>
|
||||
<label class="field-label" for="blockchain-details-text">${t('dialogs.modals.channel_view.label_020')}</label>
|
||||
<textarea class="input" id="blockchain-details-text" rows="4" readonly>${escapeHtml(details.text)}</textarea>
|
||||
<pre class="blockchain-raw-block" id="blockchain-raw-block" hidden>${escapeHtml(rawText)}</pre>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="blockchain-details-copy" type="button">${t('dialogs.modals.channel_view.label_021')}</button>
|
||||
<button class="secondary-btn" id="blockchain-details-raw" type="button">${t('dialogs.modals.channel_view.label_022')}</button>
|
||||
</div>
|
||||
<button class="secondary-btn" id="blockchain-details-close" type="button">${t('dialogs.modals.channel_view.label_005')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
root.querySelector('#blockchain-details-close')?.addEventListener('click', () => {
|
||||
root.innerHTML = '';
|
||||
});
|
||||
root.querySelector('#blockchain-details-copy')?.addEventListener('click', async () => {
|
||||
await copyTextToClipboard(rawText);
|
||||
if (!isActive()) return;
|
||||
showToast(t('dialogs.remaining.pages.channel_view.openblockchaindetailsmodal.dannye_blokcheyna_skopirovany'));
|
||||
});
|
||||
root.querySelector('#blockchain-details-raw')?.addEventListener('click', () => {
|
||||
const rawEl = root.querySelector('#blockchain-raw-block');
|
||||
if (!rawEl) return;
|
||||
rawEl.hidden = !rawEl.hidden;
|
||||
});
|
||||
}
|
||||
|
||||
function renderDraftAttachments(container, attachments) {
|
||||
if (!container) return;
|
||||
container.innerHTML = '';
|
||||
@@ -1849,17 +1805,16 @@ function renderPostCard(post, {
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'channel-message-title author-line';
|
||||
const displayNameEl = document.createElement('span');
|
||||
displayNameEl.className = 'author-line-name';
|
||||
displayNameEl.textContent = post.authorLogin;
|
||||
const titleMain = document.createElement('div');
|
||||
titleMain.className = 'author-line-main';
|
||||
const loginEl = document.createElement('span');
|
||||
loginEl.className = 'author-line-login';
|
||||
loginEl.textContent = post.authorLogin;
|
||||
|
||||
const numberEl = document.createElement('span');
|
||||
numberEl.className = 'author-line-num';
|
||||
numberEl.textContent = `· #${post.localNumber}`;
|
||||
titleMain.append(loginEl, numberEl);
|
||||
title.append(titleMain);
|
||||
loginEl.textContent = `@${String(post.authorLogin || '').replace(/^@/, '')}`;
|
||||
titleMain.append(loginEl);
|
||||
title.append(displayNameEl, titleMain);
|
||||
|
||||
const timestamp = document.createElement('div');
|
||||
timestamp.className = 'channel-message-time';
|
||||
@@ -1912,7 +1867,19 @@ function renderPostCard(post, {
|
||||
event.stopPropagation();
|
||||
const cleanLogin = String(post.authorLogin || '').trim();
|
||||
if (!cleanLogin) return;
|
||||
navigate(makeProfileRoute(cleanLogin));
|
||||
profileMenu.toggle();
|
||||
});
|
||||
const profileMenu = createDropdownMenu({
|
||||
anchorEl: authorTile,
|
||||
minWidth: 190,
|
||||
dimBackground: false,
|
||||
items: [{ label: t('screens.chat_view.text_004'), iconHtml: iconHtml('profile'), action: () => navigate(makeProfileRoute(String(post.authorLogin || '').trim())) }],
|
||||
});
|
||||
const existingCleanup = card.cleanup;
|
||||
card.cleanup = () => { existingCleanup?.(); profileMenu.destroy(); };
|
||||
void loadMessageAvatarSnapshot(post.authorLogin).then((snapshot) => {
|
||||
if (!authorTile.isConnected) return;
|
||||
displayNameEl.textContent = profileDisplayName(snapshot, post.authorLogin);
|
||||
});
|
||||
|
||||
const isOwnerPost = !!selector
|
||||
@@ -2247,7 +2214,7 @@ function renderPostCard(post, {
|
||||
raw: post.rawMessage,
|
||||
localNumber: post.localNumber,
|
||||
msgSubType: post.msgSubType,
|
||||
}), { isActive });
|
||||
}), { isActive, authService, solanaEndpoint: state.entrySettings.solanaServer });
|
||||
});
|
||||
menuItems.push({ label: t('screens.channel_view.text_034'), iconHtml: iconHtml('info'), action: () => detailsButton.click() });
|
||||
if (post.isOwnMessage) {
|
||||
|
||||
+78
-157
@@ -285,6 +285,43 @@ function openChatConfirmModal({
|
||||
});
|
||||
}
|
||||
|
||||
function openExternalLinkModal(href) {
|
||||
const root = document.getElementById('modal-root');
|
||||
const url = String(href || '').trim();
|
||||
if (!root || !/^https?:\/\//i.test(url)) return;
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="chat-external-link-modal">
|
||||
<div class="modal-card stack" role="dialog" aria-modal="true" aria-labelledby="chat-external-link-title">
|
||||
<h3 class="modal-title" id="chat-external-link-title">${t('chat_links.title')}</h3>
|
||||
<p class="meta-muted">${t('chat_links.description')}</p>
|
||||
<p class="chat-external-link-url"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" id="chat-external-link-copy">${t('chat_links.copy')}</button>
|
||||
<button class="primary-btn" type="button" id="chat-external-link-open">${t('chat_links.open')}</button>
|
||||
<button class="secondary-btn" type="button" id="chat-external-link-cancel">${t('chat_links.cancel')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
root.querySelector('.chat-external-link-url').textContent = url;
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
root.querySelector('#chat-external-link-cancel')?.addEventListener('click', close);
|
||||
root.querySelector('#chat-external-link-open')?.addEventListener('click', () => {
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
close();
|
||||
});
|
||||
root.querySelector('#chat-external-link-copy')?.addEventListener('click', async () => {
|
||||
try {
|
||||
if (!navigator?.clipboard?.writeText) throw new Error('clipboard_unavailable');
|
||||
await navigator.clipboard.writeText(url);
|
||||
close();
|
||||
showToast(t('chat_links.copied'), { timeoutMs: 1200 });
|
||||
} catch {
|
||||
showToast(t('chat_links.copy_failed'), { kind: 'error', timeoutMs: 1600 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Календарь «перейти к дате»: активны только дни, в которые была переписка.
|
||||
// days – Map dayKey → { timeMs, count }; список можно обновить, пока догружается история.
|
||||
// «октябрь 2026 г.» → «Октябрь 2026 г.» (CSS capitalize сделал бы «Г.»)
|
||||
@@ -965,6 +1002,7 @@ function renderMessageText(textNode, messageText, chatNavigate) {
|
||||
}
|
||||
appendShineMessageLinks(textNode, text, {
|
||||
navigate: chatNavigate,
|
||||
onExternalLink: ({ href }) => openExternalLinkModal(href),
|
||||
appendText: (root, part) => {
|
||||
const fragment = document.createDocumentFragment();
|
||||
if (appendTwemojiText(fragment, part, { className: 'chat-twemoji chat-twemoji--inline' })) {
|
||||
@@ -1292,21 +1330,6 @@ function renderLog(
|
||||
);
|
||||
}
|
||||
bubble.append(attachmentsWrap);
|
||||
const expiresAt = dmAttachments
|
||||
.filter((item) => Number(item?.version || 1) >= 3)
|
||||
.map((item) => Number(item.uploadedAtMs || msg?.timeMs || 0) + 14 * 24 * 60 * 60 * 1000)
|
||||
.filter((value) => value > 14 * 24 * 60 * 60 * 1000);
|
||||
if (expiresAt.length) {
|
||||
const remaining = Math.min(...expiresAt) - Date.now();
|
||||
const expiry = document.createElement('div');
|
||||
expiry.className = 'dm-attachment-expiry';
|
||||
expiry.textContent = remaining <= 0
|
||||
? t('screens.dm_attachments.file_expired_short')
|
||||
: remaining < 24 * 60 * 60 * 1000
|
||||
? t('screens.dm_attachments.remaining_less_day')
|
||||
: t('screens.dm_attachments.remaining_days', { value1: Math.ceil(remaining / (24 * 60 * 60 * 1000)) });
|
||||
bubble.append(expiry);
|
||||
}
|
||||
}
|
||||
|
||||
const textNode = document.createElement('div');
|
||||
@@ -1579,7 +1602,7 @@ export function render({ navigate, route, chrome }) {
|
||||
onClick: () => handleStartCall('video'),
|
||||
},
|
||||
{
|
||||
iconNode: createOverflowDots(),
|
||||
iconNode: createOverflowDots({ className: 'app-overflow-dots--vertical' }),
|
||||
title: t('screens.chat_view.text_013'),
|
||||
ariaLabel: t('screens.chat_view.text_014'),
|
||||
className: 'chat-header-icon-btn chat-header-menu-btn topbar-overflow-action--raised',
|
||||
@@ -1605,6 +1628,7 @@ export function render({ navigate, route, chrome }) {
|
||||
},
|
||||
}
|
||||
: null,
|
||||
{ label: t('wallet_multi.transfer_to_contact'), iconHtml: menuIconSvg('forward'), action: () => navigate(`wallet/transfer/${encodeURIComponent(chatId)}`) },
|
||||
{ divider: true },
|
||||
{
|
||||
label: t('screens.chat_view.text_020'),
|
||||
@@ -1912,11 +1936,9 @@ export function render({ navigate, route, chrome }) {
|
||||
<button class="dm-bar-icon dm-camera-btn" type="button" id="chat-camera-toggle" aria-label="${th('screens.chat_view.text_115')}" title="${th('screens.chat_view.text_116')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('camera')}</button>
|
||||
<button class="dm-bar-icon dm-file-btn" type="button" id="chat-file-toggle" aria-label="${th('screens.chat_view.text_117')}" title="${th('screens.chat_view.text_118')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('clip')}</button>
|
||||
<div class="dm-voice-recording-status" id="chat-voice-recording-status" hidden>
|
||||
<button class="dm-voice-cancel" type="button" id="chat-voice-cancel" aria-label="${th('screens.chat_view.voice_cancel')}">✕</button>
|
||||
<span class="dm-voice-recording-dot" aria-hidden="true"></span>
|
||||
<span class="dm-voice-recording-time" id="chat-voice-recording-time">0:00</span>
|
||||
<span class="dm-voice-recording-hint" id="chat-voice-recording-hint">${th('screens.chat_view.text_119')}</span>
|
||||
<button class="dm-voice-pause" type="button" id="chat-voice-pause" hidden></button>
|
||||
</div>
|
||||
<div class="dm-field">
|
||||
<textarea class="input dm-input" name="message" rows="1" placeholder="${th('screens.chat_view.text_120')}" maxlength="12000" enterkeyhint="enter"></textarea>
|
||||
@@ -1924,7 +1946,6 @@ export function render({ navigate, route, chrome }) {
|
||||
<button class="dm-bar-icon dm-emoji-btn" type="button" id="chat-emoji-toggle" aria-label="${th('screens.chat_view.text_121')}" title="${th('screens.chat_view.text_122')}">${iconHtml('emoji')}</button>
|
||||
<button class="dm-send-btn dm-send-icon-btn" type="button" title="${th('screens.chat_view.text_123')}" data-mode="voice" aria-label="${th('screens.chat_view.text_124')}"></button>
|
||||
</div>
|
||||
<div class="dm-file-queue" id="chat-file-queue" hidden></div>
|
||||
<input id="chat-file-input" type="file" multiple hidden />
|
||||
<input id="chat-media-input" type="file" accept="image/*,video/*" multiple hidden />
|
||||
<input id="chat-camera-input" type="file" accept="image/*,video/*" capture="environment" hidden />
|
||||
@@ -1935,7 +1956,6 @@ export function render({ navigate, route, chrome }) {
|
||||
const emojiToggle = form.querySelector('#chat-emoji-toggle');
|
||||
const fileToggle = form.querySelector('#chat-file-toggle');
|
||||
const fileInput = form.querySelector('#chat-file-input');
|
||||
const fileQueue = form.querySelector('#chat-file-queue');
|
||||
// Три входа для вложений: галерея (фото/видео), камера и любой файл – дальше путь один.
|
||||
const attachSources = [
|
||||
[fileToggle, fileInput],
|
||||
@@ -1947,8 +1967,6 @@ export function render({ navigate, route, chrome }) {
|
||||
const voiceStatus = form.querySelector('#chat-voice-recording-status');
|
||||
const voiceTime = form.querySelector('#chat-voice-recording-time');
|
||||
const voiceHint = form.querySelector('#chat-voice-recording-hint');
|
||||
const voicePause = form.querySelector('#chat-voice-pause');
|
||||
const voiceCancel = form.querySelector('#chat-voice-cancel');
|
||||
const fileTransferEnabled = isDmFileTransferEnabled();
|
||||
const editBanner = form.querySelector('#chat-edit-banner');
|
||||
const editBannerText = form.querySelector('#chat-edit-banner-text');
|
||||
@@ -1961,8 +1979,6 @@ export function render({ navigate, route, chrome }) {
|
||||
let emojiLongPressTimer = null;
|
||||
let emojiLongPressTriggered = false;
|
||||
let fileActionVisible = false;
|
||||
let queuedFiles = [];
|
||||
let fileSending = false;
|
||||
let voiceRecorder = null;
|
||||
let voiceStream = null;
|
||||
let voiceChunks = [];
|
||||
@@ -1972,11 +1988,6 @@ export function render({ navigate, route, chrome }) {
|
||||
let voicePointerHeld = false;
|
||||
let voiceReleaseRequested = false;
|
||||
let voiceStartY = 0;
|
||||
let voiceStartX = 0;
|
||||
let voicePressStartedAt = 0;
|
||||
let voiceCancelRequested = false;
|
||||
let voicePausedMs = 0;
|
||||
let voicePausedAt = 0;
|
||||
let voicePointerId = null;
|
||||
let voiceBusy = false;
|
||||
let suppressVoiceClick = false;
|
||||
@@ -2052,7 +2063,7 @@ export function render({ navigate, route, chrome }) {
|
||||
return iconHtml('send');
|
||||
}
|
||||
if (mode === 'stop') {
|
||||
return iconHtml('send');
|
||||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor"/></svg>';
|
||||
}
|
||||
if (mode === 'busy') {
|
||||
return '<span class="dm-send-busy-dot">…</span>';
|
||||
@@ -2060,8 +2071,7 @@ export function render({ navigate, route, chrome }) {
|
||||
return iconHtml('mic');
|
||||
};
|
||||
|
||||
const currentVoiceDurationMs = () => voiceStartedAt > 0
|
||||
? Math.max(0, (voicePausedAt || Date.now()) - voiceStartedAt - voicePausedMs) : 0;
|
||||
const currentVoiceDurationMs = () => voiceStartedAt > 0 ? Math.max(0, Date.now() - voiceStartedAt) : 0;
|
||||
|
||||
const syncVoiceTimer = () => {
|
||||
if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs());
|
||||
@@ -2087,22 +2097,22 @@ export function render({ navigate, route, chrome }) {
|
||||
if (!sendBtn) return;
|
||||
const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive');
|
||||
let mode = 'voice';
|
||||
if (voiceBusy || fileSending) mode = 'busy';
|
||||
if (voiceBusy) mode = 'busy';
|
||||
else if (recording && voiceLocked) mode = 'stop';
|
||||
else if (recording) mode = 'voice';
|
||||
else if (activeEdit || queuedFiles.length || String(input?.value || '').trim()) mode = 'send';
|
||||
else if (activeEdit || String(input?.value || '').trim()) mode = 'send';
|
||||
|
||||
sendBtn.dataset.mode = mode;
|
||||
sendBtn.innerHTML = sendIconMarkup(mode);
|
||||
sendBtn.classList.toggle('is-recording', recording);
|
||||
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
|
||||
sendBtn.disabled = voiceBusy || fileSending || (mode === 'voice' && !recording && !fileTransferEnabled);
|
||||
sendBtn.disabled = voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
|
||||
if (mode === 'send') {
|
||||
sendBtn.title = t('screens.chat_view.text_029');
|
||||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029'));
|
||||
} else if (mode === 'stop') {
|
||||
sendBtn.title = t('screens.chat_view.voice_send');
|
||||
sendBtn.setAttribute('aria-label', t('screens.chat_view.voice_send'));
|
||||
sendBtn.title = t('screens.chat_view.text_030');
|
||||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030'));
|
||||
} else if (mode === 'busy') {
|
||||
sendBtn.title = t('screens.chat_view.text_031');
|
||||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_031'));
|
||||
@@ -2112,13 +2122,6 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
form.classList.toggle('dm-chat-input--recording', recording);
|
||||
if (voiceStatus) voiceStatus.hidden = !recording;
|
||||
if (voicePause) {
|
||||
voicePause.hidden = !recording || !voiceLocked;
|
||||
voicePause.textContent = voiceRecorder?.state === 'paused' ? '▶' : 'Ⅱ';
|
||||
voicePause.setAttribute('aria-label', t(voiceRecorder?.state === 'paused' ? 'screens.chat_view.voice_resume' : 'screens.chat_view.voice_pause'));
|
||||
}
|
||||
form.classList.toggle('dm-chat-input--voice-locked', recording && voiceLocked);
|
||||
form.classList.toggle('dm-chat-input--voice-paused', recording && voiceRecorder?.state === 'paused');
|
||||
if (input) input.hidden = recording;
|
||||
if (emojiToggle) emojiToggle.hidden = recording;
|
||||
attachButtons.forEach((button) => { button.hidden = recording || !fileTransferEnabled; });
|
||||
@@ -2146,10 +2149,7 @@ export function render({ navigate, route, chrome }) {
|
||||
const stopVoiceRecording = ({ send = true } = {}) => {
|
||||
voicePointerHeld = false;
|
||||
voiceReleaseRequested = true;
|
||||
if (!voiceRecorder || voiceRecorder.state === 'inactive') {
|
||||
if (!send) voiceCancelRequested = true;
|
||||
return;
|
||||
}
|
||||
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
|
||||
voiceRecorder.__shineShouldSend = Boolean(send);
|
||||
try {
|
||||
voiceRecorder.stop();
|
||||
@@ -2158,7 +2158,7 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
};
|
||||
|
||||
const startVoiceRecording = async ({ pointerY = 0, pointerX = 0, pointerId = null } = {}) => {
|
||||
const startVoiceRecording = async ({ pointerY = 0, pointerId = null } = {}) => {
|
||||
if (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
|
||||
if (!fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
|
||||
@@ -2177,11 +2177,7 @@ export function render({ navigate, route, chrome }) {
|
||||
voiceReleaseRequested = false;
|
||||
voiceLocked = false;
|
||||
voiceStartY = Number(pointerY || 0);
|
||||
voiceStartX = Number(pointerX || 0);
|
||||
voicePointerId = pointerId;
|
||||
voiceCancelRequested = false;
|
||||
voicePausedMs = 0;
|
||||
voicePausedAt = 0;
|
||||
suppressVoiceClick = false;
|
||||
|
||||
try {
|
||||
@@ -2209,15 +2205,13 @@ export function render({ navigate, route, chrome }) {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
|
||||
});
|
||||
recorder.addEventListener('stop', async () => {
|
||||
const shouldSend = recorder.__shineShouldSend !== false && !voiceCancelRequested;
|
||||
const shouldSend = recorder.__shineShouldSend !== false;
|
||||
const durationMs = currentVoiceDurationMs();
|
||||
const chunks = voiceChunks.slice();
|
||||
voiceChunks = [];
|
||||
voiceRecorder = null;
|
||||
voiceLocked = false;
|
||||
voiceStartedAt = 0;
|
||||
voicePausedAt = 0;
|
||||
voicePausedMs = 0;
|
||||
clearVoiceTimer();
|
||||
stopVoiceStreamTracks();
|
||||
voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0);
|
||||
@@ -2256,8 +2250,7 @@ export function render({ navigate, route, chrome }) {
|
||||
recorder.start(1000);
|
||||
voiceTimer = window.setInterval(syncVoiceTimer, 250);
|
||||
updateSendButtonMode();
|
||||
if (voiceCancelRequested) stopVoiceRecording({ send: false });
|
||||
else if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
|
||||
if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
|
||||
} catch (error) {
|
||||
voicePointerHeld = false;
|
||||
voiceReleaseRequested = false;
|
||||
@@ -2573,7 +2566,7 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
};
|
||||
|
||||
const sendFileAttachmentMessage = async (attachmentsInput, caption = '') => {
|
||||
const sendFileAttachmentMessage = async (attachmentsInput) => {
|
||||
const attachments = (Array.isArray(attachmentsInput) ? attachmentsInput : [attachmentsInput]).filter(Boolean);
|
||||
if (!attachments.length) return;
|
||||
if (attachments.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
|
||||
@@ -2588,7 +2581,7 @@ export function render({ navigate, route, chrome }) {
|
||||
: (attachments.length === 1
|
||||
? `📎 ${String(attachments[0]?.name || 'file')}`
|
||||
: t('screens.chat_view.text_097', { value1: attachments.length }));
|
||||
const finalText = `${replyBlock}${fileBlocks}${String(caption || '').trim() || fallbackText}`;
|
||||
const finalText = `${replyBlock}${fileBlocks}${fallbackText}`;
|
||||
|
||||
hideUnreadSeparator({ rerender: false });
|
||||
const tempId = addOutgoingPendingMessage(chatId, finalText);
|
||||
@@ -2652,7 +2645,7 @@ export function render({ navigate, route, chrome }) {
|
||||
};
|
||||
|
||||
// Файлы уже лежат на сервере – повторить можно одно сообщение с ключами, без новой загрузки.
|
||||
const offerAttachmentsRetry = (attachments, error, caption = '') => {
|
||||
const offerAttachmentsRetry = (attachments, error) => {
|
||||
showToast(actionErrorText(attachments.length === 1 ? t('screens.chat_view.text_075') : t('screens.chat_view.text_076'), error), {
|
||||
kind: 'error',
|
||||
action: {
|
||||
@@ -2660,40 +2653,17 @@ export function render({ navigate, route, chrome }) {
|
||||
onClick: async () => {
|
||||
if (disposed) return;
|
||||
try {
|
||||
await sendFileAttachmentMessage(attachments, caption);
|
||||
await sendFileAttachmentMessage(attachments);
|
||||
if (!disposed) showToast(attachments.length === 1 ? t('screens.chat_view.text_077') : t('screens.chat_view.text_100', { value1: attachments.length }), { timeoutMs: 1300 });
|
||||
} catch (again) {
|
||||
if (!disposed) offerAttachmentsRetry(attachments, again, caption);
|
||||
if (!disposed) offerAttachmentsRetry(attachments, again);
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const renderQueuedFiles = () => {
|
||||
fileQueue.replaceChildren();
|
||||
fileQueue.hidden = !queuedFiles.length;
|
||||
queuedFiles.forEach((file, index) => {
|
||||
const chip = document.createElement('span');
|
||||
chip.className = 'dm-file-queue__chip';
|
||||
const name = document.createElement('span');
|
||||
name.textContent = file.name;
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.textContent = '✕';
|
||||
remove.setAttribute('aria-label', t('screens.chat_view.file_remove', { value1: file.name }));
|
||||
remove.addEventListener('click', () => {
|
||||
queuedFiles.splice(index, 1);
|
||||
renderQueuedFiles();
|
||||
});
|
||||
chip.append(name, remove);
|
||||
fileQueue.append(chip);
|
||||
});
|
||||
updateSendButtonMode();
|
||||
};
|
||||
|
||||
const handleSelectedFiles = async (fileList) => {
|
||||
if (fileSending) return;
|
||||
if (!fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
|
||||
return;
|
||||
@@ -2703,14 +2673,11 @@ export function render({ navigate, route, chrome }) {
|
||||
return;
|
||||
}
|
||||
const allFiles = Array.from(fileList || []).filter(Boolean);
|
||||
const caption = String(input?.value || '').trim();
|
||||
if (!allFiles.length) return;
|
||||
if (allFiles.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
|
||||
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error', timeoutMs: 2200 });
|
||||
return;
|
||||
}
|
||||
fileSending = true;
|
||||
updateSendButtonMode();
|
||||
|
||||
attachButtons.forEach((button) => {
|
||||
button.disabled = true;
|
||||
@@ -2738,26 +2705,13 @@ export function render({ navigate, route, chrome }) {
|
||||
attachments.push(attachment);
|
||||
}
|
||||
uploaded = true;
|
||||
await sendFileAttachmentMessage(attachments, caption);
|
||||
queuedFiles = [];
|
||||
renderQueuedFiles();
|
||||
if (caption && String(input?.value || '').trim() === caption) {
|
||||
input.value = '';
|
||||
autoResizeComposer(input);
|
||||
updateSendButtonMode();
|
||||
}
|
||||
await sendFileAttachmentMessage(attachments);
|
||||
setFileActionVisible(false);
|
||||
showToast(attachments.length === 1 ? t('screens.chat_view.text_078') : t('screens.chat_view.text_103', { value1: attachments.length }), { timeoutMs: 1300 });
|
||||
} catch (error) {
|
||||
if (uploaded) {
|
||||
queuedFiles = [];
|
||||
renderQueuedFiles();
|
||||
offerAttachmentsRetry(attachments, error, caption);
|
||||
}
|
||||
if (uploaded) offerAttachmentsRetry(attachments, error);
|
||||
else showToast(actionErrorText(allFiles.length === 1 ? t('screens.chat_view.text_079') : t('screens.chat_view.text_080'), error), { kind: 'error' });
|
||||
} finally {
|
||||
fileSending = false;
|
||||
updateSendButtonMode();
|
||||
attachButtons.forEach((button) => {
|
||||
button.disabled = false;
|
||||
button.classList.remove('is-busy');
|
||||
@@ -2895,18 +2849,30 @@ export function render({ navigate, route, chrome }) {
|
||||
// Вся история уже в памяти (её загрузил поиск или «Медиа и файлы») – листать сервер дальше незачем.
|
||||
if (isDmHistoryFullyLoaded(chatId)) historyHasMore = false;
|
||||
else if (!historyHasMore) markDmHistoryFullyLoaded(chatId);
|
||||
let scrollModeAfterLoad = isBootstrap ? 'latest' : (preserveScroll ? 'preserve' : 'latest');
|
||||
if (isBootstrap) {
|
||||
const firstUnread = getChatMessages(chatId).find((msg) => msg?.from === 'in' && msg?.unread);
|
||||
if (firstUnread?.messageKey) {
|
||||
unreadSeparatorVisible = true;
|
||||
unreadSeparatorAnchorMessageKey = String(firstUnread.messageKey);
|
||||
stickToBottom = false;
|
||||
scrollModeAfterLoad = 'unread';
|
||||
}
|
||||
}
|
||||
// Страница уже была в памяти: перерисовка не нужна, лента не дёргается.
|
||||
if (messagesBefore === JSON.stringify(getChatMessages(chatId))) {
|
||||
pageAddedNothing = true;
|
||||
void sendReadReceiptsForVisible(chatId);
|
||||
return;
|
||||
}
|
||||
renderChatLog({ markAsRead: false, scrollMode: preserveScroll ? 'preserve' : 'latest' });
|
||||
if (preserveScroll) {
|
||||
renderChatLog({ markAsRead: false, scrollMode: scrollModeAfterLoad });
|
||||
if (scrollModeAfterLoad === 'preserve') {
|
||||
window.requestAnimationFrame(() => {
|
||||
const nextHeight = Number(scrollContainer?.scrollHeight || 0);
|
||||
scrollContainer.scrollTop = Math.max(0, prevScrollTop + (nextHeight - prevScrollHeight));
|
||||
});
|
||||
} else if (scrollModeAfterLoad === 'unread') {
|
||||
window.requestAnimationFrame(() => scrollToUnreadSeparator(log));
|
||||
} else {
|
||||
window.requestAnimationFrame(() => scrollToLatestMessage(log));
|
||||
}
|
||||
@@ -3005,14 +2971,7 @@ export function render({ navigate, route, chrome }) {
|
||||
});
|
||||
picker?.addEventListener('change', () => {
|
||||
const files = Array.from(picker.files || []);
|
||||
if (!files.length) return;
|
||||
if (queuedFiles.length + files.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
|
||||
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
queuedFiles.push(...files);
|
||||
renderQueuedFiles();
|
||||
picker.value = '';
|
||||
if (files.length) void handleSelectedFiles(files);
|
||||
});
|
||||
});
|
||||
screen.addEventListener('pointerdown', (event) => {
|
||||
@@ -3045,21 +3004,14 @@ export function render({ navigate, route, chrome }) {
|
||||
voicePointerHeld = true;
|
||||
voiceReleaseRequested = false;
|
||||
voiceStartY = Number(event.clientY || 0);
|
||||
voicePressStartedAt = Date.now();
|
||||
voicePointerId = event.pointerId;
|
||||
try { sendBtn.setPointerCapture?.(event.pointerId); } catch { /* optional */ }
|
||||
void startVoiceRecording({ pointerY: voiceStartY, pointerX: event.clientX, pointerId: event.pointerId });
|
||||
void startVoiceRecording({ pointerY: voiceStartY, pointerId: event.pointerId });
|
||||
});
|
||||
|
||||
sendBtn?.addEventListener('pointermove', (event) => {
|
||||
if (!voicePointerHeld || voiceLocked || voicePointerId !== event.pointerId) return;
|
||||
if (Number(event.clientX || 0) <= voiceStartX - 72) {
|
||||
voiceCancelRequested = true;
|
||||
suppressVoiceClick = true;
|
||||
stopVoiceRecording({ send: false });
|
||||
if (voiceHint) voiceHint.textContent = t('screens.chat_view.voice_cancelled');
|
||||
return;
|
||||
}
|
||||
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
|
||||
if (Number(event.clientY || 0) <= voiceStartY - 64) {
|
||||
voiceLocked = true;
|
||||
voiceReleaseRequested = false;
|
||||
@@ -3076,40 +3028,13 @@ export function render({ navigate, route, chrome }) {
|
||||
voiceReleaseRequested = true;
|
||||
try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
|
||||
voicePointerId = null;
|
||||
if (!voiceLocked && !voiceCancelRequested && Date.now() - voicePressStartedAt < 350) {
|
||||
voiceLocked = true;
|
||||
voiceReleaseRequested = false;
|
||||
if (voiceHint) voiceHint.textContent = t('screens.chat_view.voice_tap_hint');
|
||||
updateSendButtonMode();
|
||||
if (!voiceLocked) {
|
||||
suppressVoiceClick = true;
|
||||
} else if (!voiceLocked) {
|
||||
suppressVoiceClick = true;
|
||||
stopVoiceRecording({ send: !voiceCancelRequested });
|
||||
stopVoiceRecording({ send: true });
|
||||
}
|
||||
};
|
||||
sendBtn?.addEventListener('pointerup', finishVoicePointerGesture);
|
||||
sendBtn?.addEventListener('pointercancel', (event) => {
|
||||
if (voicePointerId !== event.pointerId) return;
|
||||
voiceCancelRequested = true;
|
||||
finishVoicePointerGesture(event);
|
||||
stopVoiceRecording({ send: false });
|
||||
});
|
||||
voiceCancel?.addEventListener('click', () => {
|
||||
voiceCancelRequested = true;
|
||||
stopVoiceRecording({ send: false });
|
||||
});
|
||||
voicePause?.addEventListener('click', () => {
|
||||
if (!voiceRecorder || !voiceLocked) return;
|
||||
if (voiceRecorder.state === 'recording') {
|
||||
voiceRecorder.pause();
|
||||
voicePausedAt = Date.now();
|
||||
} else if (voiceRecorder.state === 'paused') {
|
||||
voicePausedMs += Date.now() - voicePausedAt;
|
||||
voicePausedAt = 0;
|
||||
voiceRecorder.resume();
|
||||
}
|
||||
updateSendButtonMode();
|
||||
});
|
||||
sendBtn?.addEventListener('pointercancel', finishVoicePointerGesture);
|
||||
sendBtn?.addEventListener('contextmenu', (event) => {
|
||||
if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault();
|
||||
});
|
||||
@@ -3138,10 +3063,6 @@ export function render({ navigate, route, chrome }) {
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const text = String(input.value || '').trim();
|
||||
if (queuedFiles.length) {
|
||||
await handleSelectedFiles(queuedFiles);
|
||||
return;
|
||||
}
|
||||
if (!text) return;
|
||||
input.value = '';
|
||||
autoResizeComposer(input);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createVisiblePasswordField } from '../components/visible-password-field.js';
|
||||
import { createVisiblePasswordField, createExpandablePasswordTextarea } from '../components/visible-password-field.js';
|
||||
import { createSecretGenerationOverlay } from '../components/secret-generation-overlay.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
@@ -24,31 +25,6 @@ function setStatus(statusEl, message) {
|
||||
statusEl.style.display = message ? '' : 'none';
|
||||
}
|
||||
|
||||
function createSecretOverlay() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'secret-generation-overlay';
|
||||
overlay.style.display = 'none';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'secret-generation-card stack';
|
||||
|
||||
const spinner = document.createElement('div');
|
||||
spinner.className = 'secret-generation-spinner';
|
||||
spinner.setAttribute('aria-hidden', 'true');
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'secret-generation-title';
|
||||
title.textContent = t('screens.login_password_view.text_002');
|
||||
|
||||
const progress = document.createElement('div');
|
||||
progress.className = 'secret-generation-progress';
|
||||
progress.textContent = '';
|
||||
|
||||
card.append(spinner, title, progress);
|
||||
overlay.append(card);
|
||||
return { overlay, progress };
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack auth-screen auth-screen--lower';
|
||||
@@ -70,9 +46,7 @@ export function render({ navigate }) {
|
||||
const passwordField = document.createElement('label');
|
||||
passwordField.className = 'stack';
|
||||
|
||||
const passwordInput = document.createElement('input');
|
||||
passwordInput.className = 'input';
|
||||
passwordInput.type = 'text';
|
||||
const passwordInput = createExpandablePasswordTextarea();
|
||||
passwordInput.name = 'shine-login-password';
|
||||
passwordInput.autocomplete = 'current-password';
|
||||
passwordInput.autocapitalize = 'off';
|
||||
@@ -96,7 +70,7 @@ export function render({ navigate }) {
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.append(enterButton);
|
||||
|
||||
const { overlay, progress } = createSecretOverlay();
|
||||
const keyGeneration = createSecretGenerationOverlay();
|
||||
|
||||
const submit = async () => {
|
||||
const currentLogin = String(state.loginDraft.login || '').trim();
|
||||
@@ -131,14 +105,10 @@ export function render({ navigate }) {
|
||||
return;
|
||||
}
|
||||
|
||||
overlay.style.display = 'grid';
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(currentLogin, password, {
|
||||
onProgress: ({ percent }) => {
|
||||
const value = Math.max(0, Math.min(100, Number(percent) || 0));
|
||||
progress.textContent = value > 0 && value < 100 ? `${Math.round(value)}%` : '';
|
||||
},
|
||||
});
|
||||
overlay.style.display = 'none';
|
||||
keyGeneration.show();
|
||||
await new Promise(resolve => setTimeout(resolve, 40));
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(currentLogin, password);
|
||||
keyGeneration.hide();
|
||||
|
||||
enterButton.textContent = t('screens.login_password_view.text_006');
|
||||
const result = await authService.createAuthSession(currentLogin, keyBundle);
|
||||
@@ -156,6 +126,8 @@ export function render({ navigate }) {
|
||||
});
|
||||
state.loginDraft.login = result.login;
|
||||
state.loginDraft.password = '';
|
||||
// Clear the actual textarea as soon as login succeeds, before route change.
|
||||
passwordInput.clearPasswordField();
|
||||
state.loginDraft.passwordMode = 'single';
|
||||
state.loginDraft.passwordWords = emptyPasswordWords();
|
||||
resetRegistrationFlow();
|
||||
@@ -164,7 +136,7 @@ export function render({ navigate }) {
|
||||
setAuthInfo(t('screens.login_password_view.text_010', { value1: result.login }));
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
} catch (error) {
|
||||
overlay.style.display = 'none';
|
||||
keyGeneration.hide();
|
||||
const message = toUserMessage(error, t('screens.login_password_view.text_008'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message);
|
||||
@@ -178,7 +150,7 @@ export function render({ navigate }) {
|
||||
|
||||
enterButton.addEventListener('click', submit);
|
||||
passwordInput.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
@@ -192,9 +164,9 @@ export function render({ navigate }) {
|
||||
back: { label: '←', onClick: () => navigate('login-view') },
|
||||
}),
|
||||
panel,
|
||||
overlay,
|
||||
keyGeneration.overlay,
|
||||
);
|
||||
|
||||
window.setTimeout(() => passwordInput.focus(), 0);
|
||||
window.setTimeout(() => { passwordInput.resizePasswordField(); passwordInput.focus(); }, 0);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
// SHiNE Explorer V4: та же модель V3, но две статические Canvas 2D-плоскости.
|
||||
// В простое нет requestAnimationFrame, физики, SVG-фильтров и CSS-анимаций.
|
||||
import { buildAvatarInitials } from '../../components/avatar-image.js';
|
||||
import { state } from '../../state.js';
|
||||
import { buildArweaveDataUrl } from '../../services/arweave-file-service.js';
|
||||
import { resolvePublicFileUrl } from '../../services/public-file-service.js';
|
||||
import { PALETTES, ORB_DIAMETER, clamp, rgba, color, keyOf, edgeGradient, edgeCoreGradient, geometryFor } from './graph-style.js';
|
||||
|
||||
export const ZOOM_MIN = 0.55;
|
||||
export const ZOOM_MAX = 2.2;
|
||||
export const DIVE_ZOOM = 1.7;
|
||||
|
||||
// V4: стеклянная внешняя кромка V3 под непрозрачной фотографией; неон V3 на Canvas.
|
||||
const LONG_PRESS_MS = 480;
|
||||
const DRAG_SLOP = 8;
|
||||
const MAX_SPRITES_PER_FRAME = 16;
|
||||
const SPRITE_MEMORY_BUDGET = 96 * 1024 * 1024;
|
||||
const GLASS_URL = '/assets/glass_overlay_faithful.png';
|
||||
const GLASS_SCALE = 1.19; // V3 .fg-pngorb: размер накладки 119% от узла
|
||||
const PHOTO_RATIO = 0.78; // фотография 78% от стеклянного бокса, но рисуется ПОВЕРХ
|
||||
const BADGE_URL = '/assets/shine-official-badge.svg?v=2';
|
||||
|
||||
function makeSpriteCanvas(size) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = size; canvas.height = size;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function loadImage(src, notify) {
|
||||
const img = new Image();
|
||||
img.decoding = 'async';
|
||||
img.referrerPolicy = 'no-referrer';
|
||||
// Не устанавливаем crossOrigin: не все внешние Arweave/R2 шлюзы возвращают CORS.
|
||||
// Canvas используется только для отображения, а не для экспорта/readback.
|
||||
img.onload = () => notify(true, img);
|
||||
img.onerror = () => notify(false, img);
|
||||
img.src = src;
|
||||
return img;
|
||||
}
|
||||
|
||||
function avatarSource(node) {
|
||||
const direct = String(node.photo || '').trim();
|
||||
if (direct) return direct;
|
||||
if (typeof node.avatar === 'string') return node.avatar.trim();
|
||||
const txId = String(node.avatar?.ar || '').trim();
|
||||
if (!txId) return '';
|
||||
try {
|
||||
return buildArweaveDataUrl({ gateway: state?.entrySettings?.arweaveServer, txId }) || '';
|
||||
} catch { return ''; }
|
||||
}
|
||||
|
||||
export function createExplorerCanvasGraph({ stage, model, onCenterTap, onNodeTap, onNodeLongPress, onNodeMoveEnd } = {}) {
|
||||
if (!stage) throw new Error('createExplorerCanvasGraph: stage обязателен');
|
||||
const edgesCanvas = document.createElement('canvas');
|
||||
edgesCanvas.className = 'fg-canvas-v4 fg-canvas-v4--edges';
|
||||
edgesCanvas.setAttribute('aria-hidden', 'true');
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.className = 'fg-canvas-v4 fg-canvas-v4--nodes';
|
||||
canvas.setAttribute('role', 'img');
|
||||
const ectx = edgesCanvas.getContext('2d');
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ectx || !ctx) throw new Error('Canvas 2D недоступен');
|
||||
stage.append(edgesCanvas, canvas);
|
||||
const a11y = document.createElement('div');
|
||||
a11y.className = 'fg-a11y';
|
||||
a11y.setAttribute('role', 'region');
|
||||
stage.append(a11y);
|
||||
|
||||
let destroyed = false;
|
||||
let nodes = [];
|
||||
let nodeById = new Map();
|
||||
let focusId = '';
|
||||
let width = 1, height = 1, dpr = 1;
|
||||
let zoom = 1, camX = 0, camY = 0;
|
||||
let frame = 0;
|
||||
let edgesDirty = true;
|
||||
let palette = PALETTES.dark;
|
||||
let spriteScale = 1;
|
||||
let auraSprite = null;
|
||||
const spriteCache = new Map(); // id -> { key, scale, canvas }, меняется только при смене фотографии/LOD
|
||||
const photos = new Map(); // id -> { key, image, ready }
|
||||
let badge = null, glass = null;
|
||||
let badgeReady = false, glassReady = false;
|
||||
|
||||
const requestDraw = (redrawEdges = true) => {
|
||||
if (redrawEdges) edgesDirty = true;
|
||||
if (destroyed || frame) return;
|
||||
frame = requestAnimationFrame(() => { frame = 0; if (!destroyed) draw(); });
|
||||
};
|
||||
badge = loadImage(BADGE_URL, (ok) => { badgeReady = ok; requestDraw(false); });
|
||||
glass = loadImage(GLASS_URL, (ok) => { glassReady = ok; spriteCache.clear(); requestDraw(false); });
|
||||
|
||||
function setupPhoto(node) {
|
||||
const id = keyOf(node.id);
|
||||
const key = JSON.stringify([node.avatar || null, node.photo || '', node.login || '']);
|
||||
if (photos.get(id)?.key === key) return;
|
||||
const entry = { key, image: null, ready: false };
|
||||
photos.set(id, entry);
|
||||
spriteCache.delete(id);
|
||||
let url = avatarSource(node);
|
||||
if (!url && node.avatar?.pr && !node.avatar?.ar) {
|
||||
void resolvePublicFileUrl({ pr: String(node.avatar.pr), authorLogin: String(node.login || '') })
|
||||
.then((resolved) => { if (!destroyed && photos.get(id) === entry && resolved) start(resolved); })
|
||||
.catch(() => {});
|
||||
} else if (url) start(url);
|
||||
function start(src) {
|
||||
entry.image = loadImage(src, (ok, image) => {
|
||||
if (destroyed || photos.get(id) !== entry) return;
|
||||
entry.ready = ok && image.naturalWidth > 0;
|
||||
spriteCache.delete(id);
|
||||
requestDraw(false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function makeAura() {
|
||||
const c = makeSpriteCanvas(160);
|
||||
const a = c.getContext('2d');
|
||||
const g = a.createRadialGradient(80, 80, 15, 80, 80, 80);
|
||||
g.addColorStop(0, rgba(palette.shine, .50));
|
||||
g.addColorStop(.45, rgba(palette.shine, .23));
|
||||
g.addColorStop(1, rgba(palette.shine, 0));
|
||||
a.fillStyle = g; a.fillRect(0, 0, 160, 160);
|
||||
return c;
|
||||
}
|
||||
|
||||
function desiredSpriteScale() {
|
||||
const need = Math.max(1, dpr * zoom * 1.15);
|
||||
// Подготавливаем всех пользователей, поэтому масштаб также ограничен общим бюджетом памяти.
|
||||
const bytesPerScale = Math.max(1, nodes.length) * (ORB_DIAMETER * GLASS_SCALE) ** 2 * 4;
|
||||
const budgetScale = Math.max(1, Math.sqrt(SPRITE_MEMORY_BUDGET / bytesPerScale));
|
||||
const maxScale = Math.min(8, budgetScale);
|
||||
let candidate = 1;
|
||||
while (candidate * 2 <= maxScale && candidate < need) candidate *= 2;
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function spriteKey(node, photo) {
|
||||
return JSON.stringify([node.id, node.name, node.login, photo?.key, photo?.ready, glassReady, palette === PALETTES.light]);
|
||||
}
|
||||
|
||||
function buildSprite(node) {
|
||||
const photo = photos.get(keyOf(node.id));
|
||||
const key = spriteKey(node, photo);
|
||||
// Единый спрайт: стеклянная кромка снизу, полностью непрозрачный аватар сверху.
|
||||
// Отдельного красного/синего кольца категории НЕ рисуем.
|
||||
const side = Math.max(2, Math.ceil(ORB_DIAMETER * GLASS_SCALE * spriteScale));
|
||||
const sprite = makeSpriteCanvas(side);
|
||||
const g = sprite.getContext('2d');
|
||||
const center = side / 2;
|
||||
const photoRadius = center * PHOTO_RATIO;
|
||||
const diameter = photoRadius * 2;
|
||||
|
||||
// Непрозрачный фон между фотографией и стеклянным краем:
|
||||
// неон нижнего canvas не просвечивает через стеклянную сферу.
|
||||
g.fillStyle = palette.bg;
|
||||
g.beginPath(); g.arc(center, center, center - .5 * spriteScale, 0, Math.PI * 2); g.fill();
|
||||
if (glassReady && glass?.naturalWidth) {
|
||||
g.drawImage(glass, 0, 0, side, side);
|
||||
} else {
|
||||
// Минимальный резервный стеклянный край, если файл пока не загрузился.
|
||||
g.strokeStyle = rgba(palette.shine, .33);
|
||||
g.lineWidth = Math.max(1, spriteScale * 1.2);
|
||||
g.beginPath(); g.arc(center, center, center - g.lineWidth * 1.4, 0, 2 * Math.PI); g.stroke();
|
||||
}
|
||||
|
||||
// Фото В ПОСЛЕДНЮЮ ОЧЕРЕДЬ поверх самого стекла, без затенения бликами.
|
||||
g.save();
|
||||
g.beginPath(); g.arc(center, center, photoRadius, 0, Math.PI * 2); g.clip();
|
||||
g.fillStyle = palette.bg;
|
||||
g.fillRect(center - photoRadius, center - photoRadius, diameter, diameter);
|
||||
if (photo?.ready && photo.image?.naturalWidth) {
|
||||
const img = photo.image;
|
||||
const crop = Math.min(img.naturalWidth, img.naturalHeight);
|
||||
g.drawImage(img, (img.naturalWidth - crop) / 2, (img.naturalHeight - crop) / 2,
|
||||
crop, crop, center - photoRadius, center - photoRadius, diameter, diameter);
|
||||
} else {
|
||||
const initials = buildAvatarInitials({ login: node.login || node.id, firstName: node.name || '' });
|
||||
g.fillStyle = palette.text;
|
||||
g.textAlign = 'center'; g.textBaseline = 'middle';
|
||||
g.font = `600 ${Math.round(side * .24)}px system-ui, sans-serif`;
|
||||
g.fillText(initials, center, center, side * .58);
|
||||
}
|
||||
g.restore();
|
||||
|
||||
const result = { key, scale: spriteScale, canvas: sprite };
|
||||
spriteCache.set(keyOf(node.id), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function screenPoint(node) {
|
||||
return { x: width / 2 + camX + node.x * zoom, y: height / 2 + camY + node.y * zoom };
|
||||
}
|
||||
function nodeScreenPoint(node) {
|
||||
const p = screenPoint(node);
|
||||
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
|
||||
const box = canvas.getBoundingClientRect();
|
||||
const rect = { left: box.left + p.x - size / 2, top: box.top + p.y - size / 2,
|
||||
width: size, height: size, right: box.left + p.x + size / 2, bottom: box.top + p.y + size / 2 };
|
||||
return { x: box.left + p.x, y: rect.top, rect };
|
||||
}
|
||||
|
||||
// Неоновый композит из V3: мягкое размытое поле (16px / blur6),
|
||||
// размытая трубка (6px / blur2), сверху чёткое светлое ядро (2px).
|
||||
// Каждое размытие выполняется ОДИН раз для всех сияющих связей, а не для каждого ребра.
|
||||
const flareCanvas = makeSpriteCanvas(1);
|
||||
const tubeCanvas = makeSpriteCanvas(1);
|
||||
const flareCtx = flareCanvas.getContext('2d');
|
||||
const tubeCtx = tubeCanvas.getContext('2d');
|
||||
|
||||
function drawStroke(g, path, widthPx, strokeStyle, alpha, dash = null) {
|
||||
g.save();
|
||||
g.globalAlpha = alpha;
|
||||
g.lineWidth = widthPx;
|
||||
g.strokeStyle = strokeStyle;
|
||||
g.lineCap = 'round';
|
||||
g.lineJoin = 'round';
|
||||
if (dash) g.setLineDash(dash.map((v) => v * zoom));
|
||||
g.stroke(path);
|
||||
g.restore();
|
||||
}
|
||||
|
||||
function drawNormalEdge(g, path, geo, ref) {
|
||||
// V3: две аккуратные нити вместо двух тяжёлых цветных полос.
|
||||
const gradient = edgeGradient(g, geo, ref, palette);
|
||||
const strength = clamp(Number(ref.strength) || .5, 0, 1);
|
||||
drawStroke(g, path, (2.6 + strength * 1.4) * zoom, gradient, .22);
|
||||
drawStroke(g, path, 1.2 * zoom, gradient, .70);
|
||||
}
|
||||
|
||||
function edgePath(geo, shining, directed) {
|
||||
const path = new Path2D();
|
||||
path.moveTo(geo.x1, geo.y1);
|
||||
if (shining && !directed) {
|
||||
const dx = geo.x2 - geo.x1, dy = geo.y2 - geo.y1;
|
||||
const perpX = -geo.uy, perpY = geo.ux;
|
||||
const amp = Math.min(13, 5 + Math.hypot(dx, dy) * .05);
|
||||
const bowX = geo.cpx - geo.mx, bowY = geo.cpy - geo.my;
|
||||
path.bezierCurveTo(geo.x1 + dx / 3 + bowX + perpX * amp,
|
||||
geo.y1 + dy / 3 + bowY + perpY * amp,
|
||||
geo.x1 + dx * 2 / 3 + bowX - perpX * amp,
|
||||
geo.y1 + dy * 2 / 3 + bowY - perpY * amp,
|
||||
geo.x2, geo.y2);
|
||||
} else path.quadraticCurveTo(geo.cpx, geo.cpy, geo.x2, geo.y2);
|
||||
return path;
|
||||
}
|
||||
|
||||
function paintEdges() {
|
||||
// Вспомогательные холсты создаются один раз и переиспользуются; анимации нет.
|
||||
for (const g of [flareCtx, tubeCtx]) {
|
||||
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
g.clearRect(0, 0, width, height);
|
||||
}
|
||||
const origin = { x: width / 2 + camX, y: height / 2 + camY };
|
||||
const shiningEdges = [];
|
||||
for (const node of nodes) {
|
||||
for (const ref of node.edgeParents || []) {
|
||||
const parent = nodeById.get(keyOf(ref?.id));
|
||||
if (!parent || parent === node) continue;
|
||||
const geo = geometryFor(parent, node, zoom, origin, origin);
|
||||
const shining = Boolean(node.shining && parent.shining);
|
||||
const directed = ref.mutual === false;
|
||||
const path = edgePath(geo, shining, directed);
|
||||
if (!shining) {
|
||||
drawNormalEdge(ectx, path, geo, ref);
|
||||
continue;
|
||||
}
|
||||
shiningEdges.push({ path, geo, ref, directed });
|
||||
const dash = directed ? [20, 4] : null; // V3: только направленная сияющая связь пунктирная.
|
||||
drawStroke(flareCtx, path, 16 * zoom, edgeGradient(flareCtx, geo, ref, palette), .42, dash);
|
||||
drawStroke(tubeCtx, path, 6 * zoom, edgeGradient(tubeCtx, geo, ref, palette), .85, dash);
|
||||
}
|
||||
}
|
||||
if (!shiningEdges.length) return;
|
||||
// screen-подсветка и двухслойное размытие соответствуют CSS .fg-plasma-* в V3.
|
||||
// Нет резкой непрозрачной 14px-полосы — только светлая узкая сердцевина.
|
||||
ectx.save();
|
||||
ectx.globalCompositeOperation = 'screen';
|
||||
ectx.filter = `blur(${(6 * zoom).toFixed(2)}px)`;
|
||||
ectx.drawImage(flareCanvas, 0, 0, width, height);
|
||||
ectx.filter = `blur(${(2 * zoom).toFixed(2)}px)`;
|
||||
ectx.drawImage(tubeCanvas, 0, 0, width, height);
|
||||
ectx.filter = 'none';
|
||||
for (const { path, geo, ref, directed } of shiningEdges) {
|
||||
drawStroke(ectx, path, 2 * zoom, edgeCoreGradient(ectx, geo, ref, palette), 1,
|
||||
directed ? [20, 4] : null);
|
||||
}
|
||||
ectx.restore();
|
||||
}
|
||||
|
||||
function paintNodes() {
|
||||
if (!auraSprite) auraSprite = makeAura();
|
||||
let built = 0, needsBuild = false;
|
||||
// Весь свет под всеми аватарками, а не поверх соседних фотографий.
|
||||
for (const node of nodes) {
|
||||
if (!node.shining) continue;
|
||||
const { x, y } = screenPoint(node);
|
||||
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom * 1.95;
|
||||
ctx.drawImage(auraSprite, x - size / 2, y - size / 2, size, size);
|
||||
}
|
||||
// Все пользователи рисуются, в том числе за пределами экрана — по решению для V4.
|
||||
for (const node of nodes) {
|
||||
const { x, y } = screenPoint(node);
|
||||
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
|
||||
const id = keyOf(node.id);
|
||||
const cached = spriteCache.get(id);
|
||||
const photo = photos.get(id);
|
||||
const currentKey = spriteKey(node, photo);
|
||||
let sprite = cached;
|
||||
if (!cached || cached.key !== currentKey || cached.scale !== spriteScale) {
|
||||
if (built < MAX_SPRITES_PER_FRAME) { sprite = buildSprite(node); built += 1; }
|
||||
else needsBuild = true;
|
||||
}
|
||||
if (sprite) {
|
||||
const imageSize = size * GLASS_SCALE;
|
||||
ctx.drawImage(sprite.canvas, x - imageSize / 2, y - imageSize / 2, imageSize, imageSize);
|
||||
} else {
|
||||
ctx.fillStyle = rgba(color(palette, node.relationType), .8);
|
||||
ctx.beginPath(); ctx.arc(x, y, size / 2, 0, 2 * Math.PI); ctx.fill();
|
||||
}
|
||||
if (badgeReady && node.official) {
|
||||
const badgeSize = Math.max(12, size * .32);
|
||||
ctx.drawImage(badge, x - size / 2, y + size / 2 - badgeSize, badgeSize, badgeSize);
|
||||
}
|
||||
}
|
||||
// Подписи V2: компактные округлённые плашки без толстого контура текста.
|
||||
// Приоритет центра и близких, защита от пересечений и резервная позиция сверху.
|
||||
ctx.save();
|
||||
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
const fontFamily = getComputedStyle(stage).fontFamily || 'sans-serif';
|
||||
const occupied = nodes.map((node) => {
|
||||
const { x, y } = screenPoint(node);
|
||||
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
|
||||
return { left: x - r - 2, right: x + r + 2, top: y - r - 2, bottom: y + r + 2 };
|
||||
});
|
||||
const collides = (r) => occupied.some((other) =>
|
||||
r.left < other.right && r.right > other.left && r.top < other.bottom && r.bottom > other.top);
|
||||
const priority = (node) => node.id === focusId ? 0 :
|
||||
(node.relationType === 'close_friend' ? 1 : node.relationType === 'friend' ? 2 : 3) +
|
||||
Math.max(0, Number(node.distance) || 0) * 5;
|
||||
const ordered = [...nodes].sort((a, b) => priority(a) - priority(b) || a.id.localeCompare(b.id));
|
||||
const MAX_LABEL_CHARS = 18;
|
||||
for (const node of ordered) {
|
||||
const { x, y } = screenPoint(node);
|
||||
const isFocus = node.id === focusId;
|
||||
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
|
||||
if (!isFocus && r < 6.5) continue;
|
||||
const original = String(node.name || node.login || node.id).trim();
|
||||
const words = original.split(/\s+/).filter(Boolean);
|
||||
// Вторая версия показывает «Имя Ф.» для обычных участников и полное имя центра.
|
||||
const short = !isFocus && words.length >= 2 ? `${words[0]} ${words[1][0]}.` : original;
|
||||
const label = short.length > MAX_LABEL_CHARS ? `${short.slice(0, MAX_LABEL_CHARS - 1)}…` : short;
|
||||
const fontSize = Math.round(clamp((isFocus ? 13 : node.visualSmall ? 10.5 : 12) * zoom,
|
||||
isFocus ? 12.5 : node.visualSmall ? 10 : 11, isFocus ? 16 : node.visualSmall ? 13 : 15) * 2) / 2;
|
||||
ctx.font = `${isFocus ? 700 : 500} ${fontSize}px ${fontFamily}`;
|
||||
const labelW = ctx.measureText(label).width;
|
||||
const padX = fontSize * .5;
|
||||
const w = labelW + padX * 2;
|
||||
const h = Math.round(fontSize * 1.5);
|
||||
const gap = isFocus ? 5 : 3;
|
||||
let y0 = y + r + gap;
|
||||
let bounds = { left: x - w / 2 - 2, right: x + w / 2 + 2, top: y0 - 1, bottom: y0 + h + 1 };
|
||||
if (collides(bounds)) {
|
||||
const above = y - r - gap - h;
|
||||
const alternate = { ...bounds, top: above - 1, bottom: above + h + 1 };
|
||||
if (!collides(alternate)) { y0 = above; bounds = alternate; }
|
||||
else if (!isFocus) continue;
|
||||
}
|
||||
occupied.push(bounds);
|
||||
const x0 = x - w / 2;
|
||||
ctx.fillStyle = palette === PALETTES.light ? 'rgba(230,237,243,.88)' : 'rgba(23,36,49,.82)';
|
||||
ctx.beginPath();
|
||||
if (ctx.roundRect) ctx.roundRect(x0, y0, w, h, h / 2);
|
||||
else ctx.rect(x0, y0, w, h);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = palette.text;
|
||||
ctx.fillText(label, x, y0 + h / 2 + .5);
|
||||
}
|
||||
ctx.restore();
|
||||
return needsBuild;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (width <= 0 || height <= 0) return;
|
||||
if (edgesDirty) {
|
||||
ectx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ectx.clearRect(0, 0, width, height);
|
||||
paintEdges();
|
||||
edgesDirty = false;
|
||||
}
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
if (paintNodes()) requestDraw(false);
|
||||
}
|
||||
|
||||
function updateSize() {
|
||||
const rect = stage.getBoundingClientRect();
|
||||
const w = Math.max(1, Math.round(rect.width || stage.clientWidth || 1));
|
||||
const h = Math.max(1, Math.round(rect.height || stage.clientHeight || 1));
|
||||
const ratio = clamp(window.devicePixelRatio || 1, 1, 2.5);
|
||||
if (w === width && h === height && ratio === dpr) return;
|
||||
width = w; height = h; dpr = ratio;
|
||||
for (const element of [canvas, edgesCanvas, flareCanvas, tubeCanvas]) {
|
||||
element.width = Math.ceil(w * dpr); element.height = Math.ceil(h * dpr);
|
||||
if (element === canvas || element === edgesCanvas) {
|
||||
element.style.width = `${w}px`; element.style.height = `${h}px`;
|
||||
}
|
||||
}
|
||||
const nextScale = desiredSpriteScale();
|
||||
if (nextScale !== spriteScale) spriteScale = nextScale;
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function setModel(next) {
|
||||
const oldFocus = focusId;
|
||||
focusId = keyOf(next?.focusId);
|
||||
const seen = new Set();
|
||||
nodes = (Array.isArray(next?.nodes) ? next.nodes : []).map((raw) => {
|
||||
const id = keyOf(raw.id);
|
||||
seen.add(id);
|
||||
const node = { ...raw, id, x: Number(raw.layoutX) || 0, y: Number(raw.layoutY) || 0 };
|
||||
setupPhoto(node);
|
||||
return node;
|
||||
});
|
||||
nodeById = new Map(nodes.map((n) => [n.id, n]));
|
||||
for (const id of photos.keys()) if (!seen.has(id)) { photos.delete(id); spriteCache.delete(id); }
|
||||
for (const id of spriteCache.keys()) if (!seen.has(id)) spriteCache.delete(id);
|
||||
if (oldFocus && focusId !== oldFocus) { camX = 0; camY = 0; }
|
||||
spriteScale = desiredSpriteScale();
|
||||
a11y.textContent = `Граф связей: ${nodes.length} пользователей. Центр: ${nodes.find((n) => n.id === focusId)?.name || focusId}.`;
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function updateZoom(next, sx = width / 2, sy = height / 2) {
|
||||
const value = clamp(next, ZOOM_MIN, ZOOM_MAX);
|
||||
if (Math.abs(value - zoom) < .00001) return;
|
||||
const factor = value / zoom;
|
||||
camX = sx - width / 2 - (sx - width / 2 - camX) * factor;
|
||||
camY = sy - height / 2 - (sy - height / 2 - camY) * factor;
|
||||
zoom = value;
|
||||
spriteScale = desiredSpriteScale();
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function hitNode(clientX, clientY) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const sx = clientX - rect.left, sy = clientY - rect.top;
|
||||
for (let i = nodes.length - 1; i >= 0; i -= 1) {
|
||||
const node = nodes[i];
|
||||
const p = screenPoint(node);
|
||||
const r = Math.max(8, ORB_DIAMETER / 2 * (node.visualSmall ? .5 : 1) * zoom);
|
||||
if (Math.hypot(sx - p.x, sy - p.y) <= r) return node;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const pointers = new Map();
|
||||
let gesture = null, pinchDistance = 0, longTimer = 0;
|
||||
const clearLong = () => { if (longTimer) window.clearTimeout(longTimer); longTimer = 0; };
|
||||
function pointerDown(e) {
|
||||
if (e.button !== undefined && e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
try { canvas.setPointerCapture(e.pointerId); } catch {}
|
||||
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
clearLong();
|
||||
if (pointers.size >= 2) {
|
||||
const pts = [...pointers.values()];
|
||||
pinchDistance = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
|
||||
gesture = { pinching: true };
|
||||
return;
|
||||
}
|
||||
const node = hitNode(e.clientX, e.clientY);
|
||||
gesture = { id: e.pointerId, x: e.clientX, y: e.clientY, camX, camY,
|
||||
node, nodeX: node?.x || 0, nodeY: node?.y || 0, moved: false, longFired: false };
|
||||
if (node && typeof onNodeLongPress === 'function') {
|
||||
longTimer = window.setTimeout(() => {
|
||||
if (!gesture || gesture.moved || gesture.pinching || destroyed) return;
|
||||
gesture.longFired = true;
|
||||
onNodeLongPress(node, nodeScreenPoint(node));
|
||||
}, LONG_PRESS_MS);
|
||||
}
|
||||
}
|
||||
function pointerMove(e) {
|
||||
if (pointers.has(e.pointerId)) pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (pointers.size >= 2 && gesture?.pinching) {
|
||||
const pts = [...pointers.values()];
|
||||
const dist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
updateZoom(zoom * dist / (pinchDistance || dist), (pts[0].x + pts[1].x) / 2 - rect.left,
|
||||
(pts[0].y + pts[1].y) / 2 - rect.top);
|
||||
pinchDistance = dist;
|
||||
return;
|
||||
}
|
||||
if (!gesture || gesture.id !== e.pointerId || gesture.longFired) {
|
||||
canvas.classList.toggle('is-over-node', Boolean(hitNode(e.clientX, e.clientY)));
|
||||
return;
|
||||
}
|
||||
const dx = e.clientX - gesture.x, dy = e.clientY - gesture.y;
|
||||
if (Math.hypot(dx, dy) > DRAG_SLOP) { gesture.moved = true; clearLong(); }
|
||||
if (!gesture.moved) return;
|
||||
if (gesture.node) {
|
||||
gesture.node.x = gesture.nodeX + dx / zoom;
|
||||
gesture.node.y = gesture.nodeY + dy / zoom;
|
||||
} else { camX = gesture.camX + dx; camY = gesture.camY + dy; }
|
||||
requestDraw();
|
||||
}
|
||||
function pointerUp(e) {
|
||||
pointers.delete(e.pointerId);
|
||||
clearLong();
|
||||
try { canvas.releasePointerCapture(e.pointerId); } catch {}
|
||||
if (gesture?.pinching) { if (pointers.size < 2) gesture = null; return; }
|
||||
if (!gesture || gesture.id !== e.pointerId) return;
|
||||
const completed = gesture;
|
||||
gesture = null;
|
||||
if (completed.longFired) return;
|
||||
if (completed.moved) {
|
||||
if (completed.node) onNodeMoveEnd?.(completed.node, { x: completed.node.x, y: completed.node.y });
|
||||
return;
|
||||
}
|
||||
if (!completed.node) return;
|
||||
if (completed.node.id === focusId) onCenterTap?.(completed.node, nodeScreenPoint(completed.node));
|
||||
else onNodeTap?.(completed.node);
|
||||
}
|
||||
function onCancel(e) { pointers.delete(e.pointerId); clearLong(); gesture = null; }
|
||||
function onWheel(e) {
|
||||
e.preventDefault();
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
updateZoom(zoom * Math.exp(-e.deltaY * .0016), e.clientX - rect.left, e.clientY - rect.top);
|
||||
}
|
||||
function onContextMenu(e) {
|
||||
e.preventDefault();
|
||||
const node = hitNode(e.clientX, e.clientY);
|
||||
if (node) onNodeLongPress?.(node, nodeScreenPoint(node));
|
||||
}
|
||||
function onTheme() {
|
||||
const next = document.documentElement.dataset.theme === 'light' ? PALETTES.light : PALETTES.dark;
|
||||
if (palette === next) return;
|
||||
palette = next; spriteCache.clear(); auraSprite = null; requestDraw();
|
||||
}
|
||||
|
||||
canvas.addEventListener('pointerdown', pointerDown);
|
||||
canvas.addEventListener('pointermove', pointerMove);
|
||||
canvas.addEventListener('pointerup', pointerUp);
|
||||
canvas.addEventListener('pointercancel', onCancel);
|
||||
canvas.addEventListener('lostpointercapture', onCancel);
|
||||
canvas.addEventListener('wheel', onWheel, { passive: false });
|
||||
canvas.addEventListener('contextmenu', onContextMenu);
|
||||
const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(updateSize) : null;
|
||||
observer?.observe(stage);
|
||||
window.addEventListener('resize', updateSize);
|
||||
const themeObserver = typeof MutationObserver === 'function' ?
|
||||
new MutationObserver(onTheme) : null;
|
||||
themeObserver?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||
onTheme();
|
||||
updateSize();
|
||||
setModel(model);
|
||||
|
||||
return {
|
||||
setModel, nodeScreenPoint,
|
||||
getFocusNode: () => nodeById.get(focusId) || null,
|
||||
recenter: () => { camX = 0; camY = 0; updateZoom(DIVE_ZOOM); requestDraw(); },
|
||||
destroy: () => {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
clearLong(); pointers.clear();
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
observer?.disconnect(); themeObserver?.disconnect();
|
||||
window.removeEventListener('resize', updateSize);
|
||||
canvas.removeEventListener('pointerdown', pointerDown);
|
||||
canvas.removeEventListener('pointermove', pointerMove);
|
||||
canvas.removeEventListener('pointerup', pointerUp);
|
||||
canvas.removeEventListener('pointercancel', onCancel);
|
||||
canvas.removeEventListener('lostpointercapture', onCancel);
|
||||
canvas.removeEventListener('wheel', onWheel);
|
||||
canvas.removeEventListener('contextmenu', onContextMenu);
|
||||
photos.clear(); spriteCache.clear();
|
||||
edgesCanvas.remove(); canvas.remove(); a11y.remove();
|
||||
},
|
||||
// Диагностика без зависимости от структуры canvas.
|
||||
debugState: () => ({ nodeCount: nodes.length, zoom, spriteScale, cachedSprites: spriteCache.size, frameQueued: !!frame }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Цвета и геометрия V4: чистые функции без DOM и загрузки картинок.
|
||||
export const ORB_DIAMETER = 58;
|
||||
export const PALETTES = {
|
||||
dark: {
|
||||
family: [255, 159, 94], friend: [120, 179, 255], close_friend: [255, 76, 92],
|
||||
business: [190, 150, 255], contact: [170, 190, 220], self: [140, 240, 255],
|
||||
shine: [0, 229, 255], text: '#e7ebf3', shadow: 'rgba(0, 0, 0, .78)', bg: '#172431',
|
||||
},
|
||||
light: {
|
||||
family: [184, 92, 20], friend: [38, 96, 196], close_friend: [214, 38, 55],
|
||||
business: [108, 62, 200], contact: [92, 98, 121], self: [6, 86, 122],
|
||||
shine: [10, 127, 179], text: '#202332', shadow: 'rgba(255, 255, 255, .86)', bg: '#e6edf3',
|
||||
},
|
||||
};
|
||||
|
||||
export const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
|
||||
export const rgba = (rgb, alpha = 1) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${alpha})`;
|
||||
export const color = (palette, type) => palette[type] || palette.contact;
|
||||
export const keyOf = (id) => String(id ?? '').toLowerCase();
|
||||
|
||||
export function hash01(value) {
|
||||
let h = 2166136261;
|
||||
for (const ch of String(value)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); }
|
||||
return (h >>> 0) / 4294967296;
|
||||
}
|
||||
// Градиент на концах кривой: исходящий тип -> обратный тип (если он известен).
|
||||
// У одностороннего отношения линия затухает к адресату, без бегущих штрихов.
|
||||
export function edgeGradient(ctx, geometry, ref, palette) {
|
||||
const forward = color(palette, ref.relationType || 'friend');
|
||||
const reverse = color(palette, ref.reverseRelationType || ref.relationType || 'friend');
|
||||
const grad = ctx.createLinearGradient(geometry.x1, geometry.y1, geometry.x2, geometry.y2);
|
||||
grad.addColorStop(0, rgba(forward, 0.98));
|
||||
grad.addColorStop(1, rgba(reverse, ref.mutual === false ? 0.035 : 0.98));
|
||||
return grad;
|
||||
}
|
||||
// V3 рисует светлую сердцевину, а не ещё один толстый насыщенный цветной слой.
|
||||
// Здесь слегка высветляем цвет для сохранения сине-красного перехода взаимной связи.
|
||||
export function edgeCoreGradient(ctx, geometry, ref, palette) {
|
||||
const tint = (rgb, alpha) => rgba(rgb.map((v) => Math.round(v * .36 + 255 * .64)), alpha);
|
||||
const forward = color(palette, ref.relationType || 'friend');
|
||||
const reverse = color(palette, ref.reverseRelationType || ref.relationType || 'friend');
|
||||
const grad = ctx.createLinearGradient(geometry.x1, geometry.y1, geometry.x2, geometry.y2);
|
||||
grad.addColorStop(0, tint(forward, .98));
|
||||
grad.addColorStop(1, tint(reverse, ref.mutual === false ? .035 : .98));
|
||||
return grad;
|
||||
}
|
||||
|
||||
export function geometryFor(parent, child, zoom, cx, cy) {
|
||||
const fx = cx.x + parent.x * zoom, fy = cx.y + parent.y * zoom;
|
||||
const tx = cx.x + child.x * zoom, ty = cx.y + child.y * zoom;
|
||||
const dx = tx - fx, dy = ty - fy;
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
const ux = dx / len, uy = dy / len;
|
||||
const startR = ORB_DIAMETER * (parent.visualSmall ? .25 : .5) * zoom;
|
||||
const endR = ORB_DIAMETER * (child.visualSmall ? .25 : .5) * zoom;
|
||||
const x1 = fx + ux * startR, y1 = fy + uy * startR;
|
||||
const x2 = tx - ux * endR, y2 = ty - uy * endR;
|
||||
const mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
|
||||
const bow = clamp(Math.hypot(x2 - x1, y2 - y1) * .10, 7, 22) *
|
||||
(hash01(`${parent.id}|${child.id}|edge`) > .5 ? 1 : -1);
|
||||
const cpx = mx - uy * bow * 2, cpy = my + ux * bow * 2;
|
||||
return { x1, y1, x2, y2, cpx, cpy, ux, uy, mx, my, bow };
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Экран V4 использует ту же модель/состояние/фильтры, что и V3.
|
||||
import { pageMeta, renderExplorer } from '../network-explorer/network-view.js';
|
||||
export { pageMeta };
|
||||
export function render(context = {}) {
|
||||
return renderExplorer(context, { canvas: true });
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { authService, state } from '../../state.js';
|
||||
import { makeProfileRoute, makeProfileLinksRoute } from '../../services/shine-routes.js';
|
||||
import { CONNECTIONS_GRAPH_CHANGED } from '../../services/connections-graph-cache.js';
|
||||
import { createForceGraph } from '../network-legacy/force-graph.js';
|
||||
import { createExplorerCanvasGraph } from '../network-canvas-v4/graph-renderer.js';
|
||||
import { openNodeMenu } from '../network-legacy/node-menu.js';
|
||||
import { createExplorerGraph, keyOf, EXPLORER_DEFAULT_DEPTH, EXPLORER_MAX_DEPTH } from './graph-model.js';
|
||||
import { getExplorerGraph, readExplorerCachedGraphs, clearExplorerGraphCache, explorerCacheScope, explorerGraphSavedAt } from './graph-cache.js';
|
||||
@@ -33,12 +34,24 @@ function hash01(value) {
|
||||
return (h >>> 0) / 4294967296;
|
||||
}
|
||||
|
||||
// V3 state survives switching between tabs; long-term graph responses reside in IndexedDB.
|
||||
// V3/V4 сохраняют исследование при переключении версий внутри вкладки.
|
||||
// Новый вход через нижнюю кнопку «Связи» очищает карту и IndexedDB-графы.
|
||||
let retained = null;
|
||||
let resetBarrier = Promise.resolve();
|
||||
export function resetExplorerOnTabEntry() {
|
||||
retained = null;
|
||||
// Новые загрузки обязаны дождаться очистки, иначе IndexedDB вернёт старую карту.
|
||||
resetBarrier = resetBarrier.catch(() => {}).then(() => clearExplorerGraphCache());
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome } = {}) {
|
||||
export function render(context = {}) {
|
||||
return renderExplorer(context);
|
||||
}
|
||||
|
||||
// Общие для V3 и V4 поиск, кэш, BFS, фильтры и жизненный цикл страницы.
|
||||
export function renderExplorer({ navigate, route, chrome } = {}, { canvas = false } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'network-screen network-explorer';
|
||||
screen.className = `network-screen network-explorer${canvas ? ' network-explorer--canvas' : ''}`;
|
||||
const stage = document.createElement('div');
|
||||
stage.className = 'network-stage';
|
||||
const board = document.createElement('div');
|
||||
@@ -137,7 +150,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
layoutY: session.positions.get(node.id)?.y || 0, fixedLayout: true,
|
||||
}));
|
||||
if (engine) engine.setModel(model);
|
||||
else engine = createForceGraph({
|
||||
else engine = (canvas ? createExplorerCanvasGraph : createForceGraph)({
|
||||
stage: board, model, explorerMode: true,
|
||||
onNodeTap: (node) => { void load(node.login, true); },
|
||||
onCenterTap: (node) => nodeMenu(node, false),
|
||||
@@ -157,11 +170,12 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
});
|
||||
}
|
||||
function nodeMenu(node, long = false, point = null) {
|
||||
const rect = node?.el?.getBoundingClientRect?.();
|
||||
const canvasPoint = canvas ? engine?.nodeScreenPoint?.(node) : null;
|
||||
const rect = node?.el?.getBoundingClientRect?.() || canvasPoint?.rect;
|
||||
openNodeMenu({
|
||||
login: normalizeLogin(node?.login), displayName: String(node?.name || '').trim(),
|
||||
relationType: node?.relationType,
|
||||
point: point || (rect ? { x: rect.left + rect.width / 2, y: rect.top, rect } : undefined),
|
||||
point: point || canvasPoint || (rect ? { x: rect.left + rect.width / 2, y: rect.top, rect } : undefined),
|
||||
actions: [
|
||||
{ label: t(long ? 'screens.network_view.text_006' : 'screens.network_view.text_004'), onClick: () => navigate?.(profileRoute(node?.login)) },
|
||||
{ label: t(long ? 'screens.network_view.text_007' : 'screens.network_view.text_005'), onClick: () => navigate?.(`chat/${encodeURIComponent(normalizeLogin(node?.login))}`) },
|
||||
@@ -446,17 +460,21 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
searchClose?.();
|
||||
// TopBar lifetime owned by AppShell, not this screen.
|
||||
};
|
||||
// Восстановление уже открытых веток из IndexedDB (без сетевых запросов).
|
||||
// Первую карту показываем сразу, восстановление идёт параллельно.
|
||||
void readExplorerCachedGraphs(scope).then((entries) => {
|
||||
// Кэш графов восстанавливаем только после завершения возможного сброса вкладки.
|
||||
// Фотографии и кэш изображений сброс не затрагивает.
|
||||
void resetBarrier.then(async () => {
|
||||
if (disposed || session !== retained) return;
|
||||
const entries = await readExplorerCachedGraphs(scope);
|
||||
if (disposed || cacheWasCleared || session !== retained) return;
|
||||
entries.forEach((entry) => {
|
||||
const login = entry?.graph?.login || entry?.key?.slice(scope.length + 1);
|
||||
if (login && !session.graph.isFresh(login)) session.graph.add(entry.graph, login, entry.savedAt);
|
||||
});
|
||||
scheduleDraw();
|
||||
if (centerLogin) void load(centerLogin);
|
||||
else window.setTimeout(() => { if (!disposed) openSearchModal(); }, 0);
|
||||
}).catch((error) => {
|
||||
if (!disposed) { console.warn('[Network explorer] Cache reset/read failed', error); if (centerLogin) void load(centerLogin); }
|
||||
});
|
||||
if (centerLogin) void load(centerLogin);
|
||||
else window.setTimeout(() => { if (!disposed) openSearchModal(); }, 0);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -2,18 +2,23 @@ import { t, th } from '../i18n/index.js';
|
||||
import * as modernNetworkView from './network-view.js';
|
||||
import * as legacyNetworkView from './network-legacy/network-view.js';
|
||||
import * as explorerNetworkView from './network-explorer/network-view.js';
|
||||
import * as explorerCanvasView from './network-canvas-v4/network-view.js';
|
||||
|
||||
const NETWORK_VERSION_STORAGE_KEY = 'shine.network.version';
|
||||
const MODES = new Set(['legacy', 'modern', 'explorer']);
|
||||
const MODES = new Set(['legacy', 'modern', 'explorer', 'explorer-canvas']);
|
||||
const DEFAULT_MODE = 'explorer-canvas';
|
||||
|
||||
// Нижняя вкладка сбрасывает только исследованный граф V3/V4, не изображения и не V1/V2.
|
||||
window.addEventListener('shine:network-tab-enter', explorerNetworkView.resetExplorerOnTabEntry);
|
||||
|
||||
export const pageMeta = modernNetworkView.pageMeta;
|
||||
|
||||
function selectedMode() {
|
||||
try {
|
||||
const saved = window.localStorage.getItem(NETWORK_VERSION_STORAGE_KEY);
|
||||
return MODES.has(saved) ? saved : 'modern';
|
||||
return MODES.has(saved) ? saved : DEFAULT_MODE;
|
||||
} catch {
|
||||
return 'modern';
|
||||
return DEFAULT_MODE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,10 +41,11 @@ function createModeSwitcher(mode, navigate) {
|
||||
<option value="legacy">${th('screens.network_version_switcher.text_002')}</option>
|
||||
<option value="modern">${th('screens.network_version_switcher.text_003')}</option>
|
||||
<option value="explorer">${th('screens.network_version_switcher.text_005')}</option>
|
||||
<option value="explorer-canvas">V4 · Canvas</option>
|
||||
`;
|
||||
select.value = mode;
|
||||
select.addEventListener('change', () => {
|
||||
const nextMode = MODES.has(select.value) ? select.value : 'modern';
|
||||
const nextMode = MODES.has(select.value) ? select.value : DEFAULT_MODE;
|
||||
saveMode(nextMode);
|
||||
navigate?.('network-view');
|
||||
});
|
||||
@@ -49,7 +55,7 @@ function createModeSwitcher(mode, navigate) {
|
||||
|
||||
export function render(context = {}) {
|
||||
const mode = selectedMode();
|
||||
const implementation = mode === 'legacy' ? legacyNetworkView : (mode === 'explorer' ? explorerNetworkView : modernNetworkView);
|
||||
const implementation = mode === 'legacy' ? legacyNetworkView : (mode === 'explorer' ? explorerNetworkView : (mode === 'explorer-canvas' ? explorerCanvasView : modernNetworkView));
|
||||
const screen = implementation.render(context);
|
||||
screen.classList.add(`network-screen--${mode}`);
|
||||
|
||||
|
||||
@@ -57,6 +57,24 @@ function actionLabel(item, activeTab) {
|
||||
: eventActionLabel(item.sourceMsgSubType, gender);
|
||||
}
|
||||
|
||||
function reciprocalRelationKind(item) {
|
||||
return Number(item?.connectionTypeCode ?? item?.sourceMsgSubType) === CONNECTION_CLOSE_FRIEND
|
||||
? 'close_friend'
|
||||
: 'friend';
|
||||
}
|
||||
|
||||
function reciprocalRelationLabel(kind) {
|
||||
return kind === 'close_friend'
|
||||
? t('screens.notifications_view.text_072')
|
||||
: t('screens.notifications_view.text_009');
|
||||
}
|
||||
|
||||
function reciprocalRelationSuccessLabel(kind) {
|
||||
return kind === 'close_friend'
|
||||
? t('screens.notifications_view.text_073')
|
||||
: t('screens.notifications_view.text_015');
|
||||
}
|
||||
|
||||
export const pageMeta = { id: 'notifications-view', get title() { return t('screens.notifications_view.text_001'); } };
|
||||
|
||||
function normalizeItem(item) {
|
||||
@@ -192,10 +210,19 @@ function renderHead(item) {
|
||||
|| item.sourceLogin || t('screens.notifications_view.text_030');
|
||||
const head = document.createElement('div');
|
||||
head.className = 'notification-card__head';
|
||||
const identity = document.createElement('div');
|
||||
identity.className = 'notification-card__identity';
|
||||
const name = document.createElement('strong');
|
||||
name.className = 'notification-card__name';
|
||||
name.textContent = fullName;
|
||||
head.append(name);
|
||||
identity.append(name);
|
||||
if (item.sourceLogin) {
|
||||
const login = document.createElement('span');
|
||||
login.className = 'notification-card__login';
|
||||
login.textContent = item.sourceLogin;
|
||||
identity.append(login);
|
||||
}
|
||||
head.append(identity);
|
||||
const time = document.createElement('span');
|
||||
time.className = 'notification-card__time';
|
||||
time.textContent = formatListTime(item.createdAtMs);
|
||||
@@ -301,8 +328,7 @@ function renderItem(item, activeTab, navigate) {
|
||||
function refreshItemRow(row, item, activeTab) {
|
||||
if (!row?.isConnected) return;
|
||||
row.querySelector('.notification-avatar')?.replaceWith(renderAvatar(item));
|
||||
const name = row.querySelector('.notification-card__name');
|
||||
if (name) name.textContent = renderHead(item).querySelector('.notification-card__name').textContent;
|
||||
row.querySelector('.notification-card__head')?.replaceWith(renderHead(item));
|
||||
const action = row.querySelector('.notification-card__action');
|
||||
if (action && activeTab !== 'replies') action.textContent = actionLabel(item, activeTab);
|
||||
if (activeTab === 'replies' && item.engagement && !row.querySelector('.notification-engagement')) {
|
||||
@@ -453,24 +479,25 @@ export function render({ navigate, chrome } = {}) {
|
||||
const row = rowByItem.get(item);
|
||||
const body = row?.querySelector('.notification-card__body');
|
||||
if (!body) continue;
|
||||
const kind = reciprocalRelationKind(item);
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'secondary-btn notification-card__answer';
|
||||
button.textContent = t('screens.notifications_view.text_009');
|
||||
button.textContent = reciprocalRelationLabel(kind);
|
||||
button.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
button.disabled = true;
|
||||
button.textContent = t('screens.notifications_view.text_010');
|
||||
try {
|
||||
await authService.setUserRelation({ login: self, toLogin: login, kind: 'friend', enabled: true, storagePwd: state.session.storagePwdInMemory });
|
||||
await authService.setUserRelation({ login: self, toLogin: login, kind, enabled: true, storagePwd: state.session.storagePwdInMemory });
|
||||
const done = document.createElement('span');
|
||||
done.className = 'notification-card__answered';
|
||||
done.innerHTML = `${iconHtml('check')}<span>${th('screens.notifications_view.text_046')}</span>`;
|
||||
done.innerHTML = `${iconHtml('check')}<span>${th(reciprocalRelationSuccessLabel(kind))}</span>`;
|
||||
button.replaceWith(done);
|
||||
showToast(t('screens.notifications_view.text_015'));
|
||||
showToast(reciprocalRelationSuccessLabel(kind));
|
||||
} catch (error) {
|
||||
button.disabled = false;
|
||||
button.textContent = t('screens.notifications_view.text_011');
|
||||
button.textContent = reciprocalRelationLabel(kind);
|
||||
showToast(toUserMessage(error, t('screens.notifications_view.text_016')), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createVisiblePasswordField } from '../components/visible-password-field.js';
|
||||
import { createVisiblePasswordField, createExpandablePasswordTextarea } from '../components/visible-password-field.js';
|
||||
import { createSecretGenerationOverlay } from '../components/secret-generation-overlay.js';
|
||||
import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js';
|
||||
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
||||
import { authService, clearAuthMessages, clearRegistrationDraft, state } from '../state.js';
|
||||
@@ -18,7 +19,8 @@ export function render({ navigate }) {
|
||||
const body = document.createElement('div');
|
||||
body.className = 'card stack registration-form signup-wizard__body';
|
||||
const header = createTopBar({ title: t('screens.register_view.text_002'), back: { label: '←', onClick: goBack } });
|
||||
screen.append(header, body);
|
||||
const keyGeneration = createSecretGenerationOverlay();
|
||||
screen.append(header, body, keyGeneration.overlay);
|
||||
|
||||
let namespaces = [];
|
||||
let isLoading = true;
|
||||
@@ -143,14 +145,21 @@ export function render({ navigate }) {
|
||||
const labelText = document.createElement('span');
|
||||
labelText.className = 'field-label';
|
||||
labelText.textContent = t('screens.register_view.text_031', { value1: PASSWORD_MAX_LENGTH });
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input';
|
||||
input.type = 'text';
|
||||
const input = createExpandablePasswordTextarea();
|
||||
input.autocomplete = 'new-password';
|
||||
input.maxLength = PASSWORD_MAX_LENGTH;
|
||||
input.placeholder = t('screens.register_view.text_009');
|
||||
input.value = draft.password || '';
|
||||
label.append(labelText, createVisiblePasswordField(input));
|
||||
// Never repopulate a successfully submitted secret on returning to this step.
|
||||
input.value = '';
|
||||
const passwordCount = document.createElement('span');
|
||||
passwordCount.className = 'password-length-hint';
|
||||
passwordCount.setAttribute('aria-live', 'off');
|
||||
const refreshPasswordCount = () => {
|
||||
passwordCount.textContent = t('screens.register_view.password_counter', { value1: input.value.length, value2: PASSWORD_MAX_LENGTH });
|
||||
};
|
||||
label.append(labelText, createVisiblePasswordField(input), passwordCount);
|
||||
refreshPasswordCount();
|
||||
requestAnimationFrame(() => input.resizePasswordField());
|
||||
const guidance = document.createElement('div');
|
||||
guidance.className = 'signup-guidance';
|
||||
guidance.innerHTML = `
|
||||
@@ -167,7 +176,13 @@ export function render({ navigate }) {
|
||||
next.className = 'primary-btn signup-next';
|
||||
next.type = 'button';
|
||||
next.textContent = t('screens.register_view.text_010');
|
||||
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; });
|
||||
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; refreshPasswordCount(); });
|
||||
input.addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
next.click();
|
||||
}
|
||||
});
|
||||
next.addEventListener('click', async () => {
|
||||
const value = input.value;
|
||||
if (value.length < 1 || value.length > PASSWORD_MAX_LENGTH) {
|
||||
@@ -188,9 +203,13 @@ export function render({ navigate }) {
|
||||
}
|
||||
const revision = inputRevision;
|
||||
const thisRequest = ++requestId;
|
||||
const needsGeneration = draft.password !== value || !draft.preGeneratedKeyBundle;
|
||||
next.disabled = true;
|
||||
status.textContent = t('screens.register_view.text_013');
|
||||
status.textContent = '';
|
||||
if (needsGeneration) keyGeneration.show();
|
||||
try {
|
||||
// Дать браузеру отрисовать заставку до тяжёлого KDF.
|
||||
if (needsGeneration) await new Promise(resolve => setTimeout(resolve, 40));
|
||||
const changed = draft.password !== value;
|
||||
draft.password = value;
|
||||
if (changed) draft.preGeneratedKeyBundle = null;
|
||||
@@ -198,10 +217,14 @@ export function render({ navigate }) {
|
||||
if (!screen.isConnected || thisRequest !== requestId) return;
|
||||
if (revision !== inputRevision) throw new Error(t('screens.register_view.text_027'));
|
||||
draft.preGeneratedKeyBundle = bundle;
|
||||
// Hide the password before navigation to prevent a visible flash.
|
||||
input.clearPasswordField();
|
||||
refreshPasswordCount();
|
||||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||||
} catch (error) {
|
||||
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || t('screens.register_view.text_028');
|
||||
} finally {
|
||||
keyGeneration.hide();
|
||||
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { resetRegistrationFlow, state } from '../state.js';
|
||||
import { getRegistrationNamespaces } from '../services/registration-v2-api.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-choice-view', get title() { return t('screens.registration_choice_view.text_001'); }, showAppChrome: false };
|
||||
|
||||
@@ -55,23 +56,31 @@ export function render({ navigate }) {
|
||||
box.append(top, description, list, action);
|
||||
return box;
|
||||
}
|
||||
screen.append(
|
||||
createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } }),
|
||||
title, intro,
|
||||
card({
|
||||
const topBar = createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } });
|
||||
const plans = document.createElement('div');
|
||||
plans.className = 'stack';
|
||||
const paidCard = card({
|
||||
type: 'paid', icon: '◇', heading: t('screens.registration_choice_view.text_005'),
|
||||
price: t('screens.registration_choice_view.text_007'),
|
||||
lead: t('screens.registration_choice_view.text_008'),
|
||||
perks: [t('screens.registration_choice_view.text_009'), t('screens.registration_choice_view.text_010'), t('screens.registration_choice_view.text_011')],
|
||||
button: t('screens.registration_choice_view.text_012'),
|
||||
}),
|
||||
card({
|
||||
});
|
||||
plans.append(paidCard);
|
||||
screen.append(topBar, title, intro, plans);
|
||||
|
||||
// Бесплатная регистрация доступна только если текущий сервер сам объявил
|
||||
// привязанный к нему type-2 namespace. При ошибке запроса безопасно оставляем
|
||||
// только платный сценарий.
|
||||
void getRegistrationNamespaces().then(({ namespaces }) => {
|
||||
if (!screen.isConnected || !Array.isArray(namespaces) || !namespaces.some(n => Number(n.type) === 2)) return;
|
||||
plans.append(card({
|
||||
type: 'free', icon: '♧', heading: t('screens.registration_choice_view.text_006'),
|
||||
price: t('screens.registration_choice_view.text_013'),
|
||||
lead: t('screens.registration_choice_view.text_014'),
|
||||
perks: [t('screens.registration_choice_view.text_015'), t('screens.registration_choice_view.text_016'), t('screens.registration_choice_view.text_017')],
|
||||
button: t('screens.registration_choice_view.text_018'),
|
||||
}),
|
||||
);
|
||||
}));
|
||||
});
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/** SHiNE wallet beta swap — in-app Jupiter routing, user's blockchainKey signs locally. */
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { getBalanceSol, getWalletFromStoredBlockchainKey } from '../services/solana-wallet-service.js';
|
||||
import { getUsdtBalance, formatAtomicAmount } from '../services/solana-usdt-service.js';
|
||||
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { requestSwapBuild, validateSwapInput, validateSwapBuildResponse, executeJupiterSwap, getPendingSwapSignature } from '../services/jupiter-swap-service.js';
|
||||
|
||||
export const pageMeta = { id: 'wallet-swap-view', get title() { return t('wallet_swap.title'); } };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
chrome?.setTopbar(createTopBar({ title: t('wallet_swap.title'), back: { label: '←', onClick: () => navigate('wallet') } }));
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack wallet-transfer-screen wallet-swap-screen';
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack wallet-transfer-card wallet-swap-card';
|
||||
card.innerHTML = `
|
||||
<h2 data-heading></h2>
|
||||
<p class="wallet-swap-beta-tag" data-beta></p>
|
||||
<p class="wallet-swap-warning" data-warning></p>
|
||||
<div class="wallet-transfer-balances">
|
||||
<div class="wallet-transfer-balance"><span>SOL</span><strong data-balance-sol>—</strong></div>
|
||||
<div class="wallet-transfer-balance"><span>USDT</span><strong data-balance-usdt>—</strong></div>
|
||||
</div>
|
||||
<label class="wallet-transfer-field"><span data-from-label></span><select class="input wallet-transfer-select" data-from><option value="SOL">SOL → USDT</option><option value="USDT">USDT → SOL</option></select></label>
|
||||
<label class="wallet-transfer-field"><span data-amount-label></span><input class="input" inputmode="decimal" autocomplete="off" data-amount type="text" placeholder="0.01" /></label>
|
||||
<p class="meta-muted wallet-swap-limit" data-limit></p>
|
||||
<button type="button" class="secondary-btn wallet-swap-quote-button" data-quote></button>
|
||||
<div class="wallet-swap-quote-box" data-preview hidden>
|
||||
<div><span data-receive-label></span><strong data-receive>—</strong></div>
|
||||
<div><span data-min-label></span><strong data-min>—</strong></div>
|
||||
<div><span data-route-label></span><strong>Jupiter Metis</strong></div>
|
||||
<p class="meta-muted" data-preview-hint></p>
|
||||
</div>
|
||||
<label class="wallet-transfer-notice wallet-swap-consent" data-consent-row hidden><input type="checkbox" data-consent /><span data-consent-label></span></label>
|
||||
<button type="button" class="primary-btn wallet-swap-confirm" data-confirm hidden disabled></button>
|
||||
<p class="meta-muted wallet-transfer-status" data-status role="status" aria-live="polite"></p>
|
||||
<a data-explorer target="_blank" rel="noopener noreferrer" class="wallet-swap-explorer" hidden></a>
|
||||
<button type="button" class="secondary-btn wallet-swap-check" data-check hidden></button>
|
||||
`;
|
||||
const el = (name) => card.querySelector(`[data-${name}]`);
|
||||
el('heading').textContent = t('wallet_swap.title');
|
||||
el('beta').textContent = t('wallet_swap.beta');
|
||||
el('warning').textContent = t('wallet_swap.warning');
|
||||
el('from-label').textContent = t('wallet_swap.direction');
|
||||
el('amount-label').textContent = t('wallet_swap.amount');
|
||||
el('quote').textContent = t('wallet_swap.get_quote');
|
||||
el('receive-label').textContent = t('wallet_swap.expected');
|
||||
el('min-label').textContent = t('wallet_swap.minimum');
|
||||
el('route-label').textContent = t('wallet_swap.route');
|
||||
el('preview-hint').textContent = t('wallet_swap.quote_note');
|
||||
el('consent-label').textContent = t('wallet_swap.accept_risk');
|
||||
el('confirm').textContent = t('wallet_swap.execute');
|
||||
el('check').textContent = t('wallet_swap.check_status');
|
||||
screen.append(card);
|
||||
const mainnet = getSolanaCluster() === 'mainnet-beta';
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
let destroyed = false;
|
||||
let busy = false;
|
||||
let walletAddress = '';
|
||||
let balances = { solLamports: null, usdtAtomic: null };
|
||||
let lastQuote = null;
|
||||
let lastAmount = '';
|
||||
let lastCurrency = '';
|
||||
let blocked = false;
|
||||
|
||||
const status = (s) => { if (!destroyed) el('status').textContent = s || ''; };
|
||||
const showExplorer = (signature) => {
|
||||
const link = el('explorer');
|
||||
if (!signature || !/^[1-9A-HJ-NP-Za-km-z]{80,100}$/.test(signature)) { link.hidden = true; return; }
|
||||
link.href = `https://solscan.io/tx/${encodeURIComponent(signature)}`;
|
||||
link.textContent = `${t('wallet_swap.transaction')}: ${signature}`;
|
||||
link.hidden = false;
|
||||
};
|
||||
const resetQuote = () => {
|
||||
lastQuote = null;
|
||||
el('preview').hidden = true;
|
||||
el('consent-row').hidden = true;
|
||||
el('consent').checked = false;
|
||||
el('confirm').hidden = true;
|
||||
el('confirm').disabled = true;
|
||||
};
|
||||
const setBusy = (value) => {
|
||||
busy = value;
|
||||
el('amount').disabled = value || !mainnet;
|
||||
el('from').disabled = value || !mainnet;
|
||||
el('quote').disabled = value || !mainnet || blocked;
|
||||
el('confirm').disabled = value || !lastQuote || blocked || !el('consent').checked;
|
||||
};
|
||||
const updateLimit = () => {
|
||||
el('limit').textContent = el('from').value === 'SOL' ? t('wallet_swap.sol_limit') : t('wallet_swap.usdt_limit');
|
||||
resetQuote();
|
||||
};
|
||||
el('from').addEventListener('change', updateLimit);
|
||||
el('amount').addEventListener('input', resetQuote);
|
||||
el('consent').addEventListener('change', () => { el('confirm').disabled = !el('consent').checked || blocked || busy; });
|
||||
updateLimit();
|
||||
|
||||
async function refreshBalances() {
|
||||
const login = state.session.login;
|
||||
const storagePwd = state.session.storagePwdInMemory;
|
||||
if (!login || !storagePwd) throw new Error(t('wallet_swap.session_required'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd });
|
||||
walletAddress = wallet.address;
|
||||
const [sol, usdt] = await Promise.all([getBalanceSol({ endpoint, address: walletAddress }), getUsdtBalance({ endpoint, address: walletAddress })]);
|
||||
if (destroyed) return;
|
||||
balances = { solLamports: BigInt(sol.lamports), usdtAtomic: usdt.atomic };
|
||||
el('balance-sol').textContent = `${sol.sol.toFixed(6)} SOL`;
|
||||
el('balance-usdt').textContent = `${usdt.text} USDT`;
|
||||
}
|
||||
|
||||
async function checkPrevious() {
|
||||
const pending = await getPendingSwapSignature(endpoint);
|
||||
if (destroyed) return;
|
||||
const wasBlocked = blocked;
|
||||
blocked = Boolean(pending);
|
||||
el('check').hidden = !pending;
|
||||
if (pending) {
|
||||
status(t('wallet_swap.pending'));
|
||||
showExplorer(pending);
|
||||
} else if (wasBlocked) {
|
||||
status(t('wallet_swap.pending_resolved'));
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
el('check').addEventListener('click', () => { void checkPrevious().catch((error) => status(error.message || String(error))); });
|
||||
if (!mainnet) {
|
||||
status(t('wallet_swap.devnet_unavailable'));
|
||||
setBusy(false);
|
||||
} else {
|
||||
void (async () => {
|
||||
try { await refreshBalances(); await checkPrevious(); }
|
||||
catch (error) { status(error.message || String(error)); }
|
||||
})();
|
||||
}
|
||||
|
||||
el('quote').addEventListener('click', async () => {
|
||||
if (busy || destroyed || blocked || !mainnet) return;
|
||||
resetQuote();
|
||||
showExplorer('');
|
||||
try {
|
||||
const { pair, amount } = validateSwapInput(el('from').value, el('amount').value, balances);
|
||||
setBusy(true);
|
||||
status(t('wallet_swap.fetching'));
|
||||
if (!walletAddress) throw new Error(t('wallet_swap.session_required'));
|
||||
const prepared = await requestSwapBuild({ inputCurrency: pair.inputCurrency, amountAtomic: amount, walletAddress });
|
||||
if (destroyed) return;
|
||||
const checked = validateSwapBuildResponse(prepared.response, pair, amount);
|
||||
lastQuote = prepared;
|
||||
lastAmount = el('amount').value;
|
||||
lastCurrency = el('from').value;
|
||||
el('receive').textContent = `${formatAtomicAmount(checked.expected, pair.outputDecimals)} ${pair.outputCurrency}`;
|
||||
el('min').textContent = `${formatAtomicAmount(checked.minimum, pair.outputDecimals)} ${pair.outputCurrency}`;
|
||||
el('preview').hidden = false;
|
||||
el('consent-row').hidden = false;
|
||||
el('confirm').hidden = false;
|
||||
status(t('wallet_swap.review'));
|
||||
} catch (error) { status(error.message || String(error)); }
|
||||
finally { if (!destroyed) setBusy(false); }
|
||||
});
|
||||
|
||||
el('confirm').addEventListener('click', async () => {
|
||||
if (busy || blocked || !lastQuote || !el('consent').checked || destroyed) return;
|
||||
if (lastCurrency !== el('from').value || lastAmount !== el('amount').value) { resetQuote(); return; }
|
||||
if (Date.now() - lastQuote.fetchedAt > 30_000) { resetQuote(); status(t('wallet_swap.stale')); return; }
|
||||
const checked = validateSwapBuildResponse(lastQuote.response, lastQuote.pair, lastQuote.amount);
|
||||
const info = `${formatAtomicAmount(lastQuote.amount, lastQuote.pair.inputDecimals)} ${lastQuote.pair.inputCurrency} → ${formatAtomicAmount(checked.expected, lastQuote.pair.outputDecimals)} ${lastQuote.pair.outputCurrency}\n${t('wallet_swap.minimum')}: ${formatAtomicAmount(checked.minimum, lastQuote.pair.outputDecimals)} ${lastQuote.pair.outputCurrency}`;
|
||||
if (!window.confirm(`${t('wallet_swap.final_warning')}\n\n${info}\n\n${t('wallet_swap.final_question')}`)) return;
|
||||
const confirmedQuote = lastQuote;
|
||||
resetQuote(); // One-shot, even if signing or RPC fails.
|
||||
setBusy(true);
|
||||
status(t('wallet_swap.executing'));
|
||||
try {
|
||||
if (await getPendingSwapSignature(endpoint)) throw new Error(t('wallet_swap.pending'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login: state.session.login, storagePwd: state.session.storagePwdInMemory });
|
||||
if (wallet.address !== walletAddress) throw new Error(t('wallet_swap.wallet_changed'));
|
||||
const result = await executeJupiterSwap({ endpoint, fromKeypair: wallet.keypair, prepared: confirmedQuote });
|
||||
if (!destroyed) {
|
||||
showExplorer(result.signature);
|
||||
blocked = true; // No one-click repeat from this page after success.
|
||||
status(t('wallet_swap.success'));
|
||||
await refreshBalances();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!destroyed) {
|
||||
status(error.message || String(error));
|
||||
if (error.signature) { blocked = true; showExplorer(error.signature); el('check').hidden = false; }
|
||||
}
|
||||
} finally { if (!destroyed) setBusy(false); }
|
||||
});
|
||||
screen.cleanup = () => { destroyed = true; };
|
||||
return screen;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/** One dedicated transfer screen, opened from Wallet or an existing DM contact. */
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { getBalanceSol, getWalletFromStoredBlockchainKey, transferSolLamports, solanaAddressFromPublicKeyBase64 } from '../services/solana-wallet-service.js';
|
||||
import { getUsdtAsset, getUsdtBalance, toAtomicAmount, formatAtomicAmount, transferUsdt } from '../services/solana-usdt-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { readShineUserPda } from '../services/shine-user-pda-service.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { makeSolanaExplorerTxUrl } from '../services/solana-rpc-gateway.js';
|
||||
|
||||
export const pageMeta = { id: 'wallet-transfer-view', get title() { return t('wallet_multi.transfer_title'); } };
|
||||
|
||||
/** Use the blockchain public key, never clientKey (DM) or rootKey. */
|
||||
export async function resolveContactBlockchainAddress(login, endpoint) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
if (!cleanLogin) throw new Error('Не указан получатель');
|
||||
try {
|
||||
const pda = await readShineUserPda({ login: cleanLogin, solanaEndpoint: endpoint });
|
||||
const latest = pda?.forks?.at(-1)?.blockchainKey;
|
||||
if (latest?.length === 32) return bytesToBase58(latest);
|
||||
} catch { /* A Free account may not have a paid Solana PDA. */ }
|
||||
const user = await authService.getUser(cleanLogin);
|
||||
if (!user?.exists || !user.blockchainKey) throw new Error('Не удалось получить blockchainKey получателя');
|
||||
return solanaAddressFromPublicKeyBase64(user.blockchainKey);
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome, route }) {
|
||||
const recipientFromRoute = String(route?.params?.recipientLogin || '').trim();
|
||||
const backTarget = recipientFromRoute ? `chat/${encodeURIComponent(recipientFromRoute)}` : 'wallet';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('wallet_multi.transfer_title'),
|
||||
back: { label: '←', onClick: () => navigate(backTarget) },
|
||||
}));
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack wallet-transfer-screen';
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack wallet-transfer-card';
|
||||
card.innerHTML = `
|
||||
<h2 class="wallet-transfer-heading"></h2>
|
||||
<div class="wallet-transfer-balances">
|
||||
<div class="wallet-transfer-balance"><span>SOL</span><strong data-balance-sol>—</strong></div>
|
||||
<div class="wallet-transfer-balance"><span data-usdt-name>USDT</span><strong data-balance-usdt>—</strong></div>
|
||||
</div>
|
||||
<label class="wallet-transfer-field"><span data-currency-label></span><select class="input wallet-transfer-select" data-currency><option value="SOL">SOL</option><option value="USDT">USDT</option></select></label>
|
||||
<label class="wallet-transfer-field"><span data-amount-label></span><input class="input" data-amount type="text" inputmode="decimal" autocomplete="off" placeholder="0.01" /></label>
|
||||
<div class="wallet-transfer-selected" data-selected hidden></div>
|
||||
<label class="wallet-transfer-field"><span data-recipient-label></span><input class="input" data-recipient type="text" spellcheck="false" autocomplete="off" placeholder="Solana address (Base58)" /></label>
|
||||
<label class="wallet-transfer-notice" data-notify-row hidden><input type="checkbox" data-notify /><span data-notify-label></span></label>
|
||||
<p class="meta-muted wallet-transfer-hint" data-hint></p>
|
||||
<button type="button" class="primary-btn wallet-transfer-submit" data-send></button>
|
||||
<p class="meta-muted wallet-transfer-status" data-status role="status" aria-live="polite"></p>
|
||||
`;
|
||||
const q = (selector) => card.querySelector(`[data-${selector}]`);
|
||||
q('currency-label').textContent = t('wallet_multi.asset');
|
||||
q('amount-label').textContent = t('wallet_multi.amount');
|
||||
q('recipient-label').textContent = t('wallet_multi.recipient');
|
||||
q('notify-label').textContent = t('wallet_multi.notify');
|
||||
q('notify-row').hidden = !recipientFromRoute;
|
||||
q('send').textContent = t('wallet_multi.send');
|
||||
q('hint').textContent = t('wallet_multi.no_stars');
|
||||
q('selected').textContent = '';
|
||||
card.querySelector('.wallet-transfer-heading').textContent = t('wallet_multi.transfer_title');
|
||||
screen.append(card);
|
||||
let disposed = false;
|
||||
let busy = false;
|
||||
// A chat-bound transfer has exactly one recipient; the wallet flow accepts only an address.
|
||||
const recipientLogin = recipientFromRoute;
|
||||
let selectedAddress = '';
|
||||
let resolvingRecipient = Boolean(recipientLogin);
|
||||
let address = '';
|
||||
let usdt = { available: false, atomic: 0n, asset: getUsdtAsset() };
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
const setStatus = (value) => { if (!disposed) q('status').textContent = value; };
|
||||
const setBusy = (value) => {
|
||||
busy = value;
|
||||
q('currency').disabled = value;
|
||||
q('amount').disabled = value;
|
||||
q('recipient').disabled = value;
|
||||
q('notify').disabled = value;
|
||||
q('send').disabled = value || resolvingRecipient || (Boolean(recipientLogin) && !selectedAddress) || q('send').dataset.completed === 'true';
|
||||
};
|
||||
if (recipientLogin) {
|
||||
q('selected').hidden = false;
|
||||
q('selected').textContent = `${t('wallet_multi.contact')}: ${recipientLogin}`;
|
||||
q('recipient').readOnly = true;
|
||||
q('recipient').value = t('wallet_multi.resolving');
|
||||
q('send').disabled = true;
|
||||
void resolveContactBlockchainAddress(recipientLogin, endpoint)
|
||||
.then((resolved) => {
|
||||
if (disposed) return;
|
||||
selectedAddress = resolved;
|
||||
q('recipient').value = resolved;
|
||||
setStatus('');
|
||||
})
|
||||
.catch((error) => {
|
||||
if (disposed) return;
|
||||
q('recipient').value = '';
|
||||
setStatus(error.message || String(error));
|
||||
})
|
||||
.finally(() => {
|
||||
if (disposed) return;
|
||||
resolvingRecipient = false;
|
||||
q('send').disabled = busy || !selectedAddress;
|
||||
});
|
||||
}
|
||||
|
||||
const refreshBalances = async () => {
|
||||
try {
|
||||
const wallet = await getWalletFromStoredBlockchainKey({
|
||||
login: state.session.login, storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
if (disposed) return;
|
||||
address = wallet.address;
|
||||
const [sol, usdtResult] = await Promise.allSettled([
|
||||
getBalanceSol({ endpoint, address }), getUsdtBalance({ endpoint, address }),
|
||||
]);
|
||||
if (disposed) return;
|
||||
if (sol.status === 'fulfilled') q('balance-sol').textContent = `${sol.value.sol.toFixed(6)} SOL`;
|
||||
if (usdtResult.status === 'fulfilled') {
|
||||
usdt = usdtResult.value;
|
||||
q('balance-usdt').textContent = usdt.available ? `${usdt.text} ${usdt.asset.label}` : t('wallet_multi.test_mint_missing');
|
||||
} else q('balance-usdt').textContent = t('wallet_multi.balance_unavailable');
|
||||
q('usdt-name').textContent = usdt.asset.label;
|
||||
if (!usdt.available) q('currency').querySelector('option[value="USDT"]').disabled = true;
|
||||
q('hint').textContent = usdt.asset.test ? `${t('wallet_multi.no_stars')} ${t('wallet_multi.devnet_disclaimer')}` : t('wallet_multi.no_stars');
|
||||
} catch (error) { setStatus(error.message || String(error)); }
|
||||
};
|
||||
void refreshBalances();
|
||||
|
||||
q('send').addEventListener('click', async () => {
|
||||
if (busy || disposed) return;
|
||||
const currency = q('currency').value;
|
||||
const amountText = q('amount').value;
|
||||
const messageWanted = q('notify').checked;
|
||||
let toAddress = String(q('recipient').value || '').trim();
|
||||
let atomic;
|
||||
try {
|
||||
atomic = toAtomicAmount(amountText, currency === 'SOL' ? 9 : 6);
|
||||
if (!state.session.login || !state.session.storagePwdInMemory) throw new Error('Не найдена авторизованная сессия SHiNE');
|
||||
if (currency === 'SOL' && atomic > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('Сумма SOL слишком большая');
|
||||
if (recipientLogin) {
|
||||
if (!selectedAddress || resolvingRecipient) throw new Error('Адрес получателя ещё не получен');
|
||||
// Refresh the binding at signing time, protect against stale/rotated blockchain keys.
|
||||
toAddress = await resolveContactBlockchainAddress(recipientLogin, endpoint);
|
||||
if (selectedAddress && toAddress !== selectedAddress) {
|
||||
q('recipient').value = toAddress;
|
||||
selectedAddress = toAddress;
|
||||
throw new Error('Блокчейн-ключ получателя изменился. Проверьте новый адрес и повторите отправку.');
|
||||
}
|
||||
}
|
||||
const solana = await loadSolanaWeb3();
|
||||
const target = new solana.PublicKey(toAddress).toBase58();
|
||||
if (address && target === address) throw new Error('Нельзя переводить самому себе');
|
||||
// A wallet-to-wallet payment must never be sent to a mint, token account or executable program.
|
||||
if (!solana.PublicKey.isOnCurve(new solana.PublicKey(target).toBytes())) {
|
||||
throw new Error('Получатель должен быть обычным кошельком Solana (не PDA программы)');
|
||||
}
|
||||
const recipientInfo = await new solana.Connection(endpoint, 'confirmed').getAccountInfo(new solana.PublicKey(target), 'confirmed');
|
||||
if (recipientInfo && (recipientInfo.executable || !recipientInfo.owner.equals(solana.SystemProgram.programId))) {
|
||||
throw new Error('Адрес получателя не является обычным кошельком Solana');
|
||||
}
|
||||
if (currency === 'USDT' && !usdt.available) throw new Error('USDT в этой сети не настроен');
|
||||
const display = `${formatAtomicAmount(atomic, currency === 'SOL' ? 9 : 6)} ${currency === 'SOL' ? 'SOL' : usdt.asset.label}`;
|
||||
const contactLabel = recipientLogin ? `${recipientLogin}\n${target}` : target;
|
||||
if (!window.confirm(`${t('wallet_multi.confirm')}\n${display}\n${contactLabel}`)) return;
|
||||
setBusy(true);
|
||||
setStatus(t('wallet_multi.sending'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login: state.session.login, storagePwd: state.session.storagePwdInMemory });
|
||||
if (wallet.address === target) throw new Error('Нельзя переводить самому себе');
|
||||
const result = currency === 'SOL'
|
||||
? await transferSolLamports({ endpoint, fromKeypair: wallet.keypair, toAddress: target, amountLamports: atomic })
|
||||
: await transferUsdt({ endpoint, fromKeypair: wallet.keypair, toAddress: target, amountAtomic: atomic });
|
||||
// The transfer is confirmed even if the user navigated away. Send requested DM anyway.
|
||||
if (!disposed) {
|
||||
setStatus(`${t('wallet_multi.success')}\n${result.signature}`);
|
||||
q('send').textContent = t('wallet_multi.sent');
|
||||
q('send').dataset.completed = 'true';
|
||||
}
|
||||
if (messageWanted && recipientLogin) {
|
||||
try {
|
||||
await authService.sendDirectMessage({
|
||||
login: state.session.login, toLogin: recipientLogin,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
text: `${t('wallet_multi.dm_prefix')} ${display}\n${t('wallet_multi.dm_signature')}: ${result.signature}\n${t('wallet_multi.dm_explorer')}: ${makeSolanaExplorerTxUrl(result.signature, endpoint)}`,
|
||||
});
|
||||
if (!disposed) setStatus(`${t('wallet_multi.success')}\n${result.signature}\n${t('wallet_multi.notice_sent')}`);
|
||||
} catch (error) {
|
||||
if (!disposed) setStatus(`${t('wallet_multi.success')}\n${result.signature}\n${t('wallet_multi.notice_failed')}: ${error.message || error}`);
|
||||
}
|
||||
}
|
||||
// Prevent accidental re-send on the success screen; user must navigate away to make another transfer.
|
||||
if (!disposed) {
|
||||
q('send').disabled = true;
|
||||
q('send').dataset.completed = 'true';
|
||||
void refreshBalances();
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error?.message || String(error);
|
||||
if (/timed out|timeout|expired|confirmation/i.test(message)) {
|
||||
// RPC timeout is not evidence that funds were not moved. Avoid duplicate send.
|
||||
setStatus(`${t('wallet_multi.uncertain')}\n${message}`);
|
||||
q('send').dataset.completed = 'true';
|
||||
} else setStatus(message);
|
||||
} finally {
|
||||
if (!disposed) {
|
||||
setBusy(false);
|
||||
if (q('send').dataset.completed === 'true') q('send').disabled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
screen.cleanup = () => { disposed = true; };
|
||||
return screen;
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getWalletFromStoredBlockchainKey,
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import {
|
||||
formatAr,
|
||||
@@ -18,13 +17,11 @@ import {
|
||||
} from '../services/arweave-wallet-service.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { getUsdtBalance, getUsdtAsset } from '../services/solana-usdt-service.js';
|
||||
import { openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
|
||||
import { buildArweaveDataUrl, sha256HexFromArrayBuffer } from '../services/arweave-file-service.js';
|
||||
import {
|
||||
calcLimitTopupPriceLamports,
|
||||
getLimitStepBytes,
|
||||
getShineBlockchainUsage,
|
||||
getShineUsersEconomyConfig,
|
||||
updateShineUserPdaOnSolana,
|
||||
} from '../services/shine-blockchain-wallet-service.js?v=202605300007';
|
||||
import {
|
||||
@@ -71,16 +68,6 @@ function lamportsToSolText(lamportsBigInt) {
|
||||
return formatNumber(value, { minimumFractionDigits: 0, maximumFractionDigits: 9 });
|
||||
}
|
||||
|
||||
function formatLimitTopupError(error) {
|
||||
const message = String(error?.message || '').trim();
|
||||
const logs = Array.isArray(error?.logs) ? error.logs.join(' | ') : '';
|
||||
const haystack = `${message} ${logs}`.toLowerCase();
|
||||
if (haystack.includes('insufficient funds for rent')) {
|
||||
return t('screens.wallet_view.text_106');
|
||||
}
|
||||
return t('screens.wallet_view.text_153', { value1: message || 'unknown' });
|
||||
}
|
||||
|
||||
function createModeBackButton(renderWalletChoice) {
|
||||
const backBtn = document.createElement('button');
|
||||
backBtn.className = 'text-btn';
|
||||
@@ -537,32 +524,14 @@ export function render({navigate, chrome}) {
|
||||
|
||||
async function resolveWalletSigningMaterial() {
|
||||
const { login, storagePwd } = sessionArgsOrThrow();
|
||||
let saved = null;
|
||||
try {
|
||||
saved = await loadEncryptedUserSecrets(login, storagePwd);
|
||||
} catch {
|
||||
saved = null;
|
||||
}
|
||||
|
||||
const blockchainKey = String(saved?.blockchainKey || '').trim();
|
||||
const clientKey = String(saved?.clientKey || '').trim();
|
||||
if (blockchainKey && clientKey) {
|
||||
return {
|
||||
rootPrivatePkcs8B64: '',
|
||||
blockchainPrivatePkcs8B64: blockchainKey,
|
||||
clientPrivatePkcs8B64: clientKey,
|
||||
};
|
||||
}
|
||||
|
||||
const password = window.prompt(
|
||||
t('dialogs.pages.wallet_view.prompt_001'),
|
||||
'',
|
||||
);
|
||||
// Root key is intentionally not kept in IndexedDB or encrypted key vault.
|
||||
// Solana PDA updates are rare, so require a fresh password on every update.
|
||||
const password = window.prompt(t('dialogs.pages.wallet_view.prompt_001'), '');
|
||||
if (password == null) throw new Error(t('screens.wallet_view.text_138'));
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(login, password);
|
||||
await authService.persistSelectedKeys(login, storagePwd, keyBundle);
|
||||
return {
|
||||
rootPrivatePkcs8B64: '',
|
||||
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
};
|
||||
@@ -1419,14 +1388,11 @@ export function render({navigate, chrome}) {
|
||||
actions.className = 'stack';
|
||||
actions.innerHTML = `
|
||||
<button class="ghost-btn" id="refresh-shine-bch" style="width:100%;">${th('screens.wallet_view.text_266')}</button>
|
||||
<button class="primary-btn" id="topup-shine-limit" style="width:100%;">${th('screens.wallet_view.text_267')}</button>
|
||||
`;
|
||||
const refreshBtn = actions.querySelector('#refresh-shine-bch');
|
||||
const topupBtn = actions.querySelector('#topup-shine-limit');
|
||||
|
||||
const setButtonsDisabled = (disabled) => {
|
||||
refreshBtn.disabled = disabled;
|
||||
topupBtn.disabled = disabled;
|
||||
};
|
||||
|
||||
const refreshUsage = async () => {
|
||||
@@ -1440,11 +1406,11 @@ export function render({navigate, chrome}) {
|
||||
fetchServerBlockchainState(),
|
||||
]);
|
||||
if (modeToken !== activeModeToken) return;
|
||||
limitValue.textContent = formatKbFromBytes(usage.paidLimitBytes);
|
||||
limitValue.textContent = usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatKbFromBytes(usage.paidLimitBytes);
|
||||
const usedServerBytes = BigInt(Math.max(0, Number(serverState.sizeBytes || 0)));
|
||||
const leftServerBytes = usage.paidLimitBytes > usedServerBytes ? (usage.paidLimitBytes - usedServerBytes) : 0n;
|
||||
usedValue.textContent = formatKbFromBytes(usedServerBytes);
|
||||
leftValue.textContent = formatKbFromBytes(leftServerBytes);
|
||||
leftValue.textContent = usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatKbFromBytes(leftServerBytes);
|
||||
pdaLabel.textContent = `PDA: ${usage.userPda}`;
|
||||
endpointLabel.textContent = `RPC: ${usage.endpoint}`;
|
||||
updatedLabel.textContent = t('screens.wallet_view.text_162', { value1: nowRu() });
|
||||
@@ -1623,7 +1589,7 @@ export function render({navigate, chrome}) {
|
||||
pdaLastEl.textContent = t('screens.wallet_view.text_167', { value1: usage.lastBlockNumber });
|
||||
pdaHashEl.textContent = `Hash: ${usage.lastBlockHashHex || '–'}`;
|
||||
pdaUsedEl.textContent = t('screens.wallet_view.text_168', { value1: formatBytesRu(usage.usedBytes) });
|
||||
pdaLimitEl.textContent = t('screens.wallet_view.text_169', { value1: formatBytesRu(usage.paidLimitBytes) });
|
||||
pdaLimitEl.textContent = t('screens.wallet_view.text_169', { value1: usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatBytesRu(usage.paidLimitBytes) });
|
||||
pdaArweaveEl.textContent = `Arweave tx: ${usage.arweaveTxId || '–'}`;
|
||||
if (usage.arweaveTxId) {
|
||||
pdaArweaveLinkEl.href = buildArweaveDataUrl({ gateway: state.entrySettings.arweaveServer, txId: usage.arweaveTxId });
|
||||
@@ -1778,7 +1744,6 @@ export function render({navigate, chrome}) {
|
||||
rootPrivatePkcs8B64: signing.rootPrivatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: signing.blockchainPrivatePkcs8B64,
|
||||
clientPrivatePkcs8B64: signing.clientPrivatePkcs8B64,
|
||||
additionalLimitBytes: 0n,
|
||||
nextUsedBytes: BigInt(Math.max(0, serverState.sizeBytes)),
|
||||
nextLastBlockNumber: serverState.lastNumber,
|
||||
nextLastBlockHashHex: serverState.lastHash,
|
||||
@@ -1848,7 +1813,12 @@ export function render({navigate, chrome}) {
|
||||
const endpointLabel = document.createElement('p');
|
||||
endpointLabel.className = 'meta-muted';
|
||||
endpointLabel.textContent = `RPC: ${state.entrySettings.solanaServer}`;
|
||||
balanceWrap.append(balanceLabel, balanceValue, updatedLabel, endpointLabel);
|
||||
const usdtLine = document.createElement('div');
|
||||
usdtLine.className = 'wallet-multi-usdt-line';
|
||||
const usdtAsset = getUsdtAsset();
|
||||
usdtLine.innerHTML = `<span></span><strong>—</strong>`;
|
||||
usdtLine.querySelector('span').textContent = usdtAsset.label;
|
||||
balanceWrap.append(balanceLabel, balanceValue, usdtLine, updatedLabel, endpointLabel);
|
||||
|
||||
const addressCard = document.createElement('div');
|
||||
addressCard.className = 'card';
|
||||
@@ -1858,6 +1828,10 @@ export function render({navigate, chrome}) {
|
||||
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">—</p>
|
||||
`;
|
||||
const addressEl = addressCard.querySelector('#wallet-address-value');
|
||||
const receiveHint = document.createElement('p');
|
||||
receiveHint.className = 'meta-muted';
|
||||
receiveHint.textContent = t('wallet_multi.receive_hint');
|
||||
addressCard.append(receiveHint);
|
||||
enableAddressCopy(addressEl, () => walletAddress);
|
||||
|
||||
card.append(balanceWrap, addressCard);
|
||||
@@ -1867,7 +1841,7 @@ export function render({navigate, chrome}) {
|
||||
actions.innerHTML = `
|
||||
<div class="row">
|
||||
<button class="primary-btn" id="refresh-balance" style="flex:1;">${th('screens.wallet_view.text_293')}</button>
|
||||
<button class="primary-btn" id="send-sol" style="flex:1;">${th('screens.wallet_view.text_294')}</button>
|
||||
<button class="primary-btn" id="send-sol" style="flex:1;">${t('wallet_multi.transfer_title')}</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -1887,9 +1861,18 @@ export function render({navigate, chrome}) {
|
||||
});
|
||||
if (modeToken !== activeModeToken) return;
|
||||
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||||
let tokenErrorText = '';
|
||||
try {
|
||||
const token = await getUsdtBalance({ endpoint: state.entrySettings.solanaServer, address: walletAddress });
|
||||
if (modeToken !== activeModeToken) return;
|
||||
usdtLine.querySelector('strong').textContent = token.available ? token.text : t('wallet_multi.test_mint_missing');
|
||||
} catch (tokenError) {
|
||||
usdtLine.querySelector('strong').textContent = t('wallet_multi.balance_unavailable');
|
||||
tokenErrorText = `${t('wallet_multi.balance_unavailable')}: ${tokenError.message || tokenError}`;
|
||||
}
|
||||
updatedLabel.textContent = t('screens.wallet_view.text_181', { value1: nowRu() });
|
||||
endpointLabel.textContent = `RPC: ${balance.endpoint}`;
|
||||
setStatus(t('screens.wallet_view.text_085'));
|
||||
setStatus(tokenErrorText || t('screens.wallet_view.text_085'));
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(actionErrorText(t('screens.wallet_view.text_086'), error));
|
||||
@@ -1902,34 +1885,17 @@ export function render({navigate, chrome}) {
|
||||
void refreshBalance();
|
||||
});
|
||||
|
||||
sendBtn.addEventListener('click', async () => {
|
||||
if (!walletCtx?.keypair) {
|
||||
setStatus(t('screens.wallet_view.text_087'));
|
||||
return;
|
||||
}
|
||||
const toAddress = window.prompt(t('dialogs.pages.wallet_view.prompt_002'), '');
|
||||
if (!toAddress) return;
|
||||
const amountRaw = window.prompt(t('dialogs.pages.wallet_view.prompt_003'), '0.01');
|
||||
if (!amountRaw) return;
|
||||
sendBtn.addEventListener('click', () => navigate('wallet/transfer'));
|
||||
|
||||
sendBtn.disabled = true;
|
||||
try {
|
||||
const tx = await transferSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
fromKeypair: walletCtx.keypair,
|
||||
toAddress,
|
||||
amountSol: Number(String(amountRaw || '').replace(',', '.')),
|
||||
});
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(t('screens.wallet_view.text_182', { value1: tx.signature }));
|
||||
await refreshBalance();
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(actionErrorText(t('screens.wallet_view.text_088'), error));
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
const swapHint = document.createElement('p');
|
||||
swapHint.className = 'meta-muted wallet-jupiter-hint';
|
||||
swapHint.textContent = t('wallet_swap.wallet_hint');
|
||||
const swapButton = document.createElement('button');
|
||||
swapButton.type = 'button';
|
||||
swapButton.className = 'secondary-btn wallet-jupiter-link';
|
||||
swapButton.textContent = t('wallet_swap.wallet_button');
|
||||
swapButton.addEventListener('click', () => navigate('wallet/swap'));
|
||||
actions.append(swapButton, swapHint);
|
||||
|
||||
content.append(backBtn, card, actions);
|
||||
setStatus(t('screens.wallet_view.text_089'));
|
||||
@@ -1986,6 +1952,10 @@ export function render({navigate, chrome}) {
|
||||
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">–</p>
|
||||
`;
|
||||
const addressEl = addressCard.querySelector('#wallet-address-value');
|
||||
const receiveHint = document.createElement('p');
|
||||
receiveHint.className = 'meta-muted';
|
||||
receiveHint.textContent = t('wallet_multi.receive_hint');
|
||||
addressCard.append(receiveHint);
|
||||
enableAddressCopy(addressEl, () => walletAddress);
|
||||
|
||||
const helpCard = document.createElement('details');
|
||||
|
||||
@@ -57,6 +57,8 @@ const PRETTY_PATHS = new Map([
|
||||
['solana-users-init-view', 'settings/solana-users-init'],
|
||||
['solana-rpc-check-view', 'settings/solana-rpc-check'],
|
||||
['wallet-view', 'wallet'],
|
||||
['wallet-transfer-view', 'wallet/transfer'],
|
||||
['wallet-swap-view', 'wallet/swap'],
|
||||
['queue', 'quene'],
|
||||
['device-view', 'devices'],
|
||||
['device-session-view', 'devices'],
|
||||
@@ -380,6 +382,12 @@ export function parseRouteFromPath(pathname = '') {
|
||||
}
|
||||
|
||||
if (pageId === 'wallet') {
|
||||
if (decodePart(segments[1] || '').toLowerCase() === 'swap') {
|
||||
return { pageId: 'wallet-swap-view', params: {} };
|
||||
}
|
||||
if (decodePart(segments[1] || '').toLowerCase() === 'transfer') {
|
||||
return { pageId: 'wallet-transfer-view', params: { recipientLogin: decodePart(segments[2] || '') } };
|
||||
}
|
||||
return { pageId: 'wallet-view', params: {} };
|
||||
}
|
||||
|
||||
@@ -593,6 +601,8 @@ function resolveToolbarTab(pageId) {
|
||||
pageId === 'profile-edit-view' ||
|
||||
pageId === 'profiles-view' ||
|
||||
pageId === 'wallet-view' ||
|
||||
pageId === 'wallet-transfer-view' ||
|
||||
pageId === 'wallet-swap-view' ||
|
||||
pageId === 'settings-view' ||
|
||||
pageId === 'registration-upgrade-view' ||
|
||||
pageId === 'access-keys-view' ||
|
||||
|
||||
@@ -201,3 +201,14 @@ export async function createAns104DataItemWithRawParts({
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/** Проверка исходной подписи ANS-104 локально, без доверия к серверному статусу. */
|
||||
export async function verifyAns104DataItem(rawBytes) {
|
||||
const item = parseAns104DataItem(rawBytes);
|
||||
const signedMessage = await ans104SigningMessageRaw(item);
|
||||
const key = await crypto.subtle.importKey('raw', item.owner32, { name: 'Ed25519' }, false, ['verify']);
|
||||
const signatureValid = await crypto.subtle.verify('Ed25519', key, item.signature, signedMessage);
|
||||
const idHash = await digest('SHA-256', item.signature);
|
||||
const frameHash = await digest('SHA-256', item.data);
|
||||
return { ...item, signatureValid, dataItemIdBytes: idHash, frameHashBytes: frameHash };
|
||||
}
|
||||
|
||||
@@ -7,7 +7,11 @@ import { resolvePublicFileUrl } from './public-file-service.js';
|
||||
import { updatedUserFileUrlAfterError } from './user-file-server-service.js';
|
||||
import { validatePublicPiecesRoot } from './public-pieces-root.js';
|
||||
|
||||
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>]*)>\n?/u;
|
||||
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>\n]{1,2048})>\n?/u;
|
||||
// В v=2 ASCII-разделители и управляющие синтаксисом символы экранируются, UTF-8 остаётся как есть.
|
||||
const V2_RESERVED = /[%<>=;\r\n]/g;
|
||||
const V2_ESCAPE = { '%': '%25', '<': '%3C', '>': '%3E', '=': '%3D', ';': '%3B', '\r': '%0D', '\n': '%0A' };
|
||||
const ATTACH_ALLOWED_FIELDS = new Set(['v', 'nm', 'sz', 'pr', 'sha256', 'mm', 'ar']);
|
||||
export const MAX_MESSAGE_ATTACHMENTS = 10;
|
||||
const RECENT_UNAVAILABLE_MS = 20 * 60 * 1000;
|
||||
const IMAGE_EXTENSIONS = new Set(['apng', 'avif', 'bmp', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);
|
||||
@@ -49,21 +53,22 @@ export function normalizeAttachment(input = {}) {
|
||||
const mm = String(input.mm || '').trim();
|
||||
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
||||
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
||||
if (new TextEncoder().encode(name).length > 255) throw new Error('Имя файла превышает 255 байт UTF-8');
|
||||
if (txId && !validateArweaveTxId(txId)) throw new Error(t('remaining.attachment_errors.invalid_arweave_transaction_id'));
|
||||
if (!validatePublicPiecesRoot(pr) && !validateSha256Hex(sha256Hex)) throw new Error('Некорректный идентификатор файла');
|
||||
if (pr && !validatePublicPiecesRoot(pr)) throw new Error('Некорректный Pieces Root');
|
||||
if (mm && (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(mm) || mm.length > 127)) throw new Error('Некорректный MIME');
|
||||
if (!Number.isInteger(size) || size <= 0) throw new Error(t('remaining.attachment_errors.invalid_file_size'));
|
||||
return { v: 1, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
||||
return { v: 2, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
||||
}
|
||||
|
||||
export function buildAttachmentBlock(attachment) {
|
||||
const item = normalizeAttachment(attachment);
|
||||
const encodedName = encodeURIComponent(item.name);
|
||||
const encodedName = item.name.replace(V2_RESERVED, (char) => V2_ESCAPE[char]);
|
||||
const id = item.pr ? `;pr=${item.pr}` : `;sha256=${item.sha256}`;
|
||||
const mmPart = item.mm ? `;mm=${item.mm}` : '';
|
||||
const arPart = item.ar ? `;ar=${item.ar}` : '';
|
||||
return `<S:att;v=1;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
||||
return `<S:att;v=2;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
||||
}
|
||||
|
||||
export function composeMessageWithAttachments(text, attachments = []) {
|
||||
@@ -76,15 +81,33 @@ export function composeMessageWithAttachments(text, attachments = []) {
|
||||
}
|
||||
|
||||
function parseFields(rawFields) {
|
||||
const out = {};
|
||||
String(rawFields || '').split(';').forEach((part) => {
|
||||
const parts = String(rawFields || '').split(';');
|
||||
const fields = Object.create(null);
|
||||
// Для v=1 сохраняем прежний мягкий разбор. Для v=2 — строгое правило полей.
|
||||
const strict = parts.some((part) => /^v\s*=\s*(?:0*2)$/u.test(part));
|
||||
for (const part of parts) {
|
||||
const eq = part.indexOf('=');
|
||||
if (eq <= 0) return;
|
||||
if (eq <= 0) {
|
||||
if (strict) throw new Error('Некорректное поле вложения');
|
||||
continue;
|
||||
}
|
||||
const key = part.slice(0, eq).trim();
|
||||
const value = part.slice(eq + 1).trim();
|
||||
if (key) out[key] = value;
|
||||
});
|
||||
return out;
|
||||
if (strict && (!ATTACH_ALLOWED_FIELDS.has(key) || Object.hasOwn(fields, key))) {
|
||||
throw new Error('Дублированное либо неизвестное поле вложения');
|
||||
}
|
||||
if (key) fields[key] = value;
|
||||
}
|
||||
if (strict) {
|
||||
if (!fields.nm || !fields.sz || !(fields.pr || fields.sha256) || (fields.pr && fields.sha256)) {
|
||||
throw new Error('Отсутствует обязательное поле вложения');
|
||||
}
|
||||
if (!/^(?:[^%]|%(?:25|3[bBcCdDeE]|0[aAdD]))*$/u.test(fields.nm)) {
|
||||
// Неизвестные и неполные %-коды запрещаем; это исключает неоднозначное толкование.
|
||||
throw new Error('Неканоническое экранирование имени файла');
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
export function parseMessageAttachments(rawText) {
|
||||
@@ -94,14 +117,20 @@ export function parseMessageAttachments(rawText) {
|
||||
while (true) {
|
||||
const match = rest.match(ATTACH_BLOCK_RE);
|
||||
if (!match) break;
|
||||
const fields = parseFields(match[2]);
|
||||
try {
|
||||
const fields = parseFields(match[2]);
|
||||
const version = Number(fields.v || 0);
|
||||
if (version !== 1 && version !== 2) {
|
||||
throw new Error('unsupported attachment version');
|
||||
}
|
||||
if (version === 2 && (!fields.v || fields.v !== '2')) throw new Error('Неканоническая версия');
|
||||
if (version === 2 && (/[<>=;]/u.test(fields.nm) || !/^[1-9][0-9]*$/u.test(fields.sz))) {
|
||||
throw new Error('Неканонические поля вложения');
|
||||
}
|
||||
const name = decodeURIComponent(String(fields.nm || fields.name || 'file'));
|
||||
if (version === 2 && /[\u0000-\u001f\u007f]/u.test(name)) throw new Error('Управляющий символ в имени файла');
|
||||
attachments.push(normalizeAttachment({
|
||||
nm: decodeURIComponent(String(fields.nm || fields.name || 'file')),
|
||||
nm: name,
|
||||
sz: fields.sz || fields.size,
|
||||
sha256: fields.sha256,
|
||||
pr: fields.pr,
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { verifyAns104DataItem } from './ans104-data-item.js';
|
||||
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
|
||||
import { readShineUserPda } from './shine-user-pda-service.js';
|
||||
|
||||
const HASH_RE = /^[0-9a-f]{64}$/iu;
|
||||
const DATA_ITEM_ID_RE = /^[A-Za-z0-9_-]{43}$/u;
|
||||
const MAX_SIGNED_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
function hex(bytes) {
|
||||
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function equalBytes(left, right) {
|
||||
return left.length === right.length && left.every((byte, index) => byte === right[index]);
|
||||
}
|
||||
export function arweaveBlockUrl(id) {
|
||||
return DATA_ITEM_ID_RE.test(String(id || '')) ? `https://arweave.net/raw/${id}` : '';
|
||||
}
|
||||
export function signedDataItemFilename(chain, number) {
|
||||
const safe = String(chain || 'block').replace(/[^a-z0-9@._-]/giu, '_').slice(0, 100);
|
||||
return `SHiNE-${safe}-${Number(number)}.ans104`;
|
||||
}
|
||||
|
||||
/** Получаем полный оригинал по существующему публичному API (не «от Arweave»). */
|
||||
export async function readSignedBlock({ authService, blockchainName, blockNumber, blockHash, dataItemId }) {
|
||||
const resp = await authService.ws.request('GetBlockchainBlock', { blockchainName, blockNumber });
|
||||
if (Number(resp?.status) !== 200) throw new Error('GetBlockchainBlock: блок недоступен');
|
||||
const body = resp?.payload || resp;
|
||||
if (!HASH_RE.test(String(body?.blockHash || '')) || String(body.blockHash).toLowerCase() !== String(blockHash).toLowerCase()) {
|
||||
throw new Error('Сервер вернул другой хеш блока');
|
||||
}
|
||||
const rawText = String(body?.blockBytesB64 || '');
|
||||
if (rawText.length > Math.ceil(MAX_SIGNED_BYTES * 4 / 3) + 8) throw new Error('Размер подписанного блока превышает лимит');
|
||||
const bytes = base64ToBytes(rawText);
|
||||
if (!bytes.length || bytes.length > MAX_SIGNED_BYTES) throw new Error('Некорректный размер блока');
|
||||
const proof = await verifyAns104DataItem(bytes);
|
||||
if (!proof.signatureValid) throw new Error('Недействительная подпись ANS-104');
|
||||
if (hex(proof.frameHashBytes) !== String(blockHash).toLowerCase()) throw new Error('Хеш содержимого блока не совпал');
|
||||
const actualId = bytesToBase64Url(proof.dataItemIdBytes);
|
||||
if (dataItemId && actualId !== dataItemId) throw new Error('Идентификатор Arweave отличается от ожидаемого');
|
||||
return { bytes, ...proof, actualId };
|
||||
}
|
||||
|
||||
/** Вспомогательная независимая сверка: шлюз возвращает payload, а не ANS-104 оболочку. */
|
||||
export async function checkArweavePayload(dataItemId, signedPayload) {
|
||||
const url = arweaveBlockUrl(dataItemId);
|
||||
if (!url) return { status: 'unavailable', reason: 'Нет идентификатора Arweave' };
|
||||
try {
|
||||
const response = await fetch(url, { cache: 'no-store', signal: AbortSignal.timeout(15000) });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const length = Number(response.headers.get('Content-Length') || 0);
|
||||
if (length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
||||
const raw = new Uint8Array(await response.arrayBuffer());
|
||||
if (raw.length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
||||
return equalBytes(raw, signedPayload)
|
||||
? { status: 'valid' }
|
||||
: { status: 'invalid', reason: 'Содержимое Arweave не совпадает с подписанным блоком' };
|
||||
} catch (error) {
|
||||
return { status: 'unavailable', reason: String(error?.message || error) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkSolanaAuthor({ authorLogin, blockchainName, owner32, solanaEndpoint }) {
|
||||
const forkMatch = String(blockchainName || '').match(/-(\d{3})$/u);
|
||||
const forkIndex = forkMatch ? Number(forkMatch[1]) - 1 : -1;
|
||||
if (forkIndex < 0 || !authorLogin || !solanaEndpoint) {
|
||||
return { status: 'unavailable', reason: 'Недостаточно данных для проверки Solana' };
|
||||
}
|
||||
try {
|
||||
const pda = await readShineUserPda({ login: authorLogin, solanaEndpoint });
|
||||
const key = pda?.forks?.[forkIndex]?.blockchainKey;
|
||||
if (!key) return { status: 'unavailable', reason: 'Исторический ключ форка отсутствует в PDA' };
|
||||
return equalBytes(new Uint8Array(key), owner32)
|
||||
? { status: 'valid', reason: `Solana PDA, форк ${forkMatch[1]}` }
|
||||
: { status: 'invalid', reason: 'Ключ подписанта не совпадает с ключом форка в Solana PDA' };
|
||||
} catch (error) {
|
||||
// FREE_CERT может не иметь PDA: это не доказательство подделки.
|
||||
return { status: 'unavailable', reason: String(error?.message || error) };
|
||||
}
|
||||
}
|
||||
@@ -95,11 +95,11 @@ export function formatShortAge(timestampMs) {
|
||||
if (!ts) return '';
|
||||
const ageMinutes = Math.max(0, Math.floor((Date.now() - ts) / 60000));
|
||||
if (ageMinutes < 1) return formatRelative(0, 'second');
|
||||
if (ageMinutes < 60) return formatRelative(-ageMinutes, 'minute', { numeric: 'always', style: 'narrow' });
|
||||
if (ageMinutes < 60) return formatRelative(-ageMinutes, 'minute', { numeric: 'always' });
|
||||
const ageHours = Math.floor(ageMinutes / 60);
|
||||
if (ageHours < 24) return formatRelative(-ageHours, 'hour', { numeric: 'always', style: 'narrow' });
|
||||
if (ageHours < 24) return formatRelative(-ageHours, 'hour', { numeric: 'always' });
|
||||
const ageDays = Math.floor(ageHours / 24);
|
||||
if (ageDays < 7) return formatRelative(-ageDays, 'day', { numeric: 'always', style: 'narrow' });
|
||||
if (ageDays < 7) return formatRelative(-ageDays, 'day', { numeric: 'always' });
|
||||
const dt = new Date(ts);
|
||||
const day = shortDay(dt);
|
||||
return dt.getFullYear() === new Date().getFullYear() ? day : `${day} ${dt.getFullYear()}`;
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
/** Jupiter Swap API V2: beta, SOL <-> canonical USDT Mainnet only.
|
||||
* No third-party script or private-key transmission. Jupiter supplies *instructions*;
|
||||
* SHiNE validates and compiles them, signs locally, and sends via its current Solana RPC.
|
||||
* This is not a security audit. Unknown instruction shapes are rejected (fail closed).
|
||||
*/
|
||||
import { getSolanaCluster, confirmSolanaTransactionHttp } from './solana-rpc-gateway.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { associatedTokenAddress, USDT_MAINNET_MINT, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, toAtomicAmount, formatAtomicAmount } from './solana-usdt-service.js';
|
||||
import { bytesToBase58 } from './crypto-utils.js';
|
||||
|
||||
export const JUPITER_API_BASE = 'https://api.jup.ag/swap/v2';
|
||||
export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
|
||||
export const JUPITER_ROUTER_PROGRAM = 'JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4';
|
||||
export const SWAP_SLIPPAGE_BPS = 50; // Max slippage: 0.5%
|
||||
export const SWAP_BETA_MAX_SOL_LAMPORTS = 20_000_000n; // 0.02 SOL
|
||||
export const SWAP_BETA_MAX_USDT_ATOMIC = 5_000_000n; // 5 USDT
|
||||
const MAX_CU_PRICE = 50_000n; // micro-lamports per compute unit
|
||||
const MAX_CU = 1_400_000;
|
||||
const SYSTEM_PROGRAM_ID = '11111111111111111111111111111111';
|
||||
const COMPUTE_PROGRAM_ID = 'ComputeBudget111111111111111111111111111111';
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
|
||||
function assertMainnet() {
|
||||
if (getSolanaCluster() !== 'mainnet-beta') throw new Error('Jupiter работает только в Solana Mainnet. Обмен на Devnet отключён.');
|
||||
}
|
||||
export function swapPair(inputCurrency) {
|
||||
if (inputCurrency === 'SOL') return {
|
||||
inputCurrency: 'SOL', outputCurrency: 'USDT', inputMint: WSOL_MINT, outputMint: USDT_MAINNET_MINT,
|
||||
inputDecimals: 9, outputDecimals: 6, maxInput: SWAP_BETA_MAX_SOL_LAMPORTS,
|
||||
};
|
||||
if (inputCurrency === 'USDT') return {
|
||||
inputCurrency: 'USDT', outputCurrency: 'SOL', inputMint: USDT_MAINNET_MINT, outputMint: WSOL_MINT,
|
||||
inputDecimals: 6, outputDecimals: 9, maxInput: SWAP_BETA_MAX_USDT_ATOMIC,
|
||||
};
|
||||
throw new Error('Для тестового обмена доступны только SOL и USDT');
|
||||
}
|
||||
|
||||
export function validateSwapInput(currency, text, balances = {}) {
|
||||
const pair = swapPair(currency);
|
||||
const amount = toAtomicAmount(text, pair.inputDecimals);
|
||||
if (amount > pair.maxInput) throw new Error(`Бета-лимит за один обмен: ${formatAtomicAmount(pair.maxInput, pair.inputDecimals)} ${currency}`);
|
||||
const available = currency === 'SOL' ? balances.solLamports : balances.usdtAtomic;
|
||||
if (available != null && amount > BigInt(available)) throw new Error(`Недостаточно ${currency}`);
|
||||
// Even USDT -> SOL requires a little SOL for tx fees and ATA rent.
|
||||
if (balances.solLamports != null && BigInt(balances.solLamports) < amount * (currency === 'SOL' ? 1n : 0n) + 10_000_000n) {
|
||||
throw new Error('Оставьте не менее 0,01 SOL для сетевых комиссий и создания токеновых счетов');
|
||||
}
|
||||
return { pair, amount };
|
||||
}
|
||||
|
||||
async function fetchJson(url) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(url, { method: 'GET', signal: controller.signal, headers: { Accept: 'application/json' }, cache: 'no-store' });
|
||||
if (!response.ok) throw new Error(`Jupiter API: HTTP ${response.status}. ${response.status === 429 ? 'Превышен лимит запросов, попробуйте позже.' : 'Котировка недоступна.'}`);
|
||||
return await response.json();
|
||||
} catch (e) {
|
||||
if (e?.name === 'AbortError') throw new Error('Jupiter не ответил вовремя');
|
||||
throw e;
|
||||
} finally { clearTimeout(timer); }
|
||||
}
|
||||
|
||||
/** Fetch real Metis instructions (not an opaque transaction) and verify the quoted amounts. */
|
||||
export async function requestSwapBuild({ inputCurrency, amountAtomic, walletAddress }) {
|
||||
assertMainnet();
|
||||
const pair = swapPair(inputCurrency);
|
||||
const amount = BigInt(amountAtomic);
|
||||
if (amount <= 0n || amount > pair.maxInput) throw new Error('Сумма вне лимита бета-обмена');
|
||||
if (!walletAddress) throw new Error('Кошелёк не выбран');
|
||||
const params = new URLSearchParams({
|
||||
inputMint: pair.inputMint, outputMint: pair.outputMint,
|
||||
amount: amount.toString(), taker: walletAddress,
|
||||
slippageBps: String(SWAP_SLIPPAGE_BPS), wrapAndUnwrapSol: 'true', transactionVersion: '0',
|
||||
});
|
||||
const response = await fetchJson(`${JUPITER_API_BASE}/build?${params}`);
|
||||
validateSwapBuildResponse(response, pair, amount);
|
||||
return { pair, amount, response, fetchedAt: Date.now() };
|
||||
}
|
||||
|
||||
function readAtomic(value) {
|
||||
if (!/^(0|[1-9]\d*)$/.test(String(value))) throw new Error('Jupiter вернул некорректную целочисленную сумму');
|
||||
return BigInt(value);
|
||||
}
|
||||
export function validateSwapBuildResponse(build, pair, amountAtomic) {
|
||||
if (!build || typeof build !== 'object' ||
|
||||
build.inputMint !== pair.inputMint || build.outputMint !== pair.outputMint ||
|
||||
readAtomic(build.inAmount) !== BigInt(amountAtomic) ||
|
||||
build.swapMode !== 'ExactIn' || !Number.isInteger(build.slippageBps) ||
|
||||
build.slippageBps < 0 || build.slippageBps > SWAP_SLIPPAGE_BPS ||
|
||||
!Array.isArray(build.routePlan) || !build.routePlan.length ||
|
||||
!build.swapInstruction || build.transactionVersion != null && String(build.transactionVersion) !== '0') {
|
||||
throw new Error('Jupiter вернул неожиданные параметры обмена');
|
||||
}
|
||||
const expected = readAtomic(build.outAmount);
|
||||
const minimum = readAtomic(build.otherAmountThreshold);
|
||||
if (expected <= 0n || minimum <= 0n || minimum > expected ||
|
||||
minimum < expected * BigInt(10_000 - SWAP_SLIPPAGE_BPS) / 10_000n) {
|
||||
throw new Error('Jupiter вернул недопустимый минимум получения');
|
||||
}
|
||||
// Protect against extra fees, additional instructions, and unexpected router contracts.
|
||||
if ((build.otherInstructions?.length || 0) !== 0 || build.tipInstruction ||
|
||||
build.swapInstruction.programId !== JUPITER_ROUTER_PROGRAM) {
|
||||
throw new Error('Неподдерживаемый маршрут Jupiter: дополнительные инструкции или другая программа');
|
||||
}
|
||||
return { expected, minimum };
|
||||
}
|
||||
|
||||
function fromBase64(encoded) {
|
||||
if (typeof encoded !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) throw new Error('Неверные данные инструкции Jupiter');
|
||||
const binary = atob(encoded);
|
||||
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
||||
}
|
||||
function accountStrings(ix) { return ix.accounts.map((a) => String(a.pubkey)); }
|
||||
function validateIxShape(ix, walletAddress) {
|
||||
if (!ix || typeof ix.programId !== 'string' || !Array.isArray(ix.accounts) || typeof ix.data !== 'string') throw new Error('Некорректная инструкция Jupiter');
|
||||
if (ix.accounts.length > 64) throw new Error('Слишком много аккаунтов в инструкции Jupiter');
|
||||
for (const a of ix.accounts) {
|
||||
if (!a || typeof a.pubkey !== 'string' || typeof a.isSigner !== 'boolean' || typeof a.isWritable !== 'boolean') throw new Error('Некорректный аккаунт инструкции');
|
||||
if (a.isSigner && a.pubkey !== walletAddress) throw new Error('Jupiter требует неизвестного подписанта');
|
||||
}
|
||||
}
|
||||
function checkedIx(apiIx, walletAddress, solana) {
|
||||
validateIxShape(apiIx, walletAddress);
|
||||
return new solana.TransactionInstruction({
|
||||
programId: new solana.PublicKey(apiIx.programId),
|
||||
keys: apiIx.accounts.map((a) => ({ pubkey: new solana.PublicKey(a.pubkey), isSigner: a.isSigner, isWritable: a.isWritable })),
|
||||
data: fromBase64(apiIx.data),
|
||||
});
|
||||
}
|
||||
function u64le(bytes, from = 1) {
|
||||
if (bytes.length < from + 8) throw new Error('Неожиданная длина инструкции');
|
||||
let value = 0n;
|
||||
for (let i = 0; i < 8; i++) value |= BigInt(bytes[from + i]) << (BigInt(i) * 8n);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The instructions are *untrusted*. Only safe setup/cleanup for the user's USDT/WSOL ATAs. */
|
||||
export function validateSwapInstructions(build, pair, amountAtomic, walletAddress, solana) {
|
||||
const token = TOKEN_PROGRAM_ID;
|
||||
const wsolAta = associatedTokenAddress(solana, walletAddress, WSOL_MINT).toBase58();
|
||||
const usdtAta = associatedTokenAddress(solana, walletAddress, USDT_MAINNET_MINT).toBase58();
|
||||
const permittedAtas = new Set([wsolAta, usdtAta]);
|
||||
const setup = Array.isArray(build.setupInstructions) ? build.setupInstructions : [];
|
||||
const cleanup = build.cleanupInstruction ? [build.cleanupInstruction] : [];
|
||||
if (setup.length > 8 || cleanup.length > 1 || (build.computeBudgetInstructions || []).length > 4) throw new Error('Слишком много инструкций Jupiter');
|
||||
let wrappedLamports = 0n;
|
||||
const checked = (ix) => {
|
||||
const validated = checkedIx(ix, walletAddress, solana);
|
||||
const bytes = validated.data;
|
||||
const ac = accountStrings(ix);
|
||||
if (ix.programId === ASSOCIATED_TOKEN_PROGRAM_ID) {
|
||||
if (![0, 1].includes(bytes[0]) || bytes.length > 1 || ac.length < 6 ||
|
||||
ac[0] !== walletAddress || ac[2] !== walletAddress ||
|
||||
!permittedAtas.has(ac[1]) ||
|
||||
(ac[3] === WSOL_MINT ? ac[1] !== wsolAta : ac[3] !== USDT_MAINNET_MINT || ac[1] !== usdtAta) ||
|
||||
ac[5] !== token) throw new Error('Jupiter пытается создать посторонний токеновый счёт');
|
||||
} else if (ix.programId === SYSTEM_PROGRAM_ID) {
|
||||
// Only wrapping SOL into the user's canonical WSOL ATA is allowed.
|
||||
if (bytes.length !== 12 || new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true) !== 2 ||
|
||||
ac[0] !== walletAddress || ac[1] !== wsolAta) throw new Error('Недопустимый системный перевод Jupiter');
|
||||
wrappedLamports += u64le(bytes, 4);
|
||||
if (pair.inputCurrency !== 'SOL' || wrappedLamports > BigInt(amountAtomic)) throw new Error('Jupiter запрашивает лишние SOL');
|
||||
} else if (ix.programId === token) {
|
||||
if (bytes[0] === 17) { // SyncNative
|
||||
if (bytes.length !== 1 || ac[0] !== wsolAta) throw new Error('Jupiter синхронизирует чужой WSOL');
|
||||
} else if (bytes[0] === 9) { // CloseAccount
|
||||
if (bytes.length !== 1 || ac[0] !== wsolAta || ac[1] !== walletAddress || ac[2] !== walletAddress) throw new Error('Jupiter закрывает чужой токеновый счёт');
|
||||
} else throw new Error('Небезопасная операция SPL в Jupiter');
|
||||
} else throw new Error(`Недопустимая программа в Jupiter: ${ix.programId}`);
|
||||
return validated;
|
||||
};
|
||||
const setupIxs = setup.map(checked);
|
||||
const cleanupIxs = cleanup.map(checked);
|
||||
const swapIx = checkedIx(build.swapInstruction, walletAddress, solana);
|
||||
if (swapIx.programId.toBase58() !== JUPITER_ROUTER_PROGRAM ||
|
||||
!build.swapInstruction.accounts.some((a) => a.pubkey === walletAddress && a.isSigner)) {
|
||||
throw new Error('Jupiter не использует ожидаемый on-chain router');
|
||||
}
|
||||
return { setupIxs, swapIx, cleanupIxs };
|
||||
}
|
||||
|
||||
async function verifiedLookupTables(conn, build, solana) {
|
||||
const tables = build.addressesByLookupTableAddress || {};
|
||||
const items = Object.entries(tables);
|
||||
if (items.length > 4) throw new Error('Слишком много таблиц адресов в Jupiter');
|
||||
const result = [];
|
||||
for (const [address, expected] of items) {
|
||||
if (!Array.isArray(expected) || expected.length > 256) throw new Error('Некорректная таблица Jupiter');
|
||||
const key = new solana.PublicKey(address);
|
||||
const account = await conn.getAccountInfo(key, 'confirmed');
|
||||
if (!account || !account.owner.equals(solana.AddressLookupTableProgram.programId)) throw new Error('Таблица адресов Jupiter отсутствует в Solana');
|
||||
const parsed = solana.AddressLookupTableAccount.deserialize(account.data);
|
||||
const actual = parsed.addresses.map((x) => x.toBase58());
|
||||
// Never trust a list of addresses given by Jupiter without checking on-chain data.
|
||||
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error('Таблица адресов Jupiter не соответствует Solana');
|
||||
if (parsed.deactivationSlot !== 18_446_744_073_709_551_615n) throw new Error('Таблица адресов Jupiter отключена');
|
||||
result.push(new solana.AddressLookupTableAccount({ key, state: parsed }));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** SPL Token account data: mint(32), owner(32), amount(u64 LE); fail closed. */
|
||||
function parseUsdtTokenAccount(data, walletAddress) {
|
||||
if (!data) return 0n;
|
||||
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
||||
if (bytes.length < 72 || bytesToBase58(bytes.subarray(0, 32)) !== USDT_MAINNET_MINT ||
|
||||
bytesToBase58(bytes.subarray(32, 64)) !== walletAddress) {
|
||||
throw new Error('В симуляции обнаружен посторонний токеновый счёт');
|
||||
}
|
||||
return u64le(bytes, 64);
|
||||
}
|
||||
|
||||
function limitedComputeBudget(build, solana, walletAddress) {
|
||||
let price = 0n;
|
||||
for (const raw of build.computeBudgetInstructions || []) {
|
||||
const ix = checkedIx(raw, walletAddress, solana);
|
||||
if (ix.programId.toBase58() !== COMPUTE_PROGRAM_ID || ix.data.length !== 9 || ix.data[0] !== 3) {
|
||||
throw new Error('Неожиданная настройка комиссии Jupiter');
|
||||
}
|
||||
const candidate = u64le(ix.data);
|
||||
if (candidate > price) price = candidate;
|
||||
}
|
||||
price = price > MAX_CU_PRICE ? MAX_CU_PRICE : price;
|
||||
return solana.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: Number(price) });
|
||||
}
|
||||
|
||||
export async function buildVerifiedSwapTransaction({ endpoint, walletAddress, build, pair, amountAtomic }) {
|
||||
assertMainnet();
|
||||
validateSwapBuildResponse(build, pair, amountAtomic);
|
||||
const solana = await loadSolanaWeb3();
|
||||
const conn = new solana.Connection(endpoint, 'confirmed');
|
||||
const { setupIxs, swapIx, cleanupIxs } = validateSwapInstructions(build, pair, amountAtomic, walletAddress, solana);
|
||||
const lookups = await verifiedLookupTables(conn, build, solana);
|
||||
const priceIx = limitedComputeBudget(build, solana, walletAddress);
|
||||
const latest = await conn.getLatestBlockhash('confirmed');
|
||||
const buildTx = (units) => new solana.VersionedTransaction(new solana.TransactionMessage({
|
||||
payerKey: new solana.PublicKey(walletAddress), recentBlockhash: latest.blockhash,
|
||||
instructions: [
|
||||
solana.ComputeBudgetProgram.setComputeUnitLimit({ units }), priceIx,
|
||||
...setupIxs, swapIx, ...cleanupIxs,
|
||||
],
|
||||
}).compileToV0Message(lookups));
|
||||
// Snapshot the wallet and canonical USDT ATA before and *after* simulation.
|
||||
// Do not rely exclusively on the untrusted Jupiter JSON quote for the actual spend.
|
||||
const usdtAta = associatedTokenAddress(solana, walletAddress, USDT_MAINNET_MINT);
|
||||
const [beforeSol, beforeUsdtInfo] = await Promise.all([
|
||||
conn.getBalance(new solana.PublicKey(walletAddress), 'confirmed'),
|
||||
conn.getAccountInfo(usdtAta, 'confirmed'),
|
||||
]);
|
||||
if (beforeUsdtInfo && beforeUsdtInfo.owner.toBase58() !== TOKEN_PROGRAM_ID) throw new Error('USDT ATA управляется неизвестной программой');
|
||||
const beforeUsdt = parseUsdtTokenAccount(beforeUsdtInfo?.data, walletAddress);
|
||||
const simulated = await conn.simulateTransaction(buildTx(MAX_CU), {
|
||||
sigVerify: false, replaceRecentBlockhash: true, commitment: 'confirmed',
|
||||
accounts: { encoding: 'base64', addresses: [walletAddress, usdtAta.toBase58()] },
|
||||
});
|
||||
if (simulated?.value?.err) throw new Error(`Обмен не прошёл проверку Solana: ${JSON.stringify(simulated.value.err)}`);
|
||||
if (!simulated?.value || !Array.isArray(simulated.value.accounts) || simulated.value.accounts.length !== 2 || !simulated.value.accounts[0]) {
|
||||
throw new Error('Solana не предоставила итоговые балансы симуляции');
|
||||
}
|
||||
const afterSol = BigInt(simulated.value.accounts[0].lamports);
|
||||
const tokenSnapshot = simulated.value.accounts[1];
|
||||
if (!tokenSnapshot) throw new Error('После симуляции USDT-счёт отсутствует');
|
||||
if (tokenSnapshot.owner !== TOKEN_PROGRAM_ID) throw new Error('После симуляции USDT-счёт управляется неизвестной программой');
|
||||
const afterUsdtBytes = typeof tokenSnapshot.data === 'string' ? fromBase64(tokenSnapshot.data)
|
||||
: Array.isArray(tokenSnapshot.data) ? fromBase64(tokenSnapshot.data[0]) : tokenSnapshot.data;
|
||||
const afterUsdt = parseUsdtTokenAccount(afterUsdtBytes, walletAddress);
|
||||
const minOut = readAtomic(build.otherAmountThreshold);
|
||||
const maxFeeAndRent = 15_000_000n; // 0.015 SOL; actual fees/rent generally much lower.
|
||||
if (pair.inputCurrency === 'SOL') {
|
||||
if (afterUsdt - beforeUsdt < minOut || BigInt(beforeSol) - afterSol > BigInt(amountAtomic) + maxFeeAndRent) {
|
||||
throw new Error('Симуляция показывает неожиданные списания или недостачу USDT');
|
||||
}
|
||||
} else if (beforeUsdt - afterUsdt !== BigInt(amountAtomic) ||
|
||||
afterSol - BigInt(beforeSol) < minOut - maxFeeAndRent) {
|
||||
throw new Error('Симуляция показывает неожиданные списания или недостачу SOL');
|
||||
}
|
||||
const consumed = Number(simulated.value.unitsConsumed);
|
||||
const limit = Number.isFinite(consumed) && consumed > 0 ? Math.min(MAX_CU, Math.max(200_000, Math.ceil(consumed * 1.25))) : MAX_CU;
|
||||
return { transaction: buildTx(limit), conn, latest, solana };
|
||||
}
|
||||
|
||||
/** The caller must have shown the exact quote and obtained explicit user consent before this. */
|
||||
export async function executeJupiterSwap({ endpoint, fromKeypair, prepared }) {
|
||||
assertMainnet();
|
||||
if (!prepared || Date.now() - prepared.fetchedAt > 30_000) throw new Error('Котировка устарела. Получите новую перед подтверждением.');
|
||||
const address = fromKeypair.publicKey.toBase58();
|
||||
const { transaction, conn, latest } = await buildVerifiedSwapTransaction({
|
||||
endpoint, walletAddress: address, build: prepared.response, pair: prepared.pair, amountAtomic: prepared.amount,
|
||||
});
|
||||
// Keys stay inside the running SHiNE client; never passed to Jupiter or SHiNE server.
|
||||
transaction.sign([fromKeypair]);
|
||||
const signature = bytesToBase58(transaction.signatures[0]);
|
||||
let submitted = false;
|
||||
try {
|
||||
// Mark the signed signature before the network call to avoid accidental duplicate swaps on RPC timeouts.
|
||||
if (typeof sessionStorage !== 'undefined') sessionStorage.setItem('shine_swap_beta_pending_signature', signature);
|
||||
submitted = true;
|
||||
await conn.sendRawTransaction(transaction.serialize(), { skipPreflight: false, maxRetries: 0 });
|
||||
await confirmSolanaTransactionHttp(conn, signature, { lastValidBlockHeight: latest.lastValidBlockHeight, timeoutMs: 100_000 });
|
||||
if (typeof sessionStorage !== 'undefined') sessionStorage.removeItem('shine_swap_beta_pending_signature');
|
||||
return { signature };
|
||||
} catch (error) {
|
||||
if (submitted) {
|
||||
const uncertain = new Error(`Статус обмена не подтверждён. Он мог выполниться! Проверьте ${signature} в Solana Explorer, прежде чем повторять. ${error?.message || error}`);
|
||||
uncertain.signature = signature;
|
||||
throw uncertain;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPendingSwapSignature(endpoint) {
|
||||
const signature = typeof sessionStorage === 'undefined' ? '' : String(sessionStorage.getItem('shine_swap_beta_pending_signature') || '');
|
||||
if (!signature) return '';
|
||||
const solana = await loadSolanaWeb3();
|
||||
const conn = new solana.Connection(endpoint, 'confirmed');
|
||||
const status = (await conn.getSignatureStatuses([signature], { searchTransactionHistory: true }))?.value?.[0];
|
||||
if (status?.confirmationStatus === 'confirmed' || status?.confirmationStatus === 'finalized' || status?.err) {
|
||||
sessionStorage.removeItem('shine_swap_beta_pending_signature');
|
||||
return '';
|
||||
}
|
||||
return signature;
|
||||
}
|
||||
@@ -209,6 +209,7 @@ export class KeyRotationClient {
|
||||
payerPrivatePkcs8B64:oldBundle.blockchainPair.privatePkcs8B64,
|
||||
authorityMode:'root',
|
||||
newRootPublicKey32:base64ToBytes(newBundle.rootPair.publicKeyB64),
|
||||
newRootPrivatePkcs8B64:newBundle.rootPair.privatePkcs8B64,
|
||||
nextClientPublicKey32:base64ToBytes(newBundle.clientPair.publicKeyB64),
|
||||
newBlockchainPublicKey32:base64ToBytes(newBundle.blockchainPair.publicKeyB64),
|
||||
newBlockchainPrivatePkcs8B64:newBundle.blockchainPair.privatePkcs8B64,
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
export {
|
||||
calcLimitTopupPriceLamports,
|
||||
getLimitStepBytes,
|
||||
getShineBlockchainUsage,
|
||||
getShineUsersEconomyConfig,
|
||||
updateShineUserPdaOnSolana,
|
||||
|
||||
@@ -70,7 +70,7 @@ export function tokenizeShineMessageLinks(text, options = {}) {
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function appendShineMessageLinks(root, text, { navigate, viewMode = 'thread', appendText } = {}) {
|
||||
export function appendShineMessageLinks(root, text, { navigate, onExternalLink, viewMode = 'thread', appendText } = {}) {
|
||||
for (const token of tokenizeShineMessageLinks(text, { viewMode })) {
|
||||
if (token.type === 'text') {
|
||||
if (typeof appendText === 'function') appendText(root, token.value);
|
||||
@@ -87,6 +87,12 @@ export function appendShineMessageLinks(root, text, { navigate, viewMode = 'thre
|
||||
}
|
||||
link.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
if (token.type === 'external' && typeof onExternalLink === 'function'
|
||||
&& event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) {
|
||||
event.preventDefault();
|
||||
onExternalLink({ href: token.href, value: token.value });
|
||||
return;
|
||||
}
|
||||
if (token.type === 'internal' && typeof navigate === 'function'
|
||||
&& event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) {
|
||||
event.preventDefault();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user