SHA256
Добавить учёт публикации блоков и обновить загрузку UI
This commit is contained in:
@@ -4939,6 +4939,11 @@
|
||||
"wallet_hint": "🧪 Experimental SOL ↔ USDT swaps via Jupiter. Not recommended for real funds; please review the warnings before trying.",
|
||||
"wallet_button": "Swap · Jupiter β"
|
||||
},
|
||||
"block_publication": {
|
||||
"add_failed": "Could not add the block. Please try again later.",
|
||||
"insufficient_credits": "Block #{number} was accepted by the server, but there are not enough Turbo credits to publish it. Top up the Turbo wallet; the block is saved and upload will retry.",
|
||||
"upload_failed": "Block #{number} was accepted, but could not be uploaded to Turbo. Upload will retry automatically."
|
||||
},
|
||||
"blockchain_details": {
|
||||
"invalid_attachment": "Attachment metadata is invalid; the original block remains unchanged.",
|
||||
"title": "Blockchain data",
|
||||
|
||||
@@ -4939,6 +4939,11 @@
|
||||
"wallet_hint": "🧪 Тестовый обмен SOL ↔ USDT через Jupiter. Функция не рекомендована для реальных средств: откройте предупреждение перед использованием.",
|
||||
"wallet_button": "Обменять · Jupiter β"
|
||||
},
|
||||
"block_publication": {
|
||||
"add_failed": "Не получается добавить блок. Попробуйте ещё раз позже.",
|
||||
"insufficient_credits": "Блок №{number} принят сервером, но в Turbo недостаточно средств для публикации. Пополните Turbo-кошелёк; блок сохранён и загрузка повторится.",
|
||||
"upload_failed": "Блок №{number} принят, но не удалось опубликовать его в Turbo. Загрузка повторится автоматически."
|
||||
},
|
||||
"blockchain_details": {
|
||||
"invalid_attachment": "Вложение содержит некорректные метаданные; исходный блок сохранён без изменений.",
|
||||
"title": "Данные блокчейна",
|
||||
|
||||
@@ -41,6 +41,8 @@ import {
|
||||
saveSessionMaterial,
|
||||
} from './key-vault.js';
|
||||
import { signEventContainer, submitSignedEvent, readStoredLineMeta } from './core-content.js';
|
||||
import { showToast } from './channels-ux.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { defaultServerWs } from '../deploy-config.js';
|
||||
import { readPendingHeaderIdentity, clearPendingHeaderIdentity } from './pending-header-identity.js';
|
||||
|
||||
@@ -1172,6 +1174,14 @@ export class AuthService {
|
||||
const connectionScope = String(createResp?.payload?.connectionScope || '').trim().toUpperCase();
|
||||
|
||||
const canonicalLogin = await this.resolveCanonicalDisplayLogin(cleanLogin);
|
||||
void (async () => {
|
||||
try {
|
||||
const user = await this.getUser(canonicalLogin);
|
||||
const { publishPendingBlocks } = await import('./block-publication-service.js');
|
||||
await publishPendingBlocks({ ws: this.ws, login: canonicalLogin, storagePwd,
|
||||
blockchainName: String(user?.blockchainName || `${canonicalLogin}-${BCH_SUFFIX}`) });
|
||||
} catch (error) { console.warn('Block publication resume failed', error); }
|
||||
})();
|
||||
|
||||
return {
|
||||
login: canonicalLogin,
|
||||
@@ -1350,6 +1360,14 @@ export class AuthService {
|
||||
const connectionScope = String(loginResp?.payload?.connectionScope || '').trim().toUpperCase();
|
||||
|
||||
const canonicalLogin = await this.resolveCanonicalDisplayLogin(cleanLogin);
|
||||
void (async () => {
|
||||
try {
|
||||
const user = await this.getUser(canonicalLogin);
|
||||
const { publishPendingBlocks } = await import('./block-publication-service.js');
|
||||
await publishPendingBlocks({ ws: this.ws, login: canonicalLogin, storagePwd,
|
||||
blockchainName: String(user?.blockchainName || `${canonicalLogin}-${BCH_SUFFIX}`) });
|
||||
} catch (error) { console.warn('Block publication resume failed', error); }
|
||||
})();
|
||||
|
||||
return {
|
||||
login: canonicalLogin,
|
||||
@@ -1723,26 +1741,34 @@ export class AuthService {
|
||||
}
|
||||
|
||||
async runAddBlockWithRetry({ login, storagePwd, resolveFreshState, event }) {
|
||||
const freshState = await resolveFreshState();
|
||||
const blockchainName = String(freshState?.blockchainName || '').trim();
|
||||
if (!blockchainName) throw new Error('runAddBlockWithRetry: blockchainName is empty');
|
||||
const tryAdd = cursor => this.submitPreparedAddBlock({ login, storagePwd, blockchainName,
|
||||
blockNumber: Number(cursor?.serverLastGlobalNumber ?? -1) + 1,
|
||||
prevBlockHash: normalizeHex32(cursor?.serverLastGlobalHash, ZERO64), event });
|
||||
let response = await tryAdd(freshState.cursor);
|
||||
// Only a definitive global cursor conflict allows a new signature. An ambiguous
|
||||
// delivery is handled by submitSignedEvent using the original signed bytes.
|
||||
const code = String(response?.payload?.code || response?.code || '').toLowerCase();
|
||||
if (response.status !== 200 && ['bad_block_number', 'bad_prev_hash'].includes(code)) {
|
||||
const refreshed = await resolveFreshState();
|
||||
if (refreshed.blockchainName !== blockchainName) throw new Error('Blockchain changed during AddBlock');
|
||||
// HEADER must never be recreated at a nonzero number.
|
||||
if (!(event.msgType === MSG_TYPE_TECH && event.msgSubType === MSG_SUBTYPE_TECH_HEADER)) {
|
||||
response = await tryAdd(refreshed.cursor);
|
||||
try {
|
||||
const freshState = await resolveFreshState();
|
||||
const blockchainName = String(freshState?.blockchainName || '').trim();
|
||||
if (!blockchainName) throw new Error('runAddBlockWithRetry: blockchainName is empty');
|
||||
const tryAdd = cursor => this.submitPreparedAddBlock({ login, storagePwd, blockchainName,
|
||||
blockNumber: Number(cursor?.serverLastGlobalNumber ?? -1) + 1,
|
||||
prevBlockHash: normalizeHex32(cursor?.serverLastGlobalHash, ZERO64), event });
|
||||
let response = await tryAdd(freshState.cursor);
|
||||
// Only a definitive global cursor conflict allows a new signature. An ambiguous
|
||||
// delivery is handled by submitSignedEvent using the original signed bytes.
|
||||
const code = String(response?.payload?.code || response?.code || '').toLowerCase();
|
||||
if (response.status !== 200 && ['bad_block_number', 'bad_prev_hash'].includes(code)) {
|
||||
const refreshed = await resolveFreshState();
|
||||
if (refreshed.blockchainName !== blockchainName) throw new Error('Blockchain changed during AddBlock');
|
||||
// HEADER must never be recreated at a nonzero number.
|
||||
if (!(event.msgType === MSG_TYPE_TECH && event.msgSubType === MSG_SUBTYPE_TECH_HEADER)) {
|
||||
response = await tryAdd(refreshed.cursor);
|
||||
}
|
||||
}
|
||||
if (response.status !== 200) throw opError('AddBlock', response);
|
||||
void import('./block-publication-service.js').then(({ publishPendingBlocks }) =>
|
||||
publishPendingBlocks({ ws: this.ws, login, storagePwd, blockchainName }))
|
||||
.catch(error => console.warn('Block publication start failed', error));
|
||||
return { response, blockchainName };
|
||||
} catch (error) {
|
||||
showToast(t('block_publication.add_failed'), { kind: 'error' });
|
||||
throw error;
|
||||
}
|
||||
if (response.status !== 200) throw opError('AddBlock', response);
|
||||
return { response, blockchainName };
|
||||
}
|
||||
|
||||
async addBlockSigned({ login, storagePwd, msgType, msgSubType, msgVersion = 1, bodyBytes, channelSlug = '', _skipHeaderEnsure = false }) {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { base64ToBytes } from './crypto-utils.js';
|
||||
import { unpackCoreContent } from './core-content.js';
|
||||
import { uploadSignedBlockDataItem } from './turbo-upload-service.js';
|
||||
import { showToast } from './channels-ux.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
const running = new Set();
|
||||
const scheduled = new Map();
|
||||
const lastNotice = new Map();
|
||||
|
||||
/** После перезапуска браузер повторно получает подписанные bytes с сервера. */
|
||||
export async function publishPendingBlocks({ ws, login, storagePwd, blockchainName }) {
|
||||
if (!ws || !login || !storagePwd || !blockchainName || running.has(blockchainName)) return;
|
||||
running.add(blockchainName);
|
||||
let keepPolling = false;
|
||||
try {
|
||||
const response = await ws.request('BlockPublication', { action: 'list', blockchainName });
|
||||
if (response.status !== 200) return;
|
||||
keepPolling = true;
|
||||
for (const block of response.payload?.pendingBlocks || []) {
|
||||
const read = await ws.request('GetBlockchainBlock', { blockchainName, blockNumber: block.blockNumber });
|
||||
if (read.status !== 200 || String(read.payload?.blockHash || '').toLowerCase() !== block.coreHash) {
|
||||
throw new Error('Pending block bytes unavailable or changed');
|
||||
}
|
||||
const { contentDataItem, coreDataItem } = unpackCoreContent(base64ToBytes(read.payload.blockBytesB64));
|
||||
let uploadError = '';
|
||||
try {
|
||||
if (!block.contentConfirmed) await uploadSignedBlockDataItem({ login, storagePwd, bytes: contentDataItem, expectedId: block.contentId });
|
||||
if (!block.coreConfirmed) await uploadSignedBlockDataItem({ login, storagePwd, bytes: coreDataItem, expectedId: block.coreId });
|
||||
} catch (error) {
|
||||
uploadError = String(error?.message || error);
|
||||
const insufficientCredits = /(?:\b402\b|insufficient (?:balance|funds|credits)|not enough (?:balance|funds|credits)|payment required|недостаточно (?:средств|кредитов))/i.test(uploadError);
|
||||
const noticeKey = `${blockchainName}:${block.blockNumber}`;
|
||||
if (Date.now() - (lastNotice.get(noticeKey) || 0) >= 30 * 60_000) {
|
||||
showToast(t(insufficientCredits ? 'block_publication.insufficient_credits' : 'block_publication.upload_failed',
|
||||
{ number: block.blockNumber }), { kind: 'error', timeoutMs: 7000 });
|
||||
lastNotice.set(noticeKey, Date.now());
|
||||
}
|
||||
}
|
||||
await ws.request('BlockPublication', {
|
||||
action: 'report', blockchainName, blockNumber: block.blockNumber,
|
||||
contentId: block.contentId, coreId: block.coreId,
|
||||
contentHash: block.contentHash, coreHash: block.coreHash, error: uploadError,
|
||||
});
|
||||
if (uploadError) break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Block publication queue unavailable', error);
|
||||
} finally {
|
||||
running.delete(blockchainName);
|
||||
if (keepPolling && !scheduled.has(blockchainName)) {
|
||||
const timer = globalThis.setTimeout(() => {
|
||||
scheduled.delete(blockchainName);
|
||||
void publishPendingBlocks({ ws, login, storagePwd, blockchainName });
|
||||
}, 30_000);
|
||||
scheduled.set(blockchainName, timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,39 @@ export async function uploadFileWithTurbo({
|
||||
};
|
||||
}
|
||||
|
||||
/** Загружает готовый подписанный DataItem, сохраняя исходные bytes и ID. */
|
||||
export async function uploadSignedBlockDataItem({ login, storagePwd, bytes, expectedId }) {
|
||||
if (!(bytes instanceof Uint8Array) || bytes.length === 0) throw new Error('Empty signed DataItem');
|
||||
const alreadyUploaded = async () => {
|
||||
try {
|
||||
const response = await fetch(`https://turbo.ardrive.io/tx/${encodeURIComponent(expectedId)}/status`);
|
||||
if (!response.ok) return false;
|
||||
const status = String((await response.json())?.status || '').toUpperCase();
|
||||
return ['PENDING', 'CONFIRMED', 'BUNDLED', 'FINALIZED'].includes(status);
|
||||
} catch { return false; }
|
||||
};
|
||||
if (await alreadyUploaded()) return { id: expectedId, alreadyUploaded: true };
|
||||
const { turbo } = await getTurboContextForStoredSolanaKey({ login, storagePwd });
|
||||
let result;
|
||||
try {
|
||||
result = await turbo.uploadSignedDataItem({
|
||||
dataItemStreamFactory: () => new ReadableStream({
|
||||
start(controller) { controller.enqueue(bytes); controller.close(); },
|
||||
}),
|
||||
dataItemSizeFactory: () => bytes.length,
|
||||
});
|
||||
} catch (error) {
|
||||
// Потерянный ответ Turbo или повтор того же DataItem не создаёт новый блок.
|
||||
if (await alreadyUploaded()) return { id: expectedId, alreadyUploaded: true };
|
||||
if (/data item exists|already exists/i.test(String(error?.message || error))) {
|
||||
return { id: expectedId, alreadyUploaded: true };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (String(result?.id || '') !== expectedId) throw new Error('Turbo returned another DataItem ID');
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function topUpTurboWithSolana({
|
||||
login,
|
||||
storagePwd,
|
||||
|
||||
Reference in New Issue
Block a user