Skip to content

Commit 444b9e2

Browse files
authored
Merge pull request #28 from Grumme2/hashfix
Fixed hashing errors, put and get now working
2 parents 5c5a229 + 2f49e8f commit 444b9e2

File tree

6 files changed

+63
-68
lines changed

6 files changed

+63
-68
lines changed

cmd/main/main.go

+2-8
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
package main
22

33
import (
4-
"fmt"
4+
//"fmt"
55
"strings"
6-
76
"github.com/Grumme2/D7024E/internal/d7024e"
87
)
98

109
func main() {
1110
meid := d7024e.NewRandomKademliaID()
1211
ip := d7024e.GetLocalIP()
1312
splitIP := strings.Split(ip, ".")
14-
fmt.Println(splitIP)
1513
if splitIP[3] == "3" {
1614
mestr := "2111111300000000000000000000123000000000"
17-
meid = d7024e.NewKademliaID(&mestr)
15+
meid = d7024e.NewKademliaID(mestr)
1816
}
1917
me := d7024e.NewContact(&meid, ip)
2018
rt := d7024e.NewRoutingTable(me)
@@ -25,10 +23,6 @@ func main() {
2523
go network.CheckNodesAwaitingResponse()
2624
kademlia.JoinNetwork()
2725

28-
fmt.Println(me.Address)
29-
// go network.Listen()
30-
// go network.CheckNodesAwaitingResponse()
31-
3226
cli := d7024e.NewCli(&kademlia)
3327
cli.AwaitCommand()
3428
}

internal/d7024e/cli.go

+22-33
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"regexp"
88
"strings"
99
"time"
10+
"encoding/json"
1011
)
1112

1213
type cli struct {
@@ -31,34 +32,6 @@ func (cli *cli) AwaitCommand() {
3132
case "EXIT":
3233
fmt.Println("EXIT command detected")
3334
return //Exits the function and terminates the node
34-
case "PRINT":
35-
if len(inputSplit) > 1 {
36-
fmt.Println("Printing test: " + inputSplit[1])
37-
} else {
38-
fmt.Println("Error! Invalid arguments!")
39-
}
40-
case "TESTPUT":
41-
if len(inputSplit) == 3 {
42-
fileUpload := inputSplit[1]
43-
targetIP := inputSplit[2]
44-
_ = targetIP
45-
//Uploads file
46-
cli.kademlia.Store(fileUpload) //File upload works (well atleast the RPC is sent and received properly)
47-
//See if file is uploaded
48-
49-
time.Sleep(1000 * time.Millisecond) //Sleep for 3s
50-
51-
findValueRPC := NewRPC(cli.kademlia.network.routingTable.me, targetIP, "FINDVALUE", cli.kademlia.network.MakeHash(fileUpload))
52-
cli.kademlia.network.SendMessage(findValueRPC)
53-
54-
time.Sleep(1000 * time.Millisecond) //Sleep for 3s
55-
56-
fmt.Println(cli.kademlia.network.lookUpDataResponse.DataFound)
57-
fmt.Println(cli.kademlia.network.lookUpDataResponse.Data)
58-
fmt.Println(cli.kademlia.network.lookUpDataResponse.Node)
59-
} else {
60-
fmt.Println("Error! Invalid arguments!")
61-
}
6235
case "PUT":
6336
if len(inputSplit) == 2 {
6437
fileUpload := inputSplit[1]
@@ -67,14 +40,21 @@ func (cli *cli) AwaitCommand() {
6740
cli.kademlia.Store(fileUpload) //File upload works (well atleast the RPC is sent and received properly)
6841
//See if file is uploaded
6942

70-
time.Sleep(3000 * time.Millisecond) //Sleep for 3s
43+
time.Sleep(300 * time.Millisecond) //Sleep for 0.3s
7144

7245
hashedUpload := cli.kademlia.network.MakeHash(fileUpload)
73-
dataFound, data, node := cli.kademlia.LookupData(hashedUpload)
46+
47+
hashedJson, err := json.Marshal(hashedUpload)
48+
if err != nil {
49+
fmt.Println(err)
50+
}
51+
52+
dataFound, data, node := cli.kademlia.LookupData(string(hashedJson))
7453
_ = data //Prevent data declared and not used compilation error
7554
_ = node //Prevent data declared and not used compilation error
7655
if dataFound {
77-
fmt.Println("File upload successfully! Hashed upload: " + hashedUpload)
56+
fmt.Println("File upload successfully! Hashed upload: ")
57+
fmt.Println(hashedUpload)
7858
} else {
7959
fmt.Println(dataFound)
8060
fmt.Println(data)
@@ -86,9 +66,18 @@ func (cli *cli) AwaitCommand() {
8666
fmt.Println("Error! Invalid arguments!")
8767
}
8868
case "GET":
89-
if len(inputSplit) == 2 {
69+
if len(inputSplit) > 2 {
70+
inputSplit = space.Split(inputText, 2)
9071
hash := inputSplit[1]
91-
dataFound, data, node := cli.kademlia.LookupData(hash)
72+
73+
hashedJson, err := json.Marshal(hash)
74+
if err != nil {
75+
fmt.Println(err)
76+
}
77+
78+
fmt.Println("Hashedjson: " + string(hashedJson))
79+
80+
dataFound, data, node := cli.kademlia.LookupData(string(hashedJson))
9281
_ = data //Prevent data declared and not used compilation error
9382
if dataFound {
9483
//Also return which node it was retrieved from

internal/d7024e/contact.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ func (contact *Contact) CalcDistance(target *KademliaID) {
2727

2828
// Less returns true if contact.distance < otherContact.distance
2929
func (contact *Contact) Less(otherContact *Contact) bool {
30-
fmt.Println(contact.distance)
31-
fmt.Println(otherContact.distance)
30+
//fmt.Println(contact.distance)
31+
//fmt.Println(otherContact.distance)
3232
return contact.distance.Less(otherContact.distance)
3333
}
3434

internal/d7024e/kademlia.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@ func (Kademlia *Kademlia) JoinNetwork() {
2626
bootStrapSplitIP := append(splitIP, "3")
2727
bootStrapIP := strings.Join(bootStrapSplitIP, ".") // Bootstrap nodes iP address
2828
bootStrapNodeStr := "2111111300000000000000000000123000000000" // hardcoded bootstrapnode ID
29-
bootStrapKademID := NewKademliaID(&bootStrapNodeStr)
29+
bootStrapKademID := NewKademliaID(bootStrapNodeStr)
3030
bootStrapNode := NewContact(&bootStrapKademID, bootStrapIP)
3131

3232
if x == "3" { // if Bootstrap node nothing needs to be done
33-
fmt.Println("bootstrapnode")
33+
//fmt.Println("bootstrapnode")
3434
return
3535
} else {
3636
i := 0
@@ -95,7 +95,7 @@ func (kademlia *Kademlia) LookupContact(target *Contact) string {
9595
}
9696

9797
if j == 10 {
98-
fmt.Printf("hej")
98+
//fmt.Printf("hej")
9999
return "ERROR! Did not get response in time"
100100
}
101101
}
@@ -127,8 +127,8 @@ func (kademlia *Kademlia) LookupContact(target *Contact) string {
127127

128128
}
129129
KTrJson := kademlia.network.KTriplesJSON(shortlist.contacts)
130-
fmt.Println(KTrJson)
131-
fmt.Println(kademlia.network.routingTable.me)
130+
//fmt.Println(KTrJson)
131+
//fmt.Println(kademlia.network.routingTable.me)
132132
return KTrJson
133133

134134
}
@@ -144,7 +144,7 @@ func in(a Contact, list []Contact) bool {
144144

145145
func (kademlia *Kademlia) LookupData(hash string) (bool, string, Contact) {
146146
kademlia.network.lookUpDataResponse = LookUpDataResponse{} //Resets LookUpDataResponse so we dont collect old results
147-
newkademid := NewKademliaID(&hash)
147+
newkademid := NewKademliaID(hash)
148148

149149
shortlist := ContactCandidates{kademlia.network.routingTable.FindClosestContacts(&newkademid, alpha)}
150150
alreadyused := ContactCandidates{contacts: []Contact{}}

internal/d7024e/kademliaid.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"crypto/sha1"
55
"encoding/hex"
66
"math/rand"
7+
//"fmt"
78
)
89

910
// the static number of bytes in a KademliaID
@@ -13,7 +14,7 @@ const IDLength = 20
1314
type KademliaID [IDLength]byte
1415

1516
// NewKademliaID returns a new instance of a KademliaID based on the string input
16-
func NewKademliaID(data *string) KademliaID {
17+
func NewKademliaID(data string) KademliaID {
1718
/*decoded, _ := hex.DecodeString(data)
1819
1920
//Loop goes out of bounds since IDLength is 20 bytes
@@ -23,7 +24,7 @@ func NewKademliaID(data *string) KademliaID {
2324
for i := 0; i < IDLength; i++ {
2425
newKademliaID[i] = decoded[i]
2526
}*/
26-
hash := sha1.Sum([]byte(*data))
27+
hash := sha1.Sum([]byte(data))
2728

2829
return hash
2930
}

internal/d7024e/network.go

+28-17
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ package d7024e
22

33
import (
44
"container/list"
5-
"encoding/hex"
5+
//"encoding/hex"
66
"encoding/json"
77
"fmt"
88
"net"
99
"time"
10+
"crypto/sha1"
11+
"regexp"
1012
)
1113

1214
type Network struct {
@@ -70,11 +72,6 @@ func (network *Network) CheckNodesAwaitingResponse() {
7072

7173
for e := network.awaitingResponseList.Front(); e != nil; e = e.Next() {
7274
nodeTimestamp := e.Value.(AwaitingResponseObject).timestamp
73-
fmt.Println(nodeTimestamp)
74-
fmt.Println(currentTime)
75-
fmt.Println(currentTime - nodeTimestamp)
76-
fmt.Println(e.Value.(AwaitingResponseObject).oldNode)
77-
fmt.Println(e.Value.(AwaitingResponseObject).newNode)
7875
if (currentTime - nodeTimestamp) >= 5 { //If 5 seconds or more have passed
7976
network.routingTable.RemoveContact(e.Value.(AwaitingResponseObject).oldNode)
8077
network.routingTable.AddContact(e.Value.(AwaitingResponseObject).newNode)
@@ -177,9 +174,8 @@ func (network *Network) ListenHandler(receivedData []byte, connection *net.UDPCo
177174
case "OK":
178175
responseType = "NONE"
179176
case "STORE":
180-
key := network.AddToStore(decodedData.Content)
177+
network.AddToStore(decodedData.Content)
181178
responseType = "OK"
182-
responseContent = key
183179
case "FINDVALUE":
184180
dataFound, data := network.LookForData(decodedData.Content)
185181
if dataFound {
@@ -206,7 +202,7 @@ func (network *Network) ListenHandler(receivedData []byte, connection *net.UDPCo
206202

207203
case "FINDNODE_RESPONSE":
208204
network.lookUpContactResponse = LookUpContactResponse{decodedData.Content}
209-
fmt.Println(network.lookUpContactResponse)
205+
//fmt.Println(network.lookUpContactResponse)
210206
responseType = "NONE"
211207

212208
case "PONG":
@@ -223,14 +219,31 @@ func (network *Network) ListenHandler(receivedData []byte, connection *net.UDPCo
223219
}
224220
}
225221

226-
func (network *Network) AddToStore(message string) string {
222+
func (network *Network) AddToStore(message string) {
227223
hxMsg := network.MakeHash(message)
228-
network.routingTable.me.KeyValueStore[hxMsg] = message
229-
return hxMsg
224+
225+
hxMsgJSON, err := json.Marshal(hxMsg)
226+
if err != nil {
227+
fmt.Println(err)
228+
}
229+
230+
network.routingTable.me.KeyValueStore[string(hxMsgJSON)] = message
230231
}
231232

232233
func (network *Network) LookForData(hash string) (bool, string) {
234+
235+
//Corrects hash if it is formatted wrong
236+
if (string(hash[0]) == "\""){
237+
hash = hash[1:len(hash)-1]
238+
var re = regexp.MustCompile(`[ ]`)
239+
hash = re.ReplaceAllString(hash, `,`)
240+
}
241+
233242
for key, element := range network.routingTable.me.KeyValueStore {
243+
//fmt.Println("LookForData loop")
244+
//fmt.Println("Key: " + key)
245+
//fmt.Println("Hash: " + hash)
246+
234247
if key == hash {
235248
fmt.Println("LookForData found element: " + element)
236249
return true, element
@@ -239,14 +252,12 @@ func (network *Network) LookForData(hash string) (bool, string) {
239252
return false, ""
240253
}
241254

242-
func (network *Network) MakeHash(message string) string {
243-
hx := hex.EncodeToString([]byte(message))
244-
return hx
255+
func (network *Network) MakeHash(message string) KademliaID {
256+
hash := sha1.Sum([]byte(message))
257+
return hash
245258
}
246259

247260
func (network *Network) storeRPC(message RPC) {
248-
hash := network.MakeHash(message.Content)
249-
fmt.Printf(hash)
250261
network.SendMessage(message)
251262
}
252263

0 commit comments

Comments
 (0)