feat: 接入天河链存证接口
This commit is contained in:
@@ -1,28 +1,123 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
||||
|
||||
export interface TianheOptions {
|
||||
baseUrl: string;
|
||||
appId: string;
|
||||
appKey: string;
|
||||
userId: string;
|
||||
userKey: string;
|
||||
}
|
||||
|
||||
function required(value: string | undefined, label: string): string {
|
||||
const v = (value || '').trim();
|
||||
if (!v) throw new Error(`天河链配置缺少 ${label}`);
|
||||
return v;
|
||||
}
|
||||
|
||||
function pickString(source: unknown, keys: string[]): string | null {
|
||||
if (!source || typeof source !== 'object') return null;
|
||||
const obj = source as Record<string, unknown>;
|
||||
for (const key of keys) {
|
||||
const value = obj[key];
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
if (typeof value === 'number') return String(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickNumber(source: unknown, keys: string[]): number | null {
|
||||
if (!source || typeof source !== 'object') return null;
|
||||
const obj = source as Record<string, unknown>;
|
||||
for (const key of keys) {
|
||||
const value = obj[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||
if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
// 天河链存证适配器(接入细节待确认,预留对接)。
|
||||
// 已知:纯存证接口 POST /api/v2/nfr/upload,appId/appKey 直接鉴权;
|
||||
// 待确认:完整返回字段、存证查询链接、是否需注册托管钱包等。
|
||||
// 确认后在 attest() 内补全真实请求与字段映射即可,对上层 BlockchainService 透明。
|
||||
export class TianheProvider implements AttestationProvider {
|
||||
readonly name = 'tianhe';
|
||||
private readonly logger = new Logger(TianheProvider.name);
|
||||
|
||||
constructor(private readonly opts: TianheOptions) {}
|
||||
|
||||
async attest(_payload: AttestPayload): Promise<AttestResult> {
|
||||
if (!this.opts.appId || !this.opts.appKey || !this.opts.baseUrl) {
|
||||
throw new Error('天河链未配置(TIANHE_APP_ID/APP_KEY/BASE_URL),请在 .env 配置后再启用 BLOCKCHAIN_DRIVER=tianhe');
|
||||
async attest(payload: AttestPayload): Promise<AttestResult> {
|
||||
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
|
||||
const userDto = {
|
||||
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'),
|
||||
};
|
||||
const meta = {
|
||||
dataHash: payload.dataHash,
|
||||
...(payload.meta || {}),
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const form = new FormData();
|
||||
form.append('userDto', JSON.stringify(userDto));
|
||||
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 text = await res.text();
|
||||
let raw: Record<string, unknown> = { text };
|
||||
try {
|
||||
raw = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
raw = { text };
|
||||
}
|
||||
// TODO: 待天河链接入细节确认后实现真实存证请求与返回字段映射。
|
||||
this.logger.warn('天河链真实接入尚未实现,请先使用 BLOCKCHAIN_DRIVER=mock');
|
||||
throw new Error('天河链真实接入待确认,请暂用 BLOCKCHAIN_DRIVER=mock');
|
||||
if (!res.ok) {
|
||||
throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||||
}
|
||||
|
||||
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, [
|
||||
'txHash',
|
||||
'transactionHash',
|
||||
'hash',
|
||||
'proofHash',
|
||||
'certHash',
|
||||
'attestationHash',
|
||||
'chainHash',
|
||||
]) || payload.dataHash;
|
||||
const explorerUrl = pickString(data, ['url', 'link', 'proofUrl', 'viewUrl', 'certUrl', 'explorerUrl', 'uri']);
|
||||
const blockHash = pickString(data, ['blockHash']);
|
||||
const blockHeight = pickNumber(data, ['blockHeight', 'height']);
|
||||
const onchainAtText = pickString(data, ['onchainAt', 'chainTime', 'createdAt', 'time']);
|
||||
const onchainAt = onchainAtText ? new Date(onchainAtText) : new Date();
|
||||
|
||||
return {
|
||||
dataHash: payload.dataHash,
|
||||
txHash,
|
||||
blockHash,
|
||||
blockHeight,
|
||||
chainName: '天河链',
|
||||
explorerUrl,
|
||||
onchainAt: Number.isNaN(onchainAt.getTime()) ? new Date() : onchainAt,
|
||||
raw: { requestMeta: meta, response: raw },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user