-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcore.clj
47 lines (43 loc) · 1.61 KB
/
core.clj
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
(ns blockchain.core
(:require [compojure.core :refer :all]
[compojure.route :as route]
[compojure.handler :as handler]
[clojure.walk :refer [keywordize-keys]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[ring.util.response :as resp]
[blockchain.init :refer :all]
[blockchain.worker :as worker]
[blockchain.agent :as agent]))
(defn generate-response [response]
(if (integer? (:status response))
(let [body (:body response)
status (:status response)]
{:body body :status status})
(resp/response response)))
(defroutes app-routes
(GET "/" request (do (agent/get-address request)
(resp/response {:chain @chain :nodes @nodes})))
(POST "/" {chain :body}
(do (println "Someone is submitting a chain...")
(-> (keywordize-keys chain)
(vec)
(worker/resolve-chain-conflict)))
(generate-response {:status 200}))
(GET "/update" [] (do (run! agent/fetch-remote-chain @nodes)
(resp/response {:chain @chain :nodes @nodes})))
(GET "/mine" []
(let [new-block (worker/forge-new-block)]
(worker/append-to-chain new-block)
(agent/broadcast)
(generate-response {:body new-block :status 201})))
(route/not-found "Not Found"))
(def app
(-> (handler/api app-routes)
(wrap-json-body)
(wrap-json-response)))
(defn init []
(try
(-> (System/getenv "BOOT_NODE")
(agent/fetch-remote-chain))
(catch Exception e
(println "Start boot.."))))