fix: 优化天河链确认策略
This commit is contained in:
@@ -202,4 +202,4 @@
|
||||
- 系统设置布局微调(2026-07-06):后台 `Settings.vue` 的基础设置区改为三列卡片:左侧平台设置,中间日志设置+备份策略,右侧区块链存证;避免区块链配置夹在日志和备份之间打断阅读,同时保持保存按钮在设置卡片组右上角。
|
||||
- 天河链用户身份临时策略(2026-07-06):天河链文档中的 `userId/userKey` 属于托管链上用户身份,不是平台截图里提供的商户 API 凭证。当前设置页先只展示 `App ID/App Key`,后端仍兼容 `.env` 或历史设置中的 `TIANHE_USER_ID/TIANHE_USER_KEY`;若未配置,则使用平台级默认 `userId=artveris-platform`,`userKey=sha256(artveris:tianhe:{appId}:{appKey})` 派生。后续需再讨论是继续平台级托管用户,还是按运营账号/机构/作品批次生成链上用户。
|
||||
- 天河链文档归档与字段校准(2026-07-06):新增 `docs/天河链文档.md` 作为本地对接资料。文档确认 `POST /api/v2/nfr/upload` 返回 `data.digest`(数字商品唯一哈希/文件哈希)、`data.url`(链上 URI/存证链接)、`data.transactionHash`(链上存证交易哈希);`TianheProvider` 现在优先使用 `transactionHash` 写入平台 `txHash`,使用 `url` 写入 `explorerUrl`,并把 `digest` 与 `transactionStatus=submitted` 保存在 `rawResponse`。天河链 FAQ 明确接口成功只代表交易已提交,不代表链上最终确认;后续如要严格展示“已确认”,应基于交易结果查询接口补延时确认任务。
|
||||
- 天河链延时确认(2026-07-06):区块链凭证状态新增 `CONFIRMING`。Mock 存证仍一次完成并直接进入 `ONCHAIN`;天河链 `nfr/upload` 成功后仅标记为 `CONFIRMING`,保存交易哈希、存证链接和提交响应,然后由同一个 `ONCHAIN` 队列延时 30 秒调用 `GET /api/v2/nfr/transaction/status` 查询交易状态。查询到 `blockHash` 或 `blockNum` 后才更新为 `ONCHAIN` 并写入 `onchainAt/blockHash/blockHeight`;最多确认 20 次,仍未查到区块信息或持续失败则转 `FAILED` 并在 `rawResponse.confirmationError` 记录原因。后台状态翻译新增“确认中 / Confirming”,客户端公开页仍只展示最终 `ONCHAIN` 的凭证。
|
||||
- 天河链延时确认(2026-07-06):区块链凭证状态新增 `CONFIRMING`。Mock 存证仍一次完成并直接进入 `ONCHAIN`;天河链 `nfr/upload` 成功后仅标记为 `CONFIRMING`,保存交易哈希、存证链接和提交响应,然后由同一个 `ONCHAIN` 队列延时 30 秒调用 `GET /api/v2/nfr/transaction/status` 查询交易状态。首次自动查询未确认时,系统只在 1 分钟后再自动查询一次;第二次仍未拿到 `blockHash/blockNum` 时不再自动请求、不判失败,继续保留 `CONFIRMING` 并标记 `rawResponse.confirmationManualRequired=true`,后台展示为“未确认”。运营可点“重新确认”手动查询已有交易哈希,不重新提交上链;查到区块信息后才更新为 `ONCHAIN` 并写入 `onchainAt/blockHash/blockHeight`。客户端公开页仍只展示最终 `ONCHAIN` 的凭证。
|
||||
|
||||
@@ -64,6 +64,7 @@ export const traceCodeApi = {
|
||||
qrUrl: (id: string) => `/api/trace-codes/${id}/qrcode`,
|
||||
qrBlob: (id: string) => download(`/trace-codes/${id}/qrcode`),
|
||||
onchain: (id: string) => post(`/trace-codes/${id}/onchain`, {}),
|
||||
confirmProof: (id: number) => post(`/blockchain-proofs/${id}/confirm`, {}),
|
||||
// 分组
|
||||
groups: (params?: object) => get<any[]>('/trace-code-groups', params),
|
||||
createGroup: (data: { name: string; remark?: string }) => post('/trace-code-groups', data),
|
||||
|
||||
@@ -263,6 +263,7 @@ const qrSrc = ref('');
|
||||
const qrUrl = ref('');
|
||||
let qrBlobUrl = '';
|
||||
const exporting = ref(false);
|
||||
const confirmingProofIds = ref<number[]>([]);
|
||||
|
||||
const groupModal = ref(false);
|
||||
const groupForm = reactive<{ name: string }>({ name: '' });
|
||||
@@ -311,7 +312,7 @@ const columns = computed<DataTableColumns<any>>(() => {
|
||||
align: 'center',
|
||||
render: (r) =>
|
||||
r.latestAnyProof
|
||||
? h(NTag, { size: 'small', type: statusType(r.latestAnyProof.status) }, { default: () => t(`common.status.${r.latestAnyProof.status}`) })
|
||||
? h(NTag, { size: 'small', type: proofStatusType(r.latestAnyProof) }, { default: () => proofStatusText(r.latestAnyProof) })
|
||||
: h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noOnchain') }),
|
||||
},
|
||||
{ title: () => t('pages.traceCode.shortCode'), key: 'shortCode', width: 120, align: 'center', ellipsis: { tooltip: true } },
|
||||
@@ -615,17 +616,23 @@ function batchDelete() {
|
||||
}
|
||||
|
||||
function rowActionOptions(row: any): DropdownOption[] {
|
||||
return [
|
||||
const options: DropdownOption[] = [
|
||||
{ label: t('pages.traceCode.changeGroup'), key: 'changeGroup', children: rowGroupOptions.value },
|
||||
{ label: t('pages.traceCode.changeBatch'), key: 'batch:open' },
|
||||
{ label: t('pages.traceCode.registerOutbound'), key: 'outbound:open' },
|
||||
];
|
||||
if (canManualConfirm(row.latestAnyProof)) {
|
||||
options.push({ label: t('pages.traceCode.reconfirmOnchain'), key: 'onchain:confirm' });
|
||||
}
|
||||
options.push(
|
||||
{ type: 'divider', key: 'divider-1' },
|
||||
{
|
||||
label: row.status === TraceCodeStatus.DISABLED ? t('pages.traceCode.enableOne') : t('pages.traceCode.disableOne'),
|
||||
key: row.status === TraceCodeStatus.DISABLED ? 'status:enable' : 'status:disable',
|
||||
},
|
||||
{ label: t('common.action.delete'), key: 'delete' },
|
||||
];
|
||||
);
|
||||
return options;
|
||||
}
|
||||
|
||||
async function onRowAction(row: any, key: string) {
|
||||
@@ -648,6 +655,11 @@ async function onRowAction(row: any, key: string) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === 'onchain:confirm') {
|
||||
await confirmProof(row.latestAnyProof);
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === 'status:disable' || key === 'status:enable') {
|
||||
await traceCodeApi.update(String(row.id), { disabled: key === 'status:disable' });
|
||||
message.success(t('common.msg.operationSuccess'));
|
||||
@@ -673,6 +685,39 @@ async function onRowAction(row: any, key: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function proofRaw(proof: any) {
|
||||
return proof?.rawResponse && typeof proof.rawResponse === 'object' ? proof.rawResponse : {};
|
||||
}
|
||||
|
||||
function isUnconfirmedProof(proof: any) {
|
||||
return proof?.status === 'CONFIRMING' && proofRaw(proof).confirmationManualRequired === true;
|
||||
}
|
||||
|
||||
function proofStatusText(proof: any) {
|
||||
return isUnconfirmedProof(proof) ? t('pages.traceCode.unconfirmed') : t(`common.status.${proof.status}`);
|
||||
}
|
||||
|
||||
function proofStatusType(proof: any): 'default' | 'success' | 'warning' | 'error' | 'info' {
|
||||
return isUnconfirmedProof(proof) ? 'warning' : statusType(proof?.status);
|
||||
}
|
||||
|
||||
function canManualConfirm(proof: any) {
|
||||
return Boolean(proof?.id && proof?.txHash && proof.status !== 'ONCHAIN');
|
||||
}
|
||||
|
||||
async function confirmProof(proof: any) {
|
||||
if (!canManualConfirm(proof) || confirmingProofIds.value.includes(proof.id)) return;
|
||||
confirmingProofIds.value.push(proof.id);
|
||||
try {
|
||||
await traceCodeApi.confirmProof(proof.id);
|
||||
message.success(t('pages.traceCode.confirmSubmitted'));
|
||||
await load();
|
||||
emit('changed');
|
||||
} finally {
|
||||
confirmingProofIds.value = confirmingProofIds.value.filter((id) => id !== proof.id);
|
||||
}
|
||||
}
|
||||
|
||||
function openBatchModal(row?: any) {
|
||||
batchTarget.value = row || null;
|
||||
batchForm.batchValue = row?.batch?.id ?? null;
|
||||
|
||||
@@ -346,6 +346,9 @@
|
||||
"outRegistered": "Recorded",
|
||||
"notOutbound": "Not Outbound",
|
||||
"noOnchain": "Not On-chain",
|
||||
"unconfirmed": "Unconfirmed",
|
||||
"reconfirmOnchain": "Reconfirm",
|
||||
"confirmSubmitted": "Reconfirm task submitted",
|
||||
"tableFilter": "Filter",
|
||||
"registerOutbound": "Record Outbound / Chain",
|
||||
"enableOne": "Enable",
|
||||
|
||||
@@ -346,6 +346,9 @@
|
||||
"outRegistered": "已登记",
|
||||
"notOutbound": "未出库",
|
||||
"noOnchain": "未上链",
|
||||
"unconfirmed": "未确认",
|
||||
"reconfirmOnchain": "重新确认",
|
||||
"confirmSubmitted": "已提交重新确认任务",
|
||||
"tableFilter": "筛选",
|
||||
"registerOutbound": "登记出库/上链",
|
||||
"enableOne": "启用",
|
||||
|
||||
@@ -78,4 +78,23 @@ export class AttestationService {
|
||||
await this.queue.add('onchain', { proofId });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async confirm(proofId: number) {
|
||||
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||
if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404);
|
||||
if (proof.status === ProofStatus.ONCHAIN) return { success: true };
|
||||
if (!proof.txHash) throw new BusinessException(ErrorCode.BAD_REQUEST, '缺少交易哈希,无法重新确认');
|
||||
await this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
status: ProofStatus.CONFIRMING,
|
||||
rawResponse: {
|
||||
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
|
||||
manualConfirmQueuedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
});
|
||||
await this.queue.add('confirm-onchain', { proofId, action: 'confirm', confirmAttempt: 1, manual: true });
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,4 +23,11 @@ export class BlockchainController {
|
||||
retry(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.attestation.retry(id);
|
||||
}
|
||||
|
||||
@Post('blockchain-proofs/:id/confirm')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '重新查询链上确认结果' })
|
||||
confirm(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.attestation.confirm(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@ interface OnchainJobData {
|
||||
proofId: number;
|
||||
action?: 'attest' | 'confirm';
|
||||
confirmAttempt?: number;
|
||||
manual?: boolean;
|
||||
}
|
||||
|
||||
const CONFIRM_DELAY_MS = 30_000;
|
||||
const MAX_CONFIRM_ATTEMPTS = 20;
|
||||
const FIRST_CONFIRM_DELAY_MS = 30_000;
|
||||
const SECOND_CONFIRM_DELAY_MS = 60_000;
|
||||
const MAX_AUTO_CONFIRM_ATTEMPTS = 2;
|
||||
|
||||
function requestMeta(raw: unknown): Record<string, unknown> | undefined {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
@@ -43,7 +45,7 @@ export class OnchainProcessor extends WorkerHost {
|
||||
|
||||
async process(job: Job<OnchainJobData>): Promise<void> {
|
||||
if (job.data.action === 'confirm') {
|
||||
await this.confirm(job.data.proofId, job.data.confirmAttempt || 1);
|
||||
await this.confirm(job.data.proofId, job.data.confirmAttempt || 1, Boolean(job.data.manual));
|
||||
return;
|
||||
}
|
||||
await this.attest(job.data.proofId);
|
||||
@@ -74,7 +76,7 @@ export class OnchainProcessor extends WorkerHost {
|
||||
},
|
||||
});
|
||||
if (result.confirmationRequired) {
|
||||
await this.scheduleConfirm(proofId, 1);
|
||||
await this.scheduleConfirm(proofId, 1, FIRST_CONFIRM_DELAY_MS);
|
||||
this.logger.log(`存证 ${proofId} 已提交链上,等待确认`);
|
||||
} else {
|
||||
this.logger.log(`存证 ${proofId} 上链成功`);
|
||||
@@ -96,9 +98,10 @@ export class OnchainProcessor extends WorkerHost {
|
||||
}
|
||||
}
|
||||
|
||||
private async confirm(proofId: number, attempt: number): Promise<void> {
|
||||
private async confirm(proofId: number, attempt: number, manual = false): Promise<void> {
|
||||
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||
if (!proof || proof.status !== ProofStatus.CONFIRMING) return;
|
||||
if (!proof || proof.status === ProofStatus.ONCHAIN) return;
|
||||
if (proof.status !== ProofStatus.CONFIRMING && !manual) return;
|
||||
if (!proof.txHash) {
|
||||
await this.markConfirmFailed(proofId, proof.rawResponse, '缺少交易哈希,无法确认链上结果', attempt);
|
||||
return;
|
||||
@@ -130,39 +133,42 @@ export class OnchainProcessor extends WorkerHost {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.recordWaiting(proofId, proof.rawResponse, result.raw, attempt);
|
||||
if (attempt >= MAX_CONFIRM_ATTEMPTS) {
|
||||
await this.markConfirmFailed(proofId, proof.rawResponse, '超过最大确认次数,仍未查询到链上区块信息', attempt);
|
||||
await this.recordWaiting(proofId, proof.rawResponse, result.raw, attempt, manual);
|
||||
if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) {
|
||||
this.logger.warn(`存证 ${proofId} 尚未查询到链上确认信息,等待手动重新确认`);
|
||||
return;
|
||||
}
|
||||
await this.scheduleConfirm(proofId, attempt + 1);
|
||||
await this.scheduleConfirm(proofId, attempt + 1, SECOND_CONFIRM_DELAY_MS);
|
||||
} catch (e) {
|
||||
const message = (e as Error).message;
|
||||
if (attempt >= MAX_CONFIRM_ATTEMPTS) {
|
||||
await this.markConfirmFailed(proofId, proof.rawResponse, message, attempt);
|
||||
if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) {
|
||||
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual);
|
||||
return;
|
||||
}
|
||||
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt);
|
||||
await this.scheduleConfirm(proofId, attempt + 1);
|
||||
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual);
|
||||
await this.scheduleConfirm(proofId, attempt + 1, SECOND_CONFIRM_DELAY_MS);
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleConfirm(proofId: number, confirmAttempt: number) {
|
||||
private scheduleConfirm(proofId: number, confirmAttempt: number, delay: number, manual = false) {
|
||||
return this.queue.add(
|
||||
'confirm-onchain',
|
||||
{ proofId, action: 'confirm', confirmAttempt } satisfies OnchainJobData,
|
||||
{ delay: CONFIRM_DELAY_MS },
|
||||
{ proofId, action: 'confirm', confirmAttempt, manual } satisfies OnchainJobData,
|
||||
{ delay },
|
||||
);
|
||||
}
|
||||
|
||||
private recordWaiting(proofId: number, raw: unknown, confirmation: Record<string, unknown>, attempt: number) {
|
||||
private recordWaiting(proofId: number, raw: unknown, confirmation: Record<string, unknown>, attempt: number, manual: boolean) {
|
||||
return this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
status: ProofStatus.CONFIRMING,
|
||||
rawResponse: jsonObject({
|
||||
...rawObject(raw),
|
||||
confirmation,
|
||||
confirmationAttempts: attempt,
|
||||
confirmationManualRequired: manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS,
|
||||
lastConfirmMode: manual ? 'manual' : 'auto',
|
||||
lastConfirmCheckedAt: new Date().toISOString(),
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -39,6 +39,7 @@ function actionOf(method: string, path: string): string {
|
||||
if (path.includes('/download')) return 'download';
|
||||
if (path.includes('/upload')) return 'upload';
|
||||
if (path.includes('/audit')) return 'audit';
|
||||
if (path.includes('/blockchain-proofs') && path.includes('/confirm')) return 'onchain';
|
||||
if (path.includes('/onchain')) return 'onchain';
|
||||
if (path.includes('/backup')) return 'backup';
|
||||
if (path.includes('/restore')) return 'restore';
|
||||
|
||||
Reference in New Issue
Block a user