|
| 1 | +package rollup |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "sync" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/33cn/chain33/common/log" |
| 9 | + "github.com/33cn/chain33/system/consensus" |
| 10 | + "github.com/33cn/chain33/types" |
| 11 | + "github.com/golang/groupcache/lru" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + minCommitTxCount = 128 |
| 16 | +) |
| 17 | + |
| 18 | +var ( |
| 19 | + rlog = log.New("module", "rollup") |
| 20 | +) |
| 21 | + |
| 22 | +func init() { |
| 23 | + consensus.RegCommitter("rollup", &RollUp{}) |
| 24 | +} |
| 25 | + |
| 26 | +// RollUp roll up |
| 27 | +type RollUp struct { |
| 28 | + nextBuildHeight int64 |
| 29 | + nextBuildRound int64 |
| 30 | + cfg Config |
| 31 | + op *optimistic |
| 32 | + |
| 33 | + initDone chan struct{} |
| 34 | + nextCommitRound int32 |
| 35 | + |
| 36 | + currCommitter string |
| 37 | + |
| 38 | + commitCache *lru.Cache |
| 39 | + batchCache sync.Map |
| 40 | + ctx context.Context |
| 41 | + base *consensus.BaseClient |
| 42 | + chainCfg *types.Chain33Config |
| 43 | +} |
| 44 | + |
| 45 | +// Init init |
| 46 | +func (r *RollUp) Init(base *consensus.BaseClient, chainCfg *types.Chain33Config, subCfg []byte) { |
| 47 | + |
| 48 | + if !chainCfg.IsPara() { |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + r.chainCfg = chainCfg |
| 53 | + r.ctx = base.Context |
| 54 | + r.op = &optimistic{} |
| 55 | + r.initDone = make(chan struct{}) |
| 56 | + |
| 57 | + go r.fetchRollupState() |
| 58 | + go r.startRollupRoutine() |
| 59 | +} |
| 60 | + |
| 61 | +func (r *RollUp) fetchRollupState() { |
| 62 | + |
| 63 | + r.initDone <- struct{}{} |
| 64 | +} |
| 65 | + |
| 66 | +func (r *RollUp) startRollupRoutine() { |
| 67 | + |
| 68 | + <-r.initDone |
| 69 | + |
| 70 | + go r.handleBuildBatch() |
| 71 | + go r.handleCommitBatch() |
| 72 | +} |
| 73 | + |
| 74 | +func (r *RollUp) handleBuildBatch() { |
| 75 | + |
| 76 | + ticker := time.NewTicker(time.Second * 10) |
| 77 | + var blocks []*types.Block |
| 78 | + for { |
| 79 | + |
| 80 | + select { |
| 81 | + case <-ticker.C: |
| 82 | + blocks = r.getNextBatchBlocks(r.nextBuildHeight) |
| 83 | + case <-r.ctx.Done(): |
| 84 | + ticker.Stop() |
| 85 | + return |
| 86 | + } |
| 87 | + // 区块内未达到最低批量数量, 需要继续等待 |
| 88 | + if blocks == nil { |
| 89 | + rlog.Debug("handleBuildBatch", "height", r.nextBuildHeight, |
| 90 | + "round", r.nextBuildRound, "msg", "wait more block") |
| 91 | + continue |
| 92 | + } |
| 93 | + |
| 94 | + batch := r.op.GetCommitBatch(blocks) |
| 95 | + r.batchCache.Store(batch.CommitRound, batch) |
| 96 | + r.nextBuildRound++ |
| 97 | + r.nextBuildHeight += int64(len(blocks)) |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +// 提交共识 |
| 102 | +func (r *RollUp) handleCommitBatch() { |
| 103 | + |
| 104 | +} |
| 105 | + |
| 106 | +// 同步链上已提交的最新 blockHeight 和 commitRound, 维护batch缓存 |
| 107 | +func (r *RollUp) syncRollupState() { |
| 108 | + |
| 109 | +} |
0 commit comments