aboutsummaryrefslogtreecommitdiffstats
path: root/simulation/verification.go
blob: a5aad8fdc9450d0d4258dcfeb3beffa194dfc06f (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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// 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 simulation

import (
    "container/heap"
    "log"
    "math"
    "time"

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

type timeStamp struct {
    time   time.Time
    length int
}

type totalOrderStatus struct {
    blockReceive             []timeStamp
    confirmLatency           []time.Duration
    blockSeen                map[common.Hash]time.Time
    internalTimestampLatency []time.Duration
    externalTimestampLatency []time.Duration
}

// TotalOrderResult is the object maintaining peer's result of
// Total Ordering Algorithm.
type TotalOrderResult struct {
    nodeID           types.NodeID
    hashList         common.Hashes
    curID            int
    pendingBlockList PendingBlockList
    status           totalOrderStatus
}

// PeerTotalOrder stores the TotalOrderResult of each node.
type PeerTotalOrder = map[types.NodeID]*TotalOrderResult

// NewTotalOrderResult returns pointer to a a new TotalOrderResult instance.
func NewTotalOrderResult(nID types.NodeID) *TotalOrderResult {
    totalOrder := &TotalOrderResult{
        nodeID: nID,
        status: totalOrderStatus{
            blockSeen: make(map[common.Hash]time.Time),
        },
    }
    heap.Init(&totalOrder.pendingBlockList)
    return totalOrder
}

func (totalOrder *TotalOrderResult) processStatus(blocks BlockList) {
    totalOrder.status.blockReceive = append(totalOrder.status.blockReceive,
        timeStamp{
            time:   time.Now(),
            length: len(blocks.BlockHash),
        })
    totalOrder.status.confirmLatency = append(totalOrder.status.confirmLatency,
        blocks.ConfirmLatency...)
}

// PushBlocks push a BlockList into the TotalOrderResult and return true if
// there are new blocks ready for verification.
func (totalOrder *TotalOrderResult) PushBlocks(blocks BlockList) (ready bool) {
    totalOrder.processStatus(blocks)
    if blocks.ID != totalOrder.curID {
        heap.Push(&totalOrder.pendingBlockList, &blocks)
        return false
    }

    // Append all of the consecutive blockList in the pendingBlockList.
    for {
        totalOrder.hashList = append(totalOrder.hashList, blocks.BlockHash...)
        totalOrder.curID++
        if len(totalOrder.pendingBlockList) == 0 ||
            totalOrder.pendingBlockList[0].ID != totalOrder.curID {
            break
        }
        blocks = *heap.Pop(&totalOrder.pendingBlockList).(*BlockList)
    }
    return true
}

// PushTimestamp logs the information in the msg.
func (totalOrder *TotalOrderResult) PushTimestamp(msg timestampMessage) bool {
    pushLatency := func(latency *[]time.Duration, t1, t2 time.Time) {
        *latency = append(*latency, t2.Sub(t1))
    }
    switch msg.Event {
    case blockSeen:
        totalOrder.status.blockSeen[msg.BlockHash] = msg.Timestamp
    case timestampConfirm:
        pushLatency(&totalOrder.status.internalTimestampLatency,
            totalOrder.status.blockSeen[msg.BlockHash], msg.Timestamp)
    case timestampAck:
        if seenTime, exist := totalOrder.status.blockSeen[msg.BlockHash]; exist {
            pushLatency(&totalOrder.status.externalTimestampLatency,
                seenTime, msg.Timestamp)
        }
    default:
        return false
    }
    return true
}

// CalculateBlocksPerSecond calculates the result using status.blockReceive
func (totalOrder *TotalOrderResult) CalculateBlocksPerSecond() float64 {
    ts := totalOrder.status.blockReceive
    if len(ts) < 2 {
        return 0
    }

    diffTime := ts[len(ts)-1].time.Sub(ts[0].time).Seconds()
    if diffTime == 0 {
        return 0
    }
    totalBlocks := 0
    for _, blocks := range ts {
        // Blocks received at time zero are confirmed beforehand.
        if blocks.time == ts[0].time {
            continue
        }
        totalBlocks += blocks.length
    }
    return float64(totalBlocks) / diffTime
}

// CalculateAverageConfirmLatency calculates the result using
// status.confirmLatency
func (totalOrder *TotalOrderResult) CalculateAverageConfirmLatency() float64 {
    sum := 0.0
    for _, latency := range totalOrder.status.confirmLatency {
        sum += latency.Seconds()
    }
    return sum / float64(len(totalOrder.status.confirmLatency))
}

// CalculateAverageTimestampLatency calculates the result using
// status.timestampLatency
func (totalOrder *TotalOrderResult) CalculateAverageTimestampLatency() (
    internal float64, external float64) {
    for _, latency := range totalOrder.status.internalTimestampLatency {
        internal += latency.Seconds()
    }
    if internal > 0 {
        internal /= float64(len(totalOrder.status.internalTimestampLatency))
    }
    for _, latency := range totalOrder.status.externalTimestampLatency {
        external += latency.Seconds()
    }
    if external > 0 {
        external /= float64(len(totalOrder.status.externalTimestampLatency))
    }
    return
}

// VerifyTotalOrder verifies if the result of Total Ordering Algorithm
// returned by all nodes are the same. However, the length of result
// of each nodes may not be the same, so only the common part is verified.
func VerifyTotalOrder(id types.NodeID,
    totalOrder PeerTotalOrder) (
    unverifiedMap PeerTotalOrder, correct bool, length int) {

    hasError := false

    // Get the common length from all nodes.
    length = math.MaxInt32
    for _, peerTotalOrder := range totalOrder {
        if len(peerTotalOrder.hashList) < length {
            length = len(peerTotalOrder.hashList)
        }
    }

    // Verify if the order of the blocks are the same by comparing
    // the hash value.
    for i := 0; i < length; i++ {
        hash := totalOrder[id].hashList[i]
        for vid, peerTotalOrder := range totalOrder {
            if peerTotalOrder.hashList[i] != hash {
                log.Printf("[%d] Unexpected hash %v from %v\n", i,
                    peerTotalOrder.hashList[i], vid)
                hasError = true
            }
        }
        if hasError {
            log.Printf("[%d] Hash is %v from %v\n", i, hash, id)
        } else {
            log.Printf("Block %v confirmed\n", hash)
        }
    }

    // Remove verified block from list.
    if length > 0 {
        for vid := range totalOrder {
            totalOrder[vid].hashList =
                totalOrder[vid].hashList[length:]
        }
    }
    return totalOrder, !hasError, length
}

// LogStatus prints all the status to log.
func LogStatus(peerTotalOrder PeerTotalOrder) {
    for nID, totalOrder := range peerTotalOrder {
        log.Printf("[Node %s]\n", nID)
        log.Printf("    BPS: %.6f\n", totalOrder.CalculateBlocksPerSecond())
        log.Printf("    Confirm Latency: %.2fms\n",
            totalOrder.CalculateAverageConfirmLatency()*1000)
        log.Printf("    Confirm Blocks: %v\n", len(totalOrder.status.confirmLatency))
        intLatency, extLatency := totalOrder.CalculateAverageTimestampLatency()
        log.Printf("    Internal Timestamp Latency: %.2fms\n", intLatency*1000)
        log.Printf("    External Timestamp Latency: %.2fms\n", extLatency*1000)
    }
    logOverallLatency(peerTotalOrder)
}

// logOverallLatency prints overall status related to latency.
func logOverallLatency(peerTotalOrder PeerTotalOrder) {
    // Let's use brute-force way since the simulation should be done
    // at this moment.
    var (
        overallConfirmLatency           []time.Duration
        overallInternalTimestampLatency []time.Duration
        overallExternalTimestampLatency []time.Duration
    )
    for _, totalOrder := range peerTotalOrder {
        overallConfirmLatency = append(
            overallConfirmLatency, totalOrder.status.confirmLatency...)
        overallInternalTimestampLatency = append(
            overallInternalTimestampLatency,
            totalOrder.status.internalTimestampLatency...)
        overallExternalTimestampLatency = append(
            overallExternalTimestampLatency,
            totalOrder.status.externalTimestampLatency...)
    }
    log.Print("[Overall]\n")
    avg, dev := test.CalcLatencyStatistics(overallConfirmLatency)
    log.Printf("    Confirm Latency: %v, dev: %v\n", avg, dev)
    avg, dev = test.CalcLatencyStatistics(overallInternalTimestampLatency)
    log.Printf("    Interal Timestamp Latency: %v, dev: %v\n", avg, dev)
    avg, dev = test.CalcLatencyStatistics(overallExternalTimestampLatency)
    log.Printf("    External Timestamp Latency: %v, dev: %v\n", avg, dev)
}