gcx/docs/guides/08-区块链生态基础设施开发指南.md

25 KiB
Raw Blame History

Genex Chain 生态基础设施开发指南

区块浏览器 + 企业API + 钱包体系 + Gas Relayer + 链监控 + 开发者SDK + 跨链桥


1. 生态全景

链和合约是区块链的内核,但量产级运营需要完整的生态工具链。

┌──────────────────────────────────────────────────────────────────────┐
│                    Genex Chain 生态基础设施                          │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │
│  │ 区块浏览器   │  │ 企业API网关  │  │ 钱包体系     │  │ 水龙头     │ │
│  │ Blockscout  │  │ RPC + REST  │  │ 托管+用户    │  │ 测试网     │ │
│  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │
│                                                                      │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │
│  │ Gas Relayer │  │ 链监控平台   │  │ 托管/密钥    │  │ 开发者SDK  │ │
│  │ Meta-TX     │  │ Prometheus  │  │ MPC/HSM     │  │ JS/Go/Dart │ │
│  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │
│                                                                      │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌────────────┐ │
│  │ 跨链桥监控   │  │ 交易监控AML │  │ 归档节点     │  │ 合约验证   │ │
│  │ Axelar/IBC  │  │ Chainalysis │  │ Archive Node│  │ 源码公示   │ │
│  └─────────────┘  └─────────────┘  └─────────────┘  └────────────┘ │
└──────────────────────────────────────────────────────────────────────┘

与06-区块链开发指南的关系

文档 范围
06-区块链开发指南 链内核Cosmos SDK链 + 9个智能合约 + 共识/合规/Gas
本文档08 链生态:围绕链内核的所有配套基础设施和工具

2. 区块链浏览器Block Explorer

用户、监管、开发者查看链上所有数据的统一入口。

2.1 技术选型

项目 说明
技术选型 Blockscout开源EVM浏览器Apache 2.0
部署地址 https://explorer.gogenex.com(主网)/ https://testnet-explorer.gogenex.com(测试网)
后端 Elixir + PostgreSQL索引 Genex Chain 全量区块数据
定制开发 券资产专属页面、合规标签、发行方档案

2.2 核心功能

功能 说明
区块/交易查询 按区块号、TX哈希、地址搜索
合约源码验证 上传Solidity源码链上bytecode比对Foundry verify集成
券资产浏览器 ERC-721/1155 券NFT详情面值、类型、转售次数、到期日、发行方
Token Tracker GNX余额、稳定币USDC/USDT流转
合约交互 Read/Write Contract UI类Etherscan
验证节点面板 节点状态、出块率、质押量、在线时间
API REST + GraphQL供第三方接入
合规标签 被冻结地址标红、Travel Rule交易标记、OFAC命中高亮

2.3 Blockscout 部署配置

# docker-compose.explorer.yml
services:
  blockscout:
    image: blockscout/blockscout:latest
    environment:
      ETHEREUM_JSONRPC_VARIANT: geth  # cosmos/evm兼容geth JSON-RPC
      ETHEREUM_JSONRPC_HTTP_URL: http://genexd:8545
      ETHEREUM_JSONRPC_WS_URL: ws://genexd:8546
      DATABASE_URL: postgresql://blockscout:password@db:5432/blockscout
      CHAIN_ID: 8888
      COIN: GNX
      COIN_NAME: Genex
      LOGO: /images/genex-logo.svg
      NETWORK: Genex Chain
      SUBNETWORK: Mainnet
    ports:
      - "4000:4000"

  db:
    image: postgres:16
    volumes:
      - blockscout-db:/var/lib/postgresql/data

2.4 券资产定制页面(二次开发)

# Blockscout定制券NFT详情页扩展
# 解析CouponFactory事件展示券业务字段

defmodule BlockScoutWeb.CouponView do
  # 从CouponBatchMinted事件解析
  def render_coupon_detail(token_id) do
    %{
      face_value: decode_face_value(token_id),
      coupon_type: decode_type(token_id),    # Utility / Security
      resale_count: call_contract(:getResaleCount, token_id),
      max_resale: call_contract(:getConfig, token_id).maxResaleCount,
      expiry_date: call_contract(:getConfig, token_id).expiryDate,
      issuer: call_contract(:getConfig, token_id).issuer,
      transferable: call_contract(:getConfig, token_id).transferable
    }
  end
end

2.5 浏览器定制功能清单

定制项 说明 优先级
券NFT详情页 展示面值、类型、到期日、转售计数等券业务字段 P0
发行方档案页 聚合某发行方的所有券批次、保障资金、信用评级 P0
合规标签系统 冻结地址标红、可疑交易标橙、Travel Rule标记 P0
CBS池详情页 资产证券化池的底层券、份额持有人、收益分配记录 P1
验证节点排行 出块率、在线时间、质押量排名 P1
Gas补贴统计 平台Gas补贴总量、趋势图、按用户/合约分布 P2

3. 企业API服务RPC + REST Gateway

为机构客户、合作伙伴、监管方提供受控的链数据访问。

3.1 架构

外部请求 → Kong API Gateway(:8080) → 企业API服务(:3020)
                                          │
                    ┌─────────────────────┼─────────────────────┐
                    ▼                     ▼                     ▼
              JSON-RPC Proxy        REST API              WebSocket
              (链上读写)           (业务聚合)            (实时订阅)
                    │                     │                     │
                    ▼                     ▼                     ▼
              genexd:8545          PostgreSQL           genexd:26657
              (EVM JSON-RPC)       (索引数据)           (CometBFT WS)

3.2 API分层与认证

层级 认证方式 调用方 接口
公开API API Key 任何开发者 区块/交易查询、合约只读调用
机构API mTLS + API Key 持牌机构 批量数据导出、高频RPC、WebSocket订阅
监管API mTLS + 机构证书 监管机构 地址关联分析、全量交易流水、Travel Rule数据、冻结操作
内部API 服务间mTLS Genex后端微服务 chain-indexer、clearing-service调用

3.3 核心端点

// enterprise-api/src/routes.ts

// === 公开API ===
GET  /v1/blocks/:height                  // 区块详情
GET  /v1/transactions/:hash              // 交易详情
GET  /v1/address/:addr/balance           // 地址余额GNX + 稳定币)
GET  /v1/address/:addr/tokens            // 地址持有的券NFT列表
GET  /v1/coupon/:tokenId                 // 券详情(面值/类型/到期/转售次数)
GET  /v1/stats                           // 链统计TPS/区块高度/活跃地址/券总量)

// === 机构API ===
POST /v1/rpc                             // JSON-RPC代理eth_call, eth_sendRawTransaction等
GET  /v1/export/transactions?from=&to=   // 批量交易导出CSV/JSON
WS   /v1/ws/events                       // 实时事件订阅(新区块/大额交易/合规事件)
GET  /v1/coupon/batch/:batchId/holders   // 某批次券的当前持有人列表

// === 监管API ===
GET  /v1/regulatory/address/:addr/graph  // 地址关联图谱(资金流向分析)
GET  /v1/regulatory/travel-rule/records  // Travel Rule记录查询
GET  /v1/regulatory/suspicious           // 可疑交易列表AI标记 + 规则触发)
POST /v1/regulatory/freeze               // 请求冻结地址触发Governance多签流程
GET  /v1/regulatory/audit-trail          // 完整审计日志

3.4 限流策略

# Kong rate-limiting配置
plugins:
  - name: rate-limiting
    config:
      # 公开API
      public_minute: 60
      public_hour: 1000
      # 机构API
      institution_minute: 600
      institution_hour: 50000
      # 监管API
      regulatory_minute: unlimited

4. 钱包体系

Genex Chain 的钱包分为三层,服务不同角色。

4.1 用户抽象钱包面向C端用户

用户不直接接触私钥和链地址。手机号 = 身份,平台托管密钥。

用户视角:
  手机号注册 → 自动创建链上地址 → 用户完全不知道
  购买券 → 法币支付 → 链上原子交换自动完成
  查看"我的券" → 实际是查询链上NFT余额

技术实现:
  ┌──────────────┐
  │ 用户手机App   │  ← 用户只看到券和余额
  └──────┬───────┘
         │ API
  ┌──────┴───────┐
  │ user-service │  ← 手机号→地址映射(加密存储)
  └──────┬───────┘
         │ 签名
  ┌──────┴───────┐
  │ MPC签名服务   │  ← 门限签名,无单点私钥
  └──────┬───────┘
         │ TX
  ┌──────┴───────┐
  │ Genex Chain  │  ← 链上执行
  └──────────────┘

MPC 钱包架构:

// wallet-service/src/mpc-signer.ts

interface MPCConfig {
  threshold: 2;        // 2-of-3 门限
  parties: 3;          // 3个签名分片
  keyShardLocations: [
    'hsm-us-east',     // AWS CloudHSM 美国
    'hsm-sg',          // AWS CloudHSM 新加坡
    'cold-storage'     // 离线冷存储(灾备)
  ];
}

class MPCSigner {
  /// 用户无感签名:平台代签,用户只需确认操作
  async signTransaction(userId: string, txData: TransactionRequest): Promise<string> {
    // 1. 从加密存储获取用户地址
    const address = await this.keyMapping.getAddress(userId);

    // 2. 构造EVM交易
    const tx = await this.buildTransaction(address, txData);

    // 3. MPC门限签名2-of-3分片协作无完整私钥出现
    const signature = await this.mpcProtocol.sign(tx.hash(), {
      keyId: address,
      parties: ['hsm-us-east', 'hsm-sg'],  // 任选2个分片
    });

    // 4. 广播
    return this.provider.sendTransaction(tx.serialize(signature));
  }
}

4.2 机构托管钱包(面向发行方/做市商)

特性 说明
密钥管理 机构自持HSM或第三方托管Fireblocks/Copper
多签 机构内部多签审批流2-of-3或3-of-5
白名单 只能向预审批地址转账
限额 单笔/日累计限额,超额需额外审批
审计 所有操作记录,导出给机构合规部门
// 机构钱包接口
interface InstitutionalWallet {
  // 发行方操作
  mintCoupons(batch: MintRequest): Promise<TxReceipt>;       // 铸造券
  depositGuarantee(amount: bigint): Promise<TxReceipt>;       // 缴纳保障资金
  withdrawRevenue(amount: bigint): Promise<TxReceipt>;        // 提取销售收入

  // 做市商操作
  placeOrder(order: OrderRequest): Promise<TxReceipt>;        // 挂单
  cancelOrder(orderId: string): Promise<TxReceipt>;           // 撤单
  batchSettle(trades: TradeRequest[]): Promise<TxReceipt[]>;  // 批量结算

  // 多签管理
  proposeTransaction(tx: TransactionRequest): Promise<string>;     // 提案
  approveTransaction(proposalId: string): Promise<void>;           // 审批
  getApprovalStatus(proposalId: string): Promise<ApprovalStatus>;  // 查询审批状态
}

4.3 治理多签钱包(面向平台管理层)

Governance多签钱包Gnosis Safe部署在Genex Chain上
  签名人5个平台高管/董事
  门限3/5常规操作或 4/5紧急操作

  职责:
  ├── 合约升级审批
  ├── 紧急冻结执行
  ├── Gas参数调整
  ├── 新稳定币白名单
  ├── 验证节点准入审批
  └── 保障资金赔付执行

5. Gas RelayerMeta-Transaction 中继器)

用户零Gas体验的技术实现。用户签名操作意图Relayer代付Gas广播上链。

5.1 工作流

用户App → 签名meta-txEIP-712→ Relayer服务 → 包装为链上TXRelayer付Gas→ Genex Chain

5.2 实现

// gas-relayer/src/relayer.ts

class GasRelayer {
  private relayerWallet: Wallet;  // Relayer热钱包预充GNX
  private nonceManager: NonceManager;

  /// 接收用户的meta-transaction代付Gas广播
  async relay(metaTx: MetaTransaction): Promise<string> {
    // 1. 验证用户签名EIP-712
    const signer = verifyTypedData(metaTx.domain, metaTx.types, metaTx.value, metaTx.signature);
    require(signer === metaTx.from, "Invalid signature");

    // 2. 防重放检查nonce
    require(await this.checkNonce(metaTx.from, metaTx.nonce), "Nonce already used");

    // 3. 构造链上交易Relayer为tx.originGas由Relayer钱包支付
    const tx = await this.relayerWallet.sendTransaction({
      to: metaTx.target,            // 目标合约
      data: metaTx.calldata,         // 用户操作编码
      gasLimit: metaTx.gasLimit,
      nonce: await this.nonceManager.next(),
    });

    // 4. Gas费用记账从平台Gas补贴池扣除
    await this.accounting.recordGasSpent(metaTx.from, tx.gasUsed);

    return tx.hash;
  }
}

5.3 运维指标

指标 阈值
Relayer热钱包GNX余额 < 10,000 GNX 时自动从补贴池补充
并发中继能力 ≥ 1,000 TPS
Nonce管理 Redis原子递增防nonce冲突
熔断器 单用户每分钟 > 50 笔时触发限流

6. 链监控与运维平台

6.1 监控栈

Genex Chain 节点 → Prometheus Exporter → Prometheus → Grafana Dashboard
                                                          │
CometBFT Metrics ──────────────────────────────────────────┤
EVM Metrics ────────────────────────────────────────────────┤
Application Metrics ────────────────────────────────────────┘
                                                          │
                                                    AlertManager → PagerDuty / Slack

6.2 关键监控指标

类别 指标 告警阈值
共识 出块时间 > 3s 告警
共识 验证节点在线率 < 80% 严重告警
共识 共识轮次 > 3轮未达成共识告警
EVM 交易成功率 < 95% 告警
EVM 待处理交易池 > 5000 笔告警
EVM 平均Gas消耗 异常波动告警
存储 区块数据磁盘使用 > 80% 告警
存储 状态数据库大小 周增长 > 20% 告警
网络 P2P连接数 < 10 peers 告警
网络 区块同步延迟 > 10 blocks 告警
业务 日铸造券数量 异常波动告警
业务 大额交易频率 突增告警(可能洗钱)
Relayer 热钱包余额 < 10,000 GNX 告警
跨链桥 桥锁定资产偏差 > 0.01% 严重告警

6.3 Grafana Dashboard

{
  "dashboard": "Genex Chain Operations",
  "panels": [
    { "title": "Block Height", "type": "stat", "query": "cometbft_consensus_height" },
    { "title": "Block Time", "type": "graph", "query": "rate(cometbft_consensus_height[1m])" },
    { "title": "Validator Status", "type": "table", "query": "cometbft_consensus_validators" },
    { "title": "TX Throughput", "type": "graph", "query": "rate(evm_tx_count[5m])" },
    { "title": "Mempool Size", "type": "gauge", "query": "cometbft_mempool_size" },
    { "title": "Relayer GNX Balance", "type": "stat", "query": "relayer_wallet_balance_gnx" },
    { "title": "Coupon Minted (24h)", "type": "stat", "query": "increase(coupon_minted_total[24h])" },
    { "title": "Bridge TVL", "type": "graph", "query": "bridge_total_value_locked" }
  ]
}

7. 测试网水龙头Faucet

为开发者和测试用户分发测试网 GNX 和测试稳定币。

// faucet-service/src/faucet.ts

class Faucet {
  // 限制每个地址每24小时最多领取一次
  // 分发量100 GNX + 10,000 USDC测试币

  async drip(address: string): Promise<{ gnxTxHash: string; usdcTxHash: string }> {
    // 频率检查
    require(!await this.hasClaimedRecently(address), "Already claimed in last 24h");

    // 分发GNX原生代币
    const gnxTx = await this.faucetWallet.sendTransaction({
      to: address,
      value: parseEther("100"),
    });

    // 分发测试USDC调用MockUSDC合约mint
    const usdcTx = await this.mockUsdc.mint(address, parseUnits("10000", 6));

    return { gnxTxHash: gnxTx.hash, usdcTxHash: usdcTx.hash };
  }
}

部署地址: https://faucet.testnet.gogenex.com


8. 开发者SDK

为外部开发者和内部微服务提供类型安全的链交互工具。

8.1 SDK 矩阵

SDK 语言 用途
genex-sdk-js TypeScript/JavaScript 前端admin-web、Node.js后端微服务
genex-sdk-go Go trading-service、chain-indexer
genex-sdk-dart Dart genex-mobile、admin-app

8.2 JS SDK 核心接口

// @genex/sdk

import { GenexClient } from '@genex/sdk';

const client = new GenexClient({
  rpcUrl: 'https://rpc.gogenex.com',
  chainId: 8888,
});

// 查询券信息
const coupon = await client.coupon.getDetail(tokenId);
// → { faceValue, couponType, expiryDate, resaleCount, transferable, issuer }

// 查询地址持有的券
const holdings = await client.coupon.getHoldings(address);

// 监听事件
client.events.on('CouponBatchMinted', (event) => {
  console.log(`新券发行: ${event.quantity}张, 面值${event.faceValue}`);
});

// 合约交互(需签名)
const tx = await client.settlement.executeSwap(tokenId, buyer, seller, price, {
  signer: mpcSigner, // MPC签名器
});

8.3 Go SDK 核心接口

// github.com/gogenex/genex-sdk-go

package genex

type Client struct {
    rpcURL  string
    chainID int64
}

// 查询券详情
func (c *Client) GetCouponDetail(tokenId *big.Int) (*CouponDetail, error)

// 监听链上事件
func (c *Client) SubscribeEvents(ctx context.Context, filter EventFilter) (<-chan ChainEvent, error)

// 构造+签名+广播交易
func (c *Client) ExecuteSwap(params SwapParams, signer Signer) (*TxReceipt, error)

8.4 Dart SDK 核心接口

// package:genex_sdk

class GenexClient {
  final String rpcUrl;
  final int chainId;

  /// 查询用户持有的券列表
  Future<List<CouponHolding>> getHoldings(String address);

  /// 查询券详情
  Future<CouponDetail> getCouponDetail(BigInt tokenId);

  /// 监听事件流
  Stream<ChainEvent> subscribeEvents(EventFilter filter);
}

9. 归档节点Archive Node

项目 说明
用途 保存链创世以来的全部历史状态,支持任意历史区块的状态查询
普通全节点 只保留最近N个区块的状态默认pruning
归档节点 保留所有状态,支持 eth_call 指定任意区块号
存储需求 远大于普通节点(预估年增长 500GB-2TB
部署数量 至少2个美国+新加坡各一)
使用者 Blockscout、监管API、历史数据分析、审计
# genex-chain/config/app.toml — 归档节点配置
[pruning]
  pruning = "nothing"    # 不裁剪任何状态
  pruning-keep-recent = "0"
  pruning-interval = "0"

[state-sync]
  snapshot-interval = 1000  # 每1000块生成快照供新节点快速同步

10. 跨链桥监控

10.1 监控架构

Ethereum ←── Axelar Bridge ──→ Genex Chain

监控要点:
├── 锁定资产一致性Ethereum侧锁定 = Genex Chain侧铸造
├── 桥交易延迟:正常 < 5分钟> 15分钟告警
├── 大额桥转账:> $100,000 触发人工审核
├── Axelar验证者状态签名节点在线率
└── 紧急暂停:异常时自动暂停桥,需多签恢复

10.2 桥对账服务

// bridge-monitor/src/monitor.ts

class BridgeMonitor {
  /// 定期对账:两侧资产必须一致
  async reconcile(): Promise<ReconciliationResult> {
    // Ethereum侧查询Axelar Gateway合约锁定的USDC
    const ethLocked = await this.ethGateway.getLockedAmount('USDC');

    // Genex Chain侧查询桥铸造的wrapped USDC总量
    const genexMinted = await this.genexBridgeToken.totalSupply();

    const discrepancy = Math.abs(ethLocked - genexMinted);

    if (discrepancy > ethLocked * 0.0001) { // > 0.01% 偏差
      await this.alert.critical('Bridge asset discrepancy detected', { ethLocked, genexMinted });
      await this.emergencyPause(); // 自动暂停桥
    }

    return { ethLocked, genexMinted, discrepancy, healthy: discrepancy === 0 };
  }
}

11. 合约源码验证与安全

工具 用途
Blockscout合约验证 上传源码+编译参数链上bytecode比对
Foundry verify CI/CD自动验证新部署合约
Slither 静态分析CI集成每次PR必须通过
Mythril 符号执行漏洞检测
第三方审计 Trail of Bits / OpenZeppelin / Certik上线前必须
# .github/workflows/contract-security.yml
name: Contract Security
on: [push, pull_request]
jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Foundry Tests
        run: cd genex-contracts && forge test -vvv
      - name: Slither Analysis
        uses: crytic/slither-action@v0.3
        with:
          target: genex-contracts/
      - name: Mythril Scan
        run: myth analyze genex-contracts/src/*.sol --solv 0.8.20

12. 生态基础设施部署清单

组件 技术栈 部署位置 端口 依赖
Blockscout Elixir + PostgreSQL US-East + SG 4000 genexd RPC
企业API NestJS US-East + SG 3020 Kong, genexd, PostgreSQL
MPC签名服务 Go + AWS CloudHSM US-East + SG + Cold 3021 CloudHSM
Gas Relayer NestJS US-East + SG 3022 genexd, Redis
Faucet NestJS US-East 3023 genexd(testnet)
Bridge Monitor Go US-East + SG 3024 Axelar, genexd, Ethereum
链监控 Prometheus + Grafana US-East 9090/3000 genexd metrics
归档节点 genexd (pruning=nothing) US-East + SG 8545/26657 大容量存储
JS SDK TypeScript (npm) npm registry
Go SDK Go module go proxy
Dart SDK Dart (pub.dev) pub.dev

与现有后端微服务的端口分配

已有服务06-区块链开发指南 / 05-后端开发指南):
  3001-3010  — 10个后端微服务
  3009       — chain-indexer已有链事件索引
  8080       — Kong API Gateway
  8545       — genexd EVM JSON-RPC
  26657      — genexd CometBFT RPC

新增生态服务(本文档):
  3020       — 企业API服务
  3021       — MPC签名服务
  3022       — Gas Relayer
  3023       — 测试网Faucet
  3024       — 跨链桥监控
  4000       — Blockscout浏览器
  9090       — Prometheus
  3000       — Grafana注意与admin-web的Next.js dev port区分

文档版本: v1.0 基于: 06-区块链开发指南 v3.0(量产版) 覆盖: 区块浏览器(Blockscout)、企业API网关(4层认证)、三层钱包体系(用户MPC/机构HSM/治理多签)、Gas Relayer(Meta-TX)、链监控(Prometheus+Grafana)、测试网水龙头、开发者SDK(JS/Go/Dart)、归档节点、跨链桥监控(Axelar)、合约安全CI(Slither+Mythril)