This repository has been archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
msgs_serde.go
90 lines (77 loc) · 1.85 KB
/
msgs_serde.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
package concord
import (
"errors"
"fmt"
"github.com/gogo/protobuf/proto"
cpb "github.com/Wondertan/iotwal/concord/pb"
)
// MsgToProto takes a consensus message type and returns the proto defined consensus message
func MsgToProto(msg Message) (*cpb.Message, error) {
if msg == nil {
return nil, errors.New("consensus: message is nil")
}
var pb cpb.Message
switch msg := msg.(type) {
case *ProposalMessage:
pbP := msg.Proposal.ToProto()
pb = cpb.Message{
Sum: &cpb.Message_Proposal{
Proposal: pbP,
},
}
case *VoteMessage:
vote := msg.Vote.ToProto()
pb = cpb.Message{
Sum: &cpb.Message_Vote{
Vote: vote,
},
}
default:
return nil, fmt.Errorf("consensus: message not recognized: %T", msg)
}
return &pb, nil
}
// MsgFromProto takes a consensus proto message and returns the native go type
func MsgFromProto(msg *cpb.Message) (Message, error) {
if msg == nil {
return nil, errors.New("consensus: nil message")
}
var pb Message
switch msg := msg.Sum.(type) {
case *cpb.Message_Proposal:
pbP, err := ProposalFromProto(msg.Proposal)
if err != nil {
return nil, fmt.Errorf("proposal msg to proto error: %w", err)
}
pb = &ProposalMessage{
Proposal: pbP,
}
case *cpb.Message_Vote:
vote, err := VoteFromProto(msg.Vote)
if err != nil {
return nil, fmt.Errorf("vote msg to proto error: %w", err)
}
pb = &VoteMessage{
Vote: vote,
}
default:
return nil, fmt.Errorf("consensus: message not recognized: %T", msg)
}
if err := pb.ValidateBasic(); err != nil {
return nil, err
}
return pb, nil
}
// MustEncode takes the reactors msg, makes it proto and marshals it
// this mimics `MustMarshalBinaryBare` in that is panics on error
func MustEncode(msg Message) []byte {
pb, err := MsgToProto(msg)
if err != nil {
panic(err)
}
enc, err := proto.Marshal(pb)
if err != nil {
panic(err)
}
return enc
}