diff --git a/README.md b/README.md index ea7d7dd..e0575a7 100644 --- a/README.md +++ b/README.md @@ -12,15 +12,21 @@ Purely peer-to-peer protocols like IPFS suffer from being way too complex and sl ## Design -Alright, let's solve all those problems above with Kela! Kela consists of three components, a name resolution system using a DHT, a storage service, and a messaging service. +Alright, let's solve all those problems above with Kela! Kela consists of three components, a name resolution service using a DHT, a storage service, and a message service. + +### Name resolution service In Kela, each user has an ID, which is a public key. Each user is associated with one or more Kela servers, which store that user's data. To find out which servers a user is associated with, you can query the name resolution system. All Kela servers participate in the name resolution system and act as DHT nodes. Each server stores a complete list of all DHT nodes. When a new server joins the DHT, it tries to peer with an existing server in the DHT. Say server `example.com` would like to peer with `test.net`. `example.com` first sends a GET request to `test.net/peer?peer=example.com`. `test.net` replies with its list of DHT nodes. Once `example.com` receives this reply, it adds `test.net` to its list of DHT nodes and attempts to peer with all servers in the reply that it hasn't peered with yet. `test.net` now also tries to peer with the server that just contacted it, in this case `example.com`. Servers periodically go through their list of DHT nodes and remove nodes that are no longer online. -The DHT stores key-value pairs. The key consists of a user's public key and timestamp (the SHA-256 hash of the public key modulo 600 plus the current Unix time in seconds all divided by 600, rounded down). The value consists of a timestamp (the current Unix time in seconds), a list of servers that the user is associated with, where the first server is their primary server, and a signature. A key-value pair is assigned to the 5 servers with smallest SHA-256 hashes of their domain name greater than the SHA-256 hash of the key. The purpose of the elaborate timestamp in the key is to ensure that the set of servers assigned to a key-value pair rotates every 600 seconds so an attacker must control a very large portion of the DHT to do a denial-of-service attack against a specific key-value pair. When servers join and leave the DHT, the servers that a user is associated with will ensure that that user's key-value pair is assigned to a new server if necessary to ensure that 5 servers store that key-value pair. The DHT supports two operations, get and set. For set operations, the server checks the signature to ensure the validity of the request. When a server receives either of these two operations, it computes the SHA-256 hash of the key and checks if it is supposed to store that key-value pair or not. If it is supposed to store that key-value pair, it performs the operation on that pair. Otherwise, the server will contact in parallel the 5 servers that store this key-value pair. If the operation is a get, the server will look at the 5 replies and return the value with the most recent timestamp. If the operation is a set, and one of the 5 parallel requests fails, the server will remove that offline server from its DHT node list and assign a new server to this key-value pair to replace the offline one. Each server periodically goes through its stored key-value pairs and deletes old ones. +The DHT stores key-value pairs. The key consists of a user's public key and timestamp (the SHA-256 hash of the public key modulo 600 plus the current Unix time in seconds all divided by 600, rounded down). The value consists of a timestamp (the current Unix time in seconds), a list of servers that the user is associated with, where the first server is their primary server, and a signature. A key-value pair is assigned to the 5 servers with smallest SHA-256 hashes of their domain name greater than the SHA-256 hash of the key. The purpose of the elaborate timestamp in the key is to ensure that the set of servers assigned to a key-value pair rotates every 600 seconds so an attacker must control a very large portion of the DHT to do a denial-of-service attack against a specific key-value pair. When servers join and leave the DHT, the servers that a user is associated with will ensure that that user's key-value pair is assigned to a new server if necessary to ensure that 5 servers store that key-value pair. The DHT supports two operations, get and put. For put operations, the server checks the signature to ensure the validity of the request. When a server receives either of these two operations, it computes the SHA-256 hash of the key and checks if it is supposed to store that key-value pair or not. If it is supposed to store that key-value pair, it performs the operation on that pair. Otherwise, the server will contact in parallel the 5 servers that store this key-value pair. If the operation is a get, the server will look at the 5 replies and return the value with the most recent timestamp. If the operation is a put, and one of the 5 parallel requests fails, the server will remove that offline server from its DHT node list and assign a new server to this key-value pair to replace the offline one. Each server periodically goes through its stored key-value pairs and deletes old ones. -The storage service uses a weaker form of primary-backup replication. The storage service supports the three operations get, set and delete, and a user's primary server always handles operations. Get operations are trivial. For a set or delete operation, the primary makes the modification and notifies all the backups about the operation, but responds to the user immediately without ensuring that the backups have performed the operation. All operations are stored in a log, which only stores the operation type and filename of the modified file, but not the contents of the operation. The log and files are persisted to disk. If a backup is offline, the primary maintains a log of all pending operations to be sent to the backup and will keep retrying. If the primary is offline, no progress can be made, but the user can designate any of the backups as the new primary, which also requires a set operation to the DHT to update that user's list of servers. When a backup becomes a primary, it must ensure that any other backups that are ahead of this one rollback their operations to match this backup. To rollback a delete operation, a backup can contact the new primary to get the file. +### Storage service -The messaging service allows you to send arbitrary signed HTTP requests to other users. These messages are ephemeral. If the recipient is not online, then the message fails. In Kela, applications are users too and have a public key. They are functionally equivalent to automated users. To host a website over Kela, you can create an application and make that application listen to incoming messages and tunnel them over WebSockets to a website hosted locally on your computer. Even better, Kela can replace your website's authentication system so you don't need passwords anymore! If you want to build a messaging app using Kela, you need a different design, kind of like RSS. Basically, you have a file containing messages that you have sent to the other person, and they periodically fetch that file to see your messages. +The storage service uses a weaker form of primary-backup replication. The storage service supports the three operations get, put and delete, and a user's primary server always handles operations. Get operations are trivial. For a put or delete operation, the primary makes the modification and notifies all the backups about the operation, but responds to the user immediately without ensuring that the backups have performed the operation. All operations are stored in a log, which only stores the operation type and filename of the modified file, but not the contents of the operation. The log and files are persisted to disk. If a backup is offline, the primary maintains a log of all pending operations to be sent to the backup and will keep retrying. If the primary is offline, no progress can be made, but the user can designate any of the backups as the new primary, which also requires a put operation to the DHT to update that user's list of servers. When a backup becomes a primary, it must ensure that any other backups that are ahead of this one rollback their operations to match this backup. To rollback a put or delete operation, a backup can contact the new primary to get the file. + +### Message service + +The message service allows you to send arbitrary signed HTTP requests to other users. These messages are ephemeral. If the recipient is not online, then the message fails. In Kela, applications are users too and have a public key. They are functionally equivalent to automated users. To host a website over Kela, you can create an application and make that application listen to incoming messages and tunnel them over WebSockets to a website hosted locally on your computer. Even better, Kela can replace your website's authentication system so you don't need passwords anymore! If you want to build a messaging app using Kela, you need a different design, kind of like RSS. Basically, you have a file containing messages that you have sent to the other person, and they periodically fetch that file to see your messages. ## History diff --git a/server/server.go b/server/server.go index e84b4e0..11aae25 100644 --- a/server/server.go +++ b/server/server.go @@ -1,6 +1,7 @@ package main import ( + "crypto/ed25519" "crypto/sha256" "encoding/hex" "flag" @@ -13,20 +14,26 @@ import ( "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 hex string func sha256sum(s string) string { - // Get the sha256sum of string as a hex string b := sha256.Sum256([]byte(s)) return hex.EncodeToString(b[:]) } +// Try to peer with another server func addPeer(peer string) error { - // Try to peer with another server peerHash := sha256sum(peer) // Check if already peered mu.Lock() @@ -52,8 +59,11 @@ func addPeer(peer string) error { log.Printf("%s successfully peered with %s", me, peer) mu.Lock() - peerHashes = append(peerHashes, peerHash) - sort.Sort(sort.StringSlice(peerHashes)) + i := sort.SearchStrings(peerHashes, peerHash) + peerHashes = append(peerHashes, "") + copy(peerHashes[i+1:], peerHashes[i:]) + peerHashes[i] = peerHash + myPos = sort.SearchStrings(peerHashes, me) mu.Unlock() // Read response body defer resp.Body.Close() @@ -69,26 +79,87 @@ func addPeer(peer string) error { return nil } +// Handle incoming peer requests func peerHandler(w http.ResponseWriter, r *http.Request) { - // Handle incoming peer requests r.ParseForm() peer := r.Form.Get("peer") if peer == "" { w.WriteHeader(http.StatusBadRequest) return } - go addPeer(peer) for _, p := range hashToDomain { fmt.Fprintf(w, "%s\n", p) } + go addPeer(peer) } -func getHandler(w http.ResponseWriter, r *http.Request) { +// Handle DHT requests +func dhtHandler(w http.ResponseWriter, r *http.Request) { + key := r.URL.String()[5:] + keyHash := sha256sum(key) + fmt.Println(key, keyHash) + mu.Lock() + keyPos := sort.SearchStrings(peerHashes, keyHash) + if keyPos < myPos { + keyPos += len(peerHashes) + } + mu.Unlock() + if r.Method == "GET" { + if keyPos - myPos < 5 { + mu.Lock() + if val, ok := kvstore[key]; ok { + w.Write([]byte(val)) + } else { + w.WriteHeader(http.StatusNotFound) + } + mu.Unlock() + } else { + for i := 0; i < 5 && i < len(peerHashes); i++ { + j := hashToDomain[peerHashes[(keyPos+i)%len(peerHashes)]] + go func() string { + resp, err := http.Get(j + r.URL.String()) + if err != nil { + return "" + } + b, err := io.ReadAll(resp.Body) + if err != nil { + return "" + } + return string(b) + }() + } + + + } + } else if r.Method == "PUT" { + b, err := io.ReadAll(r.Body) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + } + + + if keyPos - myPos < 5 { + mu.Lock() + kvstore[key] = string(b) + } + } else { + w.WriteHeader(http.StatusMethodNotAllowed) + } } -func setHandler(w http.ResponseWriter, r *http.Request) { +// Handle storage requests +func storageHandler(w http.ResponseWriter, r *http.Request) { + filename := r.URL.String()[5:] + if r.Method == "GET" { + } else if r.Method == "PUT" { + + } else if r.Method == "DELETE" { + + } else { + w.WriteHeader(http.StatusMethodNotAllowed) + } } func main() { @@ -101,6 +172,8 @@ func main() { // Record myself me = *domain + myHash = sha256sum(me) + myPos = 0 peerHashes = append(peerHashes, sha256sum(me)) hashToDomain = map[string]string{peerHashes[0]: me} @@ -109,7 +182,7 @@ func main() { } http.HandleFunc("/peer", peerHandler) - http.HandleFunc("/get", getHandler) - http.HandleFunc("/set", setHandler) + http.HandleFunc("/dht", dhtHandler) + http.HandleFunc("/storage", storageHandler) log.Fatal(http.ListenAndServe(*bindAddr, nil)) }