-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
129 lines (116 loc) · 2.29 KB
/
client.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net"
"sync"
"time"
)
type Client struct {
nodeId int
url string
keypair Keypair
knownNodes []*KnownNode
request *RequestMsg
replyLog map[int]*ReplyMsg
mutex sync.Mutex
}
func NewClient() *Client{
client := &Client{
ClientNode.nodeID,
ClientNode.url,
KeypairMap[ClientNode.nodeID],
KnownNodes,
nil,
make(map[int]*ReplyMsg),
sync.Mutex{},
}
return client
}
func (c *Client) Start(){
c.sendRequest()
ln, err := net.Listen("tcp", c.url)
if err != nil {
panic(err)
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
go c.handleConnection(conn)
}
}
func (c *Client) handleConnection(conn net.Conn){
req, err := ioutil.ReadAll(conn)
header, payload, _:= SplitMsg(req)
if err != nil {
panic(err)
}
switch header {
case hReply:
c.handleReply(payload)
}}
func (c *Client) sendRequest() {
msg := fmt.Sprintf("%d work to do!",rand.Int())
req := Request{
msg,
hex.EncodeToString(generateDigest(msg)),
}
reqmsg := &RequestMsg{
"solve",
int(time.Now().Unix()),
c.nodeId,
req,
}
sig, err := c.signMessage(reqmsg)
if err != nil{
fmt.Printf("%v\n", err)
}
logBroadcastMsg(hRequest, reqmsg)
send(ComposeMsg(hRequest, reqmsg, sig), c.findPrimaryNode().url)
c.request = reqmsg
}
func (c *Client) handleReply(payload []byte) {
var replyMsg ReplyMsg
err := json.Unmarshal(payload,&replyMsg)
if err != nil {
fmt.Printf("error happened:%v", err)
return
}
logHandleMsg(hReply, replyMsg, replyMsg.NodeID)
c.mutex.Lock()
c.replyLog[replyMsg.NodeID] = &replyMsg
rlen := len(c.replyLog)
c.mutex.Unlock()
if rlen >= c.countNeedReceiveMsgAmount(){
fmt.Println("request success!!")
}
}
func (c *Client) signMessage(msg interface{}) ([]byte, error){
sig, err := signMessage(msg, c.keypair.privkey)
if err != nil{
return nil, err
}
return sig, nil
}
func (c *Client) findPrimaryNode() *KnownNode{
nodeId := ViewID % len(c.knownNodes)
for _, knownNode := range c.knownNodes{
if knownNode.nodeID == nodeId {
return knownNode
}
}
return nil
}
func (c *Client) countTolerateFaultNode() int {
return (len(c.knownNodes) - 1) / 3
}
func (c *Client) countNeedReceiveMsgAmount() int {
f := c.countTolerateFaultNode()
return f+1
}