/
msg.go
66 lines (54 loc) · 1.05 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
package p2p
import (
"fmt"
"github.com/librity/nc_nomadcoin/utils"
)
type MsgKind int
const (
MsgLastBlock MsgKind = iota
MsgAllBlocksReq
MsgAllBlocksResp
MsgMinedBlock
MsgNewTx
MsgNewPeer
)
type Msg struct {
Kind MsgKind
Payload []byte
}
func (m Msg) String() string {
kind := m.KindToString()
str := fmt.Sprintf("{Kind: %s, Payload: []byte{...}}", kind)
return str
}
func (m *Msg) KindToString() string {
switch m.Kind {
case MsgLastBlock:
return "MsgLastBlock"
case MsgAllBlocksReq:
return "MsgAllBlocksReq"
case MsgAllBlocksResp:
return "MsgAllBlocksResp"
case MsgMinedBlock:
return "MsgMinedBlock"
case MsgNewTx:
return "MsgNewTx"
case MsgNewPeer:
return "MsgNewPeer"
default:
return "UNKOWN"
}
}
func makeMsgJSON(kind MsgKind, payload interface{}) []byte {
message := newMsg(kind, payload)
messageJSON := utils.ToJSON(message)
return messageJSON
}
func newMsg(kind MsgKind, payload interface{}) *Msg {
jsonPayload := utils.ToJSON(payload)
message := &Msg{
Kind: kind,
Payload: jsonPayload,
}
return message
}