forked from perlin-network/noise
-
Notifications
You must be signed in to change notification settings - Fork 1
/
msg.go
77 lines (67 loc) · 1.74 KB
/
msg.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
package broadcast
import (
"github.com/cynthiatong/noise"
"github.com/cynthiatong/noise/payload"
kad "github.com/cynthiatong/noise/skademlia"
"github.com/pkg/errors"
"golang.org/x/crypto/blake2b"
)
// Message is a message to be broadcasted with custom data.
type Message struct {
From kad.ID
PrefixLen uint16
Data []byte
Hash [32]byte
}
func (m Message) Write() []byte {
writer := payload.NewWriter(nil)
writer.Write(m.From.Write())
writer.WriteUint16(m.PrefixLen)
writer.WriteUint32(uint32(len(m.Data))) // Note: need to write data byte length for reader.ReadBytes method to work
writer.Write(m.Data)
writer.Write(m.Hash[:])
return writer.Bytes()
}
func (m Message) Read(reader payload.Reader) (noise.Message, error) {
From, err := kad.ID{}.Read(reader)
if err != nil {
return nil, errors.Wrap(err, "failed to decode From ID")
}
m.From = From.(kad.ID)
prefixlen, err := reader.ReadUint16()
if err != nil {
return nil, err
}
m.PrefixLen = prefixlen
data, err := reader.ReadBytes()
if err != nil {
return nil, err
}
m.Data = data
var hash [32]byte
for i := 0; i < 32; i++ {
h, err := reader.ReadByte()
if err != nil {
return nil, err
}
hash[i] = h
}
m.Hash = hash
return m, err
}
// Note: only hash the broadcaster and the data, not prefixLen because the same broadcast msg can be rebroadcasted by multiple parties.
// QUESTION: can add a timestamp, but spamming?
func (m *Message) generateHash() {
bytes := append(m.From.Hash(), m.Data...)
m.Hash = blake2b.Sum256(bytes)
}
// NewMessage creates a new Message instance.
func NewMessage(from kad.ID, prefixlen uint16, data []byte) *Message {
msg := &Message{
From: from,
PrefixLen: prefixlen,
Data: data,
}
msg.generateHash()
return msg
}