-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeer.go
109 lines (92 loc) · 2.28 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
package common
import (
"bytes"
"github.com/gagarinchain/common/eth/common"
"github.com/gagarinchain/common/eth/crypto"
pb "github.com/gagarinchain/common/protobuff"
"github.com/libp2p/go-libp2p-core/peer"
"math/big"
)
type Peer struct {
address common.Address
publicKey *crypto.PublicKey
privateKey *crypto.PrivateKey
peerInfo *peer.AddrInfo
}
func (p *Peer) SetPublicKey(publicKey *crypto.PublicKey) {
p.publicKey = publicKey
}
func (p *Peer) SetPrivateKey(privateKey *crypto.PrivateKey) {
p.privateKey = privateKey
}
func (p *Peer) GetAddress() common.Address {
return p.address
}
func (p *Peer) SetAddress(address common.Address) {
p.address = address
}
func (p *Peer) GetPrivateKey() *crypto.PrivateKey {
return p.privateKey
}
func CreatePeer(publicKey *crypto.PublicKey, privateKey *crypto.PrivateKey, peerInfo *peer.AddrInfo) *Peer {
peer := &Peer{
publicKey: publicKey,
privateKey: privateKey,
peerInfo: peerInfo,
}
if publicKey != nil {
peer.address = common.BytesToAddress(publicKey.Bytes())
}
return peer
}
func (p *Peer) Equals(toCompare *Peer) bool {
return bytes.Compare(p.address.Bytes(), toCompare.address.Bytes()) == 0
}
func (p *Peer) GetPeerInfo() *peer.AddrInfo {
return p.peerInfo
}
func (p *Peer) PublicKey() *crypto.PublicKey {
return p.publicKey
}
func (p *Peer) ToStorageProto() *pb.Peer {
json, err := p.peerInfo.MarshalJSON()
if err != nil {
log.Error("Error while serializing peerInfo", err)
return nil
}
return &pb.Peer{
Address: p.address.Bytes(),
PublicKey: p.publicKey.Bytes(),
AddrInfo: json,
}
}
func CreatePeerFromStorage(p *pb.Peer) *Peer {
info := &peer.AddrInfo{}
if err := info.UnmarshalJSON(p.AddrInfo); err != nil {
log.Error("Can't unmarshal addrinfo")
return nil
}
return &Peer{
address: common.BytesToAddress(p.Address),
publicKey: crypto.FromBytes(p.PublicKey),
privateKey: nil,
peerInfo: info,
}
}
func PeersToPubs(peers []*Peer) (pubs []*crypto.PublicKey) {
for _, p := range peers {
pubs = append(pubs, p.PublicKey())
}
return pubs
}
func GetBitmap(src map[common.Address]*crypto.Signature, committee []common.Address) *big.Int {
bitmap := big.NewInt(0)
n := 0
for i, a := range committee {
if _, f := src[a]; f {
bitmap.SetBit(bitmap, i, 1)
n++
}
}
return bitmap
}