fix: 天河链对接修复 T1-T3/T6-T8(托管钱包注册与身份生命周期)

- TianheProvider 新增 registerUser/userInfo/ensureRegistered(接口1/8),attest 前幂等确保钱包已注册
- userDto 分段改为 application/json 类型 Blob,避免 Media Type Error
- 严格校验 code===0 且必须返回 transactionHash,杜绝以本地 dataHash 冒充链上哈希的假上链
- upload 响应不再提取恒空的区块信息,注释固化"每物一条 proof、独立 txHash"不变量
- userKey 改为一次性随机生成并明文持久化(不再从 appKey 派生),明文存储保证备份跨重装可恢复
- 新增 /settings/tianhe/register|verify|identity 接口与设置页链上身份区(注册/显示地址/揭示复制/手动录入校验)
- 单测扩至 27 个:新增注册、严格校验、userDto 类型、ensureRegistered 回退用例
This commit is contained in:
Nixevol
2026-07-09 19:05:32 +08:00
parent 8a7032070a
commit fa4215bd52
9 changed files with 512 additions and 104 deletions
+100 -18
View File
@@ -1,6 +1,8 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHash } from 'crypto';
import { createHash, randomBytes } from 'crypto';
import { ErrorCode } from '@artveris/shared';
import { BusinessException } from '../common/exceptions/business.exception';
import { SettingsService } from '../settings/settings.service';
import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } from './blockchain.types';
import { MockProvider } from './mock.provider';
@@ -8,6 +10,8 @@ import { TianheProvider } from './tianhe.provider';
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
// 单平台钱包:全平台共用一个托管钱包(公证者身份)。每件实物的存证仍各自独立
// (每物一条 proof、独立 txHash/digest),钱包只标识「谁提交的存证」,不标识物品。
const DEFAULT_TIANHE_USER_ID = 'artveris-platform';
// 递归按 key 排序的稳定序列化,用于内容哈希(与 JSON.stringify 不同,属性顺序不影响结果)
@@ -36,6 +40,9 @@ export class BlockchainService {
async attest(payload: AttestPayload): Promise<AttestResult> {
const provider = await this.buildProvider();
this.logger.log(`区块链存证驱动:${provider.name}`);
if (provider instanceof TianheProvider) {
await this.ensureTianheWallet(provider);
}
return provider.attest(payload);
}
@@ -47,37 +54,112 @@ export class BlockchainService {
return provider.confirmTransaction(txHash);
}
// ===== 天河链链上身份(userId/userKey/钱包地址)生命周期 =====
// 注册(或确认)平台托管钱包:userKey 缺失时一次性随机生成并明文持久化(不从 appKey 派生),
// 成功后保存钱包地址。返回明文 userId/userKey 供管理员离线保存(天河链不留存 userKey)。
async registerTianheIdentity(): 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() || DEFAULT_TIANHE_USER_ID;
let userKey = (settings.tianheUserKey || '').trim();
if (!userKey) {
userKey = randomBytes(32).toString('hex');
}
const provider = this.buildTianheProvider(settings, userId, userKey);
let address: string;
try {
address = (await provider.ensureRegistered()).address;
} catch (e) {
throw new BusinessException(ErrorCode.BAD_REQUEST, (e as Error).message);
}
await this.settings.setRaw('tianheUserId', userId);
await this.settings.setRaw('tianheUserKey', userKey);
await this.settings.setRaw('tianheWalletAddress', address);
return { userId, userKey, address };
}
// 手动重录(重装/迁移复用既有钱包):经接口 8 校验 userId/userKey 能解析出钱包地址后才落库。
async verifyTianheIdentity(userId: string, userKey: string): Promise<{ userId: 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 uid = (userId || '').trim();
const key = (userKey || '').trim();
if (!uid || !key) throw new BusinessException(ErrorCode.BAD_REQUEST, 'User ID 与 User Key 均不能为空');
const provider = this.buildTianheProvider(settings, uid, key);
let address: string;
try {
address = (await provider.userInfo()).address;
} catch (e) {
throw new BusinessException(ErrorCode.BAD_REQUEST, (e as Error).message);
}
await this.settings.setRaw('tianheUserId', uid);
await this.settings.setRaw('tianheUserKey', key);
await this.settings.setRaw('tianheWalletAddress', address);
return { userId: uid, address };
}
// 揭示明文 userKey(管理员离线备份用;该值本就明文存库,不加密的理由见 settings.service)
async revealTianheUserKey(): Promise<{ userId: string; userKey: string; address: string }> {
const settings = await this.settings.getAllRaw();
return {
userId: settings.tianheUserId || '',
userKey: settings.tianheUserKey || '',
address: settings.tianheWalletAddress || '',
};
}
// 存证前确保托管钱包已注册(以 tianheWalletAddress 为「已注册」标记,避免每次都调注册接口)
private async ensureTianheWallet(provider: TianheProvider): Promise<void> {
const settings = await this.settings.getAllRaw();
if (settings.tianheWalletAddress) return;
const { address } = await provider.ensureRegistered();
await this.settings.setRaw('tianheUserId', await this.resolvedUserId());
await this.settings.setRaw('tianheWalletAddress', address);
this.logger.log(`天河链托管钱包已注册:${address}`);
}
private async resolvedUserId(): Promise<string> {
const settings = await this.settings.getAllRaw();
return (settings.tianheUserId || '').trim() || DEFAULT_TIANHE_USER_ID;
}
private async buildProvider(): Promise<AttestationProvider> {
const settings = await this.settings.getAllRaw();
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
if (driver !== 'tianhe') return new MockProvider();
const userId = (settings.tianheUserId || '').trim() || DEFAULT_TIANHE_USER_ID;
let userKey = (settings.tianheUserKey || '').trim();
if (!userKey) {
// 一次性生成并持久化(明文)。不从 appKey 派生:派生会让换 appKey 时 userKey 变化,
// 与已注册钱包不匹配(天河链不留存 userKey,改 key 需旧 key)。
userKey = randomBytes(32).toString('hex');
await this.settings.setRaw('tianheUserId', userId);
await this.settings.setRaw('tianheUserKey', userKey);
this.logger.log('已生成天河链平台钱包 userKey 并持久化,请在系统设置中揭示并离线保存');
}
return this.buildTianheProvider(settings, userId, userKey);
}
private buildTianheProvider(settings: Record<string, string>, userId: string, userKey: string): TianheProvider {
const env = settings.tianheEnv || 'test';
const configuredBaseUrl =
const baseUrl =
env === 'test'
? TIANHE_TEST_URL
: env === 'production'
? TIANHE_PRODUCTION_URL
: settings.tianheBaseUrl || this.config.get<string>('blockchain.tianhe.baseUrl') || TIANHE_TEST_URL;
return new TianheProvider({
baseUrl: configuredBaseUrl,
baseUrl,
appId: settings.tianheAppId || this.config.get<string>('blockchain.tianhe.appId') || '',
appKey: settings.tianheAppKey || this.config.get<string>('blockchain.tianhe.appKey') || '',
userId: this.tianheUserId(settings),
userKey: this.tianheUserKey(settings),
userId,
userKey,
});
}
private tianheUserId(settings: Record<string, string>): string {
return settings.tianheUserId || this.config.get<string>('blockchain.tianhe.userId') || DEFAULT_TIANHE_USER_ID;
}
private tianheUserKey(settings: Record<string, string>): string {
const configured = settings.tianheUserKey || this.config.get<string>('blockchain.tianhe.userKey');
if (configured) return configured;
const appId = settings.tianheAppId || this.config.get<string>('blockchain.tianhe.appId') || '';
const appKey = settings.tianheAppKey || this.config.get<string>('blockchain.tianhe.appKey') || '';
return createHash('sha256').update(`artveris:tianhe:${appId}:${appKey}`).digest('hex');
}
}
@@ -38,6 +38,80 @@ describe('TianheProvider', () => {
expect(result.raw.digest).toBe(response.data.digest);
expect(result.raw.transactionStatus).toBe('submitted');
expect(result.confirmationRequired).toBe(true);
// upload 不返回区块信息,由 confirm 阶段补齐
expect(result.blockHash).toBeNull();
expect(result.blockHeight).toBeNull();
});
it('upload 的 userDto 分段必须为 application/json 类型', async () => {
const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () =>
JSON.stringify({ code: 0, data: { digest: 'd', url: 'u', transactionHash: '0xtx' } }),
} as Response);
await provider.attest({ dataHash: '0xhash' });
const body = fetchMock.mock.calls[0][1]?.body as FormData;
const userDto = body.get('userDto');
expect(userDto).toBeInstanceOf(Blob);
expect((userDto as Blob).type).toBe('application/json');
});
it('响应缺少 transactionHash 时抛错,不用本地 dataHash 冒充', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ code: 0, message: 'success', data: { digest: 'only-digest' } }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('transactionHash');
});
it('响应缺少 code 字段时视为异常而非成功', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ something: 'else' }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('code=缺失');
});
it('code 非 0 时抛出接口错误信息', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ code: 500, message: 'appKey invalid' }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('appKey invalid');
});
it('registerUser 按接口 1 解析托管钱包地址', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () =>
JSON.stringify({ code: 0, data: { pubKey: { address: '0xwallet', publicKey: 'ignored' } } }),
} as Response);
const result = await provider.registerUser();
expect(result.address).toBe('0xwallet');
});
it('ensureRegistered 优先查询接口 8,失败则回退注册', async () => {
const fetchMock = jest
.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ code: 1, message: 'user not found' }),
} as Response)
.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ code: 0, data: { pubKey: { address: '0xnewwallet' } } }),
} as Response);
const result = await provider.ensureRegistered();
expect(result.address).toBe('0xnewwallet');
expect(String(fetchMock.mock.calls[0][0])).toContain('/api/v2/user/info');
expect(String(fetchMock.mock.calls[1][0])).toContain('/api/v2/user');
});
it('按交易状态接口确认链上区块信息', async () => {
+95 -73
View File
@@ -36,11 +36,23 @@ function pickNumber(source: unknown, keys: string[]): number | null {
return null;
}
function responseData(raw: unknown): Record<string, unknown> {
if (!raw || typeof raw !== 'object') return {};
const obj = raw as Record<string, unknown>;
const data = obj.data;
return data && typeof data === 'object' ? { ...obj, ...(data as Record<string, unknown>) } : obj;
function parseJson(text: string): Record<string, unknown> {
try {
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
} catch {
return { text };
}
}
// 天河链响应统一为 { code, message, data };code=0 为成功(缺失 code 视为异常响应,不再宽松放行)
function assertOk(raw: Record<string, unknown>, action: string): Record<string, unknown> {
const code = pickString(raw, ['code']);
if (code !== '0') {
const msg = pickString(raw, ['message', 'msg', 'error']) || `接口返回异常(code=${code ?? '缺失'})`;
throw new Error(`${action}失败:${msg}`);
}
const data = raw.data;
return data && typeof data === 'object' ? (data as Record<string, unknown>) : {};
}
export class TianheProvider implements AttestationProvider {
@@ -48,14 +60,61 @@ export class TianheProvider implements AttestationProvider {
constructor(private readonly opts: TianheOptions) {}
async attest(payload: AttestPayload): Promise<AttestResult> {
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
const userDto = {
private baseUrl(): string {
return required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
}
private credentials() {
return {
appId: required(this.opts.appId, 'App ID'),
appKey: required(this.opts.appKey, 'App Key'),
userId: required(this.opts.userId, 'User ID'),
userKey: required(this.opts.userKey, 'User Key'),
};
}
private async postJson(path: string, body: Record<string, unknown>, action: string): Promise<Record<string, unknown>> {
const res = await fetch(`${this.baseUrl()}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const text = await res.text();
if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
return parseJson(text);
}
// 接口 1「用户链上身份注册」:注册托管钱包,返回链上地址。userKey 是钱包密码,天河链不留存。
async registerUser(): Promise<{ address: string }> {
const raw = await this.postJson('/api/v2/user', this.credentials(), '天河链链上身份注册');
const data = assertOk(raw, '天河链链上身份注册');
const pubKey = (data.pubKey && typeof data.pubKey === 'object' ? data.pubKey : data) as Record<string, unknown>;
const address = pickString(pubKey, ['address']) || pickString(data, ['address']);
if (!address) throw new Error('天河链链上身份注册失败:响应缺少钱包地址');
return { address };
}
// 接口 8「用户链上身份查询」:校验 userId/userKey 是否对应已注册钱包,返回其地址。
async userInfo(): Promise<{ address: string }> {
const raw = await this.postJson('/api/v2/user/info', this.credentials(), '天河链链上身份查询');
const data = assertOk(raw, '天河链链上身份查询');
const address = pickString(data, ['address']);
if (!address) throw new Error('天河链链上身份查询失败:响应缺少钱包地址');
return { address };
}
// 幂等确保托管钱包存在:先查询(接口 8),不存在再注册(接口 1)。
async ensureRegistered(): Promise<{ address: string }> {
try {
return await this.userInfo();
} catch {
return this.registerUser();
}
}
// 接口 6「元数据上链存证」:上传存证文件,返回 { digest, url, transactionHash }。
// 每个追溯码(每件实物)各自调用一次 → 每物一条 proof、独立 txHash(不变量,勿改为按档案共用)。
async attest(payload: AttestPayload): Promise<AttestResult> {
const meta = {
dataHash: payload.dataHash,
...(payload.meta || {}),
@@ -63,65 +122,41 @@ export class TianheProvider implements AttestationProvider {
};
const form = new FormData();
form.append('userDto', JSON.stringify(userDto));
// userDto 分段必须带 application/json content-type(文档 curl 标注 ;type=application/json,否则 Media Type Error)
form.append('userDto', new Blob([JSON.stringify(this.credentials())], { type: 'application/json' }));
form.append(
'file',
new Blob([JSON.stringify(meta, null, 2)], { type: 'application/json' }),
`artveris-proof-${payload.dataHash.replace(/^0x/, '').slice(0, 16)}.json`,
);
const res = await fetch(`${baseUrl}/api/v2/nfr/upload`, {
method: 'POST',
body: form,
});
const res = await fetch(`${this.baseUrl()}/api/v2/nfr/upload`, { method: 'POST', body: form });
const text = await res.text();
let raw: Record<string, unknown> = { text };
try {
raw = text ? JSON.parse(text) : {};
} catch {
raw = { text };
}
if (!res.ok) {
throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
}
if (!res.ok) throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
const raw = parseJson(text);
const data = assertOk(raw, '天河链存证');
const code = pickString(raw, ['code', 'statusCode', 'errCode']);
const success = code === null || code === '0' || code.toLowerCase() === 'success' || code === '200';
if (!success) {
const msg = pickString(raw, ['message', 'msg', 'error']) || '接口返回失败';
throw new Error(`天河链存证失败:${msg}`);
}
const data = responseData(raw);
const txHash =
pickString(data, [
'transactionHash',
'txHash',
'hash',
'proofHash',
'certHash',
'attestationHash',
'chainHash',
]) || payload.dataHash;
// 严格要求返回交易哈希;缺失即视为失败(绝不能用本地 dataHash 冒充链上哈希造成「假上链」)
const txHash = pickString(data, ['transactionHash', 'txHash']);
if (!txHash) throw new Error('天河链存证失败:响应缺少 transactionHash');
const digest = pickString(data, ['digest']);
const explorerUrl = pickString(data, ['url', 'link', 'proofUrl', 'viewUrl', 'certUrl', 'explorerUrl', 'uri']);
const blockHash = pickString(data, ['blockHash']);
const blockHeight = pickNumber(data, ['blockHeight', 'blockNum', 'height']);
const onchainAtText = pickString(data, ['onchainAt', 'chainTime', 'createdAt', 'time']);
const onchainAt = onchainAtText ? new Date(onchainAtText) : new Date();
// url 为「存证链接」(文件下载地址/链上 URI,可对外展示),并非区块浏览器交易页
const proofUrl = pickString(data, ['url']);
return {
dataHash: payload.dataHash,
txHash,
blockHash,
blockHeight,
// upload 接口不返回区块信息,blockHash/blockHeight 由后续 confirm 阶段补齐
blockHash: null,
blockHeight: null,
chainName: '天河链',
explorerUrl,
onchainAt: Number.isNaN(onchainAt.getTime()) ? new Date() : onchainAt,
explorerUrl: proofUrl,
onchainAt: new Date(),
raw: {
requestMeta: meta,
response: raw,
digest,
proofUrl,
transactionStatus: 'submitted',
transactionStatusNote: '天河链接口成功仅表示交易已提交;最终链上结果需通过交易查询接口确认。',
},
@@ -129,37 +164,24 @@ export class TianheProvider implements AttestationProvider {
};
}
// 接口 9「根据交易哈希查询」:确认交易是否已进块。
// 文档标注 GET,curl 样例却用 body 传参;实现取 GET+query(fetch 不支持 GET body),联调已通过则维持现状。
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
const appId = required(this.opts.appId, 'App ID');
const appKey = required(this.opts.appKey, 'App Key');
const url = new URL(`${baseUrl}/api/v2/nfr/transaction/status`);
url.searchParams.set('appId', appId);
url.searchParams.set('appKey', appKey);
const url = new URL(`${this.baseUrl()}/api/v2/nfr/transaction/status`);
url.searchParams.set('appId', required(this.opts.appId, 'App ID'));
url.searchParams.set('appKey', required(this.opts.appKey, 'App Key'));
url.searchParams.set('transactionHash', required(txHash, 'Transaction Hash'));
const res = await fetch(url);
const text = await res.text();
let raw: Record<string, unknown> = { text };
try {
raw = text ? JSON.parse(text) : {};
} catch {
raw = { text };
}
if (!res.ok) {
throw new Error(`天河链交易确认请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
}
if (!res.ok) throw new Error(`天河链交易确认请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
const raw = parseJson(text);
const data = assertOk(raw, '天河链交易确认');
const code = pickString(raw, ['code', 'statusCode', 'errCode']);
const success = code === null || code === '0' || code.toLowerCase() === 'success' || code === '200';
if (!success) {
const msg = pickString(raw, ['message', 'msg', 'error']) || '接口返回失败';
throw new Error(`天河链交易确认失败:${msg}`);
}
const data = responseData(raw);
const status = pickString(data, ['status']);
const blockHash = pickString(data, ['blockHash']);
const blockHeight = pickNumber(data, ['blockNum', 'blockHeight', 'height']);
// 已进块(拿到区块信息)即视为确认;status 字段语义文档未定义,原样记录供排查
const confirmed = Boolean(blockHash || blockHeight !== null);
return {
confirmed,
@@ -170,7 +192,7 @@ export class TianheProvider implements AttestationProvider {
response: raw,
transactionStatus: confirmed ? 'confirmed' : 'waiting',
tokenId: pickString(data, ['tokenId']),
status: pickString(data, ['status']),
status,
},
};
}