特性:001-credential-manager 日期:2025-09-29 (更新) 状态:Phase 1 - 数据模型设计 用户需求:用于多平台对冲的账号管理模块,智能注入账户分辨不同平台执行对应业务
描述:代表不同的交易平台,定义了特定的签名和认证规则。
属性:
id
: string - 平台唯一标识符name
: string - 平台显示名称signatureType
: SignatureType - 签名算法类型枚举值:
enum Platform {
PACIFICA = 'pacifica',
ASTER = 'aster',
BINANCE = 'binance'
}
enum SignatureType {
ED25519 = 'ed25519',
ECDSA_ETHEREUM = 'ecdsa-ethereum',
HMAC_SHA256 = 'hmac-sha256'
}
验证规则:
描述:包含账户ID、平台类型、凭证信息的基本数据结构。
属性:
interface Account {
id: string; // 账户唯一ID
platform: Platform; // 所属平台
credentials: Credentials; // 凭证信息
metadata?: { // 可选元数据
alias?: string; // 账户别名
description?: string; // 账户描述
[key: string]: any; // 其他自定义字段
};
}
凭证结构:
type Credentials = PacificaCredentials | AsterCredentials | BinanceCredentials;
interface PacificaCredentials {
type: 'pacifica';
privateKey: string; // 64字符十六进制Ed25519私钥
}
interface AsterCredentials {
type: 'aster';
privateKey: string; // 以太坊格式私钥
}
interface BinanceCredentials {
type: 'binance';
apiKey: string; // API密钥
secretKey: string; // 密钥对
}
验证规则:
描述:提供统一签名接口的组件,内部根据平台类型调用对应算法。
接口定义:
interface Signer {
// 统一签名接口
sign(accountId: string, message: Uint8Array): Promise<SignResult>;
// 验证签名
verify(accountId: string, message: Uint8Array, signature: string): Promise<boolean>;
// 获取账户信息
getAccount(accountId: string): Account | null;
// 列出所有账户
listAccounts(): Account[];
}
interface SignResult {
success: boolean;
signature?: string; // Base64编码的签名
algorithm: string; // 使用的签名算法
timestamp: Date; // 签名时间戳
error?: string; // 错误信息
}
平台特定签名策略:
interface SignerStrategy {
platform: Platform;
sign(message: Uint8Array, credentials: Credentials): Promise<string>;
verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean>;
}
描述:负责从配置文件加载账户信息并监听文件变更。
接口定义:
interface ConfigLoader {
// 加载配置文件
loadConfig(filePath: string): Promise<LoadResult>;
// 开始监听文件变更
watchConfig(filePath: string, callback: (accounts: Account[]) => void): void;
// 停止监听
stopWatching(): void;
}
interface LoadResult {
success: boolean;
accounts: Account[];
errors?: string[];
loadTime: number; // 加载耗时(毫秒)
}
配置文件格式:
interface ConfigFile {
version: string; // 配置文件版本
accounts: AccountConfig[];
}
interface AccountConfig {
id: string;
platform: Platform;
credentials: Credentials;
metadata?: Record<string, any>;
}
描述:支持多平台对冲业务的账户池管理,提供负载均衡和故障转移。
属性:
interface HedgingAccountPool {
poolId: string; // 账户池ID
name: string; // 池名称
strategy: LoadBalanceStrategy; // 负载均衡策略
accounts: HedgingAccountGroup; // 账户分组
status: PoolStatus; // 池状态
metadata: {
description?: string;
createdAt: Date;
updatedAt: Date;
owner?: string;
};
}
interface HedgingAccountGroup {
primary: string[]; // 主要账户ID列表
backup: string[]; // 备用账户ID列表
test: string[]; // 测试账户ID列表
}
enum LoadBalanceStrategy {
ROUND_ROBIN = 'round-robin', // 轮询
RANDOM = 'random', // 随机选择
WEIGHTED = 'weighted', // 权重分配
LEAST_USED = 'least-used' // 最少使用
}
enum PoolStatus {
ACTIVE = 'active', // 活跃
DEGRADED = 'degraded', // 降级(部分账户不可用)
INACTIVE = 'inactive' // 不可用
}
验证规则:
描述:扩展账户状态信息,支持对冲业务实时监控。
属性:
interface AccountStatus {
accountId: string; // 账户ID
platform: Platform; // 所属平台
status: AccountHealth; // 健康状态
performance: PerformanceMetrics; // 性能指标
balanceInfo?: BalanceSnapshot; // 余额快照
lastActivity: Date; // 最后活动时间
failureCount: number; // 失败计数
metadata: {
poolMembership: string[]; // 所属账户池
priority: number; // 优先级 (1-10)
maxConcurrency?: number; // 最大并发限制
};
}
enum AccountHealth {
HEALTHY = 'healthy', // 健康
WARNING = 'warning', // 警告(性能下降)
CRITICAL = 'critical', // 严重(频繁失败)
OFFLINE = 'offline' // 离线
}
interface PerformanceMetrics {
avgSignTime: number; // 平均签名时间(ms)
successRate: number; // 成功率 (0-1)
requestCount: number; // 请求次数
lastResetAt: Date; // 指标重置时间
}
interface BalanceSnapshot {
totalValue: number; // 总价值 (USD)
positions: Record<string, number>; // 持仓 {symbol: amount}
lastUpdated: Date; // 更新时间
}
状态转换规则:
描述:基于现有AccountRegistry模式的简化实现,避免复杂工厂适配器。
属性:
interface AccountRegistry {
// 基础账户管理
register(account: RegisteredAccount): void;
unregister(platform: string, accountId: string): boolean;
getCredentials(platform: string, accountId: string): Credentials | null;
hasAccount(platform: string, accountId: string): boolean;
listAccounts(): Array<{platform: string; accountId: string; metadata?: any}>;
// 对冲业务扩展
getAccountsByPool(poolId: string): RegisteredAccount[];
getHealthyAccounts(platform?: Platform): RegisteredAccount[];
selectAccountForTrading(poolId: string, strategy?: LoadBalanceStrategy): RegisteredAccount | null;
updateAccountStatus(accountId: string, status: AccountStatus): void;
// 热加载支持
reloadFromConfig(configPath: string): Promise<LoadResult>;
watchConfig(configPath: string): void;
stopWatching(): void;
}
interface RegisteredAccount {
platform: string;
accountId: string;
credentials: Credentials;
metadata?: {
name?: string;
description?: string;
pools?: string[]; // 所属账户池
priority?: number; // 优先级
};
}
设计原则:
AccountRegistry (1) ←→ (N) RegisteredAccount
↓ ↓
HedgingAccountPool (1) ←→ (N) AccountStatus
↓ ↓
LoadBalanceStrategy (1) ←→ (N) Account (基础)
↓ ↓
Signer (1) ←→ (N) SignerStrategy
↓
SignerStrategy (N) ←→ (1) Platform
关系说明(简化架构):
[文件创建] → [首次加载] → [监听变更] → [热重载] → [验证] → [更新内存]
↓ ↓ ↓ ↓ ↓ ↓
CREATED → LOADING → WATCHING → RELOADING → VALIDATED → UPDATED
enum AccountStatus {
LOADING = 'loading', // 正在加载
ACTIVE = 'active', // 活跃可用
ERROR = 'error', // 错误状态
REMOVED = 'removed' // 已移除
}
状态转换规则:
{
"version": "1.0",
"accounts": [
{
"id": "pacifica-main-001",
"platform": "pacifica",
"credentials": {
"type": "pacifica",
"privateKey": "abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab"
},
"metadata": {
"alias": "Pacifica主账户",
"description": "用于Pacifica交易的主要账户",
"environment": "production"
}
},
{
"id": "binance-api-001",
"platform": "binance",
"credentials": {
"type": "binance",
"apiKey": "your_binance_api_key",
"secretKey": "your_binance_secret_key"
},
"metadata": {
"alias": "Binance API账户",
"testnet": false
}
}
]
}
const accountConfigSchema = {
type: "object",
properties: {
version: { type: "string", pattern: "^\\d+\\.\\d+$" },
accounts: {
type: "array",
items: {
type: "object",
properties: {
id: { type: "string", minLength: 1 },
platform: { enum: ["pacifica", "aster", "binance"] },
credentials: {
oneOf: [
{
properties: {
type: { const: "pacifica" },
privateKey: {
type: "string",
pattern: "^[0-9a-fA-F]{64}$"
}
},
required: ["type", "privateKey"]
},
{
properties: {
type: { const: "binance" },
apiKey: { type: "string", minLength: 1 },
secretKey: { type: "string", minLength: 1 }
},
required: ["type", "apiKey", "secretKey"]
}
// 其他平台schema...
]
}
},
required: ["id", "platform", "credentials"]
}
}
},
required: ["version", "accounts"]
};
实体 | 性能要求 | 实现策略 |
---|---|---|
ConfigLoader | 加载<100ms | 异步文件读取 + JSON解析优化 |
Signer | 签名<50ms | 内存缓存凭证 + 高性能签名库 |
Account | 查询<10ms | 内存索引 + HashMap查找 |
Platform识别 | 识别<1ms | 正则表达式预编译 + 优先级队列 |
enum ErrorType {
CONFIG_LOAD_ERROR = 'config_load_error',
VALIDATION_ERROR = 'validation_error',
SIGNATURE_ERROR = 'signature_error',
PLATFORM_DETECTION_ERROR = 'platform_detection_error'
}
interface CredentialError {
type: ErrorType;
message: string;
accountId?: string;
timestamp: Date;
details?: any;
}
描述:提供与交易模块、风控模块、监控模块等的标准化交互接口。
属性:
interface TradingModuleIntegration {
// 为交易模块提供签名服务
signTradingRequest(request: TradingSignRequest): Promise<TradingSignResponse>;
// 批量签名支持(高频交易场景)
signBatchTradingRequests(requests: TradingSignRequest[]): Promise<TradingSignResponse[]>;
// 账户状态查询(供交易模块选择可用账户)
getAvailableAccountsForTrading(criteria: AccountSelectionCriteria): Promise<AvailableAccount[]>;
// 实时账户健康检查
checkAccountHealth(accountIds: string[]): Promise<Map<string, AccountHealthStatus>>;
// 交易后更新账户状态
updateAccountAfterTrade(accountId: string, tradeResult: TradeResult): Promise<void>;
}
interface TradingSignRequest {
accountId: string; // 指定账户ID
platform: Platform; // 目标平台
orderData: OrderData; // 订单数据
requestId: string; // 请求唯一ID(幂等性)
timestamp: number; // 请求时间戳
urgency: 'normal' | 'high' | 'critical'; // 紧急程度
}
interface OrderData {
symbol: string; // 交易对
side: 'buy' | 'sell'; // 买卖方向
type: 'market' | 'limit' | 'stop'; // 订单类型
quantity: number; // 数量
price?: number; // 价格(限价单)
timeInForce?: string; // 有效期
clientOrderId?: string; // 客户端订单ID
}
interface TradingSignResponse {
success: boolean;
signature?: string; // 签名结果
signedData?: string; // 已签名数据
publicKey?: string; // 公钥
algorithm: string; // 签名算法
timestamp: Date; // 签名时间
requestId: string; // 对应请求ID
processingTime: number; // 处理时间(ms)
error?: {
code: string;
message: string;
retryable: boolean; // 是否可重试
};
}
描述:基于事件驱动的模块间通信机制,支持松耦合集成。
属性:
interface ModuleEventBus {
// 事件订阅
subscribe<T>(eventType: string, handler: EventHandler<T>): void;
unsubscribe(eventType: string, handler: EventHandler<any>): void;
// 事件发布
publish<T>(event: ModuleEvent<T>): Promise<void>;
// 同步事件(用于关键操作)
publishSync<T>(event: ModuleEvent<T>): void;
}
interface ModuleEvent<T = any> {
type: string; // 事件类型
source: string; // 源模块
target?: string; // 目标模块(可选)
data: T; // 事件数据
timestamp: Date; // 事件时间
correlationId?: string; // 关联ID
priority: 'low' | 'normal' | 'high'; // 优先级
}
// 凭证管理相关事件类型
enum CredentialEvents {
ACCOUNT_REGISTERED = 'credential.account.registered',
ACCOUNT_REMOVED = 'credential.account.removed',
ACCOUNT_STATUS_CHANGED = 'credential.account.status_changed',
SIGN_REQUEST_COMPLETED = 'credential.sign.completed',
SIGN_REQUEST_FAILED = 'credential.sign.failed',
CONFIG_RELOADED = 'credential.config.reloaded',
POOL_STATUS_CHANGED = 'credential.pool.status_changed'
}
// 其他模块监听的事件数据
interface AccountStatusChangedEvent {
accountId: string;
platform: Platform;
oldStatus: AccountHealth;
newStatus: AccountHealth;
reason?: string;
affectedPools: string[]; // 受影响的账户池
}
interface SignRequestCompletedEvent {
requestId: string;
accountId: string;
platform: Platform;
success: boolean;
processingTime: number;
signatureAlgorithm: string;
}
描述:定义标准化的服务接口,供其他模块直接调用。
属性:
interface CrossModuleServiceInterface {
// 服务注册发现
registerService(serviceName: string, serviceInstance: any): void;
getService<T>(serviceName: string): T | null;
listServices(): string[];
// 健康检查
checkServiceHealth(serviceName: string): Promise<ServiceHealthStatus>;
// 服务依赖管理
addDependency(serviceName: string, dependsOn: string[]): void;
resolveDependencies(): Map<string, string[]>;
}
// 对外提供的核心服务
interface CredentialManagementService {
name: 'credential-manager';
version: string;
// 核心功能接口
signMessage(accountId: string, message: Uint8Array): Promise<string>;
getAccountCredentials(accountId: string): Promise<Credentials | null>;
selectAccountForPlatform(platform: Platform, poolId?: string): Promise<string | null>;
// 管理接口
reloadConfiguration(): Promise<boolean>;
getSystemStatus(): Promise<SystemStatus>;
// 监控接口
getMetrics(): Promise<PerformanceMetrics>;
getAccountStatistics(): Promise<AccountStatistics>;
}
interface SystemStatus {
status: 'healthy' | 'degraded' | 'critical';
uptime: number; // 运行时间(ms)
totalAccounts: number; // 总账户数
activeAccounts: number; // 活跃账户数
totalPools: number; // 总账户池数
lastConfigReload: Date; // 最后配置重载时间
averageSignTime: number; // 平均签名时间
requestsPerMinute: number; // 每分钟请求数
}
// 1. 交易模块发起交易请求
class TradingModule {
async executeTrade(tradeRequest: TradeRequest) {
// 选择合适的账户
const availableAccounts = await credentialService.getAvailableAccountsForTrading({
platform: tradeRequest.platform,
poolId: 'main-trading-pool',
minHealthScore: 0.9
});
if (availableAccounts.length === 0) {
throw new Error('No healthy accounts available for trading');
}
const selectedAccount = availableAccounts[0];
// 构造签名请求
const signRequest: TradingSignRequest = {
accountId: selectedAccount.accountId,
platform: tradeRequest.platform,
orderData: tradeRequest.orderData,
requestId: generateRequestId(),
timestamp: Date.now(),
urgency: tradeRequest.urgency || 'normal'
};
// 请求签名
const signResponse = await credentialService.signTradingRequest(signRequest);
if (!signResponse.success) {
// 处理签名失败,可能尝试其他账户
await this.handleSigningFailure(signRequest, signResponse.error);
return;
}
// 执行交易
const tradeResult = await this.submitToExchange(signResponse);
// 更新账户状态
await credentialService.updateAccountAfterTrade(selectedAccount.accountId, tradeResult);
}
}
// 2. 事件驱动的状态同步
credentialEventBus.subscribe(CredentialEvents.ACCOUNT_STATUS_CHANGED, (event: AccountStatusChangedEvent) => {
if (event.newStatus === AccountHealth.CRITICAL) {
// 通知交易模块暂停使用该账户
tradingModule.pauseAccountUsage(event.accountId);
}
});
// 3. 监控模块集成
class MonitoringModule {
async getSystemOverview() {
const credentialStatus = await credentialService.getSystemStatus();
const tradingMetrics = await tradingService.getMetrics();
return {
credential: credentialStatus,
trading: tradingMetrics,
integration: this.checkIntegrationHealth()
};
}
}
Phase 1.1 状态:✅ 数据模型设计完成 (更新支持对冲业务 + 模块间交互) 关键更新:
模块集成能力:
下一步:生成API契约定义