- 实测接口5/9对纯存证交易一律 500 数组越界(仅适用 token 交易),非偶发异常 - attest 改 confirmationRequired=false 直接 ONCHAIN,凭据为 txHash+digest+UDFS 存证链接 - 更新单测与问题清单/项目记忆,存量 CONFIRMING 数据已修正
300 lines
12 KiB
TypeScript
300 lines
12 KiB
TypeScript
import { Logger } from '@nestjs/common';
|
||
import { randomBytes } from 'crypto';
|
||
import { request as httpRequest } from 'node:http';
|
||
import { request as httpsRequest } from 'node:https';
|
||
import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } 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 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>) : {};
|
||
}
|
||
|
||
// 天河链 API 链路日志:打印 URL / 方法 / 发送数据 / 返回结果,appKey/userKey 脱敏
|
||
function redactSecrets(obj: Record<string, unknown>): Record<string, unknown> {
|
||
const masked: Record<string, unknown> = { ...obj };
|
||
for (const key of ['appKey', 'userKey']) {
|
||
const v = masked[key];
|
||
if (typeof v === 'string' && v) {
|
||
masked[key] = v.length > 8 ? `${v.slice(0, 3)}***${v.slice(-3)}` : '***';
|
||
}
|
||
}
|
||
return masked;
|
||
}
|
||
|
||
export class TianheProvider implements AttestationProvider {
|
||
readonly name = 'tianhe';
|
||
private readonly logger = new Logger('TianheAPI');
|
||
|
||
constructor(private readonly opts: TianheOptions) {}
|
||
|
||
private logRequest(method: string, url: string, payload: unknown): void {
|
||
this.logger.log(`→ ${method} ${url} 发送=${JSON.stringify(payload)}`);
|
||
}
|
||
|
||
private logResponse(method: string, url: string, status: number, text: string): void {
|
||
this.logger.log(`← ${method} ${url} HTTP ${status} 返回=${text.slice(0, 500)}`);
|
||
}
|
||
|
||
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 url = `${this.baseUrl()}${path}`;
|
||
this.logRequest('POST', url, redactSecrets(body));
|
||
const res = await fetch(url, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(body),
|
||
});
|
||
const text = await res.text();
|
||
this.logResponse('POST', url, res.status, text);
|
||
if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||
return parseJson(text);
|
||
}
|
||
|
||
// 天河链 upload 要求 userDto 分段「无 filename + Content-Type: application/json」(等价 curl 的 ;type=application/json)。
|
||
// whatwg FormData/undici 会给 Blob 分段强制加 filename,被服务端判为文件导致 500,故手工构造 multipart。
|
||
private async postMultipart(
|
||
path: string,
|
||
userDtoJson: string,
|
||
file: { field: string; filename: string; contentType: string; content: Buffer },
|
||
action: string,
|
||
): Promise<Record<string, unknown>> {
|
||
const boundary = `----artveris${randomBytes(12).toString('hex')}`;
|
||
const head = Buffer.from(
|
||
`--${boundary}\r\n` +
|
||
'Content-Disposition: form-data; name="userDto"\r\n' +
|
||
'Content-Type: application/json\r\n\r\n' +
|
||
`${userDtoJson}\r\n` +
|
||
`--${boundary}\r\n` +
|
||
`Content-Disposition: form-data; name="${file.field}"; filename="${file.filename}"\r\n` +
|
||
`Content-Type: ${file.contentType}\r\n\r\n`,
|
||
'utf8',
|
||
);
|
||
const body = Buffer.concat([head, file.content, Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8')]);
|
||
const url = `${this.baseUrl()}${path}`;
|
||
this.logRequest('POST(multipart)', url, {
|
||
userDto: redactSecrets(parseJson(userDtoJson)),
|
||
file: { field: file.field, filename: file.filename, contentType: file.contentType, bytes: file.content.length },
|
||
});
|
||
const res = await fetch(url, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
|
||
body,
|
||
});
|
||
const text = await res.text();
|
||
this.logResponse('POST(multipart)', url, res.status, text);
|
||
if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||
return parseJson(text);
|
||
}
|
||
|
||
// 接口 9 为 GET,但服务端要求「请求体传 JSON 参数」(GET query 会返回「Required request body is missing」)。
|
||
// Node 原生 fetch 不允许 GET 带 body,故用底层 http(s) 模块发送带 body 的 GET。appKey 走 body、不进 URL,避免日志泄漏。
|
||
private getWithBody(path: string, body: Record<string, unknown>, action: string): Promise<Record<string, unknown>> {
|
||
const url = new URL(`${this.baseUrl()}${path}`);
|
||
const payload = Buffer.from(JSON.stringify(body), 'utf8');
|
||
const requestFn = url.protocol === 'https:' ? httpsRequest : httpRequest;
|
||
this.logRequest('GET(body)', url.toString(), redactSecrets(body));
|
||
return new Promise((resolve, reject) => {
|
||
const req = requestFn(
|
||
url,
|
||
{
|
||
method: 'GET',
|
||
headers: { 'Content-Type': 'application/json', 'Content-Length': payload.length },
|
||
},
|
||
(res) => {
|
||
let text = '';
|
||
res.on('data', (chunk) => (text += chunk));
|
||
res.on('end', () => {
|
||
const status = res.statusCode || 0;
|
||
this.logResponse('GET(body)', url.toString(), status, text);
|
||
if (status < 200 || status >= 300) {
|
||
reject(new Error(`${action}请求失败:HTTP ${status} ${text.slice(0, 200)}`));
|
||
return;
|
||
}
|
||
resolve(parseJson(text));
|
||
});
|
||
},
|
||
);
|
||
req.on('error', (e) => reject(new Error(`${action}请求失败:${e.message}`)));
|
||
req.write(payload);
|
||
req.end();
|
||
});
|
||
}
|
||
|
||
// 接口 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 || {}),
|
||
generatedAt: new Date().toISOString(),
|
||
};
|
||
|
||
const raw = await this.postMultipart(
|
||
'/api/v2/nfr/upload',
|
||
JSON.stringify(this.credentials()),
|
||
{
|
||
field: 'file',
|
||
filename: `artveris-proof-${payload.dataHash.replace(/^0x/, '').slice(0, 16)}.json`,
|
||
contentType: 'application/json',
|
||
content: Buffer.from(JSON.stringify(meta, null, 2), 'utf8'),
|
||
},
|
||
'天河链存证',
|
||
);
|
||
const data = assertOk(raw, '天河链存证');
|
||
|
||
// 严格要求返回交易哈希;缺失即视为失败(绝不能用本地 dataHash 冒充链上哈希造成「假上链」)
|
||
const txHash = pickString(data, ['transactionHash', 'txHash']);
|
||
if (!txHash) throw new Error('天河链存证失败:响应缺少 transactionHash');
|
||
const digest = pickString(data, ['digest']);
|
||
// url 为「存证链接」(文件下载地址/链上 URI,可对外展示),并非区块浏览器交易页
|
||
const proofUrl = pickString(data, ['url']);
|
||
|
||
return {
|
||
dataHash: payload.dataHash,
|
||
txHash,
|
||
// upload 不返回区块信息;确认接口(5/9)仅适用 token 交易、对纯存证交易结构性不适用(实测数组越界),
|
||
// 故存证场景拿不到区块哈希/高度,保持 null,凭据以 txHash + digest + 存证链接为准。
|
||
blockHash: null,
|
||
blockHeight: null,
|
||
chainName: '天河链',
|
||
explorerUrl: proofUrl,
|
||
onchainAt: new Date(),
|
||
raw: {
|
||
requestMeta: meta,
|
||
response: raw,
|
||
digest,
|
||
proofUrl,
|
||
transactionStatus: 'onchain',
|
||
transactionStatusNote:
|
||
'upload 返回成功即存证生效(文件已入链上分布式存储 UDFS,链接可公开验证);' +
|
||
'交易确认接口仅适用于 mint/transfer/burn 类 token 交易,对纯存证交易不适用(2026-07-10 测试环境实测定稿)。',
|
||
},
|
||
// 存证无需(也无法)二次确认:upload 成功 = 存证完成
|
||
confirmationRequired: false,
|
||
};
|
||
}
|
||
|
||
// 接口 9「根据交易哈希查询」:确认交易是否已进块。
|
||
// 联调确认(2026-07-09 测试环境):接口为 GET 但参数须走「请求体 JSON」,query 方式返回「Required request body is missing」。
|
||
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
|
||
const raw = await this.getWithBody(
|
||
'/api/v2/nfr/transaction/status',
|
||
{
|
||
appId: required(this.opts.appId, 'App ID'),
|
||
appKey: required(this.opts.appKey, 'App Key'),
|
||
transactionHash: required(txHash, 'Transaction Hash'),
|
||
},
|
||
'天河链交易确认',
|
||
);
|
||
const data = assertOk(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,
|
||
txHash: pickString(data, ['transactionHash', 'txHash']) || txHash,
|
||
blockHash,
|
||
blockHeight,
|
||
raw: {
|
||
response: raw,
|
||
transactionStatus: confirmed ? 'confirmed' : 'waiting',
|
||
tokenId: pickString(data, ['tokenId']),
|
||
status,
|
||
},
|
||
};
|
||
}
|
||
}
|