CORE/CONTENT test5593 и адаптация UI

This commit is contained in:
AidarKC
2026-11-27 00:47:13 +03:00
parent 205b7ad971
commit 873535654e
1271 changed files with 219621 additions and 1900 deletions
+16
View File
@@ -1,3 +1,19 @@
# Актуальная точка C — локальный браузер готов к C7 (26.11.2026)
C1–C6: основной клиент с локальным blockchain key адаптирован. Exact retry обычной записи и CreateGenesis реализован. 238 Node PASS, 1 прежний skip, 0 fail; legacy 1090/1090. **Полная C не принята:** реальный T2 E2E, обе регистрации и remote ESP32 signer остаются открытыми. Старый remote Frame не подключать. Дальше C7 по `handoff-core-content/history/SHiNE_C_LOCAL_READY_REPORT.md`, затем D/E. Никаких параллельных серверов/клиентов. Не повторять выполненные этапы из исторических записей ниже.
---
# CORE/CONTENT — правила миграции C (актуально)
- Сохранять существующий vanilla JS клиент, router, state, экраны, компоненты, криптографию ключей и DM, авторизацию и пользовательские сценарии.
- Никакого второго клиента, дублирующего AuthService, новой системы ключей или WS-транспорта. Менять только зависимое от формата блокчейна.
- Исторический эталон: `../old-frame-v1/shine-UI/`; не менять, не импортировать из runtime и не деплоить.
- Текущий путь записи: `js/services/auth-service.js` → `js/services/core-content.js` → исходный `ans104-data-item.js`. Состояние и остаток: `../docs/Blockchain/CORE_CONTENT_STAGE_C.md`.
- Не переключать глобально старую константу Frame namespace: её оставшиеся читатели относятся к C/D/E. Не подписывать новые Frame. Старый remote AddBlock не совместим, не включать fallback.
---
NON-NEGOTIABLE ARCHITECTURE RULES
- Read this file before editing.
@@ -67,7 +67,8 @@ export function openBlockchainDetailsModal(details, { authService, solanaEndpoin
<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" type="button" id="block-proof-download">↓ ${safe(label('download_signed'))} (CORE)</button>
<button class="secondary-btn" type="button" id="block-proof-download-content">↓ ${safe(label('download_signed'))} (CONTENT)</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>
@@ -125,21 +126,24 @@ export function openBlockchainDetailsModal(details, { authService, solanaEndpoin
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 () => {
const contentButton = get('block-proof-download-content');
const download = async (kind) => {
if (busy) return;
busy = true; button.disabled = true; verify.disabled = true;
busy = true; button.disabled = true; contentButton.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 blobUrl = URL.createObjectURL(new Blob([kind === 'CONTENT' ? proof.contentProof.bytes : proof.bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a');
link.href = blobUrl;
link.download = signedDataItemFilename(details.authorBlockchainName, currentVersion().blockNumber);
link.download = signedDataItemFilename(details.authorBlockchainName, currentVersion().blockNumber).replace(/\.ans104$/, `-${kind.toLowerCase()}.ans104`);
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; }
});
finally { busy = false; button.disabled = false; contentButton.disabled = false; verify.disabled = false; }
};
button.addEventListener('click', () => void download('CORE'));
contentButton.addEventListener('click', () => void download('CONTENT'));
verify.addEventListener('click', async () => {
if (busy) return;
busy = true; verify.disabled = true; button.disabled = true;
@@ -148,8 +152,9 @@ export function openBlockchainDetailsModal(details, { authService, solanaEndpoin
try {
const proof = await signedBlock();
const id = currentVersion().arweaveDataItemId || proof.actualId;
const [arweave, solana] = await Promise.all([
const [arweave, contentArweave, solana] = await Promise.all([
checkArweavePayload(id, proof.data),
checkArweavePayload(proof.contentProof.actualId, proof.contentProof.data),
checkSolanaAuthor({ authorLogin: details.authorLogin, blockchainName: details.authorBlockchainName,
owner32: proof.owner32, solanaEndpoint }),
]);
@@ -157,7 +162,8 @@ export function openBlockchainDetailsModal(details, { authService, solanaEndpoin
results.innerHTML = [
resultRow(label('signature'), 'valid'),
resultRow(label('integrity'), 'valid'),
resultRow(label('arweave_check'), arweave.status, arweave.reason),
resultRow(`${label('arweave_check')} (CORE)`, arweave.status, arweave.reason),
resultRow(`${label('arweave_check')} (CONTENT)`, contentArweave.status, contentArweave.reason),
resultRow(label('solana_check'), solana.status, solana.reason),
`<p class="meta-muted">${safe(label('proof_note'))}</p>`,
].join('');
+2
View File
@@ -4325,6 +4325,7 @@
}
},
"errors": {
"core_write_outcome_unknown": "The write could not be confirmed. Check the blockchain history before submitting again.",
"text_020": "Session invalid. Sign in again.",
"text_007": "Incorrect password.",
"text_008": "This user belongs to another access server.",
@@ -4631,6 +4632,7 @@
"unknown_text_to_speech_provider": "Unknown text-to-speech provider."
},
"blockchain_snapshot": {
"core_pending": "CORE/CONTENT snapshots are not available yet.",
"server_service_unavailable": "Server service unavailable.",
"login_missing": "Login missing.",
"blockchain_name_missing": "Blockchain name missing.",
+2
View File
@@ -4325,6 +4325,7 @@
}
},
"errors": {
"core_write_outcome_unknown": "Не удалось подтвердить запись. Проверьте историю блокчейна перед повторной отправкой.",
"text_001": "Нет связи с сервером. Проверьте интернет и попробуйте ещё раз.",
"text_002": "Действие не выполнено. Попробуйте еще раз.",
"text_003": "Криптография браузера недоступна. Откройте приложение через HTTPS или localhost.",
@@ -4631,6 +4632,7 @@
"unknown_text_to_speech_provider": "Неизвестный провайдер озвучки."
},
"blockchain_snapshot": {
"core_pending": "Слепки CORE/CONTENT пока недоступны.",
"server_service_unavailable": "Сервис сервера недоступен.",
"login_missing": "Не указан логин.",
"blockchain_name_missing": "Не указано имя блокчейна.",
+1 -2
View File
@@ -213,8 +213,7 @@ async function resolveChannelSelector(route) {
const ownerUser = await authService.getUser(ownerLogin);
if (!ownerUser?.exists) throw new Error(t('screens.channel_about_view.text_025'));
const ownerFeed = await authService.listSubscriptionsFeed(ownerLogin, 500);
const ownedRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
const ownedRows = (await authService.listOwnedChannelSummaries(ownerLogin, 500));
const ownerLoginNormalized = ownerLogin.toLowerCase();
const row = ownedRows.find((item) => (
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName.toLowerCase()
+1 -2
View File
@@ -66,8 +66,7 @@ async function resolveChannelSelector(route) {
if (!ownerUser?.exists) throw new Error(t('screens.channel_donate_view.text_015'));
const ownerBlockchainName = String(ownerUser.blockchainName || ownerRef).trim();
const ownerFeed = await authService.listSubscriptionsFeed(ownerLogin, 500);
const ownedRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
const ownedRows = (await authService.listOwnedChannelSummaries(ownerLogin, 500));
const row = ownedRows.find((item) => (
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName.toLowerCase()
&& String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerBlockchainName.toLowerCase()
+2 -4
View File
@@ -320,8 +320,7 @@ async function resolveChannelDisplayNameFromServer(channelSelector) {
if (!ownerLogin) return '';
try {
const feed = await authService.listSubscriptionsFeed(ownerLogin, 1000);
const rows = Array.isArray(feed?.ownedChannels) ? feed.ownedChannels : [];
const rows = (await authService.listOwnedChannelSummaries(ownerLogin, 1000));
const row = rows.find((item) => (
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerBch.toLowerCase()
&& Number(item?.channel?.channelRoot?.blockNumber) === rootNo
@@ -1444,9 +1443,8 @@ async function loadThreadData(sel, cacheKey, isCurrent) {
}
if (!channel && ownerLoginFromBch) {
try {
const ownerFeed = await authService.listSubscriptionsFeed(ownerLoginFromBch, 500);
const ownerRows = (await authService.listOwnedChannelSummaries(ownerLoginFromBch, 500));
if (!isCurrent()) return null;
const ownerRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
channel = ownerRows.find((item) => (
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerNormalized
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
+49 -84
View File
@@ -64,7 +64,7 @@ import {
} from '../services/shine-routes.js';
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
import { dropPageData, readPageData, writePageData } from '../services/page-data-cache.js';
import { sortedChannelPublications } from '../services/channel-message-ordinals.js';
import { sortedChannelPublications, canonicalReadPosts, readPrefixCount } from '../services/channel-message-ordinals.js';
import { scrollNodeIntoContainer } from '../services/scroll-utils.js';
export const pageMeta = { id: 'channel-view', get title() { return t('screens.channel_view.text_001'); }, shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
@@ -316,27 +316,26 @@ function scrollChannelToUnreadLine(screen, unreadCount = 0, smooth = false) {
function createChannelReadTracker({
screen,
routeKey,
ownerBlockchainName,
channelName,
readSummary,
posts,
initializeIfMissing = false,
unreadCount,
messagesCount,
initialSeenCount,
onPersistError = null,
onPersistSuccess = null,
}) {
const login = String(state.session.login || '').trim();
const storagePwd = state.session.storagePwdInMemory;
const cleanOwnerBlockchainName = String(ownerBlockchainName || '').trim();
const cleanChannelName = String(channelName || '').trim();
const orderedPosts = canonicalReadPosts(posts, readSummary);
const rootRef = readSummary?.channel?.channelRoot;
const missingWriteParts = [];
if (!cleanOwnerBlockchainName) missingWriteParts.push('ownerBlockchainName');
if (!cleanChannelName) missingWriteParts.push('channelName');
if (!orderedPosts) missingWriteParts.push('CORE read prefix');
if (!login) missingWriteParts.push('login');
if (!storagePwd) missingWriteParts.push('storagePwd');
const canWrite = missingWriteParts.length === 0;
const safeMessagesCount = Math.max(0, Number(messagesCount || 0));
const safeMessagesCount = orderedPosts?.length || 0;
const safeInitialSeenCount = Math.max(0, Math.min(Number(initialSeenCount || 0), safeMessagesCount));
const seenOrdinals = new Set();
const unreadAnchorFraction = getUnreadAnchorViewportFraction(unreadCount);
let desiredSeenCount = safeInitialSeenCount;
@@ -375,16 +374,19 @@ function createChannelReadTracker({
inFlight = true;
try {
const anchor = next === 0 ? rootRef : orderedPosts[next - 1].messageRef;
const persisted = await authService.setChannelReadState({
login,
ownerBlockchainName: cleanOwnerBlockchainName,
channelName: cleanChannelName,
readCount: next,
login, owner: readSummary.channel.ownerLogin, root: rootRef.blockNumber, rootHash: rootRef.blockHash,
followHash: readSummary.followHash, anchor: anchor.blockNumber, anchorHash: anchor.blockHash,
timeMs: Date.now(),
storagePwd,
});
const serverReadCount = Math.max(0, Number(persisted?.read_count ?? next));
const serverUnreadCount = Math.max(0, Number(persisted?.unread_count ?? Math.max(0, safeMessagesCount - serverReadCount)));
if (disposed) return;
if (persisted?.state?.followHash !== readSummary.followHash || !persisted.state.initialized || !Number.isInteger(persisted.state.readCount) || !Number.isInteger(persisted.state.unreadCount)) throw new Error('READ_STATE_RETRY');
const serverReadCount = persisted.state.readCount;
const serverUnreadCount = persisted.state.unreadCount;
// A changed count can mean that the canonical prefix was replaced while the view was open.
if (serverReadCount < persistedSeenCount || serverReadCount + serverUnreadCount !== safeMessagesCount) throw new Error('READ_STATE_RETRY');
persistedSeenCount = Math.max(persistedSeenCount, Math.min(serverReadCount, safeMessagesCount));
desiredSeenCount = Math.max(desiredSeenCount, persistedSeenCount);
initialPersistPending = false;
@@ -396,8 +398,9 @@ function createChannelReadTracker({
});
}
} catch (error) {
if (disposed) return;
const errorCode = String(error?.code || '').trim().toUpperCase();
if (errorCode === 'CHANNEL_NOT_FOLLOWED') {
if (['CHANNEL_NOT_FOLLOWED','READ_ANCHOR_STALE','READ_STATE_RETRY','BAD_READ_STATE','BAD_TIME','BAD_SIGNATURE','LOGIN_MISMATCH','SESSION_NOT_FOUND','AUTH_REQUIRED','CHANNEL_NOT_FOUND','ACCOUNT_NOT_REGISTERED'].includes(errorCode || String(error?.message || ''))) {
// This is a persistent state mismatch, not a transient transport failure.
// Stop writes for the current channel view instead of hammering the server
// after every scroll/resize. A fresh view after subscribe/refresh will create
@@ -426,19 +429,14 @@ function createChannelReadTracker({
const viewportHeight = root?.clientHeight || window.innerHeight || document.documentElement.clientHeight || 0;
const thresholdTop = Math.max(0, Math.round(viewportHeight * unreadAnchorFraction));
const visibleBottom = Math.max(thresholdTop, viewportHeight - 24);
let seen = safeInitialSeenCount;
if (!orderedPosts) return safeInitialSeenCount;
for (const card of cards) {
const localNumber = Number(card.dataset.localNumber || 0);
if (!Number.isFinite(localNumber) || localNumber <= 0) continue;
if (!Number.isInteger(localNumber) || localNumber <= 0) continue;
const rect = card.getBoundingClientRect();
if (rect.top > visibleBottom) break;
if (rect.bottom < 0) {
seen = Math.max(seen, localNumber);
continue;
}
seen = Math.max(seen, localNumber);
if (rect.top <= visibleBottom && rect.bottom > 0) seenOrdinals.add(localNumber);
}
return Math.max(safeInitialSeenCount, Math.min(seen, safeMessagesCount));
return readPrefixCount(orderedPosts, persistedSeenCount, seenOrdinals);
};
const measure = () => {
@@ -1389,8 +1387,7 @@ async function loadFromApi(route, channelId) {
const ownerLoginForLookup = routeOwnerLoginFromBch || (!looksLikeBlockchainName(routeOwnerRaw) ? routeOwnerRaw : '');
if (ownerLoginForLookup) {
try {
const ownerFeed = await authService.listSubscriptionsFeed(ownerLoginForLookup, 500);
const ownerRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
const ownerRows = await authService.listOwnedChannelSummaries(ownerLoginForLookup, 500);
const ownerLoginNormalized = ownerLoginForLookup.toLowerCase();
channel = ownerRows.find((item) => (
String(item?.channel?.channelName || '').trim().toLowerCase() === selector.channelName.toLowerCase()
@@ -1457,13 +1454,11 @@ async function loadFromApi(route, channelId) {
const payload = await authService.getChannelMessages(selector, null, 'asc', currentSessionLogin);
const messages = Array.isArray(payload.messages) ? payload.messages : [];
let reverseChannelMissingWarning = '';
let mergedMessages = [...messages];
const reverseChannelMissingWarning = '';
const mergedMessages = [...messages];
if (!messagesCount) messagesCount = mergedMessages.length;
const currentLogin = currentSessionLogin;
const ownerLogin = String(payload.channel?.ownerLogin || '').trim();
const channelName = String(payload.channel?.channelName || '').trim();
const channelTypeCode = Number(payload.channel?.channelTypeCode ?? 1);
// Channel-publication URLs are only unambiguous for public channels, not merged private chats.
selector.channelName = String(payload.channel?.channelName || selector.channelName || '').trim();
@@ -1472,46 +1467,24 @@ async function loadFromApi(route, channelId) {
if (channelTypeCode === CHANNEL_TYPE_STORIES) {
throw new Error(t('screens.channel_view.text_120'));
}
const canResolveReverse = (
channelTypeCode === CHANNEL_TYPE_PERSONAL
&& !!currentLogin
&& !!ownerLogin
&& !!channelName
&& ownerLogin.toLowerCase() === currentLogin.toLowerCase()
);
if (canResolveReverse) {
const allRows = await getAllRows();
const reverseSummary = allRows.find((item) => (
Number(item?.channel?.channelTypeCode ?? 1) === CHANNEL_TYPE_PERSONAL
&& String(item?.channel?.ownerLogin || '').trim().toLowerCase() === channelName.toLowerCase()
&& String(item?.channel?.channelName || '').trim().toLowerCase() === currentLogin.toLowerCase()
));
if (reverseSummary?.channel?.ownerBlockchainName && reverseSummary?.channel?.channelRoot?.blockNumber != null) {
const reverseSelector = {
ownerBlockchainName: String(reverseSummary.channel.ownerBlockchainName),
channelRootBlockNumber: Number(reverseSummary.channel.channelRoot.blockNumber),
channelRootBlockHash: normalizeRouteHash(reverseSummary.channel.channelRoot.blockHash),
};
const reversePayload = await authService.getChannelMessages(reverseSelector, null, 'asc', currentSessionLogin);
const reverseMessages = Array.isArray(reversePayload?.messages) ? reversePayload.messages : [];
mergedMessages = mergedMessages.concat(reverseMessages);
} else {
reverseChannelMissingWarning = t('screens.channel_view.text_145', { value1: channelName });
}
}
// The current server already merges both sides of PERSONAL channels.
// Fetching and appending the reverse side again duplicates every post.
const posts = sortedChannelPublications(
mergedMessages.map((message, index) => mapApiMessageToPost(message, selector, index + 1)),
).map((post, index) => ({ ...post, localNumber: index + 1 }));
const isOwnChannel = ownerLogin.toLowerCase() === currentSessionLogin.toLowerCase();
const followedRows = Array.isArray(state.channelsFeed?.followedChannels) ? state.channelsFeed.followedChannels : [];
const isSubscribed = isAuthorized && followedRows.some((row) => (
String(row?.channel?.ownerBlockchainName || '') === String(selector.ownerBlockchainName || '')
const followedRows = isAuthorized ? (await ensureFeed())?.followedChannels || [] : [];
const readSummary = followedRows.find(row =>
String(row?.channel?.ownerBlockchainName || '').toLowerCase() === String(selector.ownerBlockchainName || '').toLowerCase()
&& Number(row?.channel?.channelRoot?.blockNumber) === Number(selector.channelRootBlockNumber)
&& normalizeRouteHash(row?.channel?.channelRoot?.blockHash) === normalizeRouteHash(selector.channelRootBlockHash)
));
&& normalizeRouteHash(row?.channel?.channelRoot?.blockHash) === normalizeRouteHash(selector.channelRootBlockHash));
const isSubscribed = !!readSummary;
if (readSummary) {
unreadCount = Number(readSummary.unreadCount || 0);
messagesCount = Number(readSummary.messagesCount || 0);
readCount = Number(readSummary.readCount || 0);
readStateInitialized = !!readSummary.readStateInitialized;
}
return {
channel: {
@@ -1539,6 +1512,7 @@ async function loadFromApi(route, channelId) {
isOwnChannel,
isSubscribed,
readStateInitialized,
readSummary,
selector,
};
}
@@ -2306,7 +2280,9 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
const postsByKey = new Map();
const metaEvents = (Array.isArray(channelData.metaEvents) ? channelData.metaEvents : [])
.map((event) => mapChannelMetaEvent(event, channelData.channel));
let unreadLineInserted = unreadCount === 0;
const canonicalPosts = canonicalReadPosts(channelData.posts, channelData.readSummary);
const unreadOrdinals = canonicalPosts ? new Set(canonicalPosts.slice(readCount).map(post => post.localNumber)) : null;
let unreadLineInserted = unreadCount === 0 || !unreadOrdinals;
const feedItems = [
...metaEvents.map((event) => ({
type: 'meta',
@@ -2339,7 +2315,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
separator.innerHTML = `<span>${escapeHtml(formatDayLabel(item.timestampMs))}</span>`;
feed.append(separator);
}
if (!unreadLineInserted && item.type === 'post' && Number(item?.post?.localNumber || 0) > readCount) {
if (!unreadLineInserted && item.type === 'post' && unreadOrdinals?.has(item.post.localNumber)) {
const unreadLine = document.createElement('div');
unreadLine.className = 'card channel-unread-line';
unreadLine.textContent = t('dialogs.modals.channel_view.label_055');
@@ -2426,17 +2402,17 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
channelData.isSubscribed
&& !channelData.isOwnChannel
&& !channelData.isDiary
&& !!channelData.readSummary?.followHash
);
const tracker = shouldTrackReadState
? createChannelReadTracker({
screen,
routeKey,
ownerBlockchainName: channelData.channel?.ownerBlockchainName || channelData.selector?.ownerBlockchainName,
channelName: channelData.channel?.name || channelData.channel?.channelName,
readSummary: channelData.readSummary,
posts: channelData.posts,
initializeIfMissing: !!(!channelData.readStateInitialized),
unreadCount,
messagesCount,
initialSeenCount: readCount,
onPersistError: (error, options = {}) => {
const detail = String(error?.message || '').trim();
@@ -2678,19 +2654,8 @@ export function render({ navigate, route, chrome }) {
});
if (disposed) return;
try {
await authService.setChannelReadState({
login,
ownerBlockchainName: apiData.channel?.ownerBlockchainName || apiData.selector?.ownerBlockchainName,
channelName: apiData.channel?.name || apiData.channel?.channelName,
readCount: Math.max(0, Number(apiData.messagesCount || 0)),
timeMs: Date.now(),
storagePwd,
});
} catch (readStateError) {
showStatus(toUserMessage(readStateError, t('screens.channel_view.text_058')));
}
// Refresh the signed subscription identity; the viewport tracker initializes
// the root and advances only over the actually seen canonical prefix.
const feed = await authService.listSubscriptionsFeed(login, 200);
if (disposed) return;
setChannelsFeed(feed, state.channelsIndex);
+1 -2
View File
@@ -186,8 +186,7 @@ async function resolveChannelTargetFromInput(rawInput) {
throw new Error(t('screens.channels_list.text_030'));
}
const ownerFeed = await authService.listSubscriptionsFeed(ownerLogin, 500);
const ownChannels = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels.filter(isVisibleChannelSummary) : [];
const ownChannels = (await authService.listOwnedChannelSummaries(ownerLogin, 500)).filter(isVisibleChannelSummary);
const matches = ownChannels.filter((item) => (
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName
));
+15 -12
View File
@@ -2,8 +2,7 @@ import { formatDateTime } from '../i18n/format.js';
import { t, th } from '../i18n/index.js';
import { createTopBar } from '../components/topbar.js';
import { authService } from '../state.js';
import { KeyRotationClient } from '../services/key-rotation-service.js';
import { inspectBlockchainDataItem } from '../services/blockchain-entry-inspector.js';
import { inspectCoreBlock } from '../services/blockchain-entry-inspector.js';
import { makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
import { actionErrorText } from '../services/ui-error-texts.js';
@@ -75,6 +74,7 @@ function shortHash(value) {
}
function formatDate(ms) {
if (ms == null) return '—';
try {
return formatDateTime(new Date(Number(ms) || 0));
} catch {
@@ -145,10 +145,10 @@ function lineTextKindLabel(subType) {
}
function describeEntry(item, inspection, channelNames) {
if (!inspection?.frame) {
if (!inspection?.frame || inspection.frame.type == null || inspection.contentStatus !== 'VALID') {
return {
title: t('screens.my_blockchain_view.text_075', { value1: item.msgType, value2: item.msgSubType }),
detailTitle: t('screens.my_blockchain_view.text_076', { value1: item.msgType, value2: item.msgSubType }),
title: 'CORE',
detailTitle: inspection?.contentStatus ? `CONTENT: ${inspection.contentStatus}` : 'CORE',
text: '',
attachmentsCount: 0,
};
@@ -436,17 +436,19 @@ function createEntryCard({ item, inspection, parseError, channelNames, blockchai
const info = document.createElement('div');
info.className = 'my-blockchain-entry__detail-grid';
const effectiveType = frame ? `${frame.type}/${frame.subType} · v${frame.version}` : `${item.msgType}/${item.msgSubType} · v${item.msgVersion}`;
const effectiveType = frame && frame.type != null && inspection?.contentStatus === 'VALID' ? `${frame.type}/${frame.subType} · v${frame.version}` : '—';
addDetailRow(info, t('screens.my_blockchain_view.text_016'), effectiveType);
addDetailRow(info, t('screens.my_blockchain_view.text_017'), `#${item.blockNumber}`);
addDetailRow(info, t('screens.my_blockchain_view.text_018'), formatDate(item.timestampMs));
addDetailRow(info, t('screens.my_blockchain_view.text_019'), item.blockHash, { code: true });
if (inspection?.dataItemId) addDetailRow(info, 'DataItem ID', inspection.dataItemId, { code: true });
if (inspection?.dataItemId) addDetailRow(info, 'CORE DataItem ID', inspection.dataItemId, { code: true });
if (inspection?.contentDataItemId) addDetailRow(info, 'CONTENT DataItem ID', inspection.contentDataItemId, { code: true });
if (inspection?.contentStatus) addDetailRow(info, 'CONTENT', inspection.contentStatus);
const body = frame?.body || {};
if (body.line) {
if (Number.isInteger(Number(body.line.lineCode))) addDetailRow(info, t('screens.my_blockchain_view.text_020'), `#${body.line.lineCode}`);
if (Number.isInteger(Number(body.line.lineSequence))) addDetailRow(info, t('screens.my_blockchain_view.text_021'), body.line.lineSequence);
if (Number.isInteger(body.line.lineSequence)) addDetailRow(info, t('screens.my_blockchain_view.text_021'), body.line.lineSequence);
}
if (body.kind === 'profile') {
addDetailRow(info, t('screens.my_blockchain_view.text_022'), body.key);
@@ -526,7 +528,6 @@ export function render({ navigate, chrome }, { historyOnly = false } = {}) {
more.hidden = true;
screen.append(more);
const client = new KeyRotationClient(authService);
const channelNames = new Map([[0, 'stories']]);
let channelsLoaded = false;
let before = null;
@@ -561,7 +562,7 @@ export function render({ navigate, chrome }, { historyOnly = false } = {}) {
before = null;
}
try {
const data = await client.getMyBlockchain({ beforeBlock: before, limit: 50, includeBlockBytes: true });
const data = await authService.getMyBlockchainPage({ beforeBlock: before, limit: 50, includeBlockBytes: true });
if (disposed || seq !== loadSeq) return;
await ensureChannelNames(String(data.login || '').trim());
if (disposed || seq !== loadSeq) return;
@@ -574,9 +575,11 @@ export function render({ navigate, chrome }, { historyOnly = false } = {}) {
}
const rows = await Promise.all((data.blocks || []).map(async (item) => {
if (!item?.blockBytesB64) return { item, inspection: null, parseError: t('screens.my_blockchain_view.text_066') };
item = { ...item, blockHash: item.coreHash };
if (!item?.coreDataItemB64) return { item, inspection: null, parseError: t('screens.my_blockchain_view.text_066') };
try {
const inspection = await inspectBlockchainDataItem(item.blockBytesB64);
const inspection = await inspectCoreBlock(item);
item = { ...item, blockHash: item.coreHash, timestampMs: inspection.frame.timestampMs, msgType: inspection.frame.type, msgSubType: inspection.frame.subType, msgVersion: inspection.frame.version };
const body = inspection?.frame?.body;
if (inspection?.frame?.type === 0 && inspection?.frame?.subType === 1) {
const root = Number(inspection.frame.blockNumber);
@@ -32,7 +32,7 @@ import { getNamespace, normalizeFullLogin } from '../services/shine-namespace-se
import { calculateRegistrationFunding, USER_PDA_SPACE, solFromLamports } from '../services/registration-upgrade-helpers.js';
export const pageMeta = { id: 'registration-payment-view', get title() { return t('screens.registration_payment_view.text_001'); }, showAppChrome: false };
const TEST_TOPUP_AMOUNT_SOL = 0.032;
const TEST_TOPUP_AMOUNT_SOL = 0.04;
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
@@ -750,7 +750,7 @@ function renderSolanaDoneStage({ navigate, status, keyBundle, registrationTxId =
}, AUTO_LOGIN_INITIAL_DELAY_MS);
}
/** Тот же тестовый источник +0.032 devnet SOL, что используется обычной регистрацией.
/** Тот же тестовый источник +0.04 devnet SOL, что используется обычной регистрацией.
* Экспорт добавлен для FREE_CERT → Solana upgrade; поведение обычной регистрации не изменяется.
* Никогда не используйте этот встроенный devnet-кошелёк для реальных средств.
*/
+155 -544
View File
@@ -39,9 +39,9 @@ import {
saveEncryptedUserSecrets,
saveSessionMaterial,
} from './key-vault.js';
import { createAns104DataItem, parseAns104DataItem } from './ans104-data-item.js';
import { coreHashBytes, coreHex, signCoreContentPair, splitEventBody } from './core-content.js';
import { defaultServerWs } from '../deploy-config.js';
import { SHINE_APP_TAG_NAME, SHINE_APP_TAG_VALUE, SHINE_CHANNEL_TAG_NAME, SHINE_TYPE_TAG_NAME } from './protocol-tags.js';
import { SHINE_CORE_LINE_PROFILE, SHINE_CORE_LINE_CONNECTION, SHINE_CORE_LINE_TECH } from './protocol-tags.js';
const BCH_SUFFIX = '001';
const ZERO64 = '0'.repeat(64);
@@ -94,8 +94,6 @@ const SESSION_TYPE_WALLET = 50;
const SESSION_TYPE_HOMESERVER = 100;
const SIGNAL_TARGET_SINGLE = 'single_session';
const SIGNAL_TARGET_ALL = 'all_sessions';
const SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST = 'remote_addblock_request';
const SIGNAL_TYPE_REMOTE_ADDBLOCK_RESULT = 'remote_addblock_result';
const CONNECTION_SUBTYPES = Object.freeze({
close_friend: { on: 10, off: 11 },
@@ -151,10 +149,6 @@ function opError(op, response) {
return error;
}
function createSignalRequestId(prefix = 'signal') {
return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function makeClientInfo() {
const ua = navigator.userAgent || 'unknown';
return ua.slice(0, 50);
@@ -224,13 +218,6 @@ function int8Byte(value) {
return new Uint8Array([n & 0xff]);
}
function int64Bytes(value) {
const bytes = new Uint8Array(8);
const view = new DataView(bytes.buffer);
view.setBigInt64(0, BigInt(value), false);
return bytes;
}
function uint16Bytes(value) {
const bytes = new Uint8Array(2);
const view = new DataView(bytes.buffer);
@@ -541,9 +528,7 @@ function extractContactsFromDialogs(dialogs) {
return out;
}
export const HEADER_LICENSE_CC0 = 'CC0-1.0';
export const HEADER_LICENSE_FIELD_CC0 = `license:${HEADER_LICENSE_CC0}`;
export const HEADER_VERSION_CC0 = 2;
export const HEADER_CONTENT_VERSION = 1;
function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
const cleanLogin = String(login || '').trim();
@@ -559,7 +544,6 @@ function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
utf8Bytes('SHiNE'),
int8Byte(loginBytes.length),
loginBytes,
utf8Bytes(HEADER_LICENSE_FIELD_CC0),
keyBytes,
);
}
@@ -892,81 +876,17 @@ function resolveLatestLineStep(message) {
return null;
}
function bytesToHexLower(bytes) {
return Array.from(bytes || [], (value) => Number(value).toString(16).padStart(2, '0')).join('');
}
function parseStoredLineMeta(blockBytesB64, { fixedLine = false } = {}) {
const raw = base64ToBytes(String(blockBytesB64 || ''));
const frame = parseAns104DataItem(raw).data;
const bodyOffset = 88;
const minLength = fixedLine ? bodyOffset + 40 : bodyOffset + 44;
if (!(frame instanceof Uint8Array) || frame.length < minLength) throw new Error('Некорректный line-блок');
const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
if (fixedLine) {
return {
lineCode: 0,
prevLineNumber: view.getInt32(bodyOffset, false),
prevLineHashHex: bytesToHexLower(frame.slice(bodyOffset + 4, bodyOffset + 36)),
lineSequence: view.getInt32(bodyOffset + 36, false),
};
}
return {
lineCode: view.getInt32(bodyOffset, false),
prevLineNumber: view.getInt32(bodyOffset + 4, false),
prevLineHashHex: bytesToHexLower(frame.slice(bodyOffset + 8, bodyOffset + 40)),
lineSequence: view.getInt32(bodyOffset + 40, false),
};
}
function typeIndexTagValue(msgType) {
switch (Number(msgType)) {
case MSG_TYPE_TECH: return 'tech';
case MSG_TYPE_CONNECTION: return 'conn';
case MSG_TYPE_USER_PROFILE: return 'prof';
default: return '';
}
}
function isLineConflictError(error) {
return new Set([
'BAD_PREV_LINE_NUMBER',
'BAD_PREV_LINE_HASH',
'BAD_LINE_SEQUENCE',
'BAD_LINE_STATE',
'LINE_HEAD_CONFLICT',
'GLOBAL_HEAD_CONFLICT',
]).has(String(error?.code || '').toUpperCase());
}
function buildBlockPreimage({ prevBlockHashHex, back32HashHex, blockNumber, msgType, msgSubType, msgVersion = 1, bodyBytes }) {
const prevHashBytes = hexToBytes(normalizeHex32(prevBlockHashHex));
const back32HashBytes = hexToBytes(normalizeHex32(back32HashHex, ZERO64));
const body = bodyBytes || new Uint8Array(0);
const blockSize = 2 + 32 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + body.length;
return concatBytes(
int16Bytes(1),
prevHashBytes,
back32HashBytes,
int32Bytes(blockSize),
int32Bytes(blockNumber),
int64Bytes(Math.floor(Date.now() / 1000)),
int16Bytes(msgType),
int16Bytes(msgSubType),
int16Bytes(msgVersion),
body
);
}
function buildRemoteBlockBodyBytes({ msgType, msgSubType, msgVersion = 1, bodyBytes }) {
const body = bodyBytes || new Uint8Array(0);
return concatBytes(
int16Bytes(msgType),
int16Bytes(msgSubType),
int16Bytes(msgVersion),
body,
);
}
export class AuthService {
constructor(serverUrl) {
this.serverUrl = normalizeServerUrl(serverUrl);
@@ -974,7 +894,6 @@ export class AuthService {
this.eventListeners = new Map();
this.wsEventUnsubscribers = new Map();
this.headerHashCache = new Map();
this.lineTailCache = new Map();
this.lineWriteQueues = new Map();
this.writeLocks = new Map();
this.passwordKeyBundleCache = new Map();
@@ -1010,7 +929,6 @@ export class AuthService {
this.ws = new WsJsonClient(this.serverUrl);
this.ws.setRequestGuard(requestGuard);
this.headerHashCache = new Map();
this.lineTailCache = new Map();
this.lineWriteQueues = new Map();
this.writeLocks.clear();
this.bindRegisteredEventsToCurrentWs();
@@ -1589,6 +1507,16 @@ export class AuthService {
return response.payload || {};
}
// Public channel lookup is not a request for another user's private feed.
async listOwnedChannelSummaries(login, limit = 500) {
const result = await this.listUserProfileChannels(login, 'owned', limit, 0, false);
return (Array.isArray(result?.channels) ? result.channels : []).map(row => ({ channel: {
ownerLogin: row.ownerLogin, ownerBlockchainName: row.ownerBlockchainName,
channelName: row.slug, displayName: row.displayName, avaAr: row.avatarAr, avaPr: row.avatarPr,
deleted: !!row.deleted, channelRoot: { blockNumber: row.rootBlockNumber, blockHash: row.rootBlockHashHex },
} }));
}
async getChannelMessages(channel, limit = null, sort = 'asc', login = '') {
const normalizedChannel = {
ownerBlockchainName: String(channel?.ownerBlockchainName || '').trim(),
@@ -1661,266 +1589,105 @@ export class AuthService {
return response.payload || {};
}
async resolveFreshBlockchainCursor(login) {
const cleanLogin = String(login || '').trim();
const user = await this.getUser(cleanLogin);
const blockchainName = String(user?.blockchainName || `${cleanLogin}-${BCH_SUFFIX}`).trim();
const freshNum = Number(user?.serverLastGlobalNumber);
const freshHash = normalizeHex32(user?.serverLastGlobalHash, ZERO64);
return {
blockchainName,
cursor: {
serverLastGlobalNumber: Number.isFinite(freshNum) ? freshNum : -1,
serverLastGlobalHash: freshHash,
},
};
}
async submitPreparedAddBlock({ login, storagePwd, blockchainName, blockNumber, prevBlockHash, preimage, ansTags }) {
const cleanLogin = String(login || '').trim();
const cleanBlockchainName = String(blockchainName || '').trim();
const cleanPrevBlockHash = normalizeHex32(prevBlockHash, ZERO_HASH_HEX);
if (!cleanLogin || !cleanBlockchainName) throw new Error('submitPreparedAddBlock: missing login/blockchainName');
if (!(preimage instanceof Uint8Array) || preimage.length === 0) {
throw new Error('submitPreparedAddBlock: bad preimage');
}
const savedKeys = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
const blockchainPrivatePkcs8 = String(savedKeys?.blockchainKey || '').trim();
if (blockchainPrivatePkcs8) {
const privateKey = await importPkcs8Ed25519(blockchainPrivatePkcs8);
const owner32 = base64ToBytes(await publicKeyB64FromPkcs8Ed25519(blockchainPrivatePkcs8));
const dataItemBytes = await createAns104DataItem({
owner32,
privateKey,
data: preimage,
tags: Array.isArray(ansTags) && ansTags.length ? ansTags : [{ name: SHINE_APP_TAG_NAME, value: SHINE_APP_TAG_VALUE }],
});
return this.ws.request('AddBlock', {
blockchainName: cleanBlockchainName,
blockNumber: Number(blockNumber),
prevBlockHash: cleanPrevBlockHash,
blockBytesB64: bytesToBase64(dataItemBytes),
});
}
const remoteSessionId = String(this.remoteAddBlockSessionId || '').trim();
if (!remoteSessionId) {
throw new Error('На устройстве нет blockchain key и не выбрана homeserver-сессия для remote AddBlock');
}
const signalRequestId = createSignalRequestId('remote-addblock');
const responseWait = this.waitForSignal({
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_RESULT,
signalRequestId,
timeoutMs: 20000,
});
const signalData = {
operation: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
login: cleanLogin,
blockchainName: cleanBlockchainName,
blockNumber: Number(blockNumber),
prevBlockHash: cleanPrevBlockHash,
blockPreimageB64: bytesToBase64(preimage),
};
await this.sendSignal({
toLogin: cleanLogin,
targetMode: SIGNAL_TARGET_SINGLE,
targetSessionId: remoteSessionId,
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
data: JSON.stringify(signalData),
storagePwd,
includeClientSignature: true,
});
const signalPayload = await responseWait;
let result = {};
try {
result = JSON.parse(String(signalPayload?.data || '{}'));
} catch {
throw new Error('Некорректный ответ remote AddBlock от homeserver');
}
if (!result?.ok) {
throw new Error(String(result?.errorMessage || result?.error || 'remote_addblock_failed'));
}
return {
status: 200,
payload: {
serverLastGlobalNumber: Number(result?.serverLastGlobalNumber ?? blockNumber),
serverLastGlobalHash: String(result?.serverLastGlobalHash || ZERO_HASH_HEX),
remote: true,
},
};
}
async submitRemoteAddBlockBody({ login, storagePwd, blockchainName, blockBodyBytes }) {
const cleanLogin = String(login || '').trim();
const cleanBlockchainName = String(blockchainName || '').trim();
if (!cleanLogin || !cleanBlockchainName) throw new Error('submitRemoteAddBlockBody: missing login/blockchainName');
if (!(blockBodyBytes instanceof Uint8Array) || blockBodyBytes.length < 6) {
throw new Error('submitRemoteAddBlockBody: bad blockBodyBytes');
}
const remoteSessionId = String(this.remoteAddBlockSessionId || '').trim();
if (!remoteSessionId) {
throw new Error('На устройстве нет blockchain key и не выбрана homeserver-сессия для remote AddBlock');
}
const signalRequestId = createSignalRequestId('remote-addblock');
const responseWait = this.waitForSignal({
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_RESULT,
signalRequestId,
timeoutMs: 20000,
});
const signalData = {
operation: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
blockchainName: cleanBlockchainName,
blockBodyB64: bytesToBase64(blockBodyBytes),
};
await this.sendSignal({
toLogin: cleanLogin,
targetMode: SIGNAL_TARGET_SINGLE,
targetSessionId: remoteSessionId,
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
data: JSON.stringify(signalData),
storagePwd,
includeClientSignature: true,
});
const signalPayload = await responseWait;
let result = {};
try {
result = JSON.parse(String(signalPayload?.data || '{}'));
} catch {
throw new Error('Некорректный ответ remote AddBlock от homeserver');
}
if (!result?.ok) {
throw new Error(String(result?.errorMessage || result?.error || 'remote_addblock_failed'));
}
return {
status: 200,
payload: {
serverLastGlobalNumber: Number(result?.serverLastGlobalNumber ?? -1),
serverLastGlobalHash: String(result?.serverLastGlobalHash || ZERO_HASH_HEX),
remote: true,
},
};
}
async runAddBlockWithRetry({ login, storagePwd, resolveFreshState, buildPreimage, ansTags }) {
let freshState = await resolveFreshState();
let blockchainName = String(freshState?.blockchainName || '').trim();
if (!blockchainName) throw new Error('runAddBlockWithRetry: blockchainName is empty');
const tryAdd = async (cursor) => {
const blockNumber = Number(cursor?.serverLastGlobalNumber ?? -1) + 1;
const prevBlockHash = normalizeHex32(cursor?.serverLastGlobalHash, ZERO64);
const back32Hash = blockNumber < 32
? ZERO64
: normalizeHex32(await this.getBlockHashByNumber(blockchainName, blockNumber - 32), ZERO64);
if (blockNumber >= 32 && back32Hash === ZERO64) {
throw new Error(`Не удалось получить hash блока #${blockNumber - 32} для back32Hash`);
}
const preimage = await buildPreimage({ blockNumber, prevBlockHash, back32Hash, blockchainName });
return this.submitPreparedAddBlock({
login,
storagePwd,
blockchainName,
blockNumber,
prevBlockHash,
preimage,
ansTags,
});
};
let cursor = freshState.cursor;
let response = await tryAdd(cursor);
if (response.status !== 200) {
const knownNum = Number(response?.payload?.serverLastGlobalNumber);
const knownHash = String(response?.payload?.serverLastGlobalHash || '');
if (Number.isFinite(knownNum) && /^[0-9a-fA-F]{64}$/.test(knownHash)) {
cursor = { serverLastGlobalNumber: knownNum, serverLastGlobalHash: knownHash.toLowerCase() };
response = await tryAdd(cursor);
} else {
freshState = await resolveFreshState();
blockchainName = String(freshState?.blockchainName || blockchainName).trim() || blockchainName;
cursor = freshState.cursor;
response = await tryAdd(cursor);
async getCoreHeads(lineCode = null) {
const response = await this.ws.request('GetMyCoreHeads', lineCode === null ? {} : { lineCode });
if (response.status !== 200) throw opError('GetMyCoreHeads', response);
const heads = response.payload?.result;
if (!heads || typeof heads.blockchainName !== 'string' || !heads.blockchainName) throw new Error('Invalid CORE heads response');
for (const head of [heads.global, heads.line]) {
if (head != null) {
if (!Number.isInteger(head.blockNumber) || head.blockNumber < 0) throw new Error('Invalid CORE head number');
coreHashBytes(head.coreHash);
}
}
if (response.status !== 200) throw opError('AddBlock', response);
return {
response,
blockchainName,
};
return heads;
}
async addBlockSigned({ login, storagePwd, msgType, msgSubType, msgVersion = 1, bodyBytes, channelSlug = '', _skipHeaderEnsure = false }) {
const cleanLogin = (login || '').trim();
if (!cleanLogin) throw new Error('Missing login for AddBlock');
if (!storagePwd) throw new Error('Missing storagePwd for AddBlock signing');
if (!cleanLogin || !storagePwd) throw new Error('Missing login/storagePwd for AddBlock');
const requestServer = this.serverUrl;
const requestLogin = this.currentLogin;
const requestSession = this.currentSessionId;
const sameContext = () => this.serverUrl === requestServer && this.currentLogin === requestLogin && this.currentSessionId === requestSession;
const isHeader = Number(msgType) === MSG_TYPE_TECH && Number(msgSubType) === MSG_SUBTYPE_TECH_HEADER;
const keyBundle = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
const blockchainPrivatePkcs8 = String(keyBundle?.blockchainKey || '').trim();
// Old homeserver/ESP32 signs Frame. Never send it a CORE write or silently fall back.
if (!blockchainPrivatePkcs8) throw new Error('CORE AddBlock requires a local blockchain key; remote signing is not migrated yet');
if (!_skipHeaderEnsure && !isHeader) {
await this.ensureBlockchainHeader(cleanLogin, storagePwd);
}
const keyBundle = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
const blockchainPrivatePkcs8 = String(keyBundle?.blockchainKey || '').trim();
if (!blockchainPrivatePkcs8) {
const user = await this.getUser(cleanLogin);
const blockchainName = String(user?.blockchainName || `${cleanLogin}-${BCH_SUFFIX}`).trim();
if (!blockchainName) throw new Error('Не удалось определить blockchainName для remote AddBlock');
const response = await this.submitRemoteAddBlockBody({
login: cleanLogin,
storagePwd,
blockchainName,
blockBodyBytes: buildRemoteBlockBodyBytes({ msgType, msgSubType, msgVersion, bodyBytes }),
});
return response.payload || {};
const { content, line } = splitEventBody({ msgType: Number(msgType), msgSubType: Number(msgSubType), msgVersion: Number(msgVersion), bodyBytes });
const privateKey = await importPkcs8Ed25519(blockchainPrivatePkcs8);
const owner32 = base64ToBytes(await publicKeyB64FromPkcs8Ed25519(blockchainPrivatePkcs8));
const heads = await this.getCoreHeads(line?.lineCode ?? null);
const blockchainName = heads.blockchainName;
if (loginFromBlockchainNameValue(blockchainName).toLowerCase() !== cleanLogin.toLowerCase()) throw new Error('CORE heads belong to another user');
if (!sameContext()) throw new Error('CORE write context changed');
if (isHeader && heads.global != null) return { serverLastGlobalNumber: heads.global.blockNumber, serverLastGlobalHash: heads.global.coreHash };
if (!isHeader && heads.global == null) throw new Error('CORE HEADER missing');
const op = isHeader ? 'CreateGenesis' : 'AddBlock';
const send = async current => {
if (current.blockchainName.toLowerCase() !== blockchainName.toLowerCase()) throw new Error('CORE fork changed; refresh before writing');
if (line && (!current.line || current.line.blockNumber !== line.prevLineBlockNumber || current.line.coreHash.toLowerCase() !== coreHex(line.prevLineCoreHash32))) {
const error = new Error('CORE line changed; rebuild event'); error.code = 'LINE_HEAD_CONFLICT'; throw error;
}
const blockNumber = current.global == null ? 0 : current.global.blockNumber + 1;
if (isHeader !== (blockNumber === 0)) throw new Error('CORE genesis state changed');
const prevBlockHash = current.global?.coreHash.toLowerCase() ?? ZERO64;
const pair = await signCoreContentPair({ owner32, privateKey, content, line, blockNumber, prevCoreHash32: coreHashBytes(prevBlockHash), timestamp: Math.floor(Date.now() / 1000) });
const payload = { blockchainName, blockNumber, prevBlockHash: isHeader ? '' : prevBlockHash,
coreDataItemB64: bytesToBase64(pair.coreDataItem), contentDataItemB64: bytesToBase64(pair.contentDataItem) };
const blockHash = coreHex(pair.coreHash32);
const accepted = response => ({ ...response, payload: { ...response.payload, submittedBlockNumber: blockNumber, submittedBlockHash: blockHash } });
const request = () => {
if (!sameContext()) throw new Error('CORE write context changed');
return this.ws.request(op, payload);
};
let response, firstError;
try { response = await request(); } catch (error) { firstError = error; }
if (!firstError && response && Number(response.status) >= 200 && Number(response.status) < 500) {
return response.status === 200 ? accepted(response) : response;
}
// A lost response (or server 5xx) is NOT an explicit head conflict. The
// first attempt may have committed. Retry exactly the same signed items.
try {
response = await request();
if (response?.status === 200) return accepted(response);
} catch {}
// If exact retry did not confirm success, check the actual signed bytes
// in the currently active fork, not just the latest global head.
if (sameContext()) {
try {
const active = await this.getCoreHeads();
if (sameContext() && active.blockchainName.toLowerCase() === blockchainName.toLowerCase()) {
const found = await this.ws.request('GetBlockchainBlock', { blockchainName, blockNumber });
const row = found?.payload;
if (sameContext() && found?.status === 200 && row?.blockNumber === blockNumber && row?.coreHash === blockHash
&& row?.contentStatus === 'VALID' && row.coreDataItemB64 === payload.coreDataItemB64 && row.contentDataItemB64 === payload.contentDataItemB64) {
return accepted({ status: 200, payload: { serverLastGlobalNumber: active.global.blockNumber, serverLastGlobalHash: active.global.coreHash } });
}
}
} catch {}
}
// Never let the existing line retry rebuild an event after an uncertain
// outcome. The caller must inspect history before manually submitting again.
const error = new Error('Результат записи неизвестен. Проверьте историю блокчейна перед повторной отправкой (CORE_WRITE_OUTCOME_UNKNOWN)', { cause: firstError });
error.code = 'CORE_WRITE_OUTCOME_UNKNOWN';
error.blockchainName = blockchainName;
error.blockNumber = blockNumber;
error.coreHash = blockHash;
throw error;
};
let response = await send(heads);
// A fresh signature is allowed only after a definite rejection, never after an ambiguous attempt.
if (!isHeader && response.status === 409 && opError('AddBlock', response).code === 'GLOBAL_HEAD_CONFLICT') {
response = await send(await this.getCoreHeads(line?.lineCode ?? null));
}
const ansTags = [{ name: SHINE_APP_TAG_NAME, value: SHINE_APP_TAG_VALUE }];
const typeIndexTag = typeIndexTagValue(msgType);
if (typeIndexTag) ansTags.push({ name: SHINE_TYPE_TAG_NAME, value: typeIndexTag });
const cleanChannelSlug = String(channelSlug || '').trim();
if (cleanChannelSlug) ansTags.push({ name: SHINE_CHANNEL_TAG_NAME, value: cleanChannelSlug });
const { response, blockchainName } = await this.runAddBlockWithRetry({
login: cleanLogin,
storagePwd,
resolveFreshState: () => this.resolveFreshBlockchainCursor(cleanLogin),
ansTags,
buildPreimage: async ({ blockNumber, prevBlockHash, back32Hash }) => buildBlockPreimage({
prevBlockHashHex: prevBlockHash,
back32HashHex: back32Hash,
blockNumber,
msgType,
msgSubType,
msgVersion,
bodyBytes,
}),
});
if (response.status !== 200) throw opError(op, response);
const payload = response.payload || {};
const acceptedNum = Number(payload?.serverLastGlobalNumber);
const acceptedHash = normalizeHex32(payload?.serverLastGlobalHash, ZERO64);
if (Number.isFinite(acceptedNum) && acceptedNum === 0 && acceptedHash !== ZERO64) {
this.headerHashCache.set(blockchainName, acceptedHash);
}
if (payload.submittedBlockNumber === 0 && payload.submittedBlockHash) this.headerHashCache.set(blockchainName, payload.submittedBlockHash);
return payload;
}
@@ -1952,7 +1719,7 @@ export class AuthService {
storagePwd,
msgType: MSG_TYPE_TECH,
msgSubType: MSG_SUBTYPE_TECH_HEADER,
msgVersion: HEADER_VERSION_CC0,
msgVersion: HEADER_CONTENT_VERSION,
// HEADER хранит исходный регистр неизменяемого имени из Solana/Arweave.
// Нормализация нужна только для уникальности и имени самой цепочки.
bodyBytes: makeHeaderBodyBytes({ login: registeredLogin, initialBlockchainKey32 }),
@@ -2143,7 +1910,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return payload;
});
}
@@ -2198,7 +1964,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return payload;
});
}
@@ -2323,97 +2088,14 @@ export class AuthService {
return response.payload || {};
}
async findLatestOwnLineBlock({
blockchainName,
msgType,
subTypes = null,
lineCode = null,
fixedLine = false,
stopAtBlock = 0,
}) {
const cleanBch = String(blockchainName || '').trim();
if (!cleanBch) throw new Error('Missing blockchainName for line lookup');
const subtypeSet = subTypes == null ? null : new Set(Array.from(subTypes, (value) => Number(value)));
const minBlock = Math.max(0, Number(stopAtBlock) || 0);
let beforeBlock = null;
for (;;) {
const page = await this.getMyBlockchainPage({ beforeBlock, limit: 100, includeBlockBytes: true });
const pageBch = String(page?.blockchainName || '').trim();
if (pageBch && pageBch !== cleanBch) throw new Error('GetMyBlockchain returned another blockchain');
const blocks = Array.isArray(page?.blocks) ? page.blocks : [];
for (const block of blocks) {
const blockNumber = Number(block?.blockNumber);
if (!Number.isInteger(blockNumber) || blockNumber <= minBlock) continue;
if (Number(block?.msgType) !== Number(msgType)) continue;
if (subtypeSet && !subtypeSet.has(Number(block?.msgSubType))) continue;
if (!block?.blockBytesB64) continue;
const meta = parseStoredLineMeta(block.blockBytesB64, { fixedLine });
if (lineCode != null && Number(meta.lineCode) !== Number(lineCode)) continue;
return {
blockNumber,
blockHash: normalizeHex32(block?.blockHash, ZERO64),
lineSequence: Number(meta.lineSequence),
lineCode: Number(meta.lineCode),
};
}
const next = page?.nextBeforeBlock;
if (next == null || !Number.isInteger(Number(next)) || Number(next) <= minBlock) return null;
beforeBlock = Number(next);
}
}
async resolveFixedLineTail({ blockchainName, kind }) {
const cleanBch = String(blockchainName || '').trim();
const kindKey = String(kind || '').trim().toLowerCase();
const config = kindKey === 'profile'
? { msgType: MSG_TYPE_USER_PROFILE, tag: 'prof' }
: kindKey === 'connections'
? { msgType: MSG_TYPE_CONNECTION, tag: 'conn' }
: kindKey === 'tech'
? { msgType: MSG_TYPE_TECH, tag: 'tech', subTypes: [MSG_SUBTYPE_TECH_CREATE_CHANNEL, MSG_SUBTYPE_TECH_FORK] }
: null;
if (!config) throw new Error(`Unknown fixed line kind: ${kind}`);
const cacheKey = `${cleanBch}|${kindKey}`;
const cached = this.lineTailCache.get(cacheKey);
if (cached) return { ...cached };
const latest = await this.findLatestOwnLineBlock({
blockchainName: cleanBch,
msgType: config.msgType,
subTypes: config.subTypes || null,
lineCode: kindKey === 'tech' ? 0 : null,
fixedLine: kindKey !== 'tech',
stopAtBlock: 0,
});
if (latest) {
const result = {
prevLineNumber: latest.blockNumber,
prevLineHashHex: latest.blockHash,
thisLineNumber: latest.lineSequence + 1,
};
this.lineTailCache.set(cacheKey, result);
return { ...result };
}
const headerHash = await this.resolveHeaderHashForBlockchain(cleanBch);
if (headerHash === ZERO64) throw new Error('HEADER блокчейна не найден');
const result = { prevLineNumber: 0, prevLineHashHex: headerHash, thisLineNumber: 1 };
this.lineTailCache.set(cacheKey, result);
return { ...result };
}
rememberLineTail(blockchainName, kind, payload, currentSequence) {
const cleanBch = String(blockchainName || '').trim();
const acceptedNumber = Number(payload?.serverLastGlobalNumber);
const acceptedHash = normalizeHex32(payload?.serverLastGlobalHash, ZERO64);
if (!cleanBch || !Number.isInteger(acceptedNumber) || acceptedNumber < 0 || acceptedHash === ZERO64) return;
this.lineTailCache.set(`${cleanBch}|${String(kind || '').trim().toLowerCase()}`, {
prevLineNumber: acceptedNumber,
prevLineHashHex: acceptedHash,
thisLineNumber: Number(currentSequence) + 1,
});
const code = { profile: SHINE_CORE_LINE_PROFILE, connections: SHINE_CORE_LINE_CONNECTION, tech: SHINE_CORE_LINE_TECH }[String(kind || '').toLowerCase()];
if (code === undefined) throw new Error(`Unknown fixed line kind: ${kind}`);
const heads = await this.getCoreHeads(code);
if (heads.blockchainName.toLowerCase() !== blockchainName.toLowerCase() || !heads.line) throw new Error('CORE fixed line not found');
// Sequence is only an in-memory compatibility argument to existing body factories.
// It is not part of signed CORE or CONTENT and is never sent.
return { prevLineNumber: heads.line.blockNumber, prevLineHashHex: heads.line.coreHash, thisLineNumber: 1 };
}
async runLineWriteLocked(lockKey, buildAndSend) {
@@ -2424,7 +2106,6 @@ export class AuthService {
return await buildAndSend();
} catch (error) {
if (!isLineConflictError(error)) throw error;
this.lineTailCache.clear();
return buildAndSend();
}
});
@@ -2504,12 +2185,11 @@ export class AuthService {
channelTypeVersion: typeVersion,
}),
});
this.rememberLineTail(blockchainName, 'tech', payload, tail.thisLineNumber);
const selector = {
ownerBlockchainName: blockchainName,
channelRootBlockNumber: Number(payload?.serverLastGlobalNumber),
channelRootBlockHash: normalizeHex32(payload?.serverLastGlobalHash, ZERO64),
channelRootBlockNumber: Number(payload?.submittedBlockNumber ?? payload?.serverLastGlobalNumber),
channelRootBlockHash: normalizeHex32(payload?.submittedBlockHash ?? payload?.serverLastGlobalHash, ZERO64),
};
return {
@@ -2546,67 +2226,12 @@ export class AuthService {
if (!channelSlug) throw new Error('Cannot resolve canonical channel slug');
if (rootHashHex === ZERO64) throw new Error('Cannot resolve channel root hash');
const cacheKey = `${blockchainName}|channel:${lineCode}`;
const cached = this.lineTailCache.get(cacheKey);
if (cached) {
return {
ownerBlockchainName,
lineCode,
rootHashHex,
channelSlug,
...cached,
};
}
const latest = await this.findLatestOwnLineBlock({
blockchainName,
msgType: MSG_TYPE_TEXT,
subTypes: [
MSG_SUBTYPE_TEXT_POST,
MSG_SUBTYPE_TEXT_EDIT_POST,
MSG_SUBTYPE_TEXT_REPOST,
MSG_SUBTYPE_TEXT_CHANNEL_META,
MSG_SUBTYPE_TEXT_CHANNEL_DELETE,
MSG_SUBTYPE_TEXT_ENTRYPOINT,
MSG_SUBTYPE_TEXT_EXERCISE,
MSG_SUBTYPE_TEXT_SERVICE,
MSG_SUBTYPE_TEXT_COURSE,
],
lineCode,
fixedLine: false,
stopAtBlock: lineCode,
});
const lineTail = latest
? {
prevLineNumber: latest.blockNumber,
prevLineHashHex: latest.blockHash,
thisLineNumber: latest.lineSequence + 1,
}
: {
prevLineNumber: lineCode,
prevLineHashHex: rootHashHex,
thisLineNumber: 0,
};
this.lineTailCache.set(cacheKey, lineTail);
return {
ownerBlockchainName,
lineCode,
rootHashHex,
channelSlug,
...lineTail,
};
}
rememberChannelLineTail(blockchainName, lineCode, payload, currentSequence) {
const acceptedNumber = Number(payload?.serverLastGlobalNumber);
const acceptedHash = normalizeHex32(payload?.serverLastGlobalHash, ZERO64);
if (!Number.isInteger(acceptedNumber) || acceptedNumber < 0 || acceptedHash === ZERO64) return;
this.lineTailCache.set(`${String(blockchainName || '').trim()}|channel:${Number(lineCode)}`, {
prevLineNumber: acceptedNumber,
prevLineHashHex: acceptedHash,
thisLineNumber: Number(currentSequence) + 1,
});
const heads = await this.getCoreHeads(lineCode);
if (heads.blockchainName.toLowerCase() !== blockchainName.toLowerCase() || !heads.line) throw new Error('CORE channel line not found');
const canonicalRootHash = await this.getBlockHashByNumber(blockchainName, lineCode);
if (canonicalRootHash !== rootHashHex) throw new Error('Channel root changed; refresh channel');
return { ownerBlockchainName, lineCode, rootHashHex, channelSlug,
prevLineNumber: heads.line.blockNumber, prevLineHashHex: heads.line.coreHash, thisLineNumber: 0 };
}
async addBlockTextPost({ login, channel, text, storagePwd, msgSubType = MSG_SUBTYPE_TEXT_POST }) {
@@ -2652,7 +2277,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return {
...payload,
@@ -2695,7 +2319,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return {
...payload,
@@ -2737,7 +2360,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return { ...payload, channel: { ownerBlockchainName: tail.ownerBlockchainName, channelRootBlockNumber: tail.lineCode, channelRootBlockHash: tail.rootHashHex } };
});
}
@@ -3316,9 +2938,30 @@ export class AuthService {
const cleanLogin = (login || '').trim();
if (!cleanLogin) throw new Error('Не передан login');
const response = await this.ws.request('ListUserParams', { login: cleanLogin });
if (response.status !== 200) throw opError('ListUserParams', response);
return response.payload || {};
// Profile writes are CORE events now. Do not read the Frame-era
// user_params projection: it is intentionally not updated by CORE.
const params = [];
let afterKey = '';
for (let page = 0; page < 100; page += 1) {
const response = await this.ws.request('GetCoreProfile', { login: cleanLogin, afterKey, limit: 20 });
if (response.status !== 200) throw opError('GetCoreProfile', response);
const result = response.payload?.result || {};
for (const row of Array.isArray(result.values) ? result.values : []) {
const param = String(row?.key || '').trim();
if (!param) continue;
const timestampSeconds = Number(row?.timestampSeconds);
params.push({
param,
value: String(row?.value || ''),
time_ms: Number.isSafeInteger(timestampSeconds) && timestampSeconds >= 0 ? timestampSeconds * 1000 : 0,
});
}
const nextAfterKey = String(result.nextAfterKey || '').trim();
if (!nextAfterKey) return { params };
if (nextAfterKey <= afterKey) throw new Error('Некорректная пагинация CORE-профиля');
afterKey = nextAfterKey;
}
throw new Error('Превышен лимит страниц CORE-профиля');
}
async listUserSettings(login) {
@@ -3330,53 +2973,23 @@ export class AuthService {
return response.payload || {};
}
async setChannelReadState({
login,
ownerBlockchainName,
channelName,
readCount,
timeMs,
storagePwd,
}) {
const cleanLogin = String(login || '').trim();
const cleanOwnerBch = String(ownerBlockchainName || '').trim();
const cleanChannelName = String(channelName || '').trim();
const cleanReadCount = Math.max(0, Math.trunc(Number(readCount || 0)));
const cleanTimeMs = Math.trunc(Number(timeMs));
if (!cleanLogin || !cleanOwnerBch || !cleanChannelName) {
throw new Error('Не переданы login/ownerBlockchainName/channelName');
}
if (!Number.isFinite(cleanTimeMs) || cleanTimeMs <= 0) {
throw new Error('Не передан корректный timeMs');
}
if (!storagePwd) throw new Error('Не передан storagePwd для подписи SetChannelReadState.');
const secrets = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
async setChannelReadState({ login, owner, root, rootHash, followHash, anchor, anchorHash, timeMs, storagePwd }) {
const viewer = String(login || '').trim();
const validLogin = value => typeof value === 'string' && value.length > 0 && value.length <= 128 && value === value.trim() && !/[|\x00-\x1f\x7f-\x9f]/u.test(value);
const validHash = value => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
if (!validLogin(viewer) || !validLogin(owner) || viewer.toLowerCase() === owner.toLowerCase()
|| !Number.isInteger(root) || root < 0 || !Number.isInteger(anchor) || anchor < root || anchor > 2147482623
|| ![rootHash, followHash, anchorHash].every(validHash) || !Number.isSafeInteger(timeMs) || timeMs < 0
|| !storagePwd) throw new Error('BAD_READ_STATE');
const secrets = await loadEncryptedUserSecrets(viewer, storagePwd);
const clientPrivPkcs8 = String(secrets?.clientKey || '').trim();
if (!clientPrivPkcs8) throw new Error('Не найден приватный clientKey');
const privateKey = await importPkcs8Ed25519(clientPrivPkcs8);
const clientKey = await publicKeyB64FromPkcs8Ed25519(clientPrivPkcs8);
const preimage = 'SHiNe/ChannelReadState:' + [
escapeUserSettingPart(cleanLogin),
escapeUserSettingPart(cleanOwnerBch),
escapeUserSettingPart(cleanChannelName),
String(cleanTimeMs),
String(cleanReadCount),
].join('|');
const signature = await signBase64(privateKey, preimage);
const response = await this.ws.request('SetChannelReadState', {
login: cleanLogin,
owner_bch_name: cleanOwnerBch,
channel_name: cleanChannelName,
read_count: cleanReadCount,
time_ms: cleanTimeMs,
client_key: clientKey,
signature,
});
const preimage = ['SHiNE_CORE_READ_V1', 'test5593', viewer, owner, root, rootHash, followHash, anchor, anchorHash, timeMs].join('|');
const signatureB64 = await signBase64(privateKey, preimage);
const response = await this.ws.request('SetChannelReadState', { owner, root, rootHash, followHash, anchor, anchorHash, timeMs, signatureB64 });
if (response.status !== 200) throw opError('SetChannelReadState', response);
return response.payload || {};
return response.payload?.result || {};
}
async upsertUserSetting({
@@ -3466,7 +3079,6 @@ export class AuthService {
msgVersion: 1,
bodyBytes,
});
this.rememberLineTail(blockchainName, 'profile', payload, tail.thisLineNumber);
return payload;
});
}
@@ -3503,7 +3115,6 @@ export class AuthService {
msgVersion: 1,
bodyBytes,
});
this.rememberLineTail(blockchainName, 'connections', payload, tail.thisLineNumber);
return payload;
});
}
@@ -1,3 +1,4 @@
import { readCoreBlock } from './core-content.js';
import { parseAns104DataItem } from './ans104-data-item.js';
import { base64ToBytes, bytesToBase64Url, sha256Bytes } from './crypto-utils.js';
@@ -117,7 +118,7 @@ function parseChannelMetaText(rawText) {
};
}
function parseTechBody(subType, body, frame) {
function parseTechBody(subType, body, frame, coreLine) {
const reader = new Reader(body);
if (subType === 0) {
const magic = reader.text(5, 'HEADER magic');
@@ -134,7 +135,7 @@ function parseTechBody(subType, body, frame) {
return { kind: 'header', magic, login, license, initialBlockchainKey };
}
if (subType === 1) {
const line = parseLinePrefix(reader);
const line = coreLine === undefined ? parseLinePrefix(reader) : coreLine;
const channelName = reader.textU8('channelName');
const channelDescription = reader.textU16('channelDescription');
const channelType = reader.u16('channelType');
@@ -146,7 +147,7 @@ function parseTechBody(subType, body, frame) {
};
}
if (subType === 2) {
const line = parseLinePrefix(reader);
const line = coreLine === undefined ? parseLinePrefix(reader) : coreLine;
const parentBlockchainKey = bytesToBase64Url(reader.raw(32, 'parentBlockchainKey'));
const forkPointBlockNumber = reader.i32('forkPointBlockNumber');
const forkPointBlockHash = reader.hash32('forkPointBlockHash');
@@ -166,10 +167,10 @@ function parseTechBody(subType, body, frame) {
return { kind: 'unknown', rawBodyLength: body.length };
}
function parseTextBody(subType, body) {
function parseTextBody(subType, body, coreLine) {
const reader = new Reader(body);
if ([10, 90, 92, 100, 110, 120, 130].includes(subType)) {
const line = parseLinePrefix(reader);
const line = coreLine === undefined ? parseLinePrefix(reader) : coreLine;
const rawText = parseTextTail(reader);
const message = splitMessageText(rawText);
return {
@@ -179,7 +180,7 @@ function parseTextBody(subType, body) {
};
}
if (subType === 11) {
const line = parseLinePrefix(reader);
const line = coreLine === undefined ? parseLinePrefix(reader) : coreLine;
const target = parseCompactTarget(reader);
const rawText = parseTextTail(reader);
const message = splitMessageText(rawText);
@@ -198,7 +199,7 @@ function parseTextBody(subType, body) {
return { kind: 'edit_reply', target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
}
if (subType === 50) {
const line = parseLinePrefix(reader);
const line = coreLine === undefined ? parseLinePrefix(reader) : coreLine;
const target = parseTarget(reader);
const rawText = parseTextTail(reader);
const message = splitMessageText(rawText);
@@ -213,17 +214,17 @@ function parseReactionBody(subType, body) {
return { kind: 'unknown', rawBodyLength: body.length };
}
function parseConnectionBody(subType, body) {
function parseConnectionBody(subType, body, coreLine) {
const reader = new Reader(body);
const line = parseFixedLinePrefix(reader, 'Connection');
const line = coreLine === undefined ? parseFixedLinePrefix(reader, 'Connection') : coreLine;
const target = parseTarget(reader);
return { kind: 'connection', subType, line, target };
}
function parseProfileBody(subType, body) {
function parseProfileBody(subType, body, coreLine) {
if (subType !== 1) return { kind: 'unknown', rawBodyLength: body.length };
const reader = new Reader(body);
const line = parseFixedLinePrefix(reader, 'Profile');
const line = coreLine === undefined ? parseFixedLinePrefix(reader, 'Profile') : coreLine;
const key = reader.textU16('paramKey');
const value = reader.textU16('paramValue');
return { kind: 'profile', line, key, value };
@@ -237,16 +238,16 @@ function parseStatusBody(subType, body) {
return { kind: 'status', subType, target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
}
function parseBody(type, subType, version, body, frame) {
function parseBody(type, subType, version, body, frame, coreLine) {
// Only TECH HEADER subtype 0 has a second version; all other records stay v1.
if (version !== 1 && !(type === 0 && subType === 0 && version === 2)) {
return { kind: 'unsupported_version', rawBodyLength: body.length };
}
if (type === 0) return parseTechBody(subType, body, frame);
if (type === 1) return parseTextBody(subType, body);
if (type === 0) return parseTechBody(subType, body, frame, coreLine);
if (type === 1) return parseTextBody(subType, body, coreLine);
if (type === 2) return parseReactionBody(subType, body);
if (type === 3) return parseConnectionBody(subType, body);
if (type === 4) return parseProfileBody(subType, body);
if (type === 3) return parseConnectionBody(subType, body, coreLine);
if (type === 4) return parseProfileBody(subType, body, coreLine);
if (type === 5) return parseStatusBody(subType, body);
return { kind: 'unknown', rawBodyLength: body.length };
}
@@ -291,3 +292,18 @@ export const blockchainInspectorInternals = Object.freeze({
FIXED_LINE_PREFIX_SIZE,
ZERO_HASH,
});
/** View model for the existing inspector; never synthesizes or signs a Frame. */
export async function inspectCoreBlock(row) {
const proof = await readCoreBlock(row);
const { core, content } = proof;
const timestampMs = Number(core.timestamp * 1000n);
if (!Number.isSafeInteger(timestampMs)) throw new Error('Invalid CORE timestamp');
const line = core.line ? { lineCode: core.line.lineCode, prevLineNumber: core.line.prevLineBlockNumber,
prevLineHash: bytesToHex(core.line.prevLineCoreHash32) } : null;
const frame = { blockNumber: core.blockNumber, timestampMs, prevHash: bytesToHex(core.prevCoreHash32),
type: content?.type, subType: content?.subType, version: content?.version };
frame.body = content && row.contentStatus === 'VALID' ? parseBody(content.type, content.subType, content.version, content.body, frame, line) : { kind: 'unknown' };
return { frame, dataItemId: proof.actualId, contentDataItemId: bytesToBase64Url(core.contentDataItemId32),
arweaveUrl: `https://arweave.net/${proof.actualId}`, owner: bytesToBase64Url(proof.owner32), contentStatus: row.contentStatus };
}
@@ -1,14 +1,10 @@
import { verifyAns104DataItem } from './ans104-data-item.js';
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
import { readCoreBlock } from './core-content.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]);
}
@@ -28,16 +24,10 @@ export async function readSignedBlock({ authService, blockchainName, blockNumber
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 };
const proof = await readCoreBlock(body, { requireContent: true });
if (proof.core.blockNumber !== blockNumber || proof.coreHash !== String(blockHash).toLowerCase()) throw new Error('CORE reference mismatch');
if (dataItemId && proof.actualId !== dataItemId) throw new Error('Arweave CORE ID mismatch');
return proof;
}
/** Вспомогательная независимая сверка: шлюз возвращает payload, а не ANS-104 оболочку. */
@@ -44,3 +44,28 @@ export function ordinalForPublication(messages, reference) {
});
return i < 0 ? null : i + 1;
}
// Read watermarks use canonical block order, not the time-sorted display ordinal.
// Require the complete list and its exact final anchor from the subscription feed.
export function canonicalReadPosts(posts, summary) {
const channel = summary?.channel, root = channel?.channelRoot;
const hash = v => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
if (!channel?.ownerLogin || !Number.isInteger(root?.blockNumber) || !hash(root.blockHash)
|| !hash(summary.followHash) || !Number.isInteger(summary.messagesCount) || summary.messagesCount !== posts.length) return null;
const ordered = [...posts].sort((a,b) => a.messageRef?.blockNumber - b.messageRef?.blockNumber);
let previous = root.blockNumber;
const ordinals = new Set();
for (const post of ordered) {
const ref = post.messageRef;
if (String(post.authorLogin || '').toLowerCase() !== channel.ownerLogin.toLowerCase() || !Number.isInteger(ref?.blockNumber) || ref.blockNumber <= previous || !hash(ref.blockHash) || !Number.isInteger(post.localNumber) || post.localNumber <= 0 || ordinals.has(post.localNumber)) return null;
previous = ref.blockNumber; ordinals.add(post.localNumber);
}
const last = ordered.at(-1)?.messageRef || root;
if (last.blockNumber !== summary.readAnchor?.blockNumber || last.blockHash !== summary.readAnchor?.blockHash) return null;
return ordered;
}
export function readPrefixCount(ordered, alreadyRead, seenOrdinals) {
let count = Math.min(ordered.length, Math.max(0, alreadyRead));
while (count < ordered.length && seenOrdinals.has(ordered[count].localNumber)) count++;
return count;
}
+159
View File
@@ -0,0 +1,159 @@
// CORE v2 / CONTENT v1. Uses the existing ANS-104 signer; no new key store or transport.
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
import { createAns104DataItem, parseAns104DataItem, verifyAns104DataItem, serializeAns104Tags } from './ans104-data-item.js';
import { SHINE_CORE_NAMESPACE, SHINE_CORE_MAX_BLOCK_NUMBER, SHINE_CORE_LINE_PROFILE,
SHINE_CORE_LINE_CONNECTION, SHINE_CORE_LINE_TECH } from './protocol-tags.js';
export const CORE_MAX_ITEM_BYTES = 8 * 1024 * 1024;
export const CORE_MAX_CONTENT_BYTES = CORE_MAX_ITEM_BYTES - 117;
const zero = new Uint8Array(32);
const channelTypes = new Set([10, 11, 50, 90, 92, 100, 110, 120, 130]);
const equal = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
export const coreHex = bytes => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
export function coreHashBytes(hex) {
if (typeof hex !== 'string' || !/^[0-9a-f]{64}$/i.test(hex)) throw new Error('Invalid CORE hash');
return Uint8Array.from(hex.match(/../g), b => parseInt(b, 16));
}
function bytes32(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.length !== 32) throw new Error('Expected 32 bytes');
return bytes;
}
function integer(value, max) {
if (!Number.isInteger(value) || value < 0 || value > max) throw new Error('Integer out of range');
return value;
}
function timestamp64(value) {
if (typeof value === 'number' && !Number.isSafeInteger(value)) throw new Error('Invalid timestamp');
if (typeof value !== 'number' && typeof value !== 'bigint') throw new Error('Invalid timestamp');
const n = BigInt(value);
if (n < 0n || n > 0x7fffffffffffffffn) throw new Error('Invalid timestamp');
return n;
}
const view = b => new DataView(b.buffer, b.byteOffset, b.byteLength);
const sha256 = async b => new Uint8Array(await crypto.subtle.digest('SHA-256', b));
export function encodeContent({ type, subType, version, body }) {
if (!(body instanceof Uint8Array) || body.length > CORE_MAX_CONTENT_BYTES - 7) throw new Error('Invalid CONTENT body length');
const out = new Uint8Array(7 + body.length), v = view(out);
out[0] = 1;
v.setUint16(1, integer(type, 65535)); v.setUint16(3, integer(subType, 65535)); v.setUint16(5, integer(version, 65535));
out.set(body, 7);
return out;
}
export function decodeContent(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.length < 7 || bytes.length > CORE_MAX_CONTENT_BYTES || bytes[0] !== 1) throw new Error('Invalid CONTENT');
const v = view(bytes);
return { type: v.getUint16(1), subType: v.getUint16(3), version: v.getUint16(5), body: bytes.slice(7) };
}
export function encodeCore({ prevCoreHash32, blockNumber, timestamp, contentHash32, contentDataItemId32, line = null }) {
integer(blockNumber, SHINE_CORE_MAX_BLOCK_NUMBER);
bytes32(prevCoreHash32); bytes32(contentHash32); bytes32(contentDataItemId32);
if (blockNumber === 0 && (line !== null || !equal(prevCoreHash32, zero))) throw new Error('Invalid genesis CORE');
const out = new Uint8Array(line === null ? 109 : 149), v = view(out);
out[0] = 1; out.set(prevCoreHash32, 1); v.setInt32(33, blockNumber);
v.setBigInt64(37, timestamp64(timestamp)); out.set(contentHash32, 45); out.set(contentDataItemId32, 77);
if (line !== null) {
const code = integer(line.lineCode, 2147483647), prev = integer(line.prevLineBlockNumber, SHINE_CORE_MAX_BLOCK_NUMBER);
if (prev >= blockNumber || (code > 0 && code <= SHINE_CORE_MAX_BLOCK_NUMBER && (code >= blockNumber || prev < code))) throw new Error('Invalid CORE line predecessor');
v.setInt32(109, code); v.setInt32(113, prev); out.set(bytes32(line.prevLineCoreHash32), 117);
}
return out;
}
export function decodeCore(bytes) {
if (!(bytes instanceof Uint8Array) || ![109, 149].includes(bytes.length) || bytes[0] !== 1) throw new Error('Invalid CORE');
const v = view(bytes);
const result = { prevCoreHash32: bytes.slice(1, 33), blockNumber: v.getInt32(33), timestamp: v.getBigInt64(37),
contentHash32: bytes.slice(45, 77), contentDataItemId32: bytes.slice(77, 109),
line: bytes.length === 109 ? null : { lineCode: v.getInt32(109), prevLineBlockNumber: v.getInt32(113), prevLineCoreHash32: bytes.slice(117, 149) } };
encodeCore(result); // identical structural validation on read and write
return result;
}
export function coreTags(core) {
const tags = [{ name: 'App', value: SHINE_CORE_NAMESPACE }, { name: 'n', value: String(core.blockNumber) }];
if (core.line) {
const code = core.line.lineCode;
const special = { [SHINE_CORE_LINE_PROFILE]: 'P', [SHINE_CORE_LINE_CONNECTION]: 'C', [SHINE_CORE_LINE_TECH]: 'T' };
if (code > SHINE_CORE_MAX_BLOCK_NUMBER && !special[code]) throw new Error('Reserved CORE line');
tags.push({ name: 'l', value: special[code] ?? String(code) });
}
return tags;
}
function checkEventLine(content, core) {
const { type, subType, version } = content;
if (version !== 1) throw new Error('Unsupported CONTENT version for creation');
const header = type === 0 && subType === 0;
if (header !== (core.blockNumber === 0)) throw new Error('HEADER must be CORE #0');
const code = core.line?.lineCode;
if (type === 0 && !header) { if (code !== SHINE_CORE_LINE_TECH) throw new Error('Wrong TECH line'); }
else if (type === 3) { if (code !== SHINE_CORE_LINE_CONNECTION) throw new Error('Wrong CONNECTION line'); }
else if (type === 4) { if (code !== SHINE_CORE_LINE_PROFILE) throw new Error('Wrong PROFILE line'); }
else if (type === 1 && channelTypes.has(subType)) { integer(code, SHINE_CORE_MAX_BLOCK_NUMBER); }
else if (core.line !== null) throw new Error('Unexpected CORE line');
}
/** Temporary boundary for existing in-memory body factories. No Frame is constructed or signed. */
export function splitEventBody({ msgType, msgSubType, msgVersion = 1, bodyBytes }) {
if (!(bodyBytes instanceof Uint8Array)) throw new Error('Invalid event body');
const fixed = msgType === 3 || msgType === 4;
const tech = msgType === 0 && msgSubType === 1;
const channel = msgType === 1 && channelTypes.has(msgSubType);
if (msgType === 0 && ![0, 1].includes(msgSubType)) throw new Error('Use the dedicated CORE FORK path for rotation');
const prefix = fixed ? 40 : tech || channel ? 44 : 0;
if (bodyBytes.length < prefix) throw new Error('Truncated event line prefix');
let line = null;
if (prefix) {
const v = view(bodyBytes), offset = fixed ? 0 : 4;
if (tech && v.getInt32(0) !== 0) throw new Error('Invalid old TECH selector');
const code = msgType === 3 ? SHINE_CORE_LINE_CONNECTION : msgType === 4 ? SHINE_CORE_LINE_PROFILE : tech ? SHINE_CORE_LINE_TECH : v.getInt32(0);
line = { lineCode: code, prevLineBlockNumber: v.getInt32(offset), prevLineCoreHash32: bodyBytes.slice(offset + 4, offset + 36) };
}
return { content: { type: msgType, subType: msgSubType, version: msgVersion, body: bodyBytes.slice(prefix) }, line };
}
export async function signCoreContentPair({ owner32, privateKey, content, prevCoreHash32, blockNumber, timestamp, line = null }) {
bytes32(owner32);
checkEventLine(content, { blockNumber, line });
const contentBytes = encodeContent(content);
const contentDataItem = await createAns104DataItem({ owner32, privateKey, data: contentBytes, tags: [] });
if (contentDataItem.length > CORE_MAX_ITEM_BYTES) throw new Error('CONTENT ANS-104 too large');
const contentHash32 = await sha256(contentBytes);
const contentDataItemId32 = await sha256(parseAns104DataItem(contentDataItem).signature);
const core = { prevCoreHash32, blockNumber, timestamp, contentHash32, contentDataItemId32, line };
const coreBytes = encodeCore(core);
const coreDataItem = await createAns104DataItem({ owner32, privateKey, data: coreBytes, tags: coreTags(core) });
return { coreBytes, contentBytes, coreDataItem, contentDataItem, coreHash32: await sha256(coreBytes), contentHash32, contentDataItemId32 };
}
/** Verifies signed pair and owner binding, not history, semantics or authorization of the owner. */
export async function verifyCoreContentPair(coreItem, contentItem, expectedOwner32) {
bytes32(expectedOwner32);
for (const item of [coreItem, contentItem]) if (!(item instanceof Uint8Array) || item.length > CORE_MAX_ITEM_BYTES) throw new Error('Invalid ANS-104 size');
const [c, p] = await Promise.all([verifyAns104DataItem(coreItem), verifyAns104DataItem(contentItem)]);
if (!c.signatureValid || !p.signatureValid || !equal(c.owner32, expectedOwner32) || !equal(p.owner32, expectedOwner32)) throw new Error('Invalid pair signature or owner');
const core = decodeCore(c.data), content = decodeContent(p.data);
// This is the canonical encoding produced by the UI. General Arweave import validation is D.
if (c.target.length || c.anchor.length || p.target.length || p.anchor.length || c.tagsCount !== coreTags(core).length || p.tagsCount !== 0 || !equal(c.rawTags, serializeAns104Tags(coreTags(core))) || !equal(p.rawTags, serializeAns104Tags([]))) throw new Error('Invalid pair tags');
if (!equal(core.contentHash32, p.frameHashBytes) || !equal(core.contentDataItemId32, p.dataItemIdBytes)) throw new Error('CONTENT does not match CORE');
return { core, content, coreHash32: c.frameHashBytes, coreDataItemId32: c.dataItemIdBytes };
}
// Read the exact signed objects returned by the current WS API. A valid signature
// does not by itself establish the signer's authorization or canonical ancestry.
export async function readCoreBlock(row, { requireContent = false } = {}) {
const decodeItem = value => {
if (typeof value !== 'string' || !value || value.length > Math.ceil(CORE_MAX_ITEM_BYTES * 4 / 3) + 8) throw new Error('Invalid CORE/CONTENT DataItem size');
const raw = base64ToBytes(value);
if (!raw.length || raw.length > CORE_MAX_ITEM_BYTES) throw new Error('Invalid CORE/CONTENT DataItem size');
return raw;
};
const bytes = decodeItem(row?.coreDataItemB64);
const proof = await verifyAns104DataItem(bytes);
const core = decodeCore(proof.data);
const hash = coreHex(proof.frameHashBytes), actualId = bytesToBase64Url(proof.dataItemIdBytes);
const contentId = bytesToBase64Url(core.contentDataItemId32);
if (!proof.signatureValid || proof.target.length || proof.anchor.length || proof.tagsCount !== coreTags(core).length || !equal(proof.rawTags, serializeAns104Tags(coreTags(core)))) throw new Error('Invalid CORE signature or tags');
if (row.blockNumber !== core.blockNumber || row.coreHash !== hash || (row.blockHash != null && row.blockHash !== hash) || row.coreDataItemId !== actualId || row.contentHash !== coreHex(core.contentHash32) || row.contentDataItemId !== contentId) throw new Error('CORE response metadata mismatch');
let content = null, contentBytes = null, contentProof = null;
if (row.contentDataItemB64) {
contentBytes = decodeItem(row.contentDataItemB64);
({ content } = await verifyCoreContentPair(bytes, contentBytes, proof.owner32));
contentProof = { actualId: contentId, data: parseAns104DataItem(contentBytes).data, bytes: contentBytes };
} else if (requireContent) throw new Error('CONTENT unavailable');
return { ...proof, bytes, actualId, core, content, contentProof, coreHash: hash, contentStatus: row.contentStatus };
}
+49 -79
View File
@@ -1,11 +1,10 @@
import { createAns104DataItem, createAns104DataItemWithRawParts, parseAns104DataItem } from './ans104-data-item.js';
import { coreHashBytes, coreHex, readCoreBlock, signCoreContentPair } from './core-content.js';
import { base64ToBytes, bytesToBase64 } from './crypto-utils.js';
import { updateShineUserPdaOnSolana, readShineUserPda } from './shine-user-pda-service.js';
import { updateEncryptedUserSecrets } from './key-vault.js';
import { SHINE_APP_TAG_NAME, SHINE_APP_TAG_VALUE, SHINE_TYPE_TAG_NAME } from './protocol-tags.js';
import { SHINE_CORE_LINE_TECH, SHINE_CORE_MAX_BLOCK_NUMBER } from './protocol-tags.js';
const TE = new TextEncoder();
const ZERO_HASH = '0'.repeat(64);
const TECH_FORK_SUBTYPE = 2;
function payload(resp) { return resp?.payload && typeof resp.payload === 'object' ? resp.payload : (resp || {}); }
@@ -29,46 +28,22 @@ function concat(...chunks) {
function be16(v) { const a=new Uint8Array(2); new DataView(a.buffer).setUint16(0, Number(v), false); return a; }
function be32(v) { const a=new Uint8Array(4); new DataView(a.buffer).setUint32(0, Number(v), false); return a; }
function be64(v) { const a=new Uint8Array(8); new DataView(a.buffer).setBigInt64(0, BigInt(v), false); return a; }
function hexToBytes(hex) {
const s=String(hex||'').trim().toLowerCase(); if(!/^[0-9a-f]{64}$/.test(s)) throw new Error('Ожидался SHA-256 hash');
const out=new Uint8Array(32); for(let i=0;i<32;i++) out[i]=parseInt(s.slice(i*2,i*2+2),16); return out;
}
function bytesToHex(bytes) { return Array.from(bytes || [], (b)=>b.toString(16).padStart(2,'0')).join(''); }
function normalizeComment(value) { return String(value || '').trim().replace(/\r\n/g,'\n').replace(/\r/g,'\n'); }
function readFrameTimestampMs(frame) {
if (!(frame instanceof Uint8Array) || frame.length < 82) throw new Error('Некорректный SHiNE Frame');
const seconds = new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getBigInt64(74, false);
return Number(seconds * 1000n);
function blockNumber(value) {
if (!Number.isInteger(value) || value < 0 || value > SHINE_CORE_MAX_BLOCK_NUMBER) throw new Error('Некорректный номер CORE');
return value;
}
function readFrameType(frame) {
if (!(frame instanceof Uint8Array) || frame.length < 88) throw new Error('Некорректный SHiNE Frame');
const view=new DataView(frame.buffer,frame.byteOffset,frame.byteLength);
return { type:view.getUint16(82,false), subType:view.getUint16(84,false) };
function timestampMs(core) {
const ms = Number(core.timestamp * 1000n);
if (!Number.isSafeInteger(ms)) throw new Error('Некорректное время CORE');
return ms;
}
function readExplicitLinePrefix(frame) {
if (!(frame instanceof Uint8Array) || frame.length < 132) throw new Error('Некорректный line Frame');
const view=new DataView(frame.buffer,frame.byteOffset,frame.byteLength);
return {
lineCode:view.getInt32(88,false),
prevLineNumber:view.getInt32(92,false),
prevLineHash:bytesToHex(frame.slice(96,128)),
lineSequence:view.getInt32(128,false),
};
}
function makeForkBody({ lineCode=0, prevLineNumber, prevLineHash, lineSequence, oldBlockchainKeyB64, forkPointBlock, forkPointHash, forkPointTimestampMs, parentTipBlock, parentTipHash, parentTipTimestampMs, reasonCode, comment }) {
function makeForkBody({ oldBlockchainKeyB64, forkPointBlock, forkPointHash, forkPointTimestampMs, parentTipBlock, parentTipHash, parentTipTimestampMs, reasonCode, comment }) {
const oldKey=base64ToBytes(oldBlockchainKeyB64); if(oldKey.length!==32) throw new Error('Некорректный старый blockchain key');
const c=TE.encode(normalizeComment(comment)); if(c.length>1024) throw new Error('Комментарий больше 1024 UTF-8 байт');
const discarded=Number(parentTipBlock)-Number(forkPointBlock);
if(discarded<0) throw new Error('Некорректная точка fork');
if(Number(lineCode)!==0 || !Number.isInteger(Number(prevLineNumber)) || Number(prevLineNumber)<0 || !Number.isInteger(Number(lineSequence)) || Number(lineSequence)<1) {
throw new Error('Некорректная TECH line для FORK');
}
return concat(be32(lineCode),be32(prevLineNumber),hexToBytes(prevLineHash),be32(lineSequence),oldKey,be32(forkPointBlock),hexToBytes(forkPointHash),be64(forkPointTimestampMs),be32(parentTipBlock),hexToBytes(parentTipHash),be64(parentTipTimestampMs),be32(discarded),Uint8Array.of(Number(reasonCode)),be16(c.length),c);
}
function makeFrame({ prevHash, back32Hash=ZERO_HASH, blockNumber, type, subType, version=1, body, timestampMs=Date.now() }) {
const bodyBytes=body || new Uint8Array(0);
const size=2+32+32+4+4+8+2+2+2+bodyBytes.length;
return concat(be16(1),hexToBytes(prevHash),hexToBytes(back32Hash),be32(size),be32(blockNumber),be64(Math.floor(Number(timestampMs)/1000)),be16(type),be16(subType),be16(version),bodyBytes);
const discarded=blockNumber(parentTipBlock)-blockNumber(forkPointBlock);
if(discarded<0 || ![1,2,3,4].includes(reasonCode)) throw new Error('Некорректная точка fork или причина');
return concat(oldKey,be32(forkPointBlock),coreHashBytes(forkPointHash),be64(forkPointTimestampMs),be32(parentTipBlock),coreHashBytes(parentTipHash),be64(parentTipTimestampMs),be32(discarded),Uint8Array.of(reasonCode),be16(c.length),c);
}
export const KEY_ROTATION_REASONS = Object.freeze([
@@ -87,68 +62,64 @@ export class KeyRotationClient {
async finishChain() { return assertOk(await this.auth.ws.request('KeyRotationFinishChain', {}), 'KeyRotationFinishChain'); }
async notifyPdaRotation(signature) { return assertOk(await this.auth.ws.request('KeyRotationRotatePda', { pdaRotationSignature: signature }), 'KeyRotationRotatePda'); }
async getMyBlockchain({ beforeBlock=null, limit=50, includeBlockBytes=false }={}) {
return assertOk(await this.auth.ws.request('GetMyBlockchain', { beforeBlock, limit, includeBlockBytes }), 'GetMyBlockchain');
const page=assertOk(await this.auth.ws.request('GetMyBlockchain', { beforeBlock, limit, includeBlockBytes }), 'GetMyBlockchain');
// The original cutoff picker needs time and hash, now derived from signed CORE.
return {...page, blocks:await Promise.all((page.blocks||[]).map(async row=>{
const checked=await readCoreBlock(row);
return {...row,blockHash:checked.coreHash,timestampMs:timestampMs(checked.core)};
}))};
}
async getBlock(blockchainName, blockNumber) {
return assertOk(await this.auth.ws.request('GetBlockchainBlock', { blockchainName, blockNumber }), 'GetBlockchainBlock');
async getBlock(blockchainName, number) {
const row=assertOk(await this.auth.ws.request('GetBlockchainBlock', { blockchainName, blockNumber:number }), 'GetBlockchainBlock');
if(row.blockNumber!==number || String(row.blockchainName||'').toLowerCase()!==blockchainName.toLowerCase()) throw new Error('CORE source mismatch');
return readCoreBlock({...row,contentDataItemB64:null});
}
async addCandidate({ blockNumber, prevBlockHash, blockBytesB64 }) {
return assertOk(await this.auth.ws.request('KeyRotationAddBlock', { blockNumber, prevBlockHash, blockBytesB64 }, 30000), 'KeyRotationAddBlock');
async addCandidate({ blockNumber, prevBlockHash, coreDataItemB64, contentDataItemB64 }) {
return assertOk(await this.auth.ws.request('KeyRotationAddBlock', { blockNumber, prevBlockHash, coreDataItemB64, contentDataItemB64 }, 30000), 'KeyRotationAddBlock');
}
async #resolveTechLineTail(source, cutoff) {
for(let n=Number(cutoff);n>0;n--) {
const block=await this.getBlock(source,n);
const parsed=parseAns104DataItem(base64ToBytes(block.blockBytesB64));
const kind=readFrameType(parsed.data);
if(kind.type!==0 || (kind.subType!==1 && kind.subType!==TECH_FORK_SUBTYPE)) continue;
const line=readExplicitLinePrefix(parsed.data);
if(line.lineCode!==0 || line.lineSequence<1) throw new Error(`Некорректная TECH line в блоке #${n}`);
return {
prevLineNumber:n,
prevLineHash:String(block.blockHash||''),
lineSequence:line.lineSequence+1,
};
async #resolveTechLineTail(source, point) {
// Search the frozen source prefix, not the active TECH head (which may be after cutoff).
// The line selector lives in CORE and works even when CONTENT is missing.
let entry=point;
for(;;) {
if(entry.core.blockNumber===0 || entry.core.line?.lineCode===SHINE_CORE_LINE_TECH) {
return {lineCode:SHINE_CORE_LINE_TECH,prevLineBlockNumber:entry.core.blockNumber,prevLineCoreHash32:coreHashBytes(entry.coreHash)};
}
const previous=await this.getBlock(source,entry.core.blockNumber-1);
if(previous.coreHash!==coreHex(entry.core.prevCoreHash32)) throw new Error('Нарушена связь CORE в исходной цепочке');
entry=previous;
}
const header=await this.getBlock(source,0);
return { prevLineNumber:0, prevLineHash:String(header.blockHash||''), lineSequence:1 };
}
async copyCandidateChain({ rotation, newBundle, onProgress=()=>{} }) {
const cutoff=Number(rotation.forkFromBlock); const source=String(rotation.sourceBlockchainName||'');
if(!source || !Number.isInteger(cutoff) || cutoff<0) throw new Error('Некорректное состояние ротации');
const cutoff=blockNumber(rotation.forkFromBlock); const source=String(rotation.sourceBlockchainName||'');
if(!source || cutoff===SHINE_CORE_MAX_BLOCK_NUMBER) throw new Error('Некорректное состояние ротации');
if(String(newBundle?.blockchainPair?.publicKeyB64||'') !== String(rotation.newBlockchainKey||'')) throw new Error('Новый пароль выводит другой blockchain key');
const total=1;
if((Number(rotation.progressCurrent)||0)>=total){onProgress({phase:'copy',current:total,total});return;}
const owner32=base64ToBytes(newBundle.blockchainPair.publicKeyB64);
const privateKey=newBundle.blockchainPair.privateKey;
const tipBlock=blockNumber(rotation.sourceTipBlock);
if(tipBlock<cutoff) throw new Error('Некорректная точка fork');
const forkSource=await this.getBlock(source,cutoff);
const tipBlock=Number(rotation.sourceTipBlock);
const tipSource=tipBlock===cutoff?forkSource:await this.getBlock(source,tipBlock);
const forkParsed=parseAns104DataItem(base64ToBytes(forkSource.blockBytesB64));
const tipParsed=parseAns104DataItem(base64ToBytes(tipSource.blockBytesB64));
const techTail=await this.#resolveTechLineTail(source,cutoff);
if(forkSource.coreHash!==coreHex(coreHashBytes(rotation.forkFromHash)) || tipSource.coreHash!==coreHex(coreHashBytes(rotation.sourceTipHash))) throw new Error('CORE hash исходной цепочки не совпадает с сессией ротации');
const line=await this.#resolveTechLineTail(source,forkSource);
const forkBody=makeForkBody({
lineCode:0, prevLineNumber:techTail.prevLineNumber, prevLineHash:techTail.prevLineHash, lineSequence:techTail.lineSequence,
oldBlockchainKeyB64:rotation.oldBlockchainKey, forkPointBlock:cutoff, forkPointHash:rotation.forkFromHash,
forkPointTimestampMs:readFrameTimestampMs(forkParsed.data), parentTipBlock:tipBlock, parentTipHash:rotation.sourceTipHash,
parentTipTimestampMs:readFrameTimestampMs(tipParsed.data), reasonCode:rotation.reasonCode, comment:rotation.comment,
forkPointTimestampMs:timestampMs(forkSource.core), parentTipBlock:tipBlock, parentTipHash:rotation.sourceTipHash,
parentTipTimestampMs:timestampMs(tipSource.core), reasonCode:rotation.reasonCode, comment:rotation.comment,
});
const techTimestampMs=Number(rotation.createdAtMs)||readFrameTimestampMs(tipParsed.data)+1000;
// Fixed session timestamp preserves identical bytes on a retry with the same new key.
const techTimestampMs=Number(rotation.createdAtMs)||timestampMs(tipSource.core)+1000;
const techBlockNumber=cutoff+1;
const techBack32Hash=techBlockNumber<32?ZERO_HASH:String((await this.getBlock(source,techBlockNumber-32)).blockHash||'');
const techFrame=makeFrame({prevHash:rotation.forkFromHash,back32Hash:techBack32Hash,blockNumber:techBlockNumber,type:0,subType:TECH_FORK_SUBTYPE,version:1,body:forkBody,timestampMs:techTimestampMs});
const techRaw=await createAns104DataItem({owner32,privateKey,data:techFrame,tags:[{name:SHINE_APP_TAG_NAME,value:SHINE_APP_TAG_VALUE},{name:SHINE_TYPE_TAG_NAME,value:'tech'}]});
await this.addCandidate({blockNumber:techBlockNumber,prevBlockHash:rotation.forkFromHash,blockBytesB64:bytesToBase64(techRaw)});
const pair=await signCoreContentPair({owner32,privateKey,content:{type:0,subType:TECH_FORK_SUBTYPE,version:1,body:forkBody},
prevCoreHash32:coreHashBytes(rotation.forkFromHash),blockNumber:techBlockNumber,timestamp:Math.floor(techTimestampMs/1000),line});
await this.addCandidate({blockNumber:techBlockNumber,prevBlockHash:rotation.forkFromHash,coreDataItemB64:bytesToBase64(pair.coreDataItem),contentDataItemB64:bytesToBase64(pair.contentDataItem)});
onProgress({phase:'copy',current:1,total:1});
}
async #sourcePrevHash(source, blockNumber) {
if(blockNumber<=0) return ZERO_HASH;
const prev=await this.getBlock(source,blockNumber-1);
return String(prev.blockHash||'');
}
async waitUntilPublished({ timeoutMs=180000, onProgress=()=>{} }={}) {
const started=Date.now();
while(Date.now()-started<timeoutMs) {
@@ -229,4 +200,3 @@ export class KeyRotationClient {
}
}
function nullIfEmpty(value) { const s=String(value||'').trim(); return s || null; }
+9
View File
@@ -5,3 +5,12 @@ export const SHINE_APP_TAG_NAME = 'App';
export const SHINE_APP_TAG_VALUE = SHINE_PROTOCOL_NAMESPACE;
export const SHINE_CHANNEL_TAG_NAME = 'c';
export const SHINE_TYPE_TAG_NAME = 't';
// Подготовленная эпоха CORE; старый runtime пока не переключён.
export const SHINE_CORE_NAMESPACE = 'test5593';
export const SHINE_CORE_NUMBER_TAG_NAME = 'n';
export const SHINE_CORE_LINE_TAG_NAME = 'l';
export const SHINE_CORE_LINE_PROFILE = 2147483645;
export const SHINE_CORE_LINE_CONNECTION = 2147483646;
export const SHINE_CORE_LINE_TECH = 2147483647;
export const SHINE_CORE_MAX_BLOCK_NUMBER = 2147482623;
@@ -3,7 +3,7 @@ import { t } from '../i18n/index.js';
export const USER_PDA_SPACE = 768; // shine-solana/shine/programs/shine_users/src/settings.rs
// Запас для предварительной проверки баланса; сеть списывает фактическую комиссию.
export const REGISTRATION_NETWORK_RESERVE_LAMPORTS = 100_000n;
export const UPGRADE_TEST_TOPUP_SOL = 0.032;
export const UPGRADE_TEST_TOPUP_SOL = 0.04;
export const LAMPORTS_PER_SOL = 1_000_000_000;
export function calculateRegistrationFunding({ namespaceFeeLamports, rentLamports }) {
@@ -1,5 +1,6 @@
import { t } from '../i18n/index.js';
const SNAPSHOT_STORAGE_KEY = 'shine-ui-blockchain-snapshot-v1';
// Keep historical Frame snapshots in their original bucket; never publish them as CORE.
const SNAPSHOT_STORAGE_KEY = 'shine-ui-blockchain-snapshot-test5593';
function normalizeLogin(login) {
return String(login || '').trim().toLowerCase();
@@ -9,15 +10,6 @@ function storageBucketKey(login) {
return normalizeLogin(login) || 'anonymous';
}
function decodeBase64ToBytes(base64) {
const raw = String(base64 || '').trim();
if (!raw) return new Uint8Array();
const bin = atob(raw);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);
return out;
}
function readStorageMap() {
try {
const raw = localStorage.getItem(SNAPSHOT_STORAGE_KEY);
@@ -61,49 +53,8 @@ export function clearStoredBlockchainSnapshot(login) {
writeStorageMap(map);
}
export async function buildBlockchainSnapshotFile({
authService,
login,
blockchainName,
lastBlockNumber,
} = {}) {
const cleanLogin = normalizeLogin(login);
const cleanBlockchainName = String(blockchainName || '').trim();
const maxBlockNumber = Number(lastBlockNumber);
if (!authService?.ws?.request) throw new Error(t('remaining.blockchain_snapshot.server_service_unavailable'));
if (!cleanLogin) throw new Error(t('remaining.blockchain_snapshot.login_missing'));
if (!cleanBlockchainName) throw new Error(t('remaining.blockchain_snapshot.blockchain_name_missing'));
if (!Number.isFinite(maxBlockNumber) || maxBlockNumber < 0) {
throw new Error(t('remaining.blockchain_snapshot.no_blocks_available_on_the_server_for_a_snapshot'));
}
const parts = [];
let totalBytes = 0;
for (let blockNumber = 0; blockNumber <= maxBlockNumber; blockNumber += 1) {
const response = await authService.ws.request('GetBlockchainBlock', {
blockchainName: cleanBlockchainName,
blockNumber,
});
if (response?.status !== 200) {
const message = String(response?.payload?.message || response?.message || t('remaining.blockchain_snapshot.could_not_retrieve_block'));
throw new Error(`Не удалось скачать блок ${blockNumber}: ${message}`);
}
const blockBytes = decodeBase64ToBytes(response?.payload?.blockBytesB64 || '');
parts.push(blockBytes);
totalBytes += blockBytes.length;
}
const file = new File(parts, `${cleanBlockchainName}.shine-blockchain`, {
type: 'application/octet-stream',
lastModified: Date.now(),
});
return {
file,
blockCount: maxBlockNumber + 1,
totalBytes,
lastBlockNumber: maxBlockNumber,
login: cleanLogin,
blockchainName: cleanBlockchainName,
};
// The old concatenated Frame file is not a CORE archive. Do not upload an empty
// or lossy replacement or invent a snapshot format before D defines recovery.
export async function buildBlockchainSnapshotFile() {
throw new Error(t('remaining.blockchain_snapshot.core_pending'));
}
+2
View File
@@ -20,6 +20,8 @@ export function toUserMessage(error, fallback = t('errors.text_002')) {
const text = normalizeText(error);
const code = String(error?.code || extractCode(raw) || '').toUpperCase();
if (code === 'CORE_WRITE_OUTCOME_UNKNOWN') return t('errors.core_write_outcome_unknown');
if (
text.includes('webcrypto') ||
text.includes('crypto.subtle') ||
@@ -1100,6 +1100,8 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
const BCH_FRAME_HEADER_SIZE = 88;
const BCH_FRAME_CODE_V1 = 0x0001;
// Transport namespace актуального standalone Viewer.
// CORE epoch: reader is switched only in part E.
const SHINE_CORE_NAMESPACE = 'test5593';
const SHINE_PROTOCOL_NAMESPACE = 'test5592';
const SHINE_ARWEAVE_APP_TAG = SHINE_PROTOCOL_NAMESPACE;
const SHINE_ARWEAVE_CHANNEL_TAG = 'c';
+2 -3
View File
@@ -27,12 +27,11 @@ test('подмена payload не проходит проверку подпис
assert.equal(proof.signatureValid, false);
assert.notEqual(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
});
test('по API нельзя скачать DataItem с подменённым хешем или ID', async () => {
test('активный CORE API не принимает старый Frame как пару', async () => {
const bytes = new Uint8Array(await readFile(signedPath));
const authService = { ws: { request: async () => ({ status: 200, payload: {
blockHash: expectedHash, blockBytesB64: Buffer.from(bytes).toString('base64'),
} }) } };
assert.equal((await readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:expectedId})).bytes.length, 412);
await assert.rejects(readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:'A'.repeat(43)}), /Arweave/);
await assert.rejects(readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:expectedId}));
assert.equal(arweaveBlockUrl('../evil'), '');
});
@@ -0,0 +1,91 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { decodeCore, readCoreBlock } from '../js/services/core-content.js';
import { inspectCoreBlock } from '../js/services/blockchain-entry-inspector.js';
import { readSignedBlock } from '../js/services/blockchain-proof-service.js';
import { AuthService } from '../js/services/auth-service.js';
import { saveEncryptedUserSecrets } from '../js/services/key-vault.js';
import { canonicalReadPosts, readPrefixCount } from '../js/services/channel-message-ordinals.js';
import { buildBlockchainSnapshotFile } from '../js/services/shine-blockchain-snapshot-service.js';
const b64 = hex => Buffer.from(hex,'hex').toString('base64');
const id = hex => Buffer.from(hex,'hex').toString('base64url');
const fixtures = fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url),'utf8').trim().split('\n').slice(1).map(line => line.split('\t'));
const rows = fixtures.map(([name,owner,core,coreHash,content,contentHash,coreItem,coreItemId,contentItem,contentItemId]) => ({name,blockNumber:decodeCore(Uint8Array.from(Buffer.from(core,'hex'))).blockNumber,coreHash,contentHash,coreDataItemId:id(coreItemId),contentDataItemId:id(contentItemId),coreDataItemB64:b64(coreItem),contentDataItemB64:b64(contentItem),contentStatus:'VALID'}));
test('signed CORE reader and existing semantic inspector decode all external vectors', async () => {
for (const row of rows) {
const p = await readCoreBlock(row,{requireContent:true});
const inspection = await inspectCoreBlock(row);
assert.equal(p.actualId,row.coreDataItemId,row.name);
assert.equal(inspection.frame.blockNumber,row.blockNumber,row.name);
assert.equal(inspection.frame.type,p.content.type,row.name);
assert.equal(inspection.contentDataItemId,row.contentDataItemId,row.name);
assert.notEqual(inspection.frame.body.kind,'unknown',row.name);
if (p.core.line) assert.equal(inspection.frame.body.line.lineCode,p.core.line.lineCode,row.name);
}
});
test('CORE can be inspected without CONTENT, but a full proof cannot be claimed',async()=>{
const row={...rows[0],contentDataItemB64:null,contentStatus:'MISSING'};
assert.equal((await inspectCoreBlock(row)).frame.body.kind,'unknown');
await assert.rejects(readCoreBlock(row,{requireContent:true}),/CONTENT unavailable/);
});
test('read rejects altered metadata, substituted content, and invalid signature',async()=>{
const row=rows[0];
for (const change of [{blockNumber:1},{coreHash:'a'.repeat(64)},{contentDataItemId:'A'.repeat(43)},{contentHash:'b'.repeat(64)},{coreDataItemId:'B'.repeat(43)},{contentDataItemB64:rows[1].contentDataItemB64}]) await assert.rejects(readCoreBlock({...row,...change}));
const raw=Buffer.from(row.coreDataItemB64,'base64'); raw[2]^=1;
await assert.rejects(readCoreBlock({...row,coreDataItemB64:raw.toString('base64')}));
assert.equal((await inspectCoreBlock({...row,contentStatus:'INVALID'})).frame.body.kind,'unknown');
});
test('existing proof request verifies both exact DataItems and expected CORE ID',async()=>{
const row=rows[2];
const authService={ws:{request:async(op,payload)=>{assert.equal(op,'GetBlockchainBlock');assert.equal(payload.blockNumber,row.blockNumber);return {status:200,payload:{...row,blockHash:row.coreHash}};}}};
const args={authService,blockchainName:'Alice-001',blockNumber:row.blockNumber,blockHash:row.coreHash,dataItemId:row.coreDataItemId};
const p=await readSignedBlock(args);
assert.equal(Buffer.from(p.bytes).toString('base64'),row.coreDataItemB64);
assert.equal(Buffer.from(p.contentProof.bytes).toString('base64'),row.contentDataItemB64);
await assert.rejects(readSignedBlock({...args,dataItemId:'A'.repeat(43)}),/Arweave/);
await assert.rejects(readSignedBlock({...args,blockHash:'a'.repeat(64)}));
});
const h=x=>x.repeat(64);
const root={blockNumber:5,blockHash:h('a')};
const p1={authorLogin:'Alice',localNumber:2,messageRef:{blockNumber:6,blockHash:h('b')}};
const p2={authorLogin:'Alice',localNumber:1,messageRef:{blockNumber:9,blockHash:h('c')}};
const summary={channel:{ownerLogin:'Alice',channelRoot:root},followHash:h('d'),messagesCount:2,readAnchor:p2.messageRef};
test('read prefix is canonical not display order, and never skips an unseen publication',()=>{
const ordered=canonicalReadPosts([p2,p1],summary);
assert.deepEqual(ordered,[p1,p2]);
assert.equal(readPrefixCount(ordered,0,new Set([1])),0);
assert.equal(readPrefixCount(ordered,0,new Set([2])),1);
assert.equal(readPrefixCount(ordered,1,new Set([1])),2);
assert.equal(canonicalReadPosts([p2],summary),null);
assert.equal(canonicalReadPosts([p2,p1],{...summary,readAnchor:{...p2.messageRef,blockHash:h('e')}}),null);
assert.equal(canonicalReadPosts([p2,{...p1,authorLogin:'Other'}],summary),null);
assert.deepEqual(canonicalReadPosts([],{...summary,messagesCount:0,readAnchor:root}),[]);
});
test('SetChannelReadState signs the exact existing server contract with client key',async()=>{
const seed=Buffer.from(Array.from({length:32},(_,i)=>i));
const pkcs8=Buffer.concat([Buffer.from('302e020100300506032b657004220420','hex'),seed]);
const auth=new AuthService('wss://test.invalid/ws');
await saveEncryptedUserSecrets('Bob','read-test',{clientKey:pkcs8.toString('base64')});
const mark={owner:'Alice',root:5,rootHash:h('a'),followHash:h('d'),anchor:6,anchorHash:h('b'),timeMs:1760000000000};
const result={applied:true,state:{followHash:mark.followHash,initialized:true,readCount:1,unreadCount:1}};
auth.ws.request=async(op,payload)=>{
assert.equal(op,'SetChannelReadState');const {signatureB64,...rest}=payload;
assert.deepEqual(rest,mark);
const pub=await crypto.subtle.importKey('raw',Buffer.from(fixtures[0][1],'hex'),{name:'Ed25519'},false,['verify']);
assert.equal(await crypto.subtle.verify('Ed25519',pub,Buffer.from(signatureB64,'base64'),new TextEncoder().encode(['SHiNE_CORE_READ_V1','test5593','Bob','Alice',5,h('a'),h('d'),6,h('b'),mark.timeMs].join('|'))),true);
return {status:200,payload:{result}};
};
assert.deepEqual(await auth.setChannelReadState({login:'Bob',storagePwd:'read-test',...mark}),result);
await assert.rejects(auth.setChannelReadState({login:'Bob',storagePwd:'read-test',...mark,anchor:4}),/BAD_READ_STATE/);
await assert.rejects(auth.setChannelReadState({login:'Bob',storagePwd:'read-test',ownerBlockchainName:'Alice-001',channelName:'news',readCount:1}),/BAD_READ_STATE/);
});
test('public channel resolution uses original profile API, not another user’s subscriptions',async()=>{
const auth=new AuthService('wss://test.invalid/ws');
auth.ws.request=async(op,payload)=>{assert.equal(op,'ListUserProfileChannels');assert.deepEqual(payload,{login:'Alice',mode:'owned',limit:500,offset:0,includeDeleted:false});return {status:200,payload:{channels:[{ownerLogin:'Alice',ownerBlockchainName:'Alice-001',slug:'news',rootBlockNumber:5,rootBlockHashHex:h('a')}]}};};
const [row]=await auth.listOwnedChannelSummaries('Alice');
assert.equal(row.channel.channelName,'news');assert.deepEqual(row.channel.channelRoot,root);
});
test('snapshot creation is blocked until D rather than generating an empty legacy file',async()=>{
await assert.rejects(buildBlockchainSnapshotFile({authService:{ws:{request:()=>assert.fail('must not fetch legacy blocks')}}}));
});
@@ -0,0 +1,202 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { encodeContent, decodeContent, encodeCore, decodeCore, coreHex, coreHashBytes,
signCoreContentPair, verifyCoreContentPair, splitEventBody, CORE_MAX_CONTENT_BYTES } from '../js/services/core-content.js';
import { AuthService } from '../js/services/auth-service.js';
import { saveEncryptedUserSecrets } from '../js/services/key-vault.js';
import { SHINE_CORE_LINE_PROFILE, SHINE_CORE_LINE_CONNECTION, SHINE_CORE_LINE_TECH } from '../js/services/protocol-tags.js';
const unhex = s=>Uint8Array.from(Buffer.from(s,'hex'));
const b64 = b=>Buffer.from(b).toString('base64');
const unb64 = s=>Uint8Array.from(Buffer.from(s,'base64'));
const seed = Buffer.from(Array.from({length:32},(_,i)=>i));
const pkcs8 = Buffer.concat([Buffer.from('302e020100300506032b657004220420','hex'),seed]);
const key = await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
const rows = fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv',import.meta.url),'utf8').trim().split('\n').slice(1).map(r=>r.split('\t'));
const owner = unhex(rows[0][1]);
const zero = new Uint8Array(32);
const h = 'ab'.repeat(32);
const head = (blockNumber, coreHash=h)=>({blockNumber,coreHash});
const names = { blockchainName:'Alice-001' };
const headResponse = (global, line=null)=>({status:200,payload:{result:{...names,global,line}}});
// The production codec, not a second Buffer implementation, must reproduce the external fixtures.
test('runtime codec and signer reproduce all eight Java/Python vectors byte for byte', async()=>{
for(const [name,ownerHex,coreHexValue,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows){
const core=decodeCore(unhex(coreHexValue)), content=decodeContent(unhex(contentHex));
assert.equal(coreHex(encodeCore(core)),coreHexValue,name);
assert.equal(coreHex(encodeContent(content)),contentHex,name);
const produced=await signCoreContentPair({...core,owner32:unhex(ownerHex),privateKey:key,content});
assert.equal(coreHex(produced.coreDataItem),coreItemHex,name);
assert.equal(coreHex(produced.contentDataItem),contentItemHex,name);
assert.equal(coreHex(produced.coreHash32),coreHash,name);
assert.equal(coreHex(produced.contentHash32),contentHash,name);
assert.equal(coreHex(produced.contentDataItemId32),contentId,name);
const checked=await verifyCoreContentPair(produced.coreDataItem,produced.contentDataItem,owner);
assert.equal(coreHex(checked.coreDataItemId32),coreId,name);
}
});
test('codec rejects malformed sizes, version bytes, indices and bad genesis', ()=>{
const core=decodeCore(unhex(rows[0][2]));
for(const bytes of [new Uint8Array(108),new Uint8Array(150),Uint8Array.of(1)]) assert.throws(()=>decodeCore(bytes));
assert.throws(()=>encodeCore({...core,blockNumber:2147482624}));
assert.throws(()=>encodeCore({...core,timestamp:-1}));
assert.throws(()=>encodeCore({...core,prevCoreHash32:unhex(h)}));
assert.throws(()=>encodeCore({...core,blockNumber:1,line:{lineCode:0,prevLineBlockNumber:1,prevLineCoreHash32:zero}}));
assert.throws(()=>decodeContent(Uint8Array.of(0,0,0,0,0,0,1)));
assert.throws(()=>encodeContent({type:65536,subType:0,version:1,body:zero}));
assert.throws(()=>encodeContent({type:1,subType:10,version:1,body:new Uint8Array(CORE_MAX_CONTENT_BYTES-6)}));
});
test('pair validation rejects wrong owner, swapped valid content and tampering', async()=>{
const c=unhex(rows[0][6]), p=unhex(rows[0][8]);
await assert.rejects(verifyCoreContentPair(c,p,zero));
await assert.rejects(verifyCoreContentPair(c,unhex(rows[1][8]),owner));
const modified=p.slice(); modified[modified.length-1]^=1;
await assert.rejects(verifyCoreContentPair(c,modified,owner));
});
test('adapter moves only predecessor/line code, never old lineSequence, into CORE',()=>{
const fixed=new Uint8Array(42); fixed.set(unhex(h),4); new DataView(fixed.buffer).setInt32(36,123); fixed.set([1,2],40);
for(const [msgType,lineCode] of [[3,SHINE_CORE_LINE_CONNECTION],[4,SHINE_CORE_LINE_PROFILE]]){
const {content,line}=splitEventBody({msgType,msgSubType:1,bodyBytes:fixed});
assert.deepEqual(Array.from(content.body),[1,2]); assert.equal(line.lineCode,lineCode); assert.equal(line.prevLineBlockNumber,0); assert.equal(coreHex(line.prevLineCoreHash32),h);
}
const explicit=new Uint8Array(46); explicit.set(fixed,4);
const tech=splitEventBody({msgType:0,msgSubType:1,bodyBytes:explicit});
assert.equal(tech.line.lineCode,SHINE_CORE_LINE_TECH); assert.deepEqual(Array.from(tech.content.body),[1,2]);
new DataView(explicit.buffer).setInt32(0,9);
const post=splitEventBody({msgType:1,msgSubType:10,bodyBytes:explicit});
assert.equal(post.line.lineCode,9); assert.deepEqual(Array.from(post.content.body),[1,2]);
assert.throws(()=>splitEventBody({msgType:4,msgSubType:1,bodyBytes:zero}));
assert.equal(splitEventBody({msgType:2,msgSubType:1,bodyBytes:zero}).line,null);
});
async function service(request, withKey=true){
const auth=new AuthService('wss://test.invalid/ws');
// Real existing encrypted vault, with in-memory fallback in Node; no network or real keys.
await saveEncryptedUserSecrets('Alice','test-password',withKey?{blockchainKey:b64(pkcs8)}:{});
auth.ws.request=request;
return auth;
}
const args={login:'Alice',storagePwd:'test-password',_skipHeaderEnsure:true};
async function checked(payload){
assert.deepEqual(Object.keys(payload).sort(),['blockNumber','blockchainName','contentDataItemB64','coreDataItemB64','prevBlockHash'].sort());
return verifyCoreContentPair(unb64(payload.coreDataItemB64),unb64(payload.contentDataItemB64),owner);
}
test('original ensureBlockchainHeader uses registered spelling and CreateGenesis, then no duplicate',async()=>{
let exists=false; const writes=[];
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(exists?head(0):null);
assert.equal(op,'CreateGenesis'); const pair=await checked(p); assert.equal(p.prevBlockHash,''); assert.equal(p.blockNumber,0);
assert.equal(pair.content.version,1); assert.equal(pair.core.line,null);
assert.equal(Buffer.from(pair.content.body).toString('hex'),Buffer.concat([Buffer.from('SHiNE'),Buffer.of(5),Buffer.from('Alice'),Buffer.from(owner)]).toString('hex'));
exists=true; writes.push(p);return {status:200,payload:{serverLastGlobalNumber:0,serverLastGlobalHash:coreHex(pair.coreHash32)}};
});
auth.getUser=async()=>({exists:true,login:'Alice',serverLastGlobalNumber:exists?0:-1,blockchainName:'Alice-001'});
await auth.ensureBlockchainHeader('alice','test-password'); await auth.ensureBlockchainHeader('alice','test-password');
assert.equal(writes.length,1);
});
test('ordinary AddBlock signs fresh global + line head; no back32 lookup or legacy payload',async()=>{
const calls=[]; const lineBody=new Uint8Array(47); lineBody.set(unhex(h),8); new DataView(lineBody.buffer).setInt32(4,3); lineBody.set([0,1,65],44);
const auth=await service(async(op,p)=>{
calls.push(op);
if(op==='GetMyCoreHeads'){assert.equal(p.lineCode,0);return headResponse(head(40),head(3));}
assert.equal(op,'AddBlock'); const pair=await checked(p);
assert.equal(p.blockNumber,41);assert.equal(p.prevBlockHash,h);assert.equal(pair.core.line.prevLineBlockNumber,3);assert.equal(pair.core.line.lineCode,0);
assert.deepEqual(Array.from(pair.content.body),[0,1,65]);return {status:200,payload:{serverLastGlobalNumber:41,serverLastGlobalHash:coreHex(pair.coreHash32)}};
});
await auth.addBlockSigned({...args,msgType:1,msgSubType:10,bodyBytes:lineBody});
assert.deepEqual(calls,['GetMyCoreHeads','AddBlock']);
});
test('retry only explicit global conflict; refresh head and re-sign without changing content',async()=>{
let reads=0,writes=0;let original;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(10+reads++,reads===1?h:'cd'.repeat(32)));
const pair=await checked(p);writes++;
if(writes===1){original=p.contentDataItemB64;return {status:409,payload:{code:'GLOBAL_HEAD_CONFLICT'}};}
assert.equal(p.blockNumber,12); assert.equal(p.prevBlockHash,'cd'.repeat(32));assert.equal(p.contentDataItemB64,original);
return {status:200,payload:{serverLastGlobalNumber:12,serverLastGlobalHash:coreHex(pair.coreHash32)}};
});
await auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});assert.equal(writes,2);
});
test('reject stale line, revoked session, unknown outcome and legacy remote signer without fallback',async()=>{
const body=new Uint8Array(44);body.set(unhex(h),8);
let writes=0;
let auth=await service(async(op)=>{if(op==='GetMyCoreHeads')return headResponse(head(4),head(1));writes++;throw new Error('should not write');});
await assert.rejects(auth.addBlockSigned({...args,msgType:1,msgSubType:10,bodyBytes:body}),e=>e.code==='LINE_HEAD_CONFLICT');assert.equal(writes,0);
auth=await service(async(op)=>{if(op==='GetMyCoreHeads')return headResponse(head(4));writes++;return {status:401,payload:{code:'SESSION_NOT_FOUND'}};});
await assert.rejects(auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero}),e=>e.code==='SESSION_NOT_FOUND');assert.equal(writes,1);
auth=await service(async(op)=>{if(op==='GetMyCoreHeads')return headResponse(head(4));if(op==='GetBlockchainBlock')return {status:404};writes++;throw new Error('timeout');});
await assert.rejects(auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero}),e=>e.code==='CORE_WRITE_OUTCOME_UNKNOWN');assert.equal(writes,3);
auth=await service(async()=>{throw new Error('unexpected network');},false);
await assert.rejects(auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero}),/remote signing is not migrated/);
});
test('existing create-channel, post and profile factories send original semantic body and CORE line',async()=>{
const writes=[];
let global=head(0), channelRoot=null;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(global,p.lineCode===1?channelRoot:p.lineCode==null?null:head(0));
if(op==='GetBlockchainBlock'){assert.equal(p.blockNumber,1);return {status:200,payload:{blockHash:channelRoot.coreHash}};}
assert.equal(op,'AddBlock'); const pair=await checked(p);writes.push(pair);
global=head(p.blockNumber,coreHex(pair.coreHash32));
if(pair.content.type===0)channelRoot=global;
return {status:200,payload:{serverLastGlobalNumber:global.blockNumber,serverLastGlobalHash:global.coreHash}};
});
auth.getUser=async()=>({exists:true,login:'Alice',blockchainName:'Alice-001',serverLastGlobalNumber:global.blockNumber});
const channel=await auth.addBlockCreateChannel({login:'Alice',storagePwd:'test-password',channelName:'News'});
assert.equal(writes[0].core.line.lineCode,SHINE_CORE_LINE_TECH);
assert.deepEqual(Array.from(writes[0].content.body),[4,78,101,119,115,0,0,0,1,0,1]);
await auth.addBlockTextPost({login:'Alice',storagePwd:'test-password',channel:{...channel.channel,channelName:'News'},text:'Hello'});
assert.equal(writes[1].core.line.lineCode,1);assert.equal(writes[1].core.line.prevLineBlockNumber,1);
assert.equal(coreHex(writes[1].content.body),'000548656c6c6f');
await auth.addBlockUserParam({login:'Alice',storagePwd:'test-password',param:'name',value:'Alice'});
assert.equal(writes[2].core.line.lineCode,SHINE_CORE_LINE_PROFILE);
assert.equal(coreHex(writes[2].content.body),'00046e616d650005416c696365');
});
test('lost AddBlock response retries the identical signed pair even when server head advances',async()=>{
let first, writes=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(4));
assert.equal(op,'AddBlock'); writes++;
if(writes===1){first=structuredClone(p);throw new Error('connection closed after commit');}
assert.deepEqual(p,first);
return {status:200,payload:{serverLastGlobalNumber:6,serverLastGlobalHash:'cd'.repeat(32)}};
});
const result=await auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});
assert.equal(writes,2);assert.equal(result.submittedBlockNumber,5);assert.equal(result.submittedBlockHash,coreHex((await checked(first)).coreHash32));assert.equal(result.serverLastGlobalNumber,6);
});
test('ambiguous 5xx followed by conflict confirms only exact signed bytes in current fork',async()=>{
let first, pair, writes=0, reads=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(++reads===1?4:6));
if(op==='GetBlockchainBlock')return {status:200,payload:{blockNumber:5,coreHash:coreHex(pair.coreHash32),contentStatus:'VALID',coreDataItemB64:first.coreDataItemB64,contentDataItemB64:first.contentDataItemB64}};
assert.equal(op,'AddBlock');writes++;
if(writes===1){first=structuredClone(p);pair=await checked(p);return {status:500,payload:{code:'DB_ERROR'}};}
assert.deepEqual(p,first);return {status:409,payload:{code:'GLOBAL_HEAD_CONFLICT'}};
});
const result=await auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});
assert.equal(writes,2);assert.equal(reads,2);assert.equal(result.submittedBlockNumber,5);
});
test('uncertain write cannot trigger line re-signing on a later explicit conflict',async()=>{
let first,writes=0,builds=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(4));
if(op==='GetBlockchainBlock')return {status:404};
writes++;
if(writes===1){first=structuredClone(p);throw new Error('lost response');}
assert.deepEqual(p,first);return {status:409,payload:{code:'GLOBAL_HEAD_CONFLICT'}};
});
await assert.rejects(auth.runLineWriteLocked('test',()=>{builds++;return auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});}),e=>e.code==='CORE_WRITE_OUTCOME_UNKNOWN');
assert.equal(builds,1);assert.equal(writes,2);
});
test('CreateGenesis retry preserves exact signed bytes',async()=>{
let first,writes=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(null);
assert.equal(op,'CreateGenesis');writes++;
if(writes===1){first=structuredClone(p);throw new Error('lost genesis response');}
assert.deepEqual(p,first);return {status:200,payload:{serverLastGlobalNumber:0,serverLastGlobalHash:coreHex((await checked(p)).coreHash32)}};
});
auth.getUser=async()=>({exists:true,login:'Alice',serverLastGlobalNumber:-1,blockchainName:'Alice-001'});
await auth.ensureBlockchainHeader('Alice','test-password');assert.equal(writes,2);
});
@@ -0,0 +1,67 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createHash } from 'node:crypto';
import { verifyAns104DataItem, createAns104DataItem } from '../js/services/ans104-data-item.js';
import { SHINE_CORE_NAMESPACE, SHINE_CORE_LINE_PROFILE, SHINE_CORE_LINE_CONNECTION,
SHINE_CORE_LINE_TECH, SHINE_CORE_MAX_BLOCK_NUMBER } from '../js/services/protocol-tags.js';
const file = new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url);
const rows = fs.readFileSync(file,'utf8').trim().split('\n').slice(1).map(r=>r.split('\t'));
const hex = b=>Buffer.from(b).toString('hex');
const unhex = s=>Buffer.from(s,'hex');
const hash = b=>createHash('sha256').update(b).digest('hex');
const special = new Map([[SHINE_CORE_LINE_PROFILE,'P'],[SHINE_CORE_LINE_CONNECTION,'C'],[SHINE_CORE_LINE_TECH,'T']]);
test('CORE v2 namespace и числовые линии согласованы в Java, UI, Viewer, Python', () => {
const server=fs.readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java',import.meta.url),'utf8');
const viewer=fs.readFileSync(new URL('../static-sites/arweave-viewer/index.html',import.meta.url),'utf8');
const publisher=fs.readFileSync(new URL('../../tools/test-publisher/protocol_tags.py',import.meta.url),'utf8');
assert.equal(SHINE_CORE_NAMESPACE,'test5593');
assert.match(server,/CORE_NAMESPACE\s*=\s*"test5593"/);
assert.match(viewer,/SHINE_CORE_NAMESPACE\s*=\s*'test5593'/);
assert.match(publisher,/CORE_NAMESPACE\s*=.*SHINE_CORE_NAMESPACE/);
assert.equal(SHINE_CORE_MAX_BLOCK_NUMBER,2147482623);
assert.deepEqual([...special.keys()],[2147483645,2147483646,2147483647]);
});
// Независимые Python fixtures, проверенные также Java. Воссоздание байтов CORE/CONTENT
// через Buffer не переключает runtime браузерного клиента (это часть C).
test('CORE/CONTENT fixtures: BigEndian, hash, ANS-104 Ed25519 и подписи браузерной библиотеки', async () => {
const pkcs8=Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]);
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
const history=[];
for(const [name,ownerHex,coreHex,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows) {
const core=unhex(coreHex), content=unhex(contentHex), owner=unhex(ownerHex);
assert.ok([109,149].includes(core.length),name);
assert.equal(core[0],1); assert.equal(content[0],1);
assert.equal(core.readInt32BE(33),history.length);
assert.equal(hash(core),coreHash); assert.equal(hash(content),contentHash);
assert.equal(hex(core.subarray(45,77)),contentHash); assert.equal(hex(core.subarray(77,109)),contentId);
assert.equal(hex(core.subarray(1,33)),history.at(-1)??'00'.repeat(32));
const newCore=Buffer.alloc(core.length);
newCore[0]=1;
unhex(history.at(-1)??'00'.repeat(32)).copy(newCore,1);
newCore.writeInt32BE(history.length,33);
newCore.writeBigInt64BE(core.readBigInt64BE(37),37);
unhex(contentHash).copy(newCore,45); unhex(contentId).copy(newCore,77);
const tags=[{name:'App',value:SHINE_CORE_NAMESPACE},{name:'n',value:String(history.length)}];
if(core.length===149) {
const line=core.readInt32BE(109), prev=core.readInt32BE(113);
newCore.writeInt32BE(line,109); newCore.writeInt32BE(prev,113); unhex(history[prev]).copy(newCore,117);
tags.push({name:'l',value:special.get(line)??String(line)});
}
const newContent=Buffer.alloc(content.length); newContent[0]=1;
for(const offset of [1,3,5]) newContent.writeUInt16BE(content.readUInt16BE(offset),offset);
content.subarray(7).copy(newContent,7);
assert.equal(hex(newCore),coreHex); assert.equal(hex(newContent),contentHex);
for(const [data,expectedItem,id,expectedTags] of [[newCore,coreItemHex,coreId,tags],[newContent,contentItemHex,contentId,[]]]) {
const verified=await verifyAns104DataItem(unhex(expectedItem));
assert.ok(verified.signatureValid,name); assert.equal(hex(verified.owner32),ownerHex);
assert.equal(hex(verified.dataItemIdBytes),id); assert.equal(hex(verified.data),hex(data));
const produced=await createAns104DataItem({owner32:owner,privateKey:key,data,tags:expectedTags});
assert.equal(hex(produced),expectedItem,name);
}
history.push(coreHash);
}
});
+60
View File
@@ -0,0 +1,60 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { KeyRotationClient } from '../js/services/key-rotation-service.js';
import { coreHex, coreHashBytes, signCoreContentPair, verifyCoreContentPair } from '../js/services/core-content.js';
import { parseAns104DataItem } from '../js/services/ans104-data-item.js';
import { SHINE_CORE_LINE_TECH } from '../js/services/protocol-tags.js';
const b64=b=>Buffer.from(b).toString('base64');
const unb64=s=>Uint8Array.from(Buffer.from(s,'base64'));
const id=b=>Buffer.from(b).toString('base64url');
const sha=async b=>new Uint8Array(await crypto.subtle.digest('SHA-256',b));
const old=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']);
const next=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']);
const owner= new Uint8Array(await crypto.subtle.exportKey('raw',old.publicKey));
const nextOwner= new Uint8Array(await crypto.subtle.exportKey('raw',next.publicKey));
const bundle={blockchainPair:{publicKeyB64:b64(nextOwner),privateKey:next.privateKey}};
const name='Alice-001', start=1760000000;
const rows=[];
async function append(type,subType,lineCode=null,prevLine=0){
const n=rows.length;
const pair=await signCoreContentPair({owner32:owner,privateKey:old.privateKey,content:{type,subType,version:1,body:new Uint8Array()},prevCoreHash32:n?coreHashBytes(rows[n-1].coreHash):new Uint8Array(32),blockNumber:n,timestamp:start+n,line:lineCode===null?null:{lineCode,prevLineBlockNumber:prevLine,prevLineCoreHash32:coreHashBytes(rows[prevLine].coreHash)}});
rows.push({blockchainName:name,blockNumber:n,coreHash:coreHex(pair.coreHash32),coreDataItemId:id(await sha(parseAns104DataItem(pair.coreDataItem).signature)),contentHash:coreHex(pair.contentHash32),contentDataItemId:id(pair.contentDataItemId32),coreDataItemB64:b64(pair.coreDataItem),contentDataItemB64:b64(pair.contentDataItem),contentStatus:'VALID'});
}
await append(0,0);await append(0,1,SHINE_CORE_LINE_TECH);await append(1,10,1,1);await append(0,1,SHINE_CORE_LINE_TECH,1);
const rotation={sourceBlockchainName:name,forkFromBlock:2,forkFromHash:rows[2].coreHash,sourceTipBlock:3,sourceTipHash:rows[3].coreHash,oldBlockchainKey:b64(owner),newBlockchainKey:b64(nextOwner),createdAtMs:(start+10)*1000,reasonCode:3,comment:' test\r\nrollback ',progressCurrent:0};
function fixture(change={}){
const writes=[],reads=[];
const client=new KeyRotationClient({ws:{request:async(op,payload)=>{
if(op==='GetBlockchainBlock'){reads.push(payload.blockNumber);assert.equal(payload.blockchainName,name);return {status:200,payload:{...rows[payload.blockNumber],...change[payload.blockNumber]}};}
if(op==='GetMyBlockchain'){assert.equal(payload.includeBlockBytes,false);return {status:200,payload:{blocks:rows.map(r=>({...r,contentDataItemB64:null})),tipBlockNumber:3,nextBeforeBlock:null}};}
assert.equal(op,'KeyRotationAddBlock');writes.push(payload);return {status:200,payload:{rotationStatus:'COPYING_CHAIN'}};
}}});
return {client,writes,reads};
}
test('original cutoff picker derives hash and time from signed CORE-only page',async()=>{
const {client}=fixture();const page=await client.getMyBlockchain();assert.equal(page.blocks[2].blockHash,rows[2].coreHash);assert.equal(page.blocks[2].timestampMs,(start+2)*1000);
});
test('rollback FORK preserves body layout and TECH predecessor before cutoff; deterministic retry',async()=>{
const {client,writes,reads}=fixture({1:{contentDataItemB64:null,contentStatus:'MISSING'}});const progress=[];
await client.copyCandidateChain({rotation,newBundle:bundle,onProgress:p=>progress.push(p)});
await client.copyCandidateChain({rotation,newBundle:bundle});assert.deepEqual(writes[0],writes[1]);assert.deepEqual(reads,[2,3,1,2,3,1]);assert.deepEqual(progress,[{phase:'copy',current:1,total:1}]);
const w=writes[0];assert.deepEqual(Object.keys(w).sort(),['blockNumber','contentDataItemB64','coreDataItemB64','prevBlockHash']);
const {core,content}=await verifyCoreContentPair(unb64(w.coreDataItemB64),unb64(w.contentDataItemB64),nextOwner);
assert.equal(core.blockNumber,3);assert.equal(core.timestamp,BigInt(start+10));assert.equal(coreHex(core.prevCoreHash32),rows[2].coreHash);assert.equal(core.line.lineCode,SHINE_CORE_LINE_TECH);assert.equal(core.line.prevLineBlockNumber,1);assert.equal(coreHex(core.line.prevLineCoreHash32),rows[1].coreHash);
assert.deepEqual([content.type,content.subType,content.version],[0,2,1]);
// Independent layout matching ForkContentBody.java, no structural prefix.
const b=Buffer.from(content.body);assert.equal(b.subarray(0,32).toString('base64'),b64(owner));assert.equal(b.readInt32BE(32),2);assert.equal(b.subarray(36,68).toString('hex'),rows[2].coreHash);assert.equal(b.readBigInt64BE(68),BigInt((start+2)*1000));assert.equal(b.readInt32BE(76),3);assert.equal(b.subarray(80,112).toString('hex'),rows[3].coreHash);assert.equal(b.readBigInt64BE(112),BigInt((start+3)*1000));assert.equal(b.readInt32BE(120),1);assert.equal(b[124],3);assert.equal(b.readUInt16BE(125),13);assert.equal(b.subarray(127).toString(),'test\nrollback');
});
test('genesis cutoff uses HEADER as TECH predecessor and preserves old source tip',async()=>{
const {client,writes}=fixture();await client.copyCandidateChain({rotation:{...rotation,forkFromBlock:0,forkFromHash:rows[0].coreHash},newBundle:bundle});const {core}=await verifyCoreContentPair(unb64(writes[0].coreDataItemB64),unb64(writes[0].contentDataItemB64),nextOwner);assert.equal(core.line.prevLineBlockNumber,0);assert.equal(coreHex(core.line.prevLineCoreHash32),rows[0].coreHash);
});
test('wrong source metadata or session hash refuses candidate before write',async()=>{
for(const [overrides,change] of [[{forkFromHash:'ff'.repeat(32)},{}],[{}, {2:{coreHash:'ff'.repeat(32)}}],[{}, {1:{blockchainName:'Bob-001'}}]]){
const {client,writes}=fixture(change);await assert.rejects(client.copyCandidateChain({rotation:{...rotation,...overrides},newBundle:bundle}));assert.equal(writes.length,0);
}
});
test('resume of published candidate does not submit again; invalid key and comment rejected',async()=>{
const {client,writes,reads}=fixture();await client.copyCandidateChain({rotation:{...rotation,progressCurrent:1},newBundle:bundle});assert.equal(writes.length,0);assert.equal(reads.length,0);
await assert.rejects(client.copyCandidateChain({rotation:{...rotation,newBlockchainKey:b64(owner)},newBundle:bundle}));
await assert.rejects(client.copyCandidateChain({rotation:{...rotation,comment:'я'.repeat(513)},newBundle:bundle}));assert.equal(writes.length,0);
});
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { AuthService } from '../js/services/auth-service.js';
test('профиль читает CORE-проекцию, а не устаревший ListUserParams', async () => {
const calls = [];
const auth = new AuthService('wss://test.invalid/ws');
auth.ws.request = async (op, payload) => {
calls.push([op, payload]);
assert.equal(op, 'GetCoreProfile');
if (!payload.afterKey) {
return { status: 200, payload: { result: {
values: [{ key: 'first_name', value: 'Алиса', timestampSeconds: 100 }], nextAfterKey: 'first_name',
} } };
}
return { status: 200, payload: { result: {
values: [{ key: 'web', value: 'https://example.test', timestampSeconds: 101 }], nextAfterKey: null,
} } };
};
assert.deepEqual(await auth.listUserParams('Alice@shine'), {
params: [
{ param: 'first_name', value: 'Алиса', time_ms: 100000 },
{ param: 'web', value: 'https://example.test', time_ms: 101000 },
],
});
assert.deepEqual(calls, [
['GetCoreProfile', { login: 'Alice@shine', afterKey: '', limit: 20 }],
['GetCoreProfile', { login: 'Alice@shine', afterKey: 'first_name', limit: 20 }],
]);
});
+4 -5
View File
@@ -14,21 +14,20 @@ const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeH
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
Uint8Array,
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
});
test('client writes HEADER v2 as SHiNE → login → literal license → key', () => {
test('client writes CORE HEADER v1 as SHiNE → login → key', () => {
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = 'Alice@shine';
const body = encode({ login, initialBlockchainKey32: key });
const loginBytes = utf8(login);
const expected = Uint8Array.from([
...utf8('SHiNE'), loginBytes.length, ...loginBytes,
...utf8('license:CC0-1.0'), ...key,
...key,
]);
assert.deepEqual(Array.from(body), Array.from(expected));
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_CONTENT_VERSION/);
assert.match(auth, /export const HEADER_CONTENT_VERSION = 1/);
});
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => {
@@ -11,11 +11,10 @@ const api=read('shine-UI/js/services/registration-v2-api.js');
const ops=['GetNamespaces','CheckRegistrationLogin','CheckRegistrationEmail',
'StartFreeRegistration','ConfirmFreeRegistration','GetRegistrationStatus'];
test('в серверном реестре ровно согласованные шесть операций, каждый op имеет request type',()=>{
for(const op of ops) {
assert.ok(registry.includes(`Map.entry("${op}", new Net_Registration_Handler`));
assert.ok(registry.includes(`Map.entry("${op}", Net_Registration_Request.class`));
}
assert.doesNotMatch(registry,/Map\.entry\("CheckRegistrationAvailability"/);
const registrationRoutes = [...registry.matchAll(/add\(handlers,types,"(\w+)",(?:[\w.]+\.)?Net_Registration_Request\.class,new (?:[\w.]+\.)?Net_Registration_Handler\("(\w+)"\)\);/g)];
assert.deepEqual(registrationRoutes.map(m => m[1]).sort(), [...ops].sort());
for (const [, route, handlerOp] of registrationRoutes) assert.equal(route, handlerOp);
assert.doesNotMatch(registry,/add\(handlers,types,"CheckRegistrationAvailability"/);
});
test('проверки login и email независимы и не отправляют лишних данных',()=>{
assert.match(api,/checkRegistrationLogin = .*call\('CheckRegistrationLogin', \{ fullLogin:/);
@@ -21,22 +21,20 @@ const context = {
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
Uint8Array,
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
};
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
test('HEADER v2 places literal license:CC0-1.0 before the initial key', () => {
test('CORE HEADER v1 preserves registration login and initial key without CC0', () => {
const key = Uint8Array.from({ length: 32 }, (_, n) => n + 1);
const result = makeHeaderBodyBytes({ login: 'Alice@shine', initialBlockchainKey32: key });
const login = new TextEncoder().encode('Alice@shine');
assert.equal(new TextDecoder().decode(result.slice(0,5)), 'SHiNE');
assert.equal(result[5], login.length);
assert.deepEqual(Array.from(result.slice(6, 6+login.length)), Array.from(login));
assert.equal(new TextDecoder().decode(result.slice(6+login.length, 6+login.length+15)), 'license:CC0-1.0');
assert.deepEqual(Array.from(result.slice(6+login.length+15)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 15 + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
assert.deepEqual(Array.from(result.slice(6+login.length)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_CONTENT_VERSION/);
assert.match(auth, /export const HEADER_CONTENT_VERSION = 1/);
});
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {