fix: 修正审查发现的出证重试、链上详情范围和手机保存证书问题

This commit is contained in:
Nixevol
2026-11-15 14:35:41 +08:00
parent d41c80a4b3
commit d1ade47864
26 changed files with 343 additions and 222 deletions
@@ -63,6 +63,32 @@ describe('Consumer certificate lifecycle', () => {
certificateNextCheck: null,
});
});
it('a connection reset during submit may have reached Tianhe, so it stays query-only', async () => {
const { service, row, prisma } = fixture();
const failure = new TypeError('fetch failed');
(failure as { cause?: unknown }).cause = Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' });
jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(failure);
await service.process(row);
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('WAITING');
});
it('re-applies with a new operation id only when the earlier request was never sent', async () => {
const { service, row, prisma } = fixture('FAILED');
row.certificateError = '暂时联系不上存证服务,证书没有生成。';
expect(await service.status('123456000001')).toMatchObject({ status: 'FAILED', retryable: true });
await service.request('123456000001');
const claim = prisma.blockchainProof.updateMany.mock.calls[0][0];
expect(claim.where).toEqual({ id: 1, certificateState: 'FAILED', certificateError: row.certificateError, status: 'ONCHAIN' });
expect(claim.data).toMatchObject({ certificateState: 'PENDING', certificateError: null, certificateAttempts: 0 });
expect(claim.data.certificateRequest.operateId).not.toBe('stable-op');
});
it('never re-applies after a rejection and does not return internal notes', async () => {
const { service, row, prisma } = fixture('FAILED');
row.certificateError = '存证提交被拒绝,请联系平台管理员';
const result = await service.request('123456000001');
expect(result).toMatchObject({ status: 'FAILED', retryable: false });
expect(JSON.stringify(result)).not.toContain('存证提交被拒绝');
expect(prisma.blockchainProof.updateMany).not.toHaveBeenCalled();
});
it('a submission timeout changes to query-only, preserving the exact operation id', async () => {
const { service, row, prisma } = fixture();
const submit = jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(new Error('timeout'));
@@ -19,8 +19,13 @@ interface CertificateRequest {
const ACTIVE_STATES = ['PENDING', 'SUBMITTING', 'WAITING', 'CHECKING'];
const MAX_CHECKS = 8;
// 这句话同时是“请求从未发出、可以重新申请”的标记,改动文字会让已有记录失去重试资格。
const UNREACHABLE_MESSAGE = '暂时联系不上存证服务,证书没有生成。';
/**
* 只认连接建立之前的失败,这时请求一定没有发出,重新申请不会重复扣费。
* 超时、连接被重置等情况下请求可能已经到达对方,不能算在内。
*/
function depositUnreachable(error: unknown) {
const texts: string[] = [];
let current: unknown = error;
@@ -30,7 +35,11 @@ function depositUnreachable(error: unknown) {
if (typeof code === 'string') texts.push(code);
current = (current as { cause?: unknown }).cause;
}
return /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ECONNRESET/.test(texts.join(' '));
return /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|UND_ERR_CONNECT_TIMEOUT/.test(texts.join(' '));
}
function neverSent(proof: BlockchainProof) {
return proof.certificateState === 'FAILED' && !proof.certificateUrl && proof.certificateError === UNREACHABLE_MESSAGE;
}
@Injectable()
@@ -59,12 +68,12 @@ export class DepositCertificateService {
const certificate = request && proof.certificateState === 'READY'
? presentStoredCertificate(proof.certificateUrl, request.environment, request.address, request.text, await this.settings.get('certificateAuthorMode'), artist)
: null;
const status = proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState;
return {
status,
status: proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState,
generatedAt: proof.certificateGeneratedAt,
certificate: certificate && request ? { ...certificate, environment: request.environment } : certificate,
message: status === 'READY' ? null : proof.certificateError,
// 只告诉页面能否重新申请,内部处理说明不对外返回
retryable: neverSent(proof),
};
}
@@ -78,8 +87,8 @@ export class DepositCertificateService {
const { code, proof } = await this.eligible(shortCode);
if (proof.certificateState === 'READY') return this.view(proof, code.artwork.artist);
const settings = await this.settings.getAllRaw();
const retryUnreachable = proof.certificateState === 'FAILED' && !proof.certificateUrl && proof.certificateError === UNREACHABLE_MESSAGE;
if (proof.certificateState !== 'NONE' && !retryUnreachable) {
const retry = neverSent(proof);
if (proof.certificateState !== 'NONE' && !retry) {
// An uncertain submission is never submitted again. User action only resumes queries.
if (proof.certificateState === 'UNKNOWN' && (!proof.certificateNextCheck || proof.certificateNextCheck <= new Date())) {
await this.prisma.blockchainProof.updateMany({
@@ -119,10 +128,12 @@ export class DepositCertificateService {
// A single conditional write claims this item; concurrent callers cannot
// replace the winner's frozen evidence or operation id. No daily quota.
await this.prisma.blockchainProof.updateMany({
where: { id: proof.id, certificateState: retryUnreachable ? 'FAILED' : 'NONE', status: ProofStatus.ONCHAIN },
where: retry
? { id: proof.id, certificateState: 'FAILED', certificateError: UNREACHABLE_MESSAGE, status: ProofStatus.ONCHAIN }
: { id: proof.id, certificateState: 'NONE', status: ProofStatus.ONCHAIN },
data: {
certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject,
certificateError: null, certificateRequestedAt: now, certificateNextCheck: now,
certificateError: null, certificateAttempts: 0, certificateRequestedAt: now, certificateNextCheck: now,
},
});
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }), code.artwork.artist);
@@ -1,18 +1,7 @@
import { certificateAuthorUrl, depositSignature, DepositProvider, DepositRejected, presentStoredCertificate, safeCertificateUrl } from './deposit.provider';
import { depositSignature, DepositProvider, DepositRejected, presentStoredCertificate, safeCertificateUrl } from './deposit.provider';
import { createHash } from 'crypto';
describe('V3 deposit protocol', () => {
it('sets only the author display name, preserves wallet and proof data, and falls back when the artist is missing', () => {
const original = 'https://test.tichain.tianhecloud.com/#/certificate?address=wallet&txHash=hash&digest=digest&depositContent=title';
const result = certificateAuthorUrl(original, 'ARTWORK_ARTIST', '黄志伟 & A');
const query = new URLSearchParams(new URL(result).hash.split('?')[1]);
expect(query.get('author')).toBe('黄志伟 & A');
expect(query.get('address')).toBe('wallet');
expect(query.get('txHash')).toBe('hash');
expect(query.get('digest')).toBe('digest');
expect(certificateAuthorUrl(result, 'WALLET')).toBe(original);
expect(certificateAuthorUrl(result, 'ARTWORK_ARTIST', '')).toBe(original);
});
afterEach(() => jest.restoreAllMocks());
it('signs parameters deterministically with the V3 prefix convention', () => {
expect(depositSignature('/v1/deposit/query', { operateId: 'x', address: 'y' }, {}, '1000', 'secret'))
@@ -20,7 +20,6 @@ export interface StoredCertificateView {
txHash: string;
author: string;
createdAt: string | null;
imageUrl?: string | null;
}
/** 公开页面只接收存证字段。天河链证书网址留在服务端,不进入浏览器。 */
@@ -50,16 +49,6 @@ export function safeCertificateUrl(value: unknown, environment: DepositEnvironme
export class DepositRejected extends Error {}
/** 官方证书页的显示参数;保留原address、digest和txHash,不改变存证身份。 */
export function certificateAuthorUrl(url: string, mode: string | null, artist?: string | null): string {
const parsed = new URL(url);
const params = new URLSearchParams(parsed.hash.slice('#/certificate?'.length));
if (mode === 'ARTWORK_ARTIST' && artist?.trim()) params.set('author', artist.trim());
else params.delete('author');
parsed.hash = '/certificate?' + params.toString();
return parsed.toString();
}
/** V3 uses signed headers and code=200, unlike the existing V2 provider. */
export class DepositProvider {
constructor(private readonly environment: DepositEnvironment, private readonly appId: string, private readonly appKey: string) {}
+46 -4
View File
@@ -1,5 +1,6 @@
import { parseChainDetail } from './chain-detail';
import { loadChainDetail, parseChainDetail, readStoredChainDetail } from './chain-detail';
const txHash = '0x' + 'a'.repeat(64);
const info = {
data: {
gasTxUsed: '3388899',
@@ -19,7 +20,8 @@ const receipt = {
describe('parseChainDetail', () => {
it('keeps gas, sender and logs and drops the raw input binary', () => {
const detail = parseChainDetail(info, receipt);
const detail = parseChainDetail(txHash, info, receipt);
expect(detail?.txHash).toBe(txHash);
expect(detail?.gasUsed).toBe('3388899');
expect(detail?.fromAddress).toBe('0x85aa7cdeba55cb08427018d066a26719b956ceff');
expect(detail?.logs).toHaveLength(1);
@@ -27,8 +29,48 @@ describe('parseChainDetail', () => {
expect(JSON.stringify(detail)).not.toContain('secret');
});
it('accepts numeric gas and token id from the explorer', () => {
const numeric = { data: { ...info.data, gasTxUsed: 66449, transactionDetail: [{ ...info.data.transactionDetail[0], tokenId: 4701 }] } };
const detail = parseChainDetail(txHash, numeric, receipt);
expect(detail?.gasUsed).toBe('66449');
expect(detail?.action?.tokenId).toBe('4701');
});
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();
expect(parseChainDetail(txHash, { data: { gasTxUsed: '', fromAddress: info.data.fromAddress } }, receipt)).toBeNull();
expect(parseChainDetail(txHash, info, { data: [] })).toBeNull();
});
});
describe('readStoredChainDetail', () => {
const stored = { chainDetail: parseChainDetail(txHash, info, receipt) };
it('returns the saved detail only for the transaction it was saved for', () => {
expect(readStoredChainDetail(stored, txHash)?.gasUsed).toBe('3388899');
expect(readStoredChainDetail(stored, '0x' + 'b'.repeat(64))).toBeNull();
expect(readStoredChainDetail(stored, null)).toBeNull();
});
it('ignores incomplete or missing snapshots', () => {
expect(readStoredChainDetail({ chainDetail: { txHash, gasUsed: '1', fromAddress: 'bad', logs: [] } }, txHash)).toBeNull();
expect(readStoredChainDetail({}, txHash)).toBeNull();
expect(readStoredChainDetail(null, txHash)).toBeNull();
});
});
describe('loadChainDetail', () => {
it('reads the transaction and its receipt from the explorer of the given environment', async () => {
const getter = jest.fn(async (url: string) => (url.includes('/receipt/info') ? receipt : info));
const detail = await loadChainDetail('production', txHash, null, getter);
expect(detail?.txHash).toBe(txHash);
expect(getter.mock.calls[0][0]).toBe(`https://explorer.tianhecloud.com/api/tichain-browser-new/transaction/info?txHash=${txHash}`);
expect(getter.mock.calls[1][0]).toBe(`https://explorer.tianhecloud.com/api/tichain-browser-new/receipt/info?hash=${txHash}&height=39944998`);
});
it('does not ask for a receipt when the block height is unknown', async () => {
const getter = jest.fn(async (_url: string) => ({ data: {} }));
expect(await loadChainDetail('test', txHash, null, getter)).toBeNull();
expect(getter).toHaveBeenCalledTimes(1);
expect(getter.mock.calls[0][0]).toContain('https://test.explorer.tianhecloud.com/');
});
});
+10 -5
View File
@@ -12,6 +12,8 @@ export interface ChainLogView {
}
export interface ChainDetail {
/** 这份详情属于哪笔交易;重新上链后旧详情不会被当成新交易的详情。 */
txHash: string;
gasUsed: string;
fromAddress: string;
toAddress: string;
@@ -27,19 +29,21 @@ export interface ChainDetail {
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
function text(value: unknown): string {
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
return typeof value === 'string' ? value.trim() : '';
}
export function readStoredChainDetail(raw: unknown): ChainDetail | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
export function readStoredChainDetail(raw: unknown, txHash: string | null | undefined): ChainDetail | null {
if (!txHash || !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.txHash !== txHash) return null;
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 {
export function parseChainDetail(txHash: string, 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>;
@@ -63,6 +67,7 @@ export function parseChainDetail(info: unknown, receipt: unknown): ChainDetail |
: {};
const action = Array.isArray(row.transactionDetail) ? row.transactionDetail[0] as Record<string, unknown> | undefined : undefined;
return {
txHash,
gasUsed,
fromAddress,
toAddress: text(row.toAddress),
@@ -87,7 +92,7 @@ export function parseChainDetail(info: unknown, receipt: unknown): ChainDetail |
};
}
export function explorerApiBase(environment: string): string {
function explorerApiBase(environment: string): string {
const host = environment === 'production' ? 'https://explorer.tianhecloud.com' : 'https://test.explorer.tianhecloud.com';
return `${host}/api/tichain-browser-new`;
}
@@ -99,7 +104,7 @@ export async function loadChainDetail(environment: string, txHash: string, block
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);
return parseChainDetail(txHash, info, receipt);
}
async function defaultGet(url: string): Promise<unknown> {
@@ -121,6 +121,13 @@ describe('PublicTraceService draft visibility', () => {
await expect(service.outboundImages('482731000001', 1, 20, true)).resolves.toEqual({ status: 'INVALID' });
expect(prisma.outboundImage.findMany).not.toHaveBeenCalled();
});
it('does not look up chain detail for an item that is not publicly visible', async () => {
const { service, prisma } = createHarness();
await expect(service.captureChainDetail('482731000001')).resolves.toEqual({ complete: false, detail: null });
expect(prisma.blockchainProof.findUnique).not.toHaveBeenCalled();
});
});
describe('PublicTraceService outbound timeline visibility', () => {
@@ -423,7 +423,7 @@ export class PublicTraceService {
productId: mint?.productId ?? code.shortCode,
feature: mint?.feature ?? null,
mintTo: mint?.mintTo ?? null,
chainDetail: readStoredChainDetail(proof.rawResponse),
chainDetail: readStoredChainDetail(proof.rawResponse, proof.txHash),
submittedAt: proof.submittedAt,
failureReason: this.publicFailureReason(proof.status, proof.failureReason),
}
@@ -442,21 +442,42 @@ export class PublicTraceService {
}
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 none = { complete: false, detail: null };
if (!TRACE_CODE_PATTERN.test(shortCode)) return none;
const code = await this.prisma.traceCode.findUnique({
where: { shortCode },
select: { id: true, status: true, artwork: { select: { status: true, auditStatus: true, deletedAt: true } } },
});
// 与公开溯源页同一可见范围:未激活、停用、未审核或已删除的实物不提供链上详情
if (
!code ||
code.status !== TraceCodeStatus.ACTIVE ||
code.artwork.deletedAt ||
code.artwork.status !== ArtworkStatus.ACTIVE ||
code.artwork.auditStatus !== AuditStatus.APPROVED
) {
return none;
}
const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: code.id } });
const stored = readStoredChainDetail(proof?.rawResponse);
// 只在确认上链之后补存:确认任务此前还会改写 rawResponse,提前写入会互相覆盖
if (!proof?.txHash || proof.status !== ProofStatus.ONCHAIN || proof.chainName !== '天河链') return none;
const stored = readStoredChainDetail(proof.rawResponse, proof.txHash);
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 detail = await loadChainDetail(
environment || 'test',
proof.txHash,
proof.blockHeight == null ? null : proof.blockHeight.toString(),
).catch((error: unknown) => {
this.logger.warn(`链上详情暂时查询不到: ${(error as Error).message}`);
return null;
});
if (!detail) return none;
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 },
await this.prisma.blockchainProof.updateMany({
where: { id: proof.id, txHash: proof.txHash, status: ProofStatus.ONCHAIN },
data: { rawResponse: { ...current, chainDetail: detail } as unknown as Prisma.InputJsonValue },
});
return { complete: true, detail };