-
Notifications
You must be signed in to change notification settings - Fork 1
/
state.go
126 lines (100 loc) · 2.29 KB
/
state.go
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
// Copyright (C) 2021 Aung Maw
// Licensed under the GNU General Public License v3.0
package hotstuff
import (
"fmt"
"sync"
"sync/atomic"
"github.com/aungmawjj/juria-blockchain/emitter"
)
type state struct {
bVote atomic.Value
bLock atomic.Value
bExec atomic.Value
qcHigh atomic.Value
bLeaf atomic.Value
proposal Block
votes map[string]Vote
pMtx sync.RWMutex
qcHighEmitter *emitter.Emitter
}
func newState(b0 Block, q0 QC) *state {
s := new(state)
s.qcHighEmitter = emitter.New()
s.setBVote(b0)
s.setBLock(b0)
s.setBExec(b0)
s.setBLeaf(b0)
s.setQCHigh(q0)
return s
}
func (s *state) setBVote(b Block) { s.bVote.Store(b) }
func (s *state) setBLock(b Block) { s.bLock.Store(b) }
func (s *state) setBExec(b Block) { s.bExec.Store(b) }
func (s *state) setBLeaf(bNew Block) { s.bLeaf.Store(bNew) }
func (s *state) setQCHigh(qcHigh QC) { s.qcHigh.Store(qcHigh) }
func (s *state) SubscribeNewQCHigh() *emitter.Subscription {
return s.qcHighEmitter.Subscribe(10)
}
func (s *state) GetBVote() Block {
return s.bVote.Load().(Block)
}
func (s *state) GetBLock() Block {
return s.bLock.Load().(Block)
}
func (s *state) GetBExec() Block {
return s.bExec.Load().(Block)
}
func (s *state) GetBLeaf() Block {
return s.bLeaf.Load().(Block)
}
func (s *state) GetQCHigh() QC {
return s.qcHigh.Load().(QC)
}
func (s *state) IsProposing() bool {
s.pMtx.RLock()
defer s.pMtx.RUnlock()
return s.proposal != nil
}
func (s *state) startProposal(b Block) {
s.pMtx.Lock()
defer s.pMtx.Unlock()
s.proposal = b
s.votes = make(map[string]Vote)
}
func (s *state) endProposal() {
s.pMtx.Lock()
defer s.pMtx.Unlock()
s.proposal = nil
s.votes = nil
}
func (s *state) addVote(v Vote) error {
s.pMtx.Lock()
defer s.pMtx.Unlock()
if s.proposal == nil {
return fmt.Errorf("no proposal in progress")
}
if !s.proposal.Equal(v.Block()) {
return fmt.Errorf("not same block")
}
key := v.Voter()
if _, found := s.votes[key]; found {
return fmt.Errorf("duplicate vote")
}
s.votes[key] = v
return nil
}
func (s *state) GetVoteCount() int {
s.pMtx.RLock()
defer s.pMtx.RUnlock()
return len(s.votes)
}
func (s *state) GetVotes() []Vote {
s.pMtx.RLock()
defer s.pMtx.RUnlock()
votes := make([]Vote, 0, len(s.votes))
for _, v := range s.votes {
votes = append(votes, v)
}
return votes
}