aboutsummaryrefslogtreecommitdiffstats
path: root/core/total-ordering-syncer.go
blob: aa90a1ded042560fa7a1c77cd0359bf730edaff8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// Copyright 2018 The dexon-consensus Authors
// This file is part of the dexon-consensus library.
//
// The dexon-consensus library is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// The dexon-consensus library is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the dexon-consensus library. If not, see
// <http://www.gnu.org/licenses/>.

package core

import (
    "sort"
    "sync"

    "github.com/dexon-foundation/dexon-consensus/common"
    "github.com/dexon-foundation/dexon-consensus/core/types"
)

type totalOrderingSyncer struct {
    lock sync.RWMutex

    numChains          uint32
    syncHeight         map[uint32]uint64
    syncDeliverySetIdx int
    pendingBlocks      []*types.Block
    inPendingBlocks    map[common.Hash]struct{}

    bootstrapChain map[uint32]struct{}

    // Data to restore delivery set.
    pendingDeliveryBlocks []*types.Block
    deliverySet           map[int][]*types.Block
    mapToDeliverySet      map[common.Hash]int
}

func newTotalOrderingSyncer(numChains uint32) *totalOrderingSyncer {
    return &totalOrderingSyncer{
        numChains:          numChains,
        syncHeight:         make(map[uint32]uint64),
        syncDeliverySetIdx: -1,
        inPendingBlocks:    make(map[common.Hash]struct{}),
        bootstrapChain:     make(map[uint32]struct{}),
        deliverySet:        make(map[int][]*types.Block),
        mapToDeliverySet:   make(map[common.Hash]int),
    }
}

func (tos *totalOrderingSyncer) synced() bool {
    tos.lock.RLock()
    defer tos.lock.RUnlock()
    return tos.syncDeliverySetIdx != -1
}

func (tos *totalOrderingSyncer) processBlock(
    block *types.Block) (delivered []*types.Block) {
    if tos.synced() {
        if tos.syncHeight[block.Position.ChainID] >= block.Position.Height {
            return
        }
        delivered = append(delivered, block)
        return
    }
    tos.lock.Lock()
    defer tos.lock.Unlock()
    tos.inPendingBlocks[block.Hash] = struct{}{}
    tos.pendingBlocks = append(tos.pendingBlocks, block)
    if block.Position.Height == 0 {
        tos.bootstrapChain[block.Position.ChainID] = struct{}{}
    }
    if uint32(len(tos.bootstrapChain)) == tos.numChains {
        // Bootstrap mode.
        delivered = tos.pendingBlocks
        tos.syncDeliverySetIdx = 0
        for i := uint32(0); i < tos.numChains; i++ {
            tos.syncHeight[i] = uint64(0)
        }
    } else {
        maxDeliverySetIdx := -1
        // TODO(jimmy-dexon): below for loop can be optimized.
    PendingBlockLoop:
        for i, block := range tos.pendingBlocks {
            idx, exist := tos.mapToDeliverySet[block.Hash]
            if !exist {
                continue
            }
            deliverySet := tos.deliverySet[idx]
            // Check if all the blocks in deliverySet are in the pendingBlocks.
            for _, dBlock := range deliverySet {
                if _, exist := tos.inPendingBlocks[dBlock.Hash]; !exist {
                    continue PendingBlockLoop
                }
            }
            if idx > maxDeliverySetIdx {
                maxDeliverySetIdx = idx
            }
            // Check if all of the chains have delivered.
            for _, dBlock := range deliverySet {
                if h, exist := tos.syncHeight[dBlock.Position.ChainID]; exist {
                    if dBlock.Position.Height < h {
                        continue
                    }
                }
                tos.syncHeight[dBlock.Position.ChainID] = dBlock.Position.Height
            }
            if uint32(len(tos.syncHeight)) != tos.numChains {
                continue
            }
            // Core is fully synced, it can start delivering blocks from idx.
            tos.syncDeliverySetIdx = maxDeliverySetIdx
            delivered = make([]*types.Block, 0, i)
            break
        }
        if tos.syncDeliverySetIdx == -1 {
            return
        }
        // Generating delivering blocks.
        for i := maxDeliverySetIdx; i < len(tos.deliverySet); i++ {
            deliverySet := tos.deliverySet[i]
            sort.Sort(types.ByHash(deliverySet))
            for _, block := range deliverySet {
                if block.Position.Height > tos.syncHeight[block.Position.ChainID] {
                    tos.syncHeight[block.Position.ChainID] = block.Position.Height
                }
                delivered = append(delivered, block)
            }
        }
        // Flush remaining blocks.
        for _, block := range tos.pendingBlocks {
            if _, exist := tos.mapToDeliverySet[block.Hash]; exist {
                continue
            }
            if block.Position.Height > tos.syncHeight[block.Position.ChainID] {
                tos.syncHeight[block.Position.ChainID] = block.Position.Height
            }
            delivered = append(delivered, block)
        }
    }
    // Clean internal data model to save memory.
    tos.pendingBlocks = nil
    tos.inPendingBlocks = nil
    tos.bootstrapChain = nil
    tos.pendingDeliveryBlocks = nil
    tos.deliverySet = nil
    tos.mapToDeliverySet = nil
    return
}

// The finalized block should be passed by the order of consensus height.
func (tos *totalOrderingSyncer) processFinalizedBlock(block *types.Block) {
    tos.lock.Lock()
    defer tos.lock.Unlock()
    if len(tos.pendingDeliveryBlocks) > 0 {
        if block.Hash.Less(
            tos.pendingDeliveryBlocks[len(tos.pendingDeliveryBlocks)-1].Hash) {
            // pendingDeliveryBlocks forms a deliverySet.
            idx := len(tos.deliverySet)
            tos.deliverySet[idx] = tos.pendingDeliveryBlocks
            for _, block := range tos.pendingDeliveryBlocks {
                tos.mapToDeliverySet[block.Hash] = idx
            }
            tos.pendingDeliveryBlocks = []*types.Block{}
        }
    }
    tos.pendingDeliveryBlocks = append(tos.pendingDeliveryBlocks, block)
}