aboutsummaryrefslogtreecommitdiff
path: root/server/dht.go
blob: 40bf4e6c5b073fe52126ca161261249ea80267bf (plain)
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package main

import (
	"bytes"
	"crypto/ed25519"
	"crypto/sha256"
	"encoding/base64"
	"encoding/binary"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

var myHash string
var myPos int
var hashToDomain map[string]string
var peerHashes []string
var kvstore map[string][]byte

// Get the sha256sum of string as a URL-safe unpadded base64 string
func sha256sum(s string) string {
	b := sha256.Sum256([]byte(s))
	return base64.RawURLEncoding.EncodeToString(b[:])
}

// Find the position of a key in the DHT
func keyPos(key string) int {
	keyPos := sort.SearchStrings(peerHashes, sha256sum(key))
	if keyPos < myPos {
		keyPos += len(peerHashes)
	}
	return keyPos
}

// Try to peer with another server
func addPeer(peer string) error {
	peerHash := sha256sum(peer)

	// Check if already peered
	mu.Lock()
	_, ok := hashToDomain[peerHash]
	mu.Unlock()
	if ok {
		return nil
	}
	mu.Lock()
	hashToDomain[peerHash] = peer
	mu.Unlock()

	// Try request to peer
	resp, err := http.Get(peer + "/peer?peer=" + me)
	if err != nil {
		// Request failed, delete peer
		mu.Lock()
		delete(hashToDomain, peerHash)
		mu.Unlock()
		return err
	}

	// Add peer
	mu.Lock()
	i := sort.SearchStrings(peerHashes, peerHash)
	peerHashes = append(peerHashes, "")
	copy(peerHashes[i+1:], peerHashes[i:])
	peerHashes[i] = peerHash
	myPos = sort.SearchStrings(peerHashes, myHash)
	// Distribute keys to new server
	for id, user := range users {
		phase := time.Now().Unix() / 600
		if keyPos(id+"\n"+fmt.Sprint(phase))-myPos < 5 {
			go http.Post(peer+"/dht/"+id+"?phase="+fmt.Sprint(phase)+"&direct", "application/octet-stream", bytes.NewBuffer(user.dhtVal))
		}
		if keyPos(id+"\n"+fmt.Sprint(phase+1))-myPos < 5 {
			go http.Post(peer+"/dht/"+id+"?phase="+fmt.Sprint(phase+1)+"&direct", "application/octet-stream", bytes.NewBuffer(user.dhtVal))
		}
	}
	mu.Unlock()
	log.Printf("%s successfully peered with %s", me, peer)

	// Read response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	// Try adding all peers of this peer
	newPeers := strings.Split(string(body), "\n")
	for _, newPeer := range newPeers[:len(newPeers)-1] {
		go addPeer(newPeer)
	}
	return nil
}

// Handle incoming peer requests
func peerHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	peer := r.Form.Get("peer")
	if peer == "" {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	mu.Lock()
	for _, p := range hashToDomain {
		fmt.Fprintf(w, "%s\n", p)
	}
	mu.Unlock()
	go addPeer(peer)
}

// Get the timestamp of this val
func timestamp(val []byte) int64 {
	if len(val) < 8+ed25519.SignatureSize {
		return 0
	}
	ret, _ := binary.Varint(val[:8])
	return ret
}

// Get the value for a key from the DHT
func dhtGet(key string, direct bool) []byte {
	phase := fmt.Sprint(time.Now().Unix() / 600)
	if direct {
		// Directly read from kvstore
		mu.Lock()
		val, ok := kvstore[key+"\n"+phase]
		mu.Unlock()
		if !ok || verify(key, val) != nil {
			return nil
		}
		return val
	}

	// Contact 5 servers that store this key-value pair
	var mu2 sync.Mutex
	var wg sync.WaitGroup
	var latest []byte
	mu.Lock()
	keyPos := keyPos(key + "\n" + phase)
	for i := 0; i < 5 && i < len(peerHashes); i++ {
		wg.Add(1)
		j := hashToDomain[peerHashes[(keyPos-i+len(peerHashes))%len(peerHashes)]]
		go func() {
			defer wg.Done()
			resp, err := http.Get(j + "/dht/" + key + "?direct")
			if err != nil {
				return
			}
			val, err := io.ReadAll(resp.Body)
			if err != nil {
				return
			}
			err = verify(key, val)
			if err != nil {
				return
			}
			mu2.Lock()
			if latest == nil || timestamp(val) > timestamp(latest) {
				latest = val
			}
			mu2.Unlock()
		}()
	}
	mu.Unlock()
	// Wait for all to finish or time out
	wg.Wait()
	return latest
}

// Post a key-value pair into the DHT
func dhtPost(key, phase string, direct bool, val []byte) error {
	err := verify(key, val)
	if err != nil {
		return err
	}
	if phase == "" {
		phase = fmt.Sprint(time.Now().Unix() / 600)
	}

	if direct {
		// Directly write to kvstore
		mu.Lock()
		curVal, ok := kvstore[key+"\n"+phase]
		if !ok || timestamp(val) > timestamp(curVal) {
			kvstore[key+"\n"+phase] = val
		}
		mu.Unlock()
		return nil
	}

	// Post the key-value pair to the next phase if necessary
	mu.Lock()
	curPhase, err := strconv.Atoi(phase)
	if err != nil {
		return err
	}
	nextPhase := time.Now().Unix()/600 + 1
	if int64(curPhase) < nextPhase {
		user, ok := users[key]
		if ok && user.phase < nextPhase {
			user.phase = nextPhase
			persist(key)
		}
		go dhtPost(key, fmt.Sprint(nextPhase), false, val)
	}
	keyPos := keyPos(key + "\n" + phase)
	mu.Unlock()

	// Contact 5 servers that store this key-value pair
	mu.Lock()
	for i := 0; i < 5 && i < len(peerHashes); i++ {
		j := hashToDomain[peerHashes[(keyPos-i+len(peerHashes))%len(peerHashes)]]
		go http.Post(j+"/dht/"+key+"?phase="+phase+"&direct", "application/octet-stream", bytes.NewBuffer(val))
	}
	mu.Unlock()
	return nil
}

// Handle DHT requests
func dhtHandler(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[5:]
	r.ParseForm()
	if r.Method == "GET" {
		val := dhtGet(key, r.Form.Has("direct"))
		if val == nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.Write(val)
	} else if r.Method == "POST" {
		val, err := io.ReadAll(r.Body)
		if err != nil {
			log.Print(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		err = dhtPost(key, r.Form.Get("phase"), r.Form.Has("direct"), val)
		if err != nil {
			log.Print(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
	}
}

// Clean out offline peers
func cleanPeers() {
	for true {
		mu.Lock()
		peer := hashToDomain[peerHashes[rand.Intn(len(peerHashes))]]
		mu.Unlock()
		_, err := http.Get(peer)
		if err != nil {
			log.Printf("Removing peer %s", peer)

			// Bad response, so remove peer
			mu.Lock()
			i := sort.SearchStrings(peerHashes, sha256sum(peer))
			peerHashes = append(peerHashes[:i], peerHashes[i+1:]...)
			myPos = sort.SearchStrings(peerHashes, myHash)

			// Distribute keys on this server to other servers
			if len(peerHashes) >= 5 {
				for id, user := range users {
					phase := time.Now().Unix() / 600
					kpos := keyPos(id + "\n" + fmt.Sprint(phase))
					if kpos-i < 5 {
						server := hashToDomain[peerHashes[(kpos-4+len(peerHashes))%len(peerHashes)]]
						go http.Post(server+"/dht/"+id+"?phase="+fmt.Sprint(phase)+"&direct", "application/octet-stream", bytes.NewBuffer(user.dhtVal))
					}
					kpos = keyPos(id + "\n" + fmt.Sprint(phase+1))
					if kpos-i < 5 {
						server := hashToDomain[peerHashes[(kpos-4+len(peerHashes))%len(peerHashes)]]
						go http.Post(server+"/dht/"+id+"?phase="+fmt.Sprint(phase+1)+"&direct", "application/octet-stream", bytes.NewBuffer(user.dhtVal))
					}
				}
			}
			mu.Unlock()
		}
		time.Sleep(5 * time.Second)
	}
}

// Clean out old keys from the KVStore every minute
func cleanKVStore() {
	for true {
		// This locks the mutex for a while which sucks
		mu.Lock()
		for key := range kvstore {
			timestamp, err := strconv.Atoi(strings.Split(key, "\n")[1])
			if err != nil || int64(timestamp)+1 < time.Now().Unix()/600 {
				delete(kvstore, key)
			}
		}
		mu.Unlock()
		time.Sleep(time.Minute)
	}
}

// Redistribute key-value pairs periodically
func redistributeKeys() {
	for true {
		mu.Lock()
		for id, user := range users {
			nextPhase := time.Now().Unix()/600 + 1
			if user.phase < nextPhase {
				go dhtPost(id, fmt.Sprint(nextPhase), false, user.dhtVal)
			}
			user.phase = nextPhase
			persist(id)
		}
		mu.Unlock()
		time.Sleep(time.Duration(rand.Intn(300)) * time.Second)
	}
}