-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd.go
More file actions
99 lines (86 loc) · 1.75 KB
/
cmd.go
File metadata and controls
99 lines (86 loc) · 1.75 KB
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
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log"
)
// Request <REQUEST,o,t,c>
type Request struct {
Message
Timestamp int64
//相当于clientID
ClientAddr string
}
// PrePrepare <<PRE-PREPARE,v,n,d>,m>
type PrePrepare struct {
RequestMessage Request
Digest string
SequenceID int
Sign []byte
}
// Prepare <PREPARE,v,n,d,i>
type Prepare struct {
Digest string
SequenceID int
NodeID string
Sign []byte
}
// Commit <COMMIT,v,n,D(m),i>
type Commit struct {
Digest string
SequenceID int
NodeID string
Sign []byte
}
// Reply <REPLY,v,t,c,i,r>
type Reply struct {
MessageID int
NodeID string
Result bool
}
type Message struct {
Content string
ID int
}
const prefixCMDLength = 12
type command string
const (
cRequest command = "request"
cPrePrepare command = "preprepare"
cPrepare command = "prepare"
cCommit command = "commit"
)
// 默认前十二位为命令名称
func jointMessage(cmd command, content []byte) []byte {
b := make([]byte, prefixCMDLength)
for i, v := range []byte(cmd) {
b[i] = v
}
joint := make([]byte, 0)
joint = append(b, content...)
return joint
}
// 默认前十二位为命令名称
func splitMessage(message []byte) (cmd string, content []byte) {
cmdBytes := message[:prefixCMDLength]
newCMDBytes := make([]byte, 0)
for _, v := range cmdBytes {
if v != byte(0) {
newCMDBytes = append(newCMDBytes, v)
}
}
cmd = string(newCMDBytes)
content = message[prefixCMDLength:]
return
}
// 对消息详情进行摘要
func getDigest(request Request) string {
b, err := json.Marshal(request)
if err != nil {
log.Panic(err)
}
hash := sha256.Sum256(b)
// 进行十六进制字符串编码
return hex.EncodeToString(hash[:])
}