Skip to content

Commit

Permalink
add simple rtt estimator
Browse files Browse the repository at this point in the history
  • Loading branch information
roman-khimov committed Dec 25, 2024
1 parent 279e52e commit 509366c
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
3 changes: 3 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ type Context[H Hash] struct {
lastBlockTime time.Time // Wall clock time of when the last block was first seen (used for timer adjustments).
lastBlockIndex uint32
lastBlockView byte

prepareSentTime time.Time
rttEstimates rtt
}

// N returns total number of validators.
Expand Down
5 changes: 5 additions & 0 deletions dbft.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ func (d *DBFT[H]) initializeConsensus(view byte, ts uint64) {
var ts = d.Timer.Now()
var diff = ts.Sub(d.lastBlockTime)
timeout -= diff
timeout -= d.rttEstimates.avg
timeout = max(0, timeout)
}
d.changeTimer(timeout)
Expand Down Expand Up @@ -446,6 +447,10 @@ func (d *DBFT[H]) onPrepareResponse(msg ConsensusPayload[H]) {
return
}

if d.IsPrimary() {
d.rttEstimates.addTime(time.Since(d.prepareSentTime))
}

// ignore PrepareResponse if in process of changing view
m := d.PreparationPayloads[msg.ValidatorIndex()]
if m != nil || d.ViewChanging() && !d.MoreThanFNodesCommittedOrLost() {
Expand Down
22 changes: 22 additions & 0 deletions rtt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package dbft

import (
"time"
)

const rttLength = 7 * 10

type rtt struct {
times [rttLength]time.Duration
idx int
avg time.Duration
}

func (r *rtt) addTime(new time.Duration) {
var old = r.times[r.idx]

r.avg = r.avg + (new-old)/time.Duration(len(r.times))
r.avg = max(0, r.avg) // Can't be less than zero.
r.times[r.idx] = new
r.idx = (r.idx + 1) % len(r.times)
}
2 changes: 2 additions & 0 deletions send.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ func (d *DBFT[H]) sendPrepareRequest() {
d.PreparationPayloads[d.MyIndex] = msg
d.broadcast(msg)

d.prepareSentTime = d.Timer.Now()

delay := d.SecondsPerBlock << (d.ViewNumber + 1)
if d.ViewNumber == 0 {
delay -= d.SecondsPerBlock
Expand Down

0 comments on commit 509366c

Please sign in to comment.