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:
@@ -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 悬挂记录
|
||||
|
||||
@@ -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> {
|
||||
|
||||
Reference in New Issue
Block a user