feat: 天河链升级为存证+发行(NFT)双层,新增轮换 UserKey 与 C 端 tokenId 展示

- 上链流程:upload 存证 → publish 铸 NFT → 接口9确认 mint → ONCHAIN,记录 tokenId/合约地址
- blockchain_proof 加 token_id/contract_address 字段(迁移),schema 补 VarChar 注解消除 drift
- TianheProvider 新增 publish/updateUserKey;合约地址与 maxTokenId 存系统设置维护 baseTokenId
- 轮换 UserKey:接口7 + 设置页「轮换密钥」(二次确认+回显强提示+操作日志)
- C 端区块链卡展示数字藏品编号(tokenId)与合约地址
- 测试环境全链路实测通过;媒体上链层级待甲方确认,暂维持 JSON 存证
- docs/天河链文档.md 标注以 APIFox 为准并列勘误
This commit is contained in:
Nixevol
2026-07-10 11:35:44 +08:00
parent f902fd0b9f
commit e644e38ff3
19 changed files with 285 additions and 35 deletions
+1
View File
@@ -139,6 +139,7 @@ export const settingsApi = {
post<{ userId: string; address: string }>('/settings/tianhe/verify', data),
tianheIdentity: () => get<{ userId: string; address: string; userKeyMasked: string }>('/settings/tianhe/identity'),
tianheReveal: () => post<{ userId: string; userKey: string; address: string }>('/settings/tianhe/identity/reveal', {}),
tianheRotate: () => post<{ userId: string; userKey: string; address: string }>('/settings/tianhe/identity/rotate', {}),
};
export const storageApi = {
+4
View File
@@ -552,6 +552,10 @@
"tianheRegister": "Register Identity",
"tianheReRegister": "Re-verify Identity",
"tianheManualEntry": "Manual Entry",
"tianheRotate": "Rotate Key",
"tianheRotateConfirmTitle": "Rotate User Key",
"tianheRotateConfirmContent": "A new User Key will be generated for the platform custodial wallet and updated on-chain; the old Key becomes invalid immediately. Be sure to save the new Key offline afterwards. Continue?",
"tianheRotateDone": "User Key rotated",
"tianheReveal": "Reveal",
"tianheHide": "Hide",
"tianheRevealConfirmTitle": "Reveal User Key",
+4
View File
@@ -552,6 +552,10 @@
"tianheRegister": "注册链上身份",
"tianheReRegister": "重新确认身份",
"tianheManualEntry": "手动录入",
"tianheRotate": "轮换密钥",
"tianheRotateConfirmTitle": "轮换 User Key",
"tianheRotateConfirmContent": "将为平台托管钱包生成新的 User Key 并在链上修改,旧 Key 立即失效。操作后请务必离线保存新 Key。确认继续?",
"tianheRotateDone": "User Key 已轮换",
"tianheReveal": "揭示",
"tianheHide": "隐藏",
"tianheRevealConfirmTitle": "揭示 User Key",
+30
View File
@@ -124,6 +124,7 @@
{{ identity.address ? t('pages.settings.tianheReRegister') : t('pages.settings.tianheRegister') }}
</n-button>
<n-button size="small" @click="manualEntryVisible = true">{{ t('pages.settings.tianheManualEntry') }}</n-button>
<n-button v-if="identity.userKeyMasked" size="small" :loading="rotatingIdentity" @click="rotateUserKey">{{ t('pages.settings.tianheRotate') }}</n-button>
</div>
</div>
<div class="setting-row">
@@ -257,6 +258,7 @@ const migratingStorage = ref(false);
const confirmingStorage = ref(false);
const registeringIdentity = ref(false);
const verifyingIdentity = ref(false);
const rotatingIdentity = ref(false);
const revealKey = ref(false);
const manualEntryVisible = ref(false);
const identity = reactive({ userId: '', userKey: '', userKeyMasked: '', address: '' });
@@ -417,6 +419,34 @@ async function registerIdentity() {
}
}
// 轮换 User Key:二次确认 → 链上修改 → 回显新 key 强提示离线保存
function rotateUserKey() {
dialog.warning({
title: t('pages.settings.tianheRotateConfirmTitle'),
content: t('pages.settings.tianheRotateConfirmContent'),
positiveText: t('common.action.confirm'),
negativeText: t('common.action.cancel'),
onPositiveClick: async () => {
rotatingIdentity.value = true;
try {
const res = await settingsApi.tianheRotate();
identity.userId = res.userId;
identity.userKey = res.userKey;
identity.userKeyMasked = res.userKey ? `${res.userKey.slice(0, 3)}******${res.userKey.slice(-3)}` : '';
identity.address = res.address;
revealKey.value = true;
dialog.warning({
title: t('pages.settings.tianheRotateDone'),
content: t('pages.settings.tianheSaveKeyWarning', { userId: res.userId, userKey: res.userKey }),
positiveText: t('common.action.confirm'),
});
} finally {
rotatingIdentity.value = false;
}
},
});
}
async function verifyIdentity() {
verifyingIdentity.value = true;
try {
@@ -0,0 +1,4 @@
-- 存证+发行模式:记录铸造的 NFT TokenId 与合约地址
ALTER TABLE `blockchain_proof`
ADD COLUMN `token_id` BIGINT NULL,
ADD COLUMN `contract_address` VARCHAR(191) NULL;
+17 -15
View File
@@ -344,18 +344,20 @@ model TraceCodeDailySequence {
}
model BlockchainProof {
id Int @id @default(autoincrement())
traceCodeId BigInt @map("trace_code_id")
dataHash String @map("data_hash")
txHash String? @map("tx_hash")
blockHash String? @map("block_hash")
blockHeight BigInt? @map("block_height")
chainName String? @map("chain_name")
explorerUrl String? @map("explorer_url")
onchainAt DateTime? @map("onchain_at")
status ProofStatus @default(PENDING)
rawResponse Json? @map("raw_response")
createdAt DateTime @default(now()) @map("created_at")
id Int @id @default(autoincrement())
traceCodeId BigInt @map("trace_code_id")
dataHash String @map("data_hash")
txHash String? @map("tx_hash")
blockHash String? @map("block_hash")
blockHeight BigInt? @map("block_height")
chainName String? @map("chain_name")
explorerUrl String? @map("explorer_url")
tokenId BigInt? @map("token_id")
contractAddress String? @map("contract_address")
onchainAt DateTime? @map("onchain_at")
status ProofStatus @default(PENDING)
rawResponse Json? @map("raw_response")
createdAt DateTime @default(now()) @map("created_at")
traceCode TraceCode @relation(fields: [traceCodeId], references: [id], onDelete: Cascade)
@@ -415,7 +417,7 @@ model OperationLog {
module String
action String
method String
path String
path String @db.VarChar(512)
targetId String? @map("target_id")
status String
message String? @db.Text
@@ -439,7 +441,7 @@ model OutboundImportSession {
id String @id @default(cuid())
status OutboundImportSessionStatus @default(PARSING)
fileName String @map("file_name")
fileKey String? @map("file_key")
fileKey String? @map("file_key") @db.VarChar(512)
total Int @default(0)
validCount Int @default(0) @map("valid_count")
invalidCount Int @default(0) @map("invalid_count")
@@ -488,7 +490,7 @@ model OutboundImportRow {
model BackupRecord {
id String @id @default(cuid())
fileName String @map("file_name")
filePath String @map("file_path")
filePath String @map("file_path") @db.VarChar(1024)
size BigInt @default(0)
status BackupStatus @default(PENDING)
mode String @default("BACKUP")
@@ -48,7 +48,11 @@ export class AttestationService {
traceCodeId,
dataHash,
status: ProofStatus.PENDING,
rawResponse: { requestMeta: summary },
rawResponse: {
requestMeta: summary,
// 发行 NFT 用的产品信息(天河链:productId=追溯码、name=作品名、author=艺术家)
product: { productId: code.shortCode, name: code.artwork.title, author: code.artwork.artist ?? undefined },
},
},
});
// 入队失败(如 Redis 抖动)时把 proof 标记 FAILED,避免留下永远处理不了的 PENDING 悬挂记录
+93 -1
View File
@@ -42,16 +42,79 @@ export class BlockchainService {
this.logger.log(`区块链存证驱动:${provider.name}`);
if (provider instanceof TianheProvider) {
await this.ensureTianheWallet(provider);
return this.attestWithTianhe(provider, payload);
}
return provider.attest(payload);
}
// 天河链「存证 + 发行」双层:① upload 存证 JSON(拿存证哈希/digest/存证链接)
// ② publish 铸 1 个 NFT(productId=追溯码、feature=存证链接)→ mint 交易可经接口 9 确认拿区块信息。
// 合约地址与已发行最大 tokenId 存系统设置(上链队列串行,无并发争用)。
private async attestWithTianhe(provider: TianheProvider, payload: AttestPayload): Promise<AttestResult> {
const attest = await provider.attest(payload);
if (!payload.product) return attest; // 无产品信息时退化为纯存证(防御,正常流程总是携带)
const settings = await this.settings.getAllRaw();
const contractAddress = (settings.tianheContractAddress || '').trim() || undefined;
const maxTokenId = settings.tianheMaxTokenId?.trim() ? Number(settings.tianheMaxTokenId) : undefined;
const pub = await provider.publish({
productId: payload.product.productId,
name: payload.product.name,
author: payload.product.author,
feature: attest.explorerUrl ?? undefined,
contractAddress,
// 官方要求:指定 contractAddress 时 baseTokenId 须为「已发行 tokenId 的最大值」
baseTokenId: contractAddress ? maxTokenId : undefined,
operateId: `av${Date.now().toString(36)}${randomBytes(3).toString('hex')}`,
});
await this.settings.setRaw('tianheContractAddress', pub.contractAddress);
if (pub.tokenId >= 0) {
await this.recordTianheMaxTokenId(pub.tokenId);
}
this.logger.log(`天河链发行完成:contract=${pub.contractAddress} tokenId=${pub.tokenId} mintTx=${pub.txHash}`);
return {
dataHash: payload.dataHash,
// 主凭据切换为 mint 交易(可确认、有区块信息、tokenId 资产语义);存证交易哈希保留在 raw.attestTxHash
txHash: pub.txHash,
blockHash: null,
blockHeight: null,
chainName: '天河链',
explorerUrl: attest.explorerUrl,
tokenId: pub.tokenId >= 0 ? pub.tokenId : null,
contractAddress: pub.contractAddress,
onchainAt: new Date(),
raw: {
...attest.raw,
attestTxHash: attest.txHash,
publishResponse: pub.raw,
transactionStatus: 'submitted',
transactionStatusNote: '存证已生效(upload);NFT 铸造交易已提交,等待接口 9 确认区块信息。',
},
confirmationRequired: true,
};
}
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
const provider = await this.buildProvider();
if (!provider.confirmTransaction) {
return { confirmed: true, txHash, raw: { provider: provider.name, transactionStatus: 'confirmed' } };
}
return provider.confirmTransaction(txHash);
const result = await provider.confirmTransaction(txHash);
// mint 待处理(发行时 tokenId=-1)的场景:确认查询返回真实 tokenId 后补记已发行最大值
const tokenId = Number((result.raw as { tokenId?: string | number })?.tokenId ?? NaN);
if (result.confirmed && Number.isInteger(tokenId) && tokenId >= 0) {
await this.recordTianheMaxTokenId(tokenId);
}
return result;
}
private async recordTianheMaxTokenId(tokenId: number): Promise<void> {
const settings = await this.settings.getAllRaw();
const current = settings.tianheMaxTokenId?.trim() ? Number(settings.tianheMaxTokenId) : -1;
if (tokenId > current) {
await this.settings.setRaw('tianheMaxTokenId', String(tokenId));
}
}
// ===== 天河链链上身份(userId/userKey/钱包地址)生命周期 =====
@@ -103,6 +166,35 @@ export class BlockchainService {
return { userId: uid, address };
}
// 轮换 userKey(接口 7):生成新随机 key → 链上修改 → 持久化。旧 key 立即失效,
// 返回明文新 key 供管理员立即离线保存(天河链不留存 userKey)。
async rotateTianheUserKey(): Promise<{ userId: string; userKey: string; address: string }> {
const settings = await this.settings.getAllRaw();
if (!settings.tianheAppId || !settings.tianheAppKey) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '请先填写并保存天河链 App ID / App Key');
}
const userId = (settings.tianheUserId || '').trim();
const oldKey = (settings.tianheUserKey || '').trim();
if (!userId || !oldKey) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '尚未注册链上身份,无法轮换 User Key');
}
const newKey = randomBytes(32).toString('hex');
const provider = this.buildTianheProvider(settings, userId, oldKey);
try {
await provider.updateUserKey(newKey);
} catch (e) {
throw new BusinessException(ErrorCode.BAD_REQUEST, (e as Error).message);
}
// 链上已生效,必须立即持久化新 key(此处失败将导致钱包失联,故不允许静默)
await this.settings.setRaw('tianheUserKey', newKey);
// 用新 key 校验一次,确保链上与本地一致
const verify = this.buildTianheProvider(settings, userId, newKey);
const { address } = await verify.userInfo();
await this.settings.setRaw('tianheWalletAddress', address);
this.logger.warn(`天河链 User Key 已轮换(userId=${userId}),请立即离线保存新 Key`);
return { userId, userKey: newKey, address };
}
// 揭示明文 userKey(管理员离线备份用;该值本就明文存库,不加密的理由见 settings.service)
async revealTianheUserKey(): Promise<{ userId: string; userKey: string; address: string }> {
const settings = await this.settings.getAllRaw();
@@ -1,6 +1,8 @@
export interface AttestPayload {
dataHash: string;
meta?: Record<string, unknown>;
// 发行 NFT 用的产品信息(天河链 publish:productId=追溯码、name=专题名≤42、author≤120)
product?: { productId: string; name: string; author?: string };
}
export interface AttestResult {
@@ -10,6 +12,8 @@ export interface AttestResult {
blockHeight?: number | null;
chainName: string;
explorerUrl?: string | null;
tokenId?: number | null;
contractAddress?: string | null;
onchainAt: Date;
raw: Record<string, unknown>;
confirmationRequired?: boolean;
@@ -23,6 +23,14 @@ function requestMeta(raw: unknown): Record<string, unknown> | undefined {
return meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : undefined;
}
function productInfo(raw: unknown): { productId: string; name: string; author?: string } | undefined {
if (!raw || typeof raw !== 'object') return undefined;
const product = (raw as Record<string, unknown>).product as { productId?: string; name?: string; author?: string } | undefined;
return product?.productId && product?.name
? { productId: product.productId, name: product.name, author: product.author }
: undefined;
}
function rawObject(raw: unknown): Record<string, unknown> {
return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
}
@@ -58,6 +66,7 @@ export class OnchainProcessor extends WorkerHost {
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 },
@@ -68,6 +77,8 @@ export class OnchainProcessor extends WorkerHost {
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),
@@ -116,6 +127,8 @@ export class OnchainProcessor extends WorkerHost {
`响应=${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: {
@@ -126,6 +139,8 @@ export class OnchainProcessor extends WorkerHost {
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),
@@ -264,6 +264,54 @@ export class TianheProvider implements AttestationProvider {
};
}
// 接口 2「数字商品发行」:铸造 NFT 并派发到平台钱包。合约地址/baseTokenId 由调用方(BlockchainService)管理。
// 注意:operateId 限 20 字符;返回 tokenId=-1 表示交易待处理(需经接口 9 用 transactionHash 查询)。
async publish(params: {
productId: string;
name: string;
author?: string;
feature?: string;
contractAddress?: string;
baseTokenId?: number;
operateId?: string;
}): Promise<{ contractAddress: string; tokenId: number; txHash: string; raw: Record<string, unknown> }> {
const body: Record<string, unknown> = {
...this.credentials(),
productIds: [params.productId],
name: params.name.slice(0, 42),
pieceCount: 1,
};
if (params.author) body.author = params.author.slice(0, 120);
if (params.feature) body.feature = params.feature.slice(0, 500);
if (params.contractAddress) {
body.contractAddress = params.contractAddress;
if (params.baseTokenId !== undefined) body.baseTokenId = params.baseTokenId;
}
if (params.operateId) body.operateId = params.operateId.slice(0, 20);
const raw = await this.postJson('/api/v2/nfr/publish', body, '天河链数字商品发行');
const data = assertOk(raw, '天河链数字商品发行');
const contractAddress = pickString(data, ['contractAddress']);
const products = Array.isArray(data.products) ? (data.products as Array<Record<string, unknown>>) : [];
const product = products[0];
const txHash = product ? pickString(product, ['transactionHash', 'txHash']) : null;
const tokenId = product ? pickNumber(product, ['tokenId']) : null;
if (!contractAddress || !txHash) {
throw new Error('天河链数字商品发行失败:响应缺少 contractAddress 或 transactionHash');
}
return { contractAddress, tokenId: tokenId ?? -1, txHash, raw };
}
// 接口 7「用户链上身份秘钥修改」:轮换托管钱包 userKey(旧 key 立即失效,调用方须持久化新 key)。
async updateUserKey(newUserKey: string): Promise<void> {
const raw = await this.postJson(
'/api/v2/user/update',
{ ...this.credentials(), newUserKey: required(newUserKey, 'New User Key') },
'天河链秘钥修改',
);
assertOk(raw, '天河链秘钥修改');
}
// 接口 9「根据交易哈希查询」:确认交易是否已进块。
// 联调确认(2026-07-09 测试环境):接口为 GET 但参数须走「请求体 JSON」,query 方式返回「Required request body is missing」。
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
@@ -210,6 +210,8 @@ export class PublicTraceService {
chainName: proof.chainName,
onchainAt: proof.onchainAt,
explorerUrl: proof.explorerUrl,
tokenId: proof.tokenId,
contractAddress: proof.contractAddress,
}
: null,
};
@@ -69,4 +69,12 @@ export class SettingsController {
revealTianheIdentity() {
return this.blockchain.revealTianheUserKey();
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Post('tianhe/identity/rotate')
@ApiOperation({ summary: '轮换天河链 User Key(旧 key 立即失效,返回新 key 明文供离线保存)' })
rotateTianheUserKey() {
return this.blockchain.rotateTianheUserKey();
}
}
+2
View File
@@ -28,6 +28,8 @@
"code": "Trace Code",
"hash": "Tx Hash",
"dataHash": "Data Hash",
"tokenId": "Token ID",
"contract": "Contract",
"blockHeight": "Block Height",
"onchainAt": "On-chain Time",
"explorer": "View Proof",
+2
View File
@@ -28,6 +28,8 @@
"code": "唯一追溯码",
"hash": "交易哈希",
"dataHash": "数据哈希",
"tokenId": "数字藏品编号",
"contract": "合约地址",
"blockHeight": "区块高度",
"onchainAt": "上链时间",
"explorer": "查看存证",
+14
View File
@@ -310,6 +310,20 @@
</svg>
</button>
</div>
<div v-if="data.blockchain.tokenId !== null && data.blockchain.tokenId !== undefined" class="chain-row">
<span class="chain-k">{{ t('chain.tokenId') }}</span>
<span class="chain-v mono">{{ data.blockchain.tokenId }}</span>
</div>
<div v-if="data.blockchain.contractAddress" class="chain-row">
<span class="chain-k">{{ t('chain.contract') }}</span>
<span class="chain-v mono">{{ ellipsis(data.blockchain.contractAddress) }}</span>
<button class="icon-copy" :aria-label="t('chain.copy')" :title="t('chain.copy')" @click="copy(data.blockchain.contractAddress)">
<svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true">
<rect x="9" y="9" width="11" height="11" rx="2" fill="none" stroke="currentColor" stroke-width="1.7" />
<path d="M5 15V5a2 2 0 0 1 2-2h8" fill="none" stroke="currentColor" stroke-width="1.7" />
</svg>
</button>
</div>
<div class="chain-row">
<span class="chain-k">{{ t('chain.blockHeight') }}</span>
<span class="chain-v">{{ data.blockchain.blockHeight ?? '-' }}</span>