feat: 支持消费者按实物点击生成天河链存证证书
This commit is contained in:
@@ -806,7 +806,9 @@
|
||||
"tianheVerifyOk": "Verified. On-chain identity saved",
|
||||
"tianheManualHint": "Enter the saved User ID and User Key. The system verifies them with TiChain before saving (for reusing the existing wallet after reinstall/migration).",
|
||||
"tianheManualUserIdPh": "e.g. artveris-platform",
|
||||
"tianheManualUserKeyPh": "The User Key you saved offline"
|
||||
"tianheManualUserKeyPh": "The User Key you saved offline",
|
||||
"certificateEnabled": "On-demand certificates",
|
||||
"certificateDailyLimit": "Daily new certificate limit"
|
||||
},
|
||||
"profile": {
|
||||
"title": "Personal Info",
|
||||
|
||||
@@ -806,7 +806,9 @@
|
||||
"tianheVerifyOk": "校验通过,链上身份已保存",
|
||||
"tianheManualHint": "输入已保存的 User ID 与 User Key,系统将向天河链校验后保存(用于重装/迁移后复用既有钱包)。",
|
||||
"tianheManualUserIdPh": "如 artveris-platform",
|
||||
"tianheManualUserKeyPh": "已离线保存的 User Key"
|
||||
"tianheManualUserKeyPh": "已离线保存的 User Key",
|
||||
"certificateEnabled": "扫码页按需出证",
|
||||
"certificateDailyLimit": "每日新增证书上限"
|
||||
},
|
||||
"profile": {
|
||||
"title": "个人信息",
|
||||
|
||||
@@ -93,6 +93,12 @@
|
||||
<n-form-item :label="t('pages.settings.blockchainDriver')">
|
||||
<n-select v-model:value="form.blockchainDriver" :options="blockchainDriverOptions" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="t('pages.settings.certificateEnabled')">
|
||||
<n-switch v-model:value="form.certificateEnabled" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="t('pages.settings.certificateDailyLimit')">
|
||||
<n-input-number v-model:value="form.certificateDailyLimit" :min="0" :max="10000" :precision="0" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="t('pages.settings.tianheEnv')">
|
||||
<n-select v-model:value="form.tianheEnv" :options="tianheEnvOptions" @update:value="onTianheEnvChange" />
|
||||
</n-form-item>
|
||||
@@ -317,6 +323,8 @@ const form = reactive({
|
||||
backupRetentionCount: 10,
|
||||
blockchainDriver: 'mock',
|
||||
tianheEnv: 'test',
|
||||
certificateEnabled: true,
|
||||
certificateDailyLimit: 100,
|
||||
tianheBaseUrl: TIANHE_TEST_URL,
|
||||
tianheAppId: '',
|
||||
tianheAppKey: '',
|
||||
@@ -362,6 +370,8 @@ async function load() {
|
||||
form.backupRetentionCount = Number(s.backupRetentionCount || 10);
|
||||
form.blockchainDriver = s.blockchainDriver || 'mock';
|
||||
form.tianheEnv = s.tianheEnv || 'test';
|
||||
form.certificateEnabled = s.certificateEnabled !== 'false';
|
||||
form.certificateDailyLimit = Number(s.certificateDailyLimit ?? '100');
|
||||
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
|
||||
form.tianheAppId = s.tianheAppId || '';
|
||||
form.tianheAppKey = s.tianheAppKey || '';
|
||||
@@ -551,6 +561,8 @@ async function save() {
|
||||
backupRetentionCount: String(form.backupRetentionCount),
|
||||
blockchainDriver: form.blockchainDriver,
|
||||
tianheEnv: form.tianheEnv,
|
||||
certificateEnabled: String(form.certificateEnabled),
|
||||
certificateDailyLimit: String(form.certificateDailyLimit ?? 0),
|
||||
tianheBaseUrl: form.tianheBaseUrl,
|
||||
tianheAppId: form.tianheAppId,
|
||||
tianheAppKey: form.tianheAppKey,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
ALTER TABLE `blockchain_proof`
|
||||
ADD COLUMN `certificate_state` VARCHAR(20) NOT NULL DEFAULT 'NONE',
|
||||
ADD COLUMN `certificate_request` JSON NULL,
|
||||
ADD COLUMN `certificate_url` TEXT NULL,
|
||||
ADD COLUMN `certificate_error` TEXT NULL,
|
||||
ADD COLUMN `certificate_attempts` INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN `certificate_next_check` DATETIME(3) NULL,
|
||||
ADD COLUMN `certificate_lease_until` DATETIME(3) NULL,
|
||||
ADD COLUMN `certificate_lease_token` VARCHAR(36) NULL,
|
||||
ADD COLUMN `certificate_requested_at` DATETIME(3) NULL,
|
||||
ADD COLUMN `certificate_generated_at` DATETIME(3) NULL;
|
||||
CREATE INDEX `blockchain_proof_certificate_state_certificate_next_check_idx`
|
||||
ON `blockchain_proof` (`certificate_state`, `certificate_next_check`);
|
||||
@@ -391,6 +391,17 @@ model BlockchainProof {
|
||||
failureReason String? @map("failure_reason") @db.Text
|
||||
lastSyncedAt DateTime? @map("last_synced_at")
|
||||
rawResponse Json? @map("raw_response")
|
||||
// Consumer-requested V3 certificate; separate from the NFT mint transaction.
|
||||
certificateState String @default("NONE") @map("certificate_state") @db.VarChar(20)
|
||||
certificateRequest Json? @map("certificate_request")
|
||||
certificateUrl String? @map("certificate_url") @db.Text
|
||||
certificateError String? @map("certificate_error") @db.Text
|
||||
certificateAttempts Int @default(0) @map("certificate_attempts")
|
||||
certificateNextCheck DateTime? @map("certificate_next_check")
|
||||
certificateLeaseUntil DateTime? @map("certificate_lease_until")
|
||||
certificateLeaseToken String? @map("certificate_lease_token") @db.VarChar(36)
|
||||
certificateRequestedAt DateTime? @map("certificate_requested_at")
|
||||
certificateGeneratedAt DateTime? @map("certificate_generated_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -399,6 +410,7 @@ model BlockchainProof {
|
||||
jobItems JobItem[]
|
||||
|
||||
@@unique([traceCodeId])
|
||||
@@index([certificateState, certificateNextCheck])
|
||||
@@index([status])
|
||||
@@index([onchainChunkId])
|
||||
@@map("blockchain_proof")
|
||||
|
||||
@@ -73,6 +73,10 @@ const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = {
|
||||
systemSetting: 'SystemSetting',
|
||||
};
|
||||
const DATE_KEYS = new Set([
|
||||
'certificateRequestedAt',
|
||||
'certificateGeneratedAt',
|
||||
'certificateNextCheck',
|
||||
'certificateLeaseUntil',
|
||||
'lastLoginAt',
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
@@ -658,6 +662,15 @@ export class BackupService {
|
||||
const rows = Array.isArray(db[model])
|
||||
? db[model].map((row: unknown) => {
|
||||
const revived = reviveRow(row as Record<string, any>) as Record<string, unknown>;
|
||||
// A snapshot cannot prove that the original worker never sent this request.
|
||||
// Restore unfinished certificates in query-only mode, never resubmit.
|
||||
if (model === 'blockchainProof' && revived.certificateRequest &&
|
||||
['PENDING', 'SUBMITTING', 'CHECKING', 'WAITING'].includes(String(revived.certificateState))) {
|
||||
revived.certificateState = 'UNKNOWN';
|
||||
revived.certificateLeaseToken = null;
|
||||
revived.certificateLeaseUntil = null;
|
||||
revived.certificateNextCheck = new Date();
|
||||
}
|
||||
return revived;
|
||||
})
|
||||
: [];
|
||||
|
||||
@@ -7,12 +7,14 @@ import { AttestationService } from './attestation.service';
|
||||
import { BlockchainController } from './blockchain.controller';
|
||||
import { OnchainProcessor } from './onchain.processor';
|
||||
import { OnchainRecoveryService } from './onchain-recovery.service';
|
||||
import { DepositCertificateService } from './deposit-certificate.service';
|
||||
import { DepositCertificateController } from './deposit-certificate.controller';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN }), SettingsModule],
|
||||
controllers: [BlockchainController],
|
||||
providers: [BlockchainService, AttestationService, OnchainProcessor, OnchainRecoveryService],
|
||||
controllers: [BlockchainController, DepositCertificateController],
|
||||
providers: [BlockchainService, AttestationService, OnchainProcessor, OnchainRecoveryService, DepositCertificateService],
|
||||
exports: [BlockchainService, AttestationService],
|
||||
})
|
||||
export class BlockchainModule {}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { DepositCertificateService } from './deposit-certificate.service';
|
||||
|
||||
@Controller('public/trace/:shortCode/certificate')
|
||||
export class DepositCertificateController {
|
||||
constructor(private readonly certificates: DepositCertificateService) {}
|
||||
|
||||
@Public()
|
||||
@Get()
|
||||
@Throttle({ default: { limit: 60, ttl: 60_000 } })
|
||||
status(@Param('shortCode') shortCode: string) { return this.certificates.status(shortCode); }
|
||||
|
||||
@Public()
|
||||
@Post()
|
||||
@Throttle({ default: { limit: 5, ttl: 60_000 } })
|
||||
request(@Param('shortCode') shortCode: string) { return this.certificates.request(shortCode); }
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { DepositCertificateService } from './deposit-certificate.service';
|
||||
import { DepositProvider } from './deposit.provider';
|
||||
|
||||
const settings = {
|
||||
certificateEnabled: 'true', certificateDailyLimit: '100', blockchainDriver: 'tianhe',
|
||||
tianheEnv: 'test', tianheAppId: 'app', tianheAppKey: 'key', tianheWalletAddress: '0x' + 'a'.repeat(40),
|
||||
};
|
||||
function fixture(state = 'PENDING') {
|
||||
const row: any = {
|
||||
id: 1, traceCodeId: 1n, status: 'ONCHAIN', txHash: '0x' + 'c'.repeat(64), chainName: '天河链',
|
||||
certificateState: state, certificateAttempts: 0, certificateLeaseUntil: null,
|
||||
certificateRequest: { version: 1, environment: 'test', appId: 'app', address: settings.tianheWalletAddress, operateId: 'stable-op', text: 'frozen-evidence' },
|
||||
};
|
||||
const prisma = {
|
||||
blockchainProof: {
|
||||
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
|
||||
findUniqueOrThrow: jest.fn().mockResolvedValue(row),
|
||||
},
|
||||
traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
const config = { getAllRaw: jest.fn().mockResolvedValue(settings), get: jest.fn().mockResolvedValue('true') };
|
||||
return { row, prisma, config, service: new DepositCertificateService(prisma as any, config as any) };
|
||||
}
|
||||
describe('Consumer certificate lifecycle', () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
it('GET only reads persisted state and never starts a job or calls Tianhe', async () => {
|
||||
const { service, prisma, config } = fixture('NONE');
|
||||
expect(await service.status('123456000001')).toMatchObject({ status: 'NONE', url: null });
|
||||
expect(prisma.blockchainProof.updateMany).not.toHaveBeenCalled();
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
expect(config.getAllRaw).not.toHaveBeenCalled();
|
||||
});
|
||||
it('returns an existing shared certificate without consulting credentials or submitting', async () => {
|
||||
const { service, row, config } = fixture('READY');
|
||||
row.certificateUrl = 'https://test.tichain.tianhecloud.com/#/certificate?address=' + settings.tianheWalletAddress + '&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64);
|
||||
expect(await service.request('123456000001')).toMatchObject({ status: 'READY', url: row.certificateUrl });
|
||||
expect(config.getAllRaw).not.toHaveBeenCalled();
|
||||
});
|
||||
it('does not send when another worker owns the lease', async () => {
|
||||
const { service, row, prisma } = fixture();
|
||||
prisma.blockchainProof.updateMany.mockResolvedValue({ count: 0 });
|
||||
const submit = jest.spyOn(DepositProvider.prototype, 'submit');
|
||||
await service.process(row);
|
||||
expect(submit).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'));
|
||||
await service.process(row);
|
||||
expect(submit).toHaveBeenCalledWith(settings.tianheWalletAddress, 'stable-op', 'frozen-evidence');
|
||||
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('WAITING');
|
||||
row.certificateState = 'WAITING';
|
||||
jest.spyOn(DepositProvider.prototype, 'query').mockResolvedValue({ operateId: 'stable-op', status: 2, createTime: '', txHash: '' });
|
||||
const cert = jest.spyOn(DepositProvider.prototype, 'certificate');
|
||||
await service.process(row);
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
expect(cert).not.toHaveBeenCalled();
|
||||
});
|
||||
it('recovers a crashed SUBMITTING worker by querying, not resubmitting', async () => {
|
||||
const { service, row } = fixture('SUBMITTING');
|
||||
const submit = jest.spyOn(DepositProvider.prototype, 'submit');
|
||||
const query = jest.spyOn(DepositProvider.prototype, 'query').mockResolvedValue({ status: 2 });
|
||||
await service.process(row);
|
||||
expect(submit).not.toHaveBeenCalled(); expect(query).toHaveBeenCalledWith(settings.tianheWalletAddress, 'stable-op');
|
||||
});
|
||||
it('stops before network calls if the wallet or environment changed', async () => {
|
||||
const { service, row, config, prisma } = fixture();
|
||||
config.getAllRaw.mockResolvedValue({ ...settings, tianheEnv: 'production' });
|
||||
const submit = jest.spyOn(DepositProvider.prototype, 'submit');
|
||||
await service.process(row);
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('UNKNOWN');
|
||||
});
|
||||
it('rejects inactive, disabled and unapproved items before creation', async () => {
|
||||
const { service, prisma } = fixture('NONE');
|
||||
prisma.traceCode.findUnique.mockResolvedValue({ status: 'INACTIVE' } as any);
|
||||
await expect(service.request('123456000001')).rejects.toThrow();
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it('uses an atomic NONE claim so a stale concurrent transaction cannot overwrite the request or consume quota', async () => {
|
||||
const { service, prisma } = fixture('NONE');
|
||||
const tx = {
|
||||
systemSetting: { upsert: jest.fn(), update: jest.fn() },
|
||||
$queryRaw: jest.fn().mockResolvedValue([{ value: '2026-09-20:1' }]),
|
||||
blockchainProof: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) },
|
||||
};
|
||||
prisma.$transaction.mockImplementation(async callback => callback(tx));
|
||||
await service.request('123456000001');
|
||||
expect(tx.blockchainProof.updateMany).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 1, certificateState: 'NONE', status: 'ONCHAIN' } }));
|
||||
expect(tx.systemSetting.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Interval } from '@nestjs/schedule';
|
||||
import { ArtworkStatus, AuditStatus, BlockchainProof, Prisma, ProofStatus, TraceCodeStatus } from '@prisma/client';
|
||||
import { randomBytes, randomUUID } from 'crypto';
|
||||
import { ErrorCode, TRACE_CODE_PATTERN } from '@artveris/shared';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { DepositEnvironment, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
|
||||
|
||||
interface CertificateRequest {
|
||||
version: 1;
|
||||
environment: DepositEnvironment;
|
||||
appId: string;
|
||||
address: string;
|
||||
operateId: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
const ACTIVE_STATES = ['PENDING', 'SUBMITTING', 'WAITING', 'CHECKING'];
|
||||
const MAX_CHECKS = 8;
|
||||
|
||||
@Injectable()
|
||||
export class DepositCertificateService {
|
||||
private readonly logger = new Logger(DepositCertificateService.name);
|
||||
private running = false;
|
||||
|
||||
constructor(private readonly prisma: PrismaService, private readonly settings: SettingsService) {}
|
||||
|
||||
private async eligible(shortCode: string) {
|
||||
if (!TRACE_CODE_PATTERN.test(shortCode)) throw new BusinessException(ErrorCode.NOT_FOUND, '追溯码不可用', 404);
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { shortCode }, include: { artwork: true, proofs: true },
|
||||
});
|
||||
const proof = code?.proofs[0];
|
||||
if (!code || code.status !== TraceCodeStatus.ACTIVE || code.artwork.deletedAt ||
|
||||
code.artwork.status !== ArtworkStatus.ACTIVE || code.artwork.auditStatus !== AuditStatus.APPROVED ||
|
||||
!proof || proof.status !== ProofStatus.ONCHAIN || !proof.txHash || proof.chainName !== '天河链') {
|
||||
throw new BusinessException(ErrorCode.NOT_FOUND, '当前实物暂不支持出证', 404);
|
||||
}
|
||||
return { code, proof };
|
||||
}
|
||||
|
||||
private view(proof: BlockchainProof) {
|
||||
const request = proof.certificateRequest as unknown as CertificateRequest | null;
|
||||
const url = request && proof.certificateState === 'READY'
|
||||
? safeCertificateUrl(proof.certificateUrl, request.environment, request.address) : null;
|
||||
return {
|
||||
status: proof.certificateState === 'READY' && !url ? 'FAILED' : proof.certificateState,
|
||||
url, generatedAt: proof.certificateGeneratedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/** No remote calls, writes, activation, or query-count changes. */
|
||||
async status(shortCode: string) {
|
||||
const { proof } = await this.eligible(shortCode);
|
||||
return this.view(proof);
|
||||
}
|
||||
|
||||
async request(shortCode: string) {
|
||||
const { code, proof } = await this.eligible(shortCode);
|
||||
if (proof.certificateState === 'READY') return this.view(proof);
|
||||
const settings = await this.settings.getAllRaw();
|
||||
if (settings.certificateEnabled === 'false') throw new BusinessException(ErrorCode.BAD_REQUEST, '证书生成暂时关闭');
|
||||
if (proof.certificateState !== 'NONE') {
|
||||
// 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({
|
||||
where: { id: proof.id, certificateState: 'UNKNOWN', certificateNextCheck: { lte: new Date() } },
|
||||
data: { certificateState: 'WAITING', certificateAttempts: 0, certificateNextCheck: new Date() },
|
||||
});
|
||||
}
|
||||
return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })));
|
||||
}
|
||||
const environment = settings.tianheEnv as DepositEnvironment;
|
||||
if (settings.blockchainDriver !== 'tianhe' || !['test', 'production'].includes(environment) ||
|
||||
!settings.tianheAppId || !settings.tianheAppKey || !/^0x[0-9a-f]{40}$/i.test(settings.tianheWalletAddress || '')) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '平台存证配置尚未就绪');
|
||||
}
|
||||
const now = new Date();
|
||||
const request: CertificateRequest = {
|
||||
version: 1, environment, appId: settings.tianheAppId, address: settings.tianheWalletAddress,
|
||||
operateId: `avc${randomBytes(8).toString('hex')}`,
|
||||
// The official TEXT certificate prints this verbatim; use readable labels.
|
||||
text: [
|
||||
`作品:${code.artwork.title}`,
|
||||
`作者:${code.artwork.artist || '未填写'}`,
|
||||
`档案编号:${code.artwork.archiveNo}`,
|
||||
`实物追溯码:${code.shortCode}`,
|
||||
`数字身份交易:${proof.txHash}`,
|
||||
`证据记录时间:${now.toISOString()}`,
|
||||
].join(';'),
|
||||
};
|
||||
// DB quota lock survives Redis restarts and serializes initial requests across workers.
|
||||
// No credentials or network calls inside the transaction.
|
||||
await this.prisma.$transaction(async tx => {
|
||||
const quotaKey = 'certificateDailyQuota';
|
||||
await tx.systemSetting.upsert({ where: { key: quotaKey }, create: { key: quotaKey, value: '' }, update: { key: quotaKey } });
|
||||
const [quota] = await tx.$queryRaw<Array<{ value: string }>>`SELECT value FROM system_setting WHERE \`key\` = ${quotaKey} FOR UPDATE`;
|
||||
// Use a conditional write, not a snapshot read: MySQL REPEATABLE READ can
|
||||
// retain an older NONE snapshot while this transaction waited for the lock.
|
||||
const claimed = await tx.blockchainProof.updateMany({ where: { id: proof.id, certificateState: 'NONE', status: ProofStatus.ONCHAIN }, data: {
|
||||
certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject,
|
||||
certificateRequestedAt: now, certificateNextCheck: now,
|
||||
} });
|
||||
if (!claimed.count) return;
|
||||
const day = new Date(now.getTime() + 8 * 3600_000).toISOString().slice(0, 10);
|
||||
const [quotaDay, quotaCount] = (quota?.value || '').split(':');
|
||||
const count = quotaDay === day ? Number(quotaCount) || 0 : 0;
|
||||
const limit = Math.min(10000, Math.max(0, Number(settings.certificateDailyLimit ?? '100') || 0));
|
||||
if (count >= limit) throw new BusinessException(ErrorCode.TOO_MANY_REQUESTS, '今日证书生成数量已达上限,请稍后再试', 429);
|
||||
await tx.systemSetting.update({ where: { key: quotaKey }, data: { value: `${day}:${count + 1}` } });
|
||||
});
|
||||
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }));
|
||||
}
|
||||
|
||||
/** Persistent DB-backed work: only explicit requests enter PENDING. Restart-safe. */
|
||||
@Interval(5000)
|
||||
async tick() {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
try {
|
||||
if ((await this.settings.get('certificateEnabled')) === 'false') return;
|
||||
const now = new Date();
|
||||
const rows = await this.prisma.blockchainProof.findMany({
|
||||
where: { certificateState: { in: ACTIVE_STATES }, certificateNextCheck: { lte: now },
|
||||
OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] },
|
||||
orderBy: { certificateRequestedAt: 'asc' }, take: 5,
|
||||
});
|
||||
for (const row of rows) await this.process(row);
|
||||
} catch {
|
||||
this.logger.warn('Certificate worker unavailable; persisted requests will be checked again');
|
||||
} finally { this.running = false; }
|
||||
}
|
||||
|
||||
async process(row: BlockchainProof) {
|
||||
const now = new Date();
|
||||
const token = randomUUID();
|
||||
const submit = row.certificateState === 'PENDING';
|
||||
const claimed = await this.prisma.blockchainProof.updateMany({
|
||||
where: { id: row.id, certificateState: row.certificateState,
|
||||
certificateAttempts: row.certificateAttempts, certificateNextCheck: { lte: now },
|
||||
OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] },
|
||||
data: { certificateState: submit ? 'SUBMITTING' : 'CHECKING', certificateLeaseToken: token,
|
||||
certificateLeaseUntil: new Date(now.getTime() + 120_000) },
|
||||
});
|
||||
if (!claimed.count) return;
|
||||
const finish = (data: Prisma.BlockchainProofUpdateManyMutationInput) => this.prisma.blockchainProof.updateMany({
|
||||
where: { id: row.id, certificateLeaseToken: token },
|
||||
data: { ...data, certificateLeaseUntil: null, certificateLeaseToken: null },
|
||||
});
|
||||
const attempts = row.certificateAttempts + 1;
|
||||
let accepted = false;
|
||||
try {
|
||||
const request = row.certificateRequest as unknown as CertificateRequest;
|
||||
const settings = await this.settings.getAllRaw();
|
||||
if (!request || request.version !== 1 || settings.blockchainDriver !== 'tianhe' ||
|
||||
settings.tianheEnv !== request.environment || settings.tianheAppId !== request.appId ||
|
||||
settings.tianheWalletAddress !== request.address || !settings.tianheAppKey) {
|
||||
await finish({ certificateState: 'UNKNOWN', certificateError: '存证环境或钱包已变更,请恢复原配置后继续查询', certificateNextCheck: now });
|
||||
return;
|
||||
}
|
||||
const provider = new DepositProvider(request.environment, request.appId, settings.tianheAppKey);
|
||||
if (submit) {
|
||||
const current = await this.prisma.traceCode.findUnique({ where: { id: row.traceCodeId }, select: { shortCode: true } });
|
||||
try { await this.eligible(current?.shortCode || ''); }
|
||||
catch {
|
||||
await finish({ certificateState: 'FAILED', certificateError: '实物当前状态不允许出证', certificateNextCheck: null });
|
||||
return;
|
||||
}
|
||||
await provider.submit(request.address, request.operateId, request.text);
|
||||
accepted = true;
|
||||
await finish({ certificateState: 'WAITING', certificateError: null, certificateNextCheck: new Date(Date.now() + 5000) });
|
||||
return;
|
||||
}
|
||||
// A crashed/timed-out SUBMITTING job also comes here, never back to submit().
|
||||
const result = await provider.query(request.address, request.operateId);
|
||||
const exists = result?.operateId === request.operateId && (Boolean(result?.createTime) || Boolean(result?.txHash));
|
||||
const url = exists ? await provider.certificate(request.address, request.operateId, request.text) : null;
|
||||
if (url) {
|
||||
await finish({ certificateState: 'READY', certificateUrl: url, certificateGeneratedAt: new Date(),
|
||||
certificateError: null, certificateNextCheck: null, certificateAttempts: attempts });
|
||||
return;
|
||||
}
|
||||
await finish({ certificateState: attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING',
|
||||
certificateAttempts: attempts, certificateError: '证书尚未就绪,后续仅查询原存证',
|
||||
certificateNextCheck: new Date(Date.now() + 30_000) });
|
||||
} catch (error) {
|
||||
const rejected = submit && !accepted && error instanceof DepositRejected;
|
||||
await finish({ certificateState: rejected ? 'FAILED' : attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING',
|
||||
certificateAttempts: attempts, certificateError: rejected ? '存证提交被拒绝,请联系平台管理员' : '远端结果暂未确认,后续仅查询原存证',
|
||||
certificateNextCheck: new Date(Date.now() + 30_000) });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { depositSignature, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
describe('V3 deposit protocol', () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
it('signs parameters deterministically with the V3 prefix convention', () => {
|
||||
expect(depositSignature('/v1/deposit/query', { operateId: 'x', address: 'y' }, {}, '1000', 'secret'))
|
||||
.toBe(depositSignature('/v1/deposit/query', { address: 'y', operateId: 'x' }, {}, '1000', 'secret'));
|
||||
expect(depositSignature('/v1/deposit/query', { address: 'y' }, {}, '1000', 'secret'))
|
||||
.not.toBe(depositSignature('/v1/deposit/query', {}, { address: 'y' }, '1000', 'secret'));
|
||||
});
|
||||
it('rejects foreign, wrong-environment and credential-bearing certificate URLs', () => {
|
||||
const suffix = '#/certificate?address=abc&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64);
|
||||
expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'abc')).toBeTruthy();
|
||||
for (const base of ['https://evil.example/', 'https://tichain.tianhecloud.com/', 'https://user@test.tichain.tianhecloud.com/']) {
|
||||
expect(safeCertificateUrl(base + suffix, 'test', 'abc')).toBeNull();
|
||||
}
|
||||
expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'wrong')).toBeNull();
|
||||
});
|
||||
it('uses signed headers, does not expose keys in URL/body and rejects ambiguous acceptance', async () => {
|
||||
const fetcher = jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 200, success: true, data: 'different-id' }) } as any);
|
||||
await expect(new DepositProvider('test', 'app', 'secret').submit('address', 'op', '证据'))
|
||||
.rejects.toThrow('uncertain');
|
||||
const [url, options] = fetcher.mock.calls[0];
|
||||
expect(String(url)).toBe('https://test.api.tichain.tianhecloud.com/v1/deposit/text/save');
|
||||
expect(JSON.stringify(options)).not.toContain('secret');
|
||||
expect(options?.redirect).toBe('error');
|
||||
});
|
||||
it('distinguishes explicit rejection from uncertain transport failure', async () => {
|
||||
jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 400, success: false }) } as any);
|
||||
await expect(new DepositProvider('test', 'app', 'key').submit('addr', 'op', 'test')).rejects.toBeInstanceOf(DepositRejected);
|
||||
});
|
||||
it('binds the returned certificate to the exact frozen evidence and preserves reserved characters', async () => {
|
||||
const text = '作品:A&B + 100% #茶器';
|
||||
const digest = createHash('sha256').update(text).digest('hex');
|
||||
const value = 'https://test.tichain.tianhecloud.com/#/certificate?depositContent=broken&type=TEXT&address=addr&txHash=0x' + 'a'.repeat(64) + '&digest=' + digest;
|
||||
jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 200, success: true, data: value }) } as any);
|
||||
const provider = new DepositProvider('test', 'app', 'key');
|
||||
const result = await provider.certificate('addr', 'op', text);
|
||||
expect(new URLSearchParams(new URL(result!).hash.split('?')[1]).get('depositContent')).toBe(text);
|
||||
await expect(provider.certificate('addr', 'op', 'different evidence')).rejects.toThrow('digest');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
export type DepositEnvironment = 'test' | 'production';
|
||||
export const DEPOSIT_ENDPOINTS = {
|
||||
test: 'https://test.api.tichain.tianhecloud.com',
|
||||
production: 'https://api.tichain.tianhecloud.com',
|
||||
} as const;
|
||||
|
||||
export function depositSignature(path: string, query: Record<string, unknown>, body: Record<string, unknown>, timestamp: string, key: string): string {
|
||||
const params: Record<string, unknown> = { path_url: path };
|
||||
for (const [k, v] of Object.entries(query)) params[`query_${k}`] = v;
|
||||
for (const [k, v] of Object.entries(body)) params[`body_${k}`] = v;
|
||||
const json = JSON.stringify(Object.fromEntries(Object.keys(params).sort().map(k => [k, params[k]])));
|
||||
return createHash('sha256').update(json + timestamp + key, 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
export function safeCertificateUrl(value: unknown, environment: DepositEnvironment, address?: string): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
const host = environment === 'test' ? 'test.tichain.tianhecloud.com' : 'tichain.tianhecloud.com';
|
||||
if (url.protocol !== 'https:' || url.hostname !== host || url.port || url.username || url.password || url.pathname !== '/' || !url.hash.startsWith('#/certificate?')) return null;
|
||||
const params = new URLSearchParams(url.hash.slice('#/certificate?'.length));
|
||||
if (address && params.get('address')?.toLowerCase() !== address.toLowerCase()) return null;
|
||||
if (!/^0x[0-9a-f]{64}$/i.test(params.get('txHash') || '') || !/^[0-9a-f]{64}$/i.test(params.get('digest') || '')) return null;
|
||||
return url.toString();
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
export class DepositRejected extends Error {}
|
||||
|
||||
/** 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) {}
|
||||
|
||||
private async request(path: string, query: Record<string, string>, body?: Record<string, unknown>): Promise<any> {
|
||||
const stamp = String(Date.now());
|
||||
const url = new URL(path, DEPOSIT_ENDPOINTS[this.environment]);
|
||||
for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
|
||||
// Do not log request headers, signed material, credentials, or evidence text.
|
||||
const response = await fetch(url, {
|
||||
method: body ? 'POST' : 'GET',
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(25_000),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'ti-appid': this.appId,
|
||||
'ti-timestamp': stamp,
|
||||
'ti-signature': depositSignature(path, query, body || {}, stamp, this.appKey),
|
||||
},
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Deposit HTTP ${response.status}`);
|
||||
const result = await response.json() as any;
|
||||
if (!result || typeof result !== 'object') throw new Error('Invalid deposit response');
|
||||
return result;
|
||||
}
|
||||
|
||||
async submit(address: string, operateId: string, text: string): Promise<void> {
|
||||
const result = await this.request('/v1/deposit/text/save', {}, { text, address, operateId, noDigest: false });
|
||||
if (result.success === false && result.code !== undefined) throw new DepositRejected(`Deposit rejected (${result.code})`);
|
||||
if (Number(result.code) !== 200 || result.success !== true || result.data !== operateId) throw new Error('Deposit submission result uncertain');
|
||||
}
|
||||
|
||||
async query(address: string, operateId: string): Promise<any> {
|
||||
const result = await this.request('/v1/deposit/query', { address, operateId });
|
||||
if (Number(result.code) !== 200 || result.success !== true) throw new Error('Deposit query failed');
|
||||
return result.data;
|
||||
}
|
||||
|
||||
async certificate(address: string, operateId: string, evidenceText: string): Promise<string | null> {
|
||||
const result = await this.request('/v1/deposit/certificate', { address, operateId });
|
||||
// Pending/not-found is not grounds for resubmitting a deposit.
|
||||
if (Number(result.code) === 400 && result.success === false) return null;
|
||||
if (Number(result.code) !== 200 || result.success !== true) throw new Error('Certificate query failed');
|
||||
const url = safeCertificateUrl(result.data, this.environment, address);
|
||||
if (!url) throw new Error('Invalid certificate URL');
|
||||
const parsed = new URL(url);
|
||||
const params = new URLSearchParams(parsed.hash.slice('#/certificate?'.length));
|
||||
if (params.get('digest') !== createHash('sha256').update(evidenceText, 'utf8').digest('hex')) {
|
||||
throw new Error('Certificate digest does not match the submitted evidence');
|
||||
}
|
||||
if (params.get('type') !== 'TEXT') throw new Error('Unexpected certificate type');
|
||||
// The provider returns partially unescaped text. Preserve &, #, +, % and Unicode
|
||||
// from our frozen evidence, rather than allowing them to become URL parameters.
|
||||
params.set('depositContent', evidenceText);
|
||||
parsed.hash = '/certificate?' + params.toString();
|
||||
return parsed.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
@@ -29,6 +29,8 @@ const EDITABLE_KEYS = [
|
||||
'storageMigrationFingerprint',
|
||||
'storageMigrationCopied',
|
||||
'blockchainDriver',
|
||||
'certificateEnabled',
|
||||
'certificateDailyLimit',
|
||||
'tianheEnv',
|
||||
'tianheBaseUrl',
|
||||
'tianheAppId',
|
||||
@@ -89,6 +91,8 @@ export class SettingsService {
|
||||
ossAccessKeySecret: this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
|
||||
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
|
||||
certificateEnabled: 'true',
|
||||
certificateDailyLimit: '100',
|
||||
tianheEnv: 'test',
|
||||
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
|
||||
tianheAppId: this.config.get<string>('blockchain.tianhe.appId') || '',
|
||||
@@ -142,6 +146,13 @@ export class SettingsService {
|
||||
}
|
||||
|
||||
async updateAtomic(values: Record<string, string>): Promise<void> {
|
||||
if (values.certificateEnabled !== undefined && !['true', 'false'].includes(String(values.certificateEnabled))) {
|
||||
throw new BadRequestException('Invalid certificate switch');
|
||||
}
|
||||
if (values.certificateDailyLimit !== undefined &&
|
||||
(!/^\d+$/.test(String(values.certificateDailyLimit)) || Number(values.certificateDailyLimit) > 10000)) {
|
||||
throw new BadRequestException('Certificate daily limit must be between 0 and 10000');
|
||||
}
|
||||
const updates: Array<{ key: string; value: string }> = [];
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (!EDITABLE_KEYS.includes(key)) continue;
|
||||
|
||||
@@ -43,3 +43,15 @@ export function fetchTracePreview(shortCode: string, token: string, state: 'inac
|
||||
export function fetchAppInfo(): Promise<any> {
|
||||
return instance.get('/settings/public') as unknown as Promise<any>;
|
||||
}
|
||||
|
||||
export interface TraceCertificateResult {
|
||||
status: 'NONE' | 'PENDING' | 'SUBMITTING' | 'CHECKING' | 'WAITING' | 'READY' | 'UNKNOWN' | 'FAILED';
|
||||
url: string | null;
|
||||
generatedAt: string | null;
|
||||
}
|
||||
export function requestTraceCertificate(shortCode: string): Promise<TraceCertificateResult> {
|
||||
return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/certificate`, {}) as unknown as Promise<TraceCertificateResult>;
|
||||
}
|
||||
export function fetchTraceCertificate(shortCode: string): Promise<TraceCertificateResult> {
|
||||
return instance.get(`/public/trace/${encodeURIComponent(shortCode)}/certificate`) as unknown as Promise<TraceCertificateResult>;
|
||||
}
|
||||
|
||||
@@ -57,22 +57,31 @@
|
||||
<span class="chain-k">{{ t('chain.onchainAt') }}</span>
|
||||
<span class="chain-v">{{ formatTime(blockchain.onchainAt) }}</span>
|
||||
</div>
|
||||
<a
|
||||
v-if="explorerUrl"
|
||||
class="chain-link"
|
||||
:href="explorerUrl"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{{ t('chain.explorer') }} →
|
||||
</a>
|
||||
<div class="chain-actions">
|
||||
<a
|
||||
v-if="explorerUrl"
|
||||
class="chain-link"
|
||||
:href="explorerUrl"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{{ t('chain.explorer') }} →
|
||||
</a>
|
||||
<button v-if="canViewCertificate" class="chain-link certificate-link" :disabled="opening || preview" @click="viewCertificate">
|
||||
{{ t(opening ? 'chain.certificateOpening' : 'chain.certificateView') }} →
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="preview && canViewCertificate" class="muted chain-status-note">{{ t('chain.certificatePreview') }}</p>
|
||||
<p v-if="certificateError" role="alert" class="chain-status-note">{{ certificateError }}</p>
|
||||
</template>
|
||||
<div v-else class="chain-empty muted">{{ t('chain.notOnchain') }}</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { fetchTraceCertificate, requestTraceCertificate } from '@/api';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import dayjs from 'dayjs';
|
||||
import { safeTraceUrl } from './media';
|
||||
@@ -90,6 +99,8 @@ const STATUSES = new Set<ProofStatus>([
|
||||
const props = defineProps<{
|
||||
title: string;
|
||||
archiveNo?: string | null;
|
||||
shortCode: string;
|
||||
preview?: boolean;
|
||||
blockchain?: {
|
||||
status?: string;
|
||||
txHash?: string | null;
|
||||
@@ -98,10 +109,38 @@ const props = defineProps<{
|
||||
onchainAt?: string | null;
|
||||
explorerUrl?: string | null;
|
||||
failureReason?: string | null;
|
||||
chainName?: string | null;
|
||||
} | null;
|
||||
}>();
|
||||
defineEmits<{ (event: 'copy', value: string): void }>();
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
const opening = ref(false);
|
||||
const certificateError = ref('');
|
||||
const canViewCertificate = computed(() => status.value === 'ONCHAIN' && props.blockchain?.chainName === '天河链');
|
||||
|
||||
async function viewCertificate() {
|
||||
if (opening.value || props.preview) return;
|
||||
certificateError.value = '';
|
||||
const href = router.resolve({ path: `/certificate/${props.shortCode}` }).href;
|
||||
// Open while the click gesture is active. The waiting page never starts a deposit itself.
|
||||
const popup = window.open(href, '_blank');
|
||||
if (popup) popup.opener = null;
|
||||
opening.value = true;
|
||||
try {
|
||||
const cached = await fetchTraceCertificate(props.shortCode);
|
||||
const result = cached.status === 'NONE' || cached.status === 'UNKNOWN'
|
||||
? await requestTraceCertificate(props.shortCode) : cached;
|
||||
if (!popup) {
|
||||
await router.push(`/certificate/${props.shortCode}`);
|
||||
} else if (result.status === 'READY' && result.url) {
|
||||
popup.location.replace(result.url);
|
||||
}
|
||||
} catch {
|
||||
if (popup && !popup.closed) popup.close();
|
||||
certificateError.value = t('chain.certificateRequestFailed');
|
||||
} finally { opening.value = false; }
|
||||
}
|
||||
|
||||
const status = computed<ProofStatus>(() => {
|
||||
const value = props.blockchain?.status as ProofStatus | undefined;
|
||||
@@ -213,4 +252,7 @@ function formatTime(value: string) {
|
||||
font-size: 13px;
|
||||
padding: 8px 0;
|
||||
}
|
||||
.chain-actions { display: flex; align-items: center; gap: 24px; flex-wrap: wrap; }
|
||||
.certificate-link { padding: 0; border: 0; background: none; cursor: pointer; font-family: inherit; }
|
||||
.certificate-link:disabled { opacity: .55; cursor: default; }
|
||||
</style>
|
||||
|
||||
@@ -41,6 +41,8 @@
|
||||
:title="moduleTitle(module)"
|
||||
:archive-no="data.artwork.archiveNo"
|
||||
:blockchain="data.blockchain"
|
||||
:short-code="shortCode"
|
||||
:preview="data.preview === true"
|
||||
@copy="(value) => $emit('copy', value)"
|
||||
/>
|
||||
<trace-image-text-module
|
||||
@@ -78,6 +80,7 @@ import TraceHorizontalGalleryModule from './TraceHorizontalGalleryModule.vue';
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
data: any;
|
||||
shortCode: string;
|
||||
layout?: TraceLayout;
|
||||
timelineItems?: any[];
|
||||
carouselInterval?: number;
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
{
|
||||
"app": { "name": "Artwork Traceability" },
|
||||
"home": { "title": "Artwork Traceability & Authentication", "hint": "Scan the anti-counterfeit QR code on the artwork to view its provenance" },
|
||||
"app": {
|
||||
"name": "Artwork Traceability"
|
||||
},
|
||||
"home": {
|
||||
"title": "Artwork Traceability & Authentication",
|
||||
"hint": "Scan the anti-counterfeit QR code on the artwork to view its provenance"
|
||||
},
|
||||
"anti": {
|
||||
"firstTitle": "Genuine · First Query",
|
||||
"repeatTitle": "Authenticity Verified",
|
||||
@@ -57,7 +62,21 @@
|
||||
"explorer": "View Proof",
|
||||
"copy": "Copy",
|
||||
"copied": "Copied",
|
||||
"notOnchain": "This artwork has not been recorded on-chain yet."
|
||||
"notOnchain": "This artwork has not been recorded on-chain yet.",
|
||||
"certificateView": "View certificate",
|
||||
"certificateOpening": "Opening…",
|
||||
"certificatePreview": "Certificates cannot be generated in preview mode.",
|
||||
"certificateRequestFailed": "Unable to request a certificate. Please try later or contact the platform.",
|
||||
"certificateGenerating": "Your certificate is being prepared. The TiChain certificate page will open when it is ready.",
|
||||
"certificateShared": "One certificate is generated for this physical item and reused on future visits.",
|
||||
"certificateOpen": "Open certificate",
|
||||
"certificateCheckAgain": "Check again",
|
||||
"certificateBack": "Back",
|
||||
"certificateReady": "Your certificate is ready.",
|
||||
"certificateFailed": "The attestation request was rejected. Please contact the platform.",
|
||||
"certificateUnknown": "The result is not yet confirmed. Check again later; the attestation will not be submitted again.",
|
||||
"certificateNotRequested": "No certificate has been requested. Select View certificate on the item trace page.",
|
||||
"certificateUnavailable": "Unable to check the certificate. Please try again later."
|
||||
},
|
||||
"field": {
|
||||
"viewFile": "View file"
|
||||
@@ -91,5 +110,9 @@
|
||||
"next": "Next"
|
||||
},
|
||||
"artist": "Artist",
|
||||
"lang": { "zh": "Simplified Chinese", "en": "English", "switch": "Switch language" }
|
||||
"lang": {
|
||||
"zh": "Simplified Chinese",
|
||||
"en": "English",
|
||||
"switch": "Switch language"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
{
|
||||
"app": { "name": "艺术品可信溯源" },
|
||||
"home": { "title": "艺术品可信溯源与认证", "hint": "请扫描艺术品上的防伪二维码以查看溯源信息" },
|
||||
"app": {
|
||||
"name": "艺术品可信溯源"
|
||||
},
|
||||
"home": {
|
||||
"title": "艺术品可信溯源与认证",
|
||||
"hint": "请扫描艺术品上的防伪二维码以查看溯源信息"
|
||||
},
|
||||
"anti": {
|
||||
"firstTitle": "正品 · 首次查询",
|
||||
"repeatTitle": "正品验证",
|
||||
@@ -57,7 +62,21 @@
|
||||
"explorer": "查看存证",
|
||||
"copy": "复制",
|
||||
"copied": "已复制",
|
||||
"notOnchain": "该作品暂未上链存证。"
|
||||
"notOnchain": "该作品暂未上链存证。",
|
||||
"certificateView": "查看证书",
|
||||
"certificateOpening": "正在打开…",
|
||||
"certificatePreview": "预览模式不生成证书。",
|
||||
"certificateRequestFailed": "暂时无法生成证书,请稍后再试或联系平台。",
|
||||
"certificateGenerating": "证书生成中,请稍候。完成后将自动打开天河链证书页面。",
|
||||
"certificateShared": "同一件实物仅生成一次,之后直接查看已有证书。",
|
||||
"certificateOpen": "打开证书",
|
||||
"certificateCheckAgain": "重新查询",
|
||||
"certificateBack": "返回",
|
||||
"certificateReady": "证书已就绪。",
|
||||
"certificateFailed": "存证申请未成功,请联系平台处理。",
|
||||
"certificateUnknown": "结果暂未确认。稍后可重新查询,系统不会重复提交存证。",
|
||||
"certificateNotRequested": "尚未申请证书,请从该实物溯源页点击“查看证书”。",
|
||||
"certificateUnavailable": "暂时无法查询证书,请稍后重试。"
|
||||
},
|
||||
"field": {
|
||||
"viewFile": "查看文件"
|
||||
@@ -91,5 +110,9 @@
|
||||
"next": "下一个"
|
||||
},
|
||||
"artist": "艺术家",
|
||||
"lang": { "zh": "简体中文", "en": "English", "switch": "切换语言" }
|
||||
"lang": {
|
||||
"zh": "简体中文",
|
||||
"en": "English",
|
||||
"switch": "切换语言"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ export default createRouter({
|
||||
routes: [
|
||||
{ path: '/', component: () => import('@/views/Home.vue') },
|
||||
{ path: '/trace/:code', component: () => import('@/views/Trace.vue') },
|
||||
{ path: '/certificate/:code', component: () => import('@/views/Certificate.vue') },
|
||||
// 后台预览模式:复用 Trace.vue,凭 ?token= 时间令牌访问,不激活/不计数
|
||||
{ path: '/trace/preview/:code', component: () => import('@/views/Trace.vue') },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<template>
|
||||
<main class="certificate-page">
|
||||
<section class="card certificate-card" aria-live="polite">
|
||||
<h1>{{ t('chain.certificateView') }}</h1>
|
||||
<p>{{ t(message) }}</p>
|
||||
<p class="muted">{{ t('chain.certificateShared') }}</p>
|
||||
<a v-if="url" class="action" :href="url" rel="noopener noreferrer">{{ t('chain.certificateOpen') }} →</a>
|
||||
<button v-else-if="retryable" class="action" :disabled="busy" @click="resume">{{ t('chain.certificateCheckAgain') }}</button>
|
||||
<button class="back" @click="router.back()">{{ t('chain.certificateBack') }}</button>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { fetchTraceCertificate, requestTraceCertificate } from '@/api';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const message = ref('chain.certificateGenerating');
|
||||
const retryable = ref(false);
|
||||
const busy = ref(false);
|
||||
const url = ref('');
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let stopped = false;
|
||||
let polls = 0;
|
||||
|
||||
async function poll() {
|
||||
if (stopped) return;
|
||||
try {
|
||||
const result = await fetchTraceCertificate(String(route.params.code));
|
||||
if (stopped) return;
|
||||
if (result.status === 'READY' && result.url) {
|
||||
url.value = result.url;
|
||||
message.value = 'chain.certificateReady';
|
||||
window.location.replace(result.url);
|
||||
return;
|
||||
}
|
||||
if (result.status === 'FAILED') { message.value = 'chain.certificateFailed'; return; }
|
||||
if (result.status === 'UNKNOWN') {
|
||||
message.value = 'chain.certificateUnknown'; retryable.value = true; return;
|
||||
}
|
||||
// A GET or link preview must never generate a certificate.
|
||||
if (result.status === 'NONE' && polls >= 5) { message.value = 'chain.certificateNotRequested'; return; }
|
||||
if (++polls >= 60) { message.value = 'chain.certificateUnknown'; retryable.value = true; return; }
|
||||
timer = setTimeout(poll, 5000);
|
||||
} catch {
|
||||
if (!stopped) { message.value = 'chain.certificateUnavailable'; retryable.value = true; }
|
||||
}
|
||||
}
|
||||
|
||||
async function resume() {
|
||||
if (busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
// Do not create a new request from this waiting page, even when opened directly.
|
||||
const state = await fetchTraceCertificate(String(route.params.code));
|
||||
if (state.status === 'NONE') { message.value = 'chain.certificateNotRequested'; retryable.value = false; return; }
|
||||
if (state.status === 'UNKNOWN') await requestTraceCertificate(String(route.params.code));
|
||||
polls = 0; retryable.value = false; message.value = 'chain.certificateGenerating';
|
||||
await poll();
|
||||
} catch { message.value = 'chain.certificateRequestFailed'; }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
onMounted(poll);
|
||||
onUnmounted(() => { stopped = true; if (timer) clearTimeout(timer); });
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.certificate-page { max-width: 600px; margin: 8vh auto; padding: 20px; }
|
||||
.certificate-card { padding: 28px; text-align: center; line-height: 1.7; }
|
||||
h1 { font-size: 23px; }
|
||||
.action, .back { display: block; margin: 20px auto 0; padding: 10px 18px; border-radius: 8px; font: inherit; cursor: pointer; }
|
||||
.action { color: white; background: var(--brand); border: none; text-decoration: none; }
|
||||
.back { background: transparent; border: 1px solid var(--border); color: var(--muted); }
|
||||
</style>
|
||||
@@ -84,6 +84,7 @@
|
||||
<template v-else-if="data">
|
||||
<trace-module-renderer
|
||||
:data="data"
|
||||
:short-code="String(route.params.code || '')"
|
||||
:layout="data.artwork.traceLayout"
|
||||
:timeline-items="timelineItems"
|
||||
:carousel-interval="carouselInterval"
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# 消费者按需出证:测试环境验证
|
||||
|
||||
日期:2026-09-20。此文记录本次实测与建议,不代表已实现新功能。
|
||||
|
||||
后续已按用户确认改为“消费者点击后生成,仅缓存证书网页链接”,实现和验证见 [消费者按需存证证书](./消费者按需存证证书.md)。以下保留最初兼容性实验结果。
|
||||
|
||||
## 用户入口
|
||||
|
||||
消费者扫码或点击追溯链接进入 C 端,在区块链信息区域主动点击生成/下载证书才触发。普通访问不调用出证服务;成功后复用缓存。调用天河链仍由服务端完成,密钥不发送到浏览器。
|
||||
|
||||
## 测试范围与结果
|
||||
|
||||
所有接口调用固定为 `https://test.api.tichain.tianhecloud.com`。使用 MemRelay 中专用测试凭据,创建合成测试内容;没有使用生产实物数据或生产域名,没有改动现有 NFT 发行流程。
|
||||
|
||||
1. 调用现有平台钱包身份查询成功。
|
||||
2. 调用 V2 `POST /api/v2/nfr/publish` 创建一个独立测试 NFT,使用新合约,不使用本地从生产导入的合约或流水。
|
||||
3. V2 交易确认返回 `status=0x0`、`blockNum=5926132`、`tokenId=0`。
|
||||
4. 使用同一钱包 address 与此次发行 operateId 调用 V3 查询,返回业务成功但存证字段为空;不能将外层成功判为记录已存在。
|
||||
5. V3 `GET /v1/deposit/certificate` 返回 HTTP 200,但业务 `code=400, success=false`,提示:出证失败,请检查对应操作id的存证操作成功。
|
||||
6. 对照:同一钱包使用独立 operateId 调用 V3 `POST /v1/deposit/text/save`,提交纯合成测试文本成功;随后出证返回 `code=200, success=true` 和证书页面 URL。
|
||||
7. 实际打开该 URL,网页显示区块链存证证书、文本、SHA256、交易哈希及下载按钮。返回值是 `https://test.tichain.tianhecloud.com/#/certificate?...` 网页,不是可直接作为 img.src 使用的图片资源。
|
||||
|
||||
发行 operateId:`avcert697127e9a12c`。
|
||||
|
||||
对照存证 operateId:`avdep213086e13050`。
|
||||
|
||||
测试结果表明:当前测试服务不能直接以 V2 发行 operateId 获取 V3 存证证书。钱包身份可以复用,业务存证记录需要单独建立。此结果不推断生产计费规则,也不排除服务方提供其他专用出证接口的可能。
|
||||
|
||||
## 建议实现
|
||||
|
||||
- C 端区块链详情弹窗增加按需生成入口;未点击时零新增存证/出证请求。
|
||||
- 按实物追溯码及证据版本建立独立存证记录;不可复用批量 NFT 发行分片的 operateId 作为单件证书编号。
|
||||
- 首次生成冻结证据快照,包含作品、实物追溯码及已有 NFT 交易的关联信息;按确定的文本/文件方案创建 V3 存证,再查询并出证。新证书的存证时间属于本次操作,不冒用旧 NFT 发行时间。
|
||||
- 用数据库唯一约束、稳定 operateId、任务状态与队列防重。请求超时后先查询原操作,禁止盲目换 ID 重提;下载失败只重试文件获取。
|
||||
- 成功后保存真实证书文件到平台存储,后续预览、下载复用。仅保存外部网页 URL 尚不足以实现图片缓存,需要继续验证官方网页下载方式与是否存在文件直链接口。
|
||||
- 普通页面读取不产生付费副作用;用户点击走 POST 创建任务,GET 仅查看本地状态/缓存。限制公开生成入口的并发、频率和每日新增数量,后台可关闭入口,避免被批量触发。
|
||||
- 保留现有 NFT 发行记录与跳转入口,新 V3 存证独立维护状态、哈希与环境。历史无 V3 记录的实物按需补建,不预先为所有实物生成。
|
||||
|
||||
目标应表述为“同一件实物、同一证据版本成功生成一次,后续复用”,不能承诺“总共只调用一次天河链接口”:实测正常流程至少涉及存证提交和出证,可能需要结果查询。付费范围和重复请求计费需服务方确认。
|
||||
|
||||
原始无密钥结果位于已被 Git 忽略的 `.deploy/local/certificate-probe-results.json`;实验脚本位于同目录 `probe-certificate.py`,凭据仅经标准输入传入,不写入该脚本或结果文件。
|
||||
|
||||
接口文档:<https://s.apifox.cn/0bded3d4-80fc-4deb-a520-eb1bf40a6e82/doc-2453118>,出证:<https://s.apifox.cn/0bded3d4-80fc-4deb-a520-eb1bf40a6e82/api-81679596>。
|
||||
@@ -0,0 +1,53 @@
|
||||
# 消费者按需存证证书
|
||||
|
||||
## 一物一证
|
||||
|
||||
`Artwork` 是款式档案,`TraceCode` 是每件实物,`BlockchainProof.traceCodeId` 唯一。NFT 发行可批量提交,但结果按每个实物分别关联。V3 存证证书也以实物为单位,不与同款其他实物共用,不使用 NFT 批次请求编号。
|
||||
|
||||
## 消费者使用
|
||||
|
||||
扫码页的区块链模块底部,在“查看存证”右侧增加“查看证书”。仅已激活、正常、已审核通过且 NFT 已确认的天河链实物可申请。普通页面打开、刷新与证书状态 GET 都不会提交存证;后台预览模式按钮禁用,不产生付费副作用。
|
||||
|
||||
点击后立即打开等待页,由原页面 POST 申请。任务完成后等待页跳转到官方证书网页;浏览器阻止弹窗时改用当前页面等待。再次点击直接读取数据库已有链接,未重复生成。官方网页提供证书展示及下载,不保存图片到本平台。
|
||||
|
||||
首次点击固定作品名称、作者、档案编号、实物追溯码、NFT 交易哈希及本次记录时间,提交 V3 文本存证。文本以中文标签呈现,不上传作品图片或生产配置。证书证明的是本次提交的文本快照,作品后续编辑不自动重生成。证书 V3 哈希和生成时间独立于原 NFT 发行哈希/时间。
|
||||
|
||||
## 服务端状态与恢复
|
||||
|
||||
状态保存在已有 `BlockchainProof` 的新增字段中:
|
||||
|
||||
```text
|
||||
NONE -> PENDING -> SUBMITTING -> WAITING -> CHECKING -> READY
|
||||
| |
|
||||
+-> WAITING +-> WAITING / UNKNOWN
|
||||
+-> FAILED(明确拒绝)
|
||||
```
|
||||
|
||||
- 首次申请使用数据库事务、配额行锁与单件凭据唯一约束,避免并发创建多份存证。
|
||||
- 请求快照包含固定 `operateId`、环境、App ID、钱包地址和原文,不含密钥。
|
||||
- 定时 Worker 每 5 秒检查已持久化任务,使用数据库租约和 CAS 防止多个进程同时处理同一条;不会扫描未申请的实物生成证书。
|
||||
- 提交前先写 `SUBMITTING`。超时、连接中断、崩溃恢复时一律仅查询原操作,不创建新编号、不重新提交;查询一轮最多 8 次,未就绪进入 `UNKNOWN`,消费者稍后可点击继续查询。
|
||||
- 远端明确拒绝进入 `FAILED`,需平台排查,不允许消费者无限重提。
|
||||
- 凭据、钱包或环境变更会暂停当前任务,不会把测试操作切到正式环境执行。
|
||||
- 官方链接仅允许对应环境天河链证书页;校验钱包、哈希、文本摘要后保存,并正确编码文本中的 URL 特殊字符。
|
||||
- 数据备份包含证书状态、请求快照和 URL。恢复进行中的证书时转入 `UNKNOWN`,避免备份前后不确定的外部副作用被再次提交。
|
||||
|
||||
## 成本控制
|
||||
|
||||
后台“系统设置 → 区块链”提供“扫码页按需出证”和“每日新增证书上限”。默认开启,上限 100;可设置 0 或关闭开关暂停新增,已生成链接仍可读取。每日配额按北京时间计算,数据库保存计数,不依赖 Redis 缓存。额度计算为首次申请数,失败申请也计入,避免错误或恶意流量反复消耗。
|
||||
|
||||
公开 POST 每 IP 每分钟最多 5 次,状态 GET 每 IP 每分钟最多 60 次。任务内部提交、查询、出证是多个 API 请求,“一次生成”不表示仅一次 HTTP 调用。
|
||||
|
||||
## 部署
|
||||
|
||||
新增迁移 `20260920020000_on_demand_certificate` 仅为 `blockchain_proof` 添加字段和索引,不重建业务表。支持当前 MySQL 5.7/8 基线。生产升级前照常备份,执行迁移后启动新版本;旧记录默认 `NONE`,不批量补证。
|
||||
|
||||
本地使用 `docker/compose.local.yml` 与专用测试天河链配置,正式天河链域名被映射到容器 loopback。线上宝塔/PM2 未部署本功能。
|
||||
|
||||
## 验证
|
||||
|
||||
- API 全套 35 组 / 285 用例通过,包含未知结果恢复、防重、证据摘要与 URL 特殊字符用例。
|
||||
- shared、API、admin、client 镜像构建通过。
|
||||
- 本地测试实物 `477238000001` 已通过消费者按钮生成证书;`295708006702`、`278977006682` 完成中文证据与并发实测。最终为 5698 条 NONE、3 条 READY,其余实物没有自动生成。
|
||||
- 最终并发首次申请实测:两个请求均返回 PENDING,但只保存一份请求快照、生成一张证书,每日配额仅增加 1;开关关闭及配额为 0 均阻止新申请,GET、重复查看和服务重启保持缓存链接及生成时间不变。
|
||||
- V2 发行 operateId 无法直接获得 V3 证书的测试结论见《天河链按需出证测试结论》。
|
||||
Reference in New Issue
Block a user