diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 049a5bb..d38fdc3 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -246,6 +246,7 @@ - 完善版分支 dev/qa-polish(2026-07-09,从 dev/qa-fix 分出):在保守版基础上实现「待完善清单」中收益明确的项。① P-2 admin bundle 拆分:`apps/admin/vite.config.ts` 加 `build.rollupOptions.output.manualChunks`(naive/echarts/vendor 独立 chunk),`index` chunk 从 ~1652KB 降到 ~69KB、Dashboard 从 474KB 降到 10KB,第三方库独立缓存。② P-3 揭示 userKey 加固:`GET /settings/tianhe/identity` 改为只回 `userKeyMasked`(不再 GET 明文);新增 `POST /settings/tianhe/identity/reveal` 回明文——POST 使其被操作日志记录、避免缓存;前端揭示前二次确认(`Settings.vue` `revealUserKey`),实测揭示动作已落操作日志。P-1(天河链 confirm status 偶发 500)、P-4(C 端骨架屏)判定为过度设计,保持现状。三分支:`dev/refine`(基线未动)、`dev/qa-fix`(保守版,严守红线)、`dev/qa-polish`(本分支,含 P-2/P-3 完善)。验证:4 包构建 + 27 单测通过。 - 天河链存证缺口发现(2026-07-10):用户追问「upload 是否上传了媒体文件」——没有,我方上传的是 ~1KB 存证 JSON;核对发现更实质的缺口:`attestation.service.ts` 的 summary **不含任何媒体内容哈希**(artwork.images 连引用都没有、outImages 仅存储 key、certificates 仅名称),媒体被替换链上存证不变,媒体内容不在防篡改闭环内。改进层级 L1(媒体 sha256 入证,零成本,建议至少做)/ L2(关键媒体本体上链 UDFS)/ L3(全量上链)已补进 `aidocs/天河链对接分析与建议.md` §4.5,与方案 A/B 正交,待用户拍板。 +- 天河链方案 B 落地(存证+发行+轮换,2026-07-10,dev/refine):按甲方决策「其余全做、媒体待定」实现。① 数据模型:`blockchain_proof` 加 `token_id`/`contract_address`(迁移 `20260710110000_add_proof_token_fields`);schema 补 `@db.VarChar` 注解消除历史 drift(operation_log.path 512 / outbound_import_session.file_key 512 / backup_record.file_path 1024)。② `TianheProvider` 新增 `publish`(接口2,operateId≤20,name≤42,author≤120,feature≤500)与 `updateUserKey`(接口7)。③ `BlockchainService.attestWithTianhe`:upload 存证→publish 铸 1 NFT(productId=追溯码、feature=存证链接)→ 主 txHash 切为 mint 交易、confirmationRequired=true 走接口9确认→ONCHAIN;合约地址存 `tianheContractAddress`、已发行最大 tokenId 存 `tianheMaxTokenId`(指定合约时作 baseTokenId,队列串行无争用);缺 product 时退化纯存证。`confirmTransaction` 确认成功回填 tokenId、更新 maxTokenId。④ `rotateTianheUserKey`:生成新随机 key→接口7链上改→持久化→接口8校验地址,`/settings/tianhe/identity/rotate` + 设置页「轮换密钥」(二次确认+回显强提示)。⑤ C 端:public-trace + Trace.vue 区块链卡增 tokenId/合约地址展示(i18n chain.tokenId/chain.contract)。⑥ 实测(测试环境):追溯码 412680781069 走通 upload→publish(合约 0xc96ae8a4... tokenId=0)→确认(区块高度 5820347)→ONCHAIN,C 端展示数字藏品编号 0/合约地址/区块高度;轮换 UserKey 成功(钱包地址不变),新 key 回填测试文档。验证:4 包构建 + 27 单测通过。**唯一待定:媒体上链层级 L1/L2/L3 待甲方确认「链上放什么」,当前维持 JSON 存证。** - 天河链决策文档(2026-07-10):完整分析沉淀为 `aidocs/天河链对接分析与建议.md`——含当前实现状态、官方文档勘误(接口5路径/status语义/operateId限20字符/upload链接定位)、三个哈希与地址的概念澄清、11 接口逐一评估表、方案 A(纯存证,现状)vs 方案 B(存证+发行 NFT,已实测可行)对比与建议、优先级建议清单(计费确认为最高优先)、已定稿事项。等待用户对方案 A/B 与「轮换 UserKey」拍板。 - 天河链全接口分析与实测(2026-07-10,dev/refine):依据 APIFox 官方文档(11 接口,比语雀 md 准确)+ 测试环境全链路实测(publish 铸 NFT→接口9/5 确认→token/query→burn,测试数据已清理)。**勘误**:接口 5 真实路径是 `/api/v2/nfr/transaction/detail`(语雀 md 少了 `/nfr`);接口 9 `status` 官方语义「"0x0"=成功,否则失败」(已修正 `confirmTransaction` 判定:status 非 0x0 → `transactionStatus:'failed'`);publish `operateId` 限 20 字符。**结论**:确认接口 9/5 对 mint 等 token 交易完全正常(拿 blockHash/blockNum/tokenId),仅对纯存证 upload 交易结构性 500。完整分析与「存证+发行」升级方案(每物铸 NFT:productId=追溯码、feature=存证链接、mint 可确认拿区块信息)已记录到 `aidocs/代码审查问题清单.md`「天河链全接口适用性分析」,等待用户决策;user/update 轮换 UserKey 建议接入(同待拍板)。 - 天河链存证确认策略定稿(2026-07-10,dev/qa-polish):实测确认接口对**纯存证(upload)交易结构性不适用**——接口 9 与接口 5(全部 methodName)对 upload 交易一律返回 `500 "Index: 3, Size: 1"`(服务端按 token 交易结构解析导致数组越界),非偶发。官方文档对 upload 的定义即「获得链上存证哈希 + 数字商品唯一哈希 + 存证链接」,无确认环节。定稿:`TianheProvider.attest` 改 `confirmationRequired=false`(upload 成功=存证生效,直接 ONCHAIN),凭据 = txHash + digest + UDFS 存证链接(`udfs/Qm...` 是天河链上分布式文件存储的内容寻址地址,可公开访问、内容即存证 JSON;它不是钱包地址也不是浏览器交易页)。概念区分:钱包地址=注册返回的 0x…(链上身份)、txHash=存证交易哈希、udfs url=存证文件链上 URI;区块浏览器为 test.explorer.tianhecloud.com。存量 CONFIRMING 已修正 ONCHAIN;确认循环代码保留(未来 token 类交易可用)。 diff --git a/aidocs/天河链对接分析与建议.md b/aidocs/天河链对接分析与建议.md index 39d2564..128c3d4 100644 --- a/aidocs/天河链对接分析与建议.md +++ b/aidocs/天河链对接分析与建议.md @@ -13,7 +13,8 @@ | --- | --- | --- | | 平台托管钱包注册(接口 1)/ 身份查询(接口 8) | `TianheProvider.registerUser / userInfo / ensureRegistered`,attest 前幂等确保钱包存在 | ✅ 测试环境实测通过,钱包 `0x4783234c...748f494` | | 元数据上链存证(接口 6 upload) | 手工构造 multipart(userDto 无 filename + `application/json`),严格校验 `code===0` 且必须返回 `transactionHash` | ✅ 实测通过,两码各得独立 txHash | -| 存证确认策略 | upload 成功即 ONCHAIN(确认接口对纯存证交易结构性不适用,见下文) | ✅ 定稿 | +| 存证 + 发行(方案 B) | upload 存证 → publish 铸 NFT → 接口 9 确认 mint → ONCHAIN;记录 tokenId/合约地址;C 端展示 | ✅ 已实现并实测通过 | +| 轮换 User Key(接口 7) | 设置页「轮换密钥」,二次确认 + 链上修改 + 回显新 key,操作日志留痕 | ✅ 已实现并实测通过 | | 链上身份生命周期(T8) | userId/userKey 明文存库(备份跨重装可恢复)、设置页注册/显示地址/揭示(二次确认+操作日志)/手动录入(经接口 8 校验) | ✅ 全部实现 | | API 调用链路日志 | 每次调用打印 URL/方法/发送数据/返回结果,appKey/userKey 脱敏 | ✅ 已实现 | | 单平台钱包决策 | 全平台一个托管钱包(公证者身份),每件实物独立存证(txHash/digest/链接均每物唯一) | ✅ 定稿并验证 | @@ -66,7 +67,7 @@ **影响**:上链后若作品图片/证书图被替换,链上存证不变、无法发现——媒体内容不在防篡改闭环内,对"可信溯源"平台是防伪语义上的实质弱点。 -**改进层级(待拍板)**: +**改进层级(⏳ 待甲方确认「链上放什么」后再做,见 §七)**: | 层级 | 做法 | 链上有什么 | 成本 | | --- | --- | --- | --- | @@ -99,26 +100,34 @@ - 合约与 tokenId 管理:首铸返回 `contractAddress` 存系统设置;后续分批铸造需传 `contractAddress` 且 `baseTokenId` 须为已发行最大值(上链走队列串行,用系统设置维护即可,风险可控); - **计费需确认**:发行(合约部署+铸造)是否比纯存证产生额外费用,需向天河链商务确认。 -### 建议 +### 决策结果:已采用方案 B(存证 + 发行),并已实现落地 -- 若甲方只要求「防伪存证可验真」:**方案 A 已满足**,维持现状。 -- 若甲方期望「每件实物有完整链上数字身份(tokenId/区块信息/资产语义)」或宣传上需要"一物一链上资产":**建议升级方案 B**,技术上已实测可行,改造范围集中在 `onchain.processor` + `tianhe.provider`(新增 publish/确认接入)+ 系统设置(合约地址与 tokenId 维护)+ C 端展示(增加 tokenId/合约地址)。 -- 无论选哪个方案,都建议先向天河链确认**生产环境计费口径**(upload 次数计费?publish 计费?)后再放量。 +**已于 2026-07-10 在 `dev/refine` 实现并经测试环境全链路实测通过**: +- 上链流程:`BlockchainService.attestWithTianhe` = upload 存证 → publish 铸 1 个 NFT(productId=追溯码、name=作品名、author=艺术家、feature=存证链接)→ 接口 9 确认 mint → ONCHAIN。 +- 数据模型:`blockchain_proof` 加 `token_id`/`contract_address`(迁移 `20260710110000_add_proof_token_fields`);合约地址与已发行最大 tokenId 存系统设置(`tianheContractAddress`/`tianheMaxTokenId`,队列串行维护 baseTokenId)。 +- C 端:区块链卡新增「数字藏品编号(tokenId)」「合约地址」展示。 +- 实测:追溯码 `412680781069` 走通 upload→publish(合约 `0xc96ae8a4...` tokenId=0)→确认(区块高度 5820347)→ONCHAIN,C 端正确展示。 + +> 保留说明:`attestWithTianhe` 在缺 product 信息时退化为纯存证;默认走方案 B。 ## 六、其余建议清单(按优先级) -| 优先级 | 建议 | 说明 | +| 优先级 | 建议 | 状态 | | --- | --- | --- | -| 高 | 与天河链确认生产计费口径 | upload/publish 的计费方式直接影响方案选择与放量节奏 | -| 高 | 决策方案 A/B(见第五节) | 影响上链流程、数据模型(是否存 tokenId/contractAddress)与 C 端展示 | -| 中 | 接入接口 7「轮换 User Key」 | 设置页增加轮换入口(调 user/update 成功后更新本地存储+提示离线保存新 key);密钥泄漏时的止损手段 | -| 中 | 生产接入检查单 | 换生产 AppID/AppKey → 生产环境重新注册钱包(勿沿用测试钱包)→ 离线保存新 userId/userKey → 抽 1 件真实上链验证存证链接可访问 | -| 低 | 更新仓库内 `docs/天河链文档.md` | 按第二节勘误修正(或直接标注"以 APIFox 在线文档为准") | -| 低 | transfer/burn 预留 | 方案 B 落地后自然获得;无需提前开发 | +| 高 | 与天河链确认生产计费口径(upload/publish 各自是否计费) | ⏳ 待甲方/商务确认(放量前必做) | +| 中 | 接入接口 7「轮换 User Key」 | ✅ 已实现(设置页「轮换密钥」,二次确认+链上修改+回显新 key,实测通过) | +| 中 | 生产接入检查单 | 待上线执行:换生产 AppID/AppKey → 生产环境重新注册钱包(勿沿用测试钱包)→ 离线保存 userId/userKey → 抽 1 件真实上链验证 | +| 低 | 更新仓库内 `docs/天河链文档.md` | ✅ 已在文件头标注「以 APIFox 在线文档为准」并列勘误 | +| 低 | transfer/burn 预留 | provider 已具 publish/updateUserKey;transfer/burn 待实际业务需要再接 | -## 七、已定稿事项(无需再议) +## 七、待甲方确认(唯一未决项) -- 单平台钱包(一个托管钱包做公证者身份),每物存证凭据独立(txHash/digest/链接互不重复)。 -- userId/userKey 明文存 `system_setting`(备份跨重装可恢复);UI 默认掩码、揭示需二次确认且记操作日志。 -- upload 必须手工构造 multipart;接口 9 必须 GET+请求体 JSON(appKey 不进 URL)。 -- 纯存证交易不走确认循环(upload 成功即 ONCHAIN);确认循环保留给 token 类交易(方案 B 启用时直接可用)。 +- **媒体文件上链层级(见 §4.5)**:当前为「存证 JSON(不含媒体内容哈希)」。待甲方明确「链上要放什么」后再定 L1(媒体 sha256 入证,零成本)/ L2(关键媒体本体上链)/ L3(全量)。**甲方确认前维持现状(仅 JSON 存证)**。 + +## 八、已定稿事项(无需再议) + +- 采用方案 B(存证 + 发行 NFT),已实现并实测通过。 +- 单平台钱包(公证者身份),每物凭据独立(txHash/digest/链接/tokenId 互不重复)。 +- userId/userKey 明文存 `system_setting`(备份跨重装可恢复);UI 默认掩码、揭示/轮换需二次确认且记操作日志。 +- upload 必须手工构造 multipart;接口 9 必须 GET+请求体 JSON(appKey 不进 URL);接口 5 路径为 `/api/v2/nfr/transaction/detail`。 +- 确认循环对 mint 交易生效(status "0x0"=成功);纯存证 upload 不适用确认。 diff --git a/apps/admin/src/api/index.ts b/apps/admin/src/api/index.ts index 0695158..579baaa 100644 --- a/apps/admin/src/api/index.ts +++ b/apps/admin/src/api/index.ts @@ -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 = { diff --git a/apps/admin/src/locales/en-US.json b/apps/admin/src/locales/en-US.json index 49970a6..e81c7dd 100644 --- a/apps/admin/src/locales/en-US.json +++ b/apps/admin/src/locales/en-US.json @@ -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", diff --git a/apps/admin/src/locales/zh-CN.json b/apps/admin/src/locales/zh-CN.json index eea5e46..30f454e 100644 --- a/apps/admin/src/locales/zh-CN.json +++ b/apps/admin/src/locales/zh-CN.json @@ -552,6 +552,10 @@ "tianheRegister": "注册链上身份", "tianheReRegister": "重新确认身份", "tianheManualEntry": "手动录入", + "tianheRotate": "轮换密钥", + "tianheRotateConfirmTitle": "轮换 User Key", + "tianheRotateConfirmContent": "将为平台托管钱包生成新的 User Key 并在链上修改,旧 Key 立即失效。操作后请务必离线保存新 Key。确认继续?", + "tianheRotateDone": "User Key 已轮换", "tianheReveal": "揭示", "tianheHide": "隐藏", "tianheRevealConfirmTitle": "揭示 User Key", diff --git a/apps/admin/src/views/Settings.vue b/apps/admin/src/views/Settings.vue index 6e0596a..f97f27d 100644 --- a/apps/admin/src/views/Settings.vue +++ b/apps/admin/src/views/Settings.vue @@ -124,6 +124,7 @@ {{ identity.address ? t('pages.settings.tianheReRegister') : t('pages.settings.tianheRegister') }} {{ t('pages.settings.tianheManualEntry') }} + {{ t('pages.settings.tianheRotate') }}
@@ -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 { diff --git a/apps/api/prisma/migrations/20260710110000_add_proof_token_fields/migration.sql b/apps/api/prisma/migrations/20260710110000_add_proof_token_fields/migration.sql new file mode 100644 index 0000000..c8042a8 --- /dev/null +++ b/apps/api/prisma/migrations/20260710110000_add_proof_token_fields/migration.sql @@ -0,0 +1,4 @@ +-- 存证+发行模式:记录铸造的 NFT TokenId 与合约地址 +ALTER TABLE `blockchain_proof` + ADD COLUMN `token_id` BIGINT NULL, + ADD COLUMN `contract_address` VARCHAR(191) NULL; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index e1435fc..fa83fe6 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -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") diff --git a/apps/api/src/blockchain/attestation.service.ts b/apps/api/src/blockchain/attestation.service.ts index 2ab721e..5fd140d 100644 --- a/apps/api/src/blockchain/attestation.service.ts +++ b/apps/api/src/blockchain/attestation.service.ts @@ -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 悬挂记录 diff --git a/apps/api/src/blockchain/blockchain.service.ts b/apps/api/src/blockchain/blockchain.service.ts index 74cb338..48f7a24 100644 --- a/apps/api/src/blockchain/blockchain.service.ts +++ b/apps/api/src/blockchain/blockchain.service.ts @@ -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 { + 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 { 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 { + 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(); diff --git a/apps/api/src/blockchain/blockchain.types.ts b/apps/api/src/blockchain/blockchain.types.ts index b20bbc4..ef39827 100644 --- a/apps/api/src/blockchain/blockchain.types.ts +++ b/apps/api/src/blockchain/blockchain.types.ts @@ -1,6 +1,8 @@ export interface AttestPayload { dataHash: string; meta?: Record; + // 发行 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; confirmationRequired?: boolean; diff --git a/apps/api/src/blockchain/onchain.processor.ts b/apps/api/src/blockchain/onchain.processor.ts index 416e19d..8bed388 100644 --- a/apps/api/src/blockchain/onchain.processor.ts +++ b/apps/api/src/blockchain/onchain.processor.ts @@ -23,6 +23,14 @@ function requestMeta(raw: unknown): Record | undefined { return meta && typeof meta === 'object' ? (meta as Record) : undefined; } +function productInfo(raw: unknown): { productId: string; name: string; author?: string } | undefined { + if (!raw || typeof raw !== 'object') return undefined; + const product = (raw as Record).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 { return raw && typeof raw === 'object' ? (raw as Record) : {}; } @@ -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), diff --git a/apps/api/src/blockchain/tianhe.provider.ts b/apps/api/src/blockchain/tianhe.provider.ts index b35ac5b..23b1da8 100644 --- a/apps/api/src/blockchain/tianhe.provider.ts +++ b/apps/api/src/blockchain/tianhe.provider.ts @@ -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 }> { + const body: Record = { + ...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>) : []; + 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 { + 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 { diff --git a/apps/api/src/public-trace/public-trace.service.ts b/apps/api/src/public-trace/public-trace.service.ts index 7860635..8ef055e 100644 --- a/apps/api/src/public-trace/public-trace.service.ts +++ b/apps/api/src/public-trace/public-trace.service.ts @@ -210,6 +210,8 @@ export class PublicTraceService { chainName: proof.chainName, onchainAt: proof.onchainAt, explorerUrl: proof.explorerUrl, + tokenId: proof.tokenId, + contractAddress: proof.contractAddress, } : null, }; diff --git a/apps/api/src/settings/settings.controller.ts b/apps/api/src/settings/settings.controller.ts index e8be7c6..278e68d 100644 --- a/apps/api/src/settings/settings.controller.ts +++ b/apps/api/src/settings/settings.controller.ts @@ -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(); + } } diff --git a/apps/client/src/locales/en-US.json b/apps/client/src/locales/en-US.json index 101a04d..af930ae 100644 --- a/apps/client/src/locales/en-US.json +++ b/apps/client/src/locales/en-US.json @@ -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", diff --git a/apps/client/src/locales/zh-CN.json b/apps/client/src/locales/zh-CN.json index 0836a2c..128d80e 100644 --- a/apps/client/src/locales/zh-CN.json +++ b/apps/client/src/locales/zh-CN.json @@ -28,6 +28,8 @@ "code": "唯一追溯码", "hash": "交易哈希", "dataHash": "数据哈希", + "tokenId": "数字藏品编号", + "contract": "合约地址", "blockHeight": "区块高度", "onchainAt": "上链时间", "explorer": "查看存证", diff --git a/apps/client/src/views/Trace.vue b/apps/client/src/views/Trace.vue index 4cd632e..a41a92a 100644 --- a/apps/client/src/views/Trace.vue +++ b/apps/client/src/views/Trace.vue @@ -310,6 +310,20 @@
+
+ {{ t('chain.tokenId') }} + {{ data.blockchain.tokenId }} +
+
+ {{ t('chain.contract') }} + {{ ellipsis(data.blockchain.contractAddress) }} + +
{{ t('chain.blockHeight') }} {{ data.blockchain.blockHeight ?? '-' }} diff --git a/docs/天河链文档.md b/docs/天河链文档.md index d480288..bce6b8b 100644 --- a/docs/天河链文档.md +++ b/docs/天河链文档.md @@ -1,3 +1,7 @@ +> ⚠️ 本文件为语雀文档的历史快照,部分内容已过时/有误(如接口 5 路径应为 `/api/v2/nfr/transaction/detail`、接口 9 `status` "0x0"=成功等)。 +> **对接以 APIFox 在线文档为准**:https://s.apifox.cn/470f2b03-5edb-49d4-8e54-e2684feab256 +> 我方对接决策与勘误详见 `aidocs/天河链对接分析与建议.md`。 + ### 测试环境接口域名:https://test.api.tichain.tianhecloud.com