Files
Artveris/apps/api/src/blockchain/onchain.processor.ts
T

221 lines
9.1 KiB
TypeScript

import { InjectQueue, Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { Job, Queue } from 'bullmq';
import { ProofStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BlockchainService } from './blockchain.service';
interface OnchainJobData {
proofId: number;
action?: 'attest' | 'confirm';
confirmAttempt?: number;
manual?: boolean;
}
// 自动确认延迟序列(毫秒):第 1 次提交后立即查、未到再 10s、再 30s,共 3 次;之后停等手动重新确认。
// 第 attempt 次(从 1 起)的延迟 = AUTO_CONFIRM_DELAYS_MS[attempt - 1]。
const AUTO_CONFIRM_DELAYS_MS = [0, 10_000, 30_000];
const MAX_AUTO_CONFIRM_ATTEMPTS = AUTO_CONFIRM_DELAYS_MS.length;
function requestMeta(raw: unknown): Record<string, unknown> | undefined {
if (!raw || typeof raw !== 'object') return undefined;
const meta = (raw as Record<string, unknown>).requestMeta;
return meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : undefined;
}
function productInfo(
raw: unknown,
): { productId: string; name: string; author?: string; feature?: string } | undefined {
if (!raw || typeof raw !== 'object') return undefined;
const product = (raw as Record<string, unknown>).product as
| { productId?: string; name?: string; author?: string; feature?: string }
| undefined;
return product?.productId && product?.name
? { productId: product.productId, name: product.name, author: product.author, feature: product.feature }
: undefined;
}
function rawObject(raw: unknown): Record<string, unknown> {
return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
}
function jsonObject(value: Record<string, unknown>): Prisma.InputJsonObject {
return value as Prisma.InputJsonObject;
}
@Processor(QUEUE_NAMES.ONCHAIN)
export class OnchainProcessor extends WorkerHost {
private readonly logger = new Logger(OnchainProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly blockchain: BlockchainService,
@InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue,
) {
super();
}
async process(job: Job<OnchainJobData>): Promise<void> {
if (job.data.action === 'confirm') {
await this.confirm(job.data.proofId, job.data.confirmAttempt || 1, Boolean(job.data.manual));
return;
}
await this.attest(job.data.proofId);
}
private async attest(proofId: number): Promise<void> {
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
if (!proof) return;
try {
const result = await this.blockchain.attest({
dataHash: proof.dataHash,
meta: requestMeta(proof.rawResponse),
product: productInfo(proof.rawResponse),
});
await this.prisma.blockchainProof.update({
where: { id: proofId },
data: {
status: result.confirmationRequired ? ProofStatus.CONFIRMING : ProofStatus.ONCHAIN,
txHash: result.txHash,
blockHash: result.blockHash || null,
blockHeight: result.blockHeight !== null && result.blockHeight !== undefined ? BigInt(result.blockHeight) : null,
chainName: result.chainName,
explorerUrl: result.explorerUrl || null,
tokenId: result.tokenId !== null && result.tokenId !== undefined ? BigInt(result.tokenId) : null,
contractAddress: result.contractAddress || null,
onchainAt: result.confirmationRequired ? null : result.onchainAt,
rawResponse: jsonObject({
...(result.raw as object),
submittedAt: new Date().toISOString(),
}),
},
});
if (result.confirmationRequired) {
// 提交完立即发起第 1 次确认查询(delay=0)
await this.scheduleConfirm(proofId, 1, AUTO_CONFIRM_DELAYS_MS[0]);
this.logger.log(`存证 ${proofId} 已提交链上,等待确认:txHash=${result.txHash} 存证链接=${result.explorerUrl ?? '-'}`);
} else {
this.logger.log(`存证 ${proofId} 上链成功:txHash=${result.txHash} blockHeight=${result.blockHeight ?? '-'}`);
}
} catch (e) {
const message = (e as Error).message;
await this.prisma.blockchainProof.update({
where: { id: proofId },
data: {
status: ProofStatus.FAILED,
rawResponse: jsonObject({
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
error: message,
failedAt: new Date().toISOString(),
}),
},
});
this.logger.error(`存证 ${proofId} 上链失败: ${message}`);
}
}
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.ONCHAIN) return;
if (proof.status !== ProofStatus.CONFIRMING && !manual) return;
if (!proof.txHash) {
await this.markConfirmFailed(proofId, proof.rawResponse, '缺少交易哈希,无法确认链上结果', attempt);
return;
}
this.logger.log(`存证 ${proofId} 开始链上确认查询(第 ${attempt} 次${manual ? ',手动' : ''}):txHash=${proof.txHash}`);
try {
const result = await this.blockchain.confirmTransaction(proof.txHash);
this.logger.log(
`存证 ${proofId} 链上查询结果:confirmed=${result.confirmed} blockHash=${result.blockHash ?? '-'} ` +
`blockHeight=${result.blockHeight ?? '-'} status=${(result.raw as { status?: string })?.status ?? '-'} ` +
`响应=${JSON.stringify((result.raw as { response?: unknown })?.response ?? result.raw).slice(0, 300)}`,
);
if (result.confirmed) {
// 发行时 tokenId=-1(待处理)的场景:确认查询返回真实 tokenId 后回填
const confirmedTokenId = Number((result.raw as { tokenId?: string | number })?.tokenId ?? NaN);
await this.prisma.blockchainProof.update({
where: { id: proofId },
data: {
status: ProofStatus.ONCHAIN,
txHash: result.txHash,
blockHash: result.blockHash || proof.blockHash || null,
blockHeight:
result.blockHeight !== null && result.blockHeight !== undefined
? BigInt(result.blockHeight)
: proof.blockHeight,
tokenId:
proof.tokenId ?? (Number.isInteger(confirmedTokenId) && confirmedTokenId >= 0 ? BigInt(confirmedTokenId) : null),
onchainAt: new Date(),
rawResponse: jsonObject({
...rawObject(proof.rawResponse),
confirmation: result.raw,
confirmationAttempts: attempt,
confirmedAt: new Date().toISOString(),
}),
},
});
this.logger.log(`存证 ${proofId} 链上确认成功`);
return;
}
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, AUTO_CONFIRM_DELAYS_MS[attempt]);
} catch (e) {
const message = (e as Error).message;
this.logger.warn(`存证 ${proofId} 链上确认查询失败(第 ${attempt} 次):${message}`);
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual);
if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) {
this.logger.warn(`存证 ${proofId} 自动确认已达上限,等待手动重新确认`);
return;
}
await this.scheduleConfirm(proofId, attempt + 1, AUTO_CONFIRM_DELAYS_MS[attempt]);
}
}
private scheduleConfirm(proofId: number, confirmAttempt: number, delay: number, manual = false) {
return this.queue.add(
'confirm-onchain',
{ proofId, action: 'confirm', confirmAttempt, manual } satisfies OnchainJobData,
{ delay },
);
}
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(),
}),
},
});
}
private markConfirmFailed(proofId: number, raw: unknown, message: string, attempt: number) {
return this.prisma.blockchainProof.update({
where: { id: proofId },
data: {
status: ProofStatus.FAILED,
rawResponse: jsonObject({
...rawObject(raw),
confirmationError: message,
confirmationAttempts: attempt,
failedAt: new Date().toISOString(),
}),
},
});
}
}