实现简化版 Optimistic/ZK Rollup 后端,包含批量交易处理、状态提交与欺诈证明
┌─────────────────────────────────────────────────────────────┐ │ User Interface │ │ (Wallet / DApp / SDK) │ ├─────────────────────────────────────────────────────────────┤ │ Sequencer Service │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ TX Receiver │ │ TX Orderer │ │Batch Builder │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ State Manager │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Merkle Tree │ │State Compute │ │ State Store │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ L1 Interaction │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │Batch Submitter│ │Fraud Prover │ │Force Withdraw│ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ L1 Contracts (Rollup, Bridge, Verifier) │ └─────────────────────────────────────────────────────────────┘
1// Sequencer L2 排序器服务2type Sequencer struct {3 pendingTxs chan *Transaction4 batchSize int5 batchTime time.Duration6 stateDB *StateDB7 l1Submitter *L1Submitter8}9 10// Transaction L2 交易11type Transaction struct {12 From common.Address13 To common.Address14 Value *big.Int15 Data []byte16 Nonce uint6417 Signature []byte18}19 20// Batch 交易批次21type Batch struct {22 Number uint6423 Transactions []*Transaction24 PreStateRoot common.Hash25 PostStateRoot common.Hash26 Timestamp time.Time27}28 29// BuildBatch 构建交易批次30func (s *Sequencer) BuildBatch(ctx context.Context) (*Batch, error) {31 batch := &Batch{32 Number: s.getNextBatchNumber(),33 PreStateRoot: s.stateDB.Root(),34 Timestamp: time.Now(),35 }36 37 timer := time.NewTimer(s.batchTime)38 defer timer.Stop()39 40 for {41 select {42 case tx := <-s.pendingTxs:43 // 验证交易44 if err := s.validateTransaction(tx); err != nil {45 log.Warn("Invalid tx", "err", err)46 continue47 }48 49 // 执行状态转换50 if err := s.stateDB.ApplyTransaction(tx); err != nil {51 log.Warn("Apply tx failed", "err", err)52 continue53 }54 55 batch.Transactions = append(batch.Transactions, tx)56 57 // 达到批次大小上限58 if len(batch.Transactions) >= s.batchSize {59 batch.PostStateRoot = s.stateDB.Root()60 return batch, nil61 }62 63 case <-timer.C:64 // 超时,提交当前批次(即使未满)65 if len(batch.Transactions) > 0 {66 batch.PostStateRoot = s.stateDB.Root()67 return batch, nil68 }69 timer.Reset(s.batchTime)70 71 case <-ctx.Done():72 return nil, ctx.Err()73 }74 }75}1// SparseMerkleTree 稀疏 Merkle 树2type SparseMerkleTree struct {3 db Database4 root common.Hash5 height int6 hasher hash.Hash7 cache *lru.Cache8}9 10// Update 更新叶子节点11func (t *SparseMerkleTree) Update(12 key common.Hash,13 value []byte,14) (common.Hash, error) {15 // 计算叶子哈希16 leafHash := t.hashLeaf(key, value)17 18 // 获取从根到叶子的路径19 path := t.getPath(key)20 21 // 从叶子向上更新22 currentHash := leafHash23 for i := t.height - 1; i >= 0; i-- {24 sibling, err := t.getSibling(path, i)25 if err != nil {26 return common.Hash{}, err27 }28 29 // 根据路径位确定左右30 if path[i] == 0 {31 currentHash = t.hashNode(currentHash, sibling)32 } else {33 currentHash = t.hashNode(sibling, currentHash)34 }35 36 // 缓存中间节点37 t.cache.Add(currentHash, struct{}{})38 }39 40 // 更新根41 oldRoot := t.root42 t.root = currentHash43 44 // 存储更新45 t.db.Put(key[:], value)46 47 log.Debug("SMT updated",48 "key", key.Hex()[:10],49 "oldRoot", oldRoot.Hex()[:10],50 "newRoot", t.root.Hex()[:10],51 )52 53 return t.root, nil54}55 56// GenerateProof 生成 Merkle 证明57func (t *SparseMerkleTree) GenerateProof(58 key common.Hash,59) (*MerkleProof, error) {60 path := t.getPath(key)61 siblings := make([]common.Hash, t.height)62 63 for i := 0; i < t.height; i++ {64 sibling, err := t.getSibling(path, i)65 if err != nil {66 return nil, err67 }68 siblings[i] = sibling69 }70 71 return &MerkleProof{72 Key: key,73 Siblings: siblings,74 Root: t.root,75 }, nil76}