-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.go
233 lines (193 loc) · 4.56 KB
/
peer.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
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
// Copyright (C) 2021 Aung Maw
// Copyright (C) 2023 Wooyang2018
// Licensed under the GNU General Public License v3.0
package p2p
import (
"encoding/binary"
"fmt"
"io"
"math/rand"
"sync"
"time"
ma "github.com/multiformats/go-multiaddr"
"github.com/wooyang2018/ppov-blockchain/core"
"github.com/wooyang2018/ppov-blockchain/emitter"
"github.com/wooyang2018/ppov-blockchain/logger"
)
// PeerStatus type
type PeerStatus int8
// PeerStatus
const (
PeerStatusDisconnected PeerStatus = iota
PeerStatusConnecting
PeerStatusConnected
PeerStatusBlocked
)
const (
// message size limit in bytes (~100 MB)
// to avoid out of memory allocation for reading next message
MessageSizeLimit uint32 = 100000000
)
// Peer type
type Peer struct {
pubKey *core.PublicKey
name string
pointAddr ma.Multiaddr
topicAddr ma.Multiaddr
status PeerStatus
rwc io.ReadWriteCloser
emitter *emitter.Emitter
mtxRWC sync.RWMutex
mtxStatus sync.RWMutex
mtxWrite sync.Mutex
reconInterval time.Duration
fastReconCount int
mtxRecon sync.RWMutex
host *Host
}
func NewPeer(pubKey *core.PublicKey, pointAddr, topicAddr ma.Multiaddr) *Peer {
p := &Peer{
pubKey: pubKey,
pointAddr: pointAddr,
topicAddr: topicAddr,
status: PeerStatusDisconnected,
emitter: emitter.New(),
}
p.resetReconnectInterval()
return p
}
// PublicKey returns public key of peer
func (p *Peer) PublicKey() *core.PublicKey {
return p.pubKey
}
// PointAddr return network address of peer
func (p *Peer) PointAddr() ma.Multiaddr {
return p.pointAddr
}
func (p *Peer) SetName(name string) {
p.name = name
}
func (p *Peer) Name() string {
return p.name
}
func (p *Peer) Status() PeerStatus {
p.mtxStatus.RLock()
defer p.mtxStatus.RUnlock()
return p.status
}
func (p *Peer) disconnect() {
p.mtxStatus.Lock()
defer p.mtxStatus.Unlock()
if p.status == PeerStatusConnected {
logger.I().Infow("peer disconnected", "pointAddr", p.pointAddr)
}
p.status = PeerStatusDisconnected
rwc := p.getRWC()
if rwc != nil {
rwc.Close()
}
p.reconnectAfterInterval()
}
func (p *Peer) reconnectAfterInterval() {
reconnInterval := p.increaseReconnectInterval() +
(time.Duration(rand.Intn(500)) * time.Millisecond)
time.AfterFunc(reconnInterval, func() {
if p.host != nil {
p.host.ConnectLeader()
}
})
}
func (p *Peer) setConnecting() error {
p.mtxStatus.Lock()
defer p.mtxStatus.Unlock()
if p.status != PeerStatusDisconnected {
return fmt.Errorf("status must be disconnected")
}
p.status = PeerStatusConnecting
logger.I().Infow("connecting", "pointAddr", p.pointAddr)
return nil
}
func (p *Peer) onConnected(rwc io.ReadWriteCloser) {
p.mtxStatus.Lock()
defer p.mtxStatus.Unlock()
logger.I().Infow("peer connected", "name", p.name, "pointAddr", p.pointAddr)
p.status = PeerStatusConnected
p.setRWC(rwc)
p.resetReconnectInterval()
go p.listen()
}
func (p *Peer) listen() {
defer p.disconnect()
for {
msg, err := p.read()
if err != nil {
return
}
p.emitter.Emit(msg)
}
}
func (p *Peer) read() ([]byte, error) {
b, err := p.readFixedSize(4)
if err != nil {
return nil, err
}
size := binary.BigEndian.Uint32(b)
if size > MessageSizeLimit {
return nil, fmt.Errorf("big message size %d", size)
}
return p.readFixedSize(size)
}
func (p *Peer) readFixedSize(size uint32) ([]byte, error) {
b := make([]byte, size)
_, err := io.ReadFull(p.getRWC(), b)
return b, err
}
func (p *Peer) WriteMsg(msg []byte) error {
p.mtxWrite.Lock()
defer p.mtxWrite.Unlock()
if p.Status() != PeerStatusConnected {
return fmt.Errorf("peer %s not connected", p.name)
}
return p.write(msg)
}
func (p *Peer) write(b []byte) error {
payload := make([]byte, 4, 4+len(b))
binary.BigEndian.PutUint32(payload, uint32(len(b)))
payload = append(payload, b...)
_, err := p.getRWC().Write(payload)
return err
}
func (p *Peer) SubscribeMsg() *emitter.Subscription {
return p.emitter.Subscribe(10)
}
func (p *Peer) setRWC(rwc io.ReadWriteCloser) {
p.mtxRWC.Lock()
defer p.mtxRWC.Unlock()
p.rwc = rwc
}
func (p *Peer) getRWC() io.ReadWriteCloser {
p.mtxRWC.RLock()
defer p.mtxRWC.RUnlock()
return p.rwc
}
func (p *Peer) resetReconnectInterval() {
p.mtxRecon.Lock()
defer p.mtxRecon.Unlock()
p.reconInterval = 1 * time.Second
p.fastReconCount = 3
}
func (p *Peer) increaseReconnectInterval() time.Duration {
p.mtxRecon.Lock()
defer p.mtxRecon.Unlock()
if p.fastReconCount > 0 {
p.fastReconCount--
return p.reconInterval
}
p.reconInterval *= 2
p.fastReconCount = 3
maxInterval := 32 * time.Second
if p.reconInterval > maxInterval {
p.reconInterval = maxInterval
}
return p.reconInterval
}