feat: 用独立页面展示存证详情并按天河链版式绘制证书

This commit is contained in:
Nixevol
2026-11-15 13:25:12 +08:00
parent 41584d0f9c
commit 697d7faebe
27 changed files with 799 additions and 321 deletions
@@ -14,6 +14,7 @@ function fixture(state = 'PENDING') {
const prisma = {
blockchainProof: {
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
update: jest.fn().mockResolvedValue(row),
findUniqueOrThrow: jest.fn().mockResolvedValue(row),
},
traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { title: '测试作品', archiveNo: 'ARTVERIS-000001', status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) },
@@ -49,7 +49,7 @@ export class DepositCertificateService {
return {
status: proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState,
generatedAt: proof.certificateGeneratedAt,
certificate,
certificate: certificate && request ? { ...certificate, environment: request.environment } : certificate,
};
}
@@ -20,6 +20,7 @@ export interface StoredCertificateView {
txHash: string;
author: string;
createdAt: string | null;
imageUrl?: string | null;
}
/** 公开页面只接收存证字段。天河链证书网址留在服务端,不进入浏览器。 */
@@ -0,0 +1,34 @@
import { parseChainDetail } from './chain-detail';
const info = {
data: {
gasTxUsed: '3388899',
fromAddress: '0x85aa7cdeba55cb08427018d066a26719b956ceff',
toAddress: '0x8c7df15858ee7c2f51ce74899a6d097ed163443f',
timeStamp: 1786261526886,
blockHeight: 39944998,
inputDataBin: '0xsecret',
inputDataDetail: { method: 'mint(address to, string author, string productId, string feature, string initPrice)', methodId: '0xa40d1b10' },
inputInfo: [{ name: 'author', type: 'string', data: '黄志伟' }],
transactionDetail: [{ fromAddress: '0x0000000000000000000000000000000000000000', toAddress: '0xae3ecbac36b5874b0372686e5b88894c22be4296', contractAddress: '0x8c7df15858ee7c2f51ce74899a6d097ed163443f', tokenId: '3051' }],
},
};
const receipt = {
data: [{ logInfo: { address: '0x8c7df15858ee7c2f51ce74899a6d097ed163443f', name: 'Transfer(address from, address to, uint256 tokenId)', data: '0x', topics: ['0xabc'] } }],
};
describe('parseChainDetail', () => {
it('keeps gas, sender and logs and drops the raw input binary', () => {
const detail = parseChainDetail(info, receipt);
expect(detail?.gasUsed).toBe('3388899');
expect(detail?.fromAddress).toBe('0x85aa7cdeba55cb08427018d066a26719b956ceff');
expect(detail?.logs).toHaveLength(1);
expect(detail?.action?.tokenId).toBe('3051');
expect(JSON.stringify(detail)).not.toContain('secret');
});
it('stays empty when gas, sender or logs are missing', () => {
expect(parseChainDetail({ data: { gasTxUsed: '', fromAddress: info.data.fromAddress } }, receipt)).toBeNull();
expect(parseChainDetail(info, { data: [] })).toBeNull();
});
});
+109
View File
@@ -0,0 +1,109 @@
export interface ChainInputField {
name: string;
type: string;
data: string;
}
export interface ChainLogView {
address: string;
name: string;
data: string;
topics: string[];
}
export interface ChainDetail {
gasUsed: string;
fromAddress: string;
toAddress: string;
timeStamp: string | null;
blockHeight: string | null;
method: string;
methodId: string;
inputs: ChainInputField[];
logs: ChainLogView[];
action: { fromAddress: string; toAddress: string; contractAddress: string; tokenId: string } | null;
}
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
export function readStoredChainDetail(raw: unknown): ChainDetail | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const detail = (raw as { chainDetail?: unknown }).chainDetail;
if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return null;
const row = detail as ChainDetail;
if (!row.gasUsed || !ADDRESS.test(row.fromAddress || '') || !Array.isArray(row.logs) || !row.logs.length) return null;
return row;
}
export function parseChainDetail(info: unknown, receipt: unknown): ChainDetail | null {
const data = info && typeof info === 'object' ? (info as { data?: unknown }).data : null;
if (!data || typeof data !== 'object') return null;
const row = data as Record<string, unknown>;
const gasUsed = text(row.gasTxUsed);
const fromAddress = text(row.fromAddress);
const logs = Array.isArray(receipt && typeof receipt === 'object' ? (receipt as { data?: unknown }).data : null)
? ((receipt as { data: unknown[] }).data)
.map((item) => (item && typeof item === 'object' ? (item as { logInfo?: unknown }).logInfo : null))
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => ({
address: text(item.address),
name: text(item.name),
data: text(item.data) || '0x',
topics: Array.isArray(item.topics) ? item.topics.filter((topic): topic is string => typeof topic === 'string') : [],
}))
.filter((item) => item.address && item.name && item.topics.length)
: [];
if (!gasUsed || !ADDRESS.test(fromAddress) || !logs.length) return null;
const method = row.inputDataDetail && typeof row.inputDataDetail === 'object'
? row.inputDataDetail as { method?: unknown; methodId?: unknown }
: {};
const action = Array.isArray(row.transactionDetail) ? row.transactionDetail[0] as Record<string, unknown> | undefined : undefined;
return {
gasUsed,
fromAddress,
toAddress: text(row.toAddress),
timeStamp: row.timeStamp == null ? null : String(row.timeStamp),
blockHeight: row.blockHeight == null ? null : String(row.blockHeight),
method: text(method.method),
methodId: text(method.methodId),
inputs: Array.isArray(row.inputInfo)
? row.inputInfo.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object')).map((item) => ({
name: text(item.name),
type: text(item.type),
data: text(item.data),
}))
: [],
logs,
action: action ? {
fromAddress: text(action.fromAddress),
toAddress: text(action.toAddress),
contractAddress: text(action.contractAddress),
tokenId: text(action.tokenId),
} : null,
};
}
export function explorerApiBase(environment: string): string {
const host = environment === 'production' ? 'https://explorer.tianhecloud.com' : 'https://test.explorer.tianhecloud.com';
return `${host}/api/tichain-browser-new`;
}
export async function loadChainDetail(environment: string, txHash: string, blockHeight: string | null, getter: (url: string) => Promise<unknown> = defaultGet): Promise<ChainDetail | null> {
const base = explorerApiBase(environment);
const info = await getter(`${base}/transaction/info?txHash=${encodeURIComponent(txHash)}`);
const infoData = info && typeof info === 'object' ? (info as { data?: { blockHeight?: unknown } }).data : null;
const height = blockHeight || (infoData?.blockHeight == null ? '' : String(infoData.blockHeight));
if (!height) return null;
const receipt = await getter(`${base}/receipt/info?hash=${encodeURIComponent(txHash)}&height=${encodeURIComponent(height)}`);
return parseChainDetail(info, receipt);
}
async function defaultGet(url: string): Promise<unknown> {
const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(15_000) });
if (!response.ok) return null;
return response.json();
}
@@ -1,4 +1,4 @@
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
import { Controller, Get, Param, Post, Query, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
@@ -39,6 +39,14 @@ export class PublicTraceController {
private readonly config: ConfigService,
) {}
@Public()
@Post('public/trace/:shortCode/chain-detail')
@Throttle({ default: { limit: 10, ttl: 60_000 } })
@ApiOperation({ summary: '首次补存交易详情;已存档后只读本地' })
chainDetail(@Param('shortCode') shortCode: string) {
return this.service.captureChainDetail(shortCode);
}
@Public()
@Get('public/trace/:shortCode')
// 公开溯源软限流:每 IP 每分钟 60 次,抑制脚本刷量污染防伪统计与日志
@@ -19,6 +19,7 @@ import { SettingsService } from '../settings/settings.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
import { readMintView } from './public-mint-view';
import { loadChainDetail, readStoredChainDetail } from './chain-detail';
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
type ArtworkWithRel = Prisma.ArtworkGetPayload<{
@@ -422,6 +423,7 @@ export class PublicTraceService {
productId: mint?.productId ?? code.shortCode,
feature: mint?.feature ?? null,
mintTo: mint?.mintTo ?? null,
chainDetail: readStoredChainDetail(proof.rawResponse),
submittedAt: proof.submittedAt,
failureReason: this.publicFailureReason(proof.status, proof.failureReason),
}
@@ -429,6 +431,37 @@ export class PublicTraceService {
};
}
private readonly chainDetailJobs = new Map<string, Promise<{ complete: boolean; detail: unknown }>>();
async captureChainDetail(shortCode: string) {
const current = this.chainDetailJobs.get(shortCode);
if (current) return current;
const job = this.captureChainDetailOnce(shortCode).finally(() => this.chainDetailJobs.delete(shortCode));
this.chainDetailJobs.set(shortCode, job);
return job;
}
private async captureChainDetailOnce(shortCode: string) {
if (!TRACE_CODE_PATTERN.test(shortCode)) return { complete: false, detail: null };
const code = await this.prisma.traceCode.findUnique({ where: { shortCode }, select: { id: true } });
if (!code) return { complete: false, detail: null };
const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: code.id } });
const stored = readStoredChainDetail(proof?.rawResponse);
if (stored) return { complete: true, detail: stored };
if (!proof?.txHash || proof.chainName !== '天河链') return { complete: false, detail: null };
const environment = await this.settings.get('tianheEnv');
const detail = await loadChainDetail(environment || 'test', proof.txHash, proof.blockHeight == null ? null : proof.blockHeight.toString());
if (!detail) return { complete: false, detail: null };
const current = proof.rawResponse && typeof proof.rawResponse === 'object' && !Array.isArray(proof.rawResponse)
? proof.rawResponse as Record<string, unknown>
: {};
await this.prisma.blockchainProof.update({
where: { id: proof.id },
data: { rawResponse: { ...current, chainDetail: detail } as unknown as Prisma.InputJsonValue },
});
return { complete: true, detail };
}
private async mintRecipient(proof: { chainName: string | null } | null): Promise<string | null> {
if (proof?.chainName !== '天河链') return null;
const value = await this.settings.get('tianheWalletAddress');