aboutsummaryrefslogtreecommitdiff
path: root/server/main.go
blob: c0f74507d35bcd030744c8f982a347a487536211 (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
package main

import (
	"crypto/ed25519"
	"crypto/sha256"
	"encoding/base64"
	"flag"
	"log"
	"net/http"
	"sync"
)

type user struct {
	pubkey []byte
}

var mu sync.Mutex
var me string
var myHash string
var myPos int
var hashToDomain map[string]string
var peerHashes []string
var kvstore map[string]string

// 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[:])
}

// Decode an ID to a public key
func asPubKey(s string) ed25519.PublicKey {
	b, err := base64.RawURLEncoding.DecodeString(s)
	if err != nil {
		return nil
	}
	return ed25519.PublicKey(b)
}

func main() {
	bindAddr := flag.String("b", ":4200", "bind address")
	publicURL := flag.String("u", "http://localhost:4200", "public URL")
	peer := flag.String("i", "", "initial peer")
	flag.Parse()
	log.Printf("Starting %s %s %s", *bindAddr, *publicURL, *peer)

	// Record myself
	me = *publicURL
	myHash = sha256sum(me)
	myPos = 0
	peerHashes = append(peerHashes, sha256sum(me))
	hashToDomain = map[string]string{peerHashes[0]: me}

	if *peer != "" {
		go addPeer(*peer)
	}

	http.HandleFunc("/peer", peerHandler)
	http.HandleFunc("/dht", dhtHandler)
	http.HandleFunc("/storage", storageHandler)
	http.HandleFunc("/message", messageHandler)
	log.Fatal(http.ListenAndServe(*bindAddr, nil))
}