You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
2.2 KiB

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "github.com/fatih/color"
  7. "github.com/gorilla/mux"
  8. )
  9. type Routes []Route
  10. var routes = Routes{
  11. Route{
  12. "Index",
  13. "GET",
  14. "/",
  15. Index,
  16. },
  17. Route{
  18. "GetPeers",
  19. "GET",
  20. "/peers",
  21. GetPeers,
  22. },
  23. Route{
  24. "PostUser",
  25. "POST",
  26. "/register",
  27. PostUser,
  28. },
  29. Route{
  30. "GenesisBlock",
  31. "GET",
  32. "/blocks/genesis",
  33. GenesisBlock,
  34. },
  35. Route{
  36. "NextBlock",
  37. "GET",
  38. "/blocks/next/{blockhash}",
  39. NextBlock,
  40. },
  41. Route{
  42. "LastBlock",
  43. "GET",
  44. "/blocks/last",
  45. LastBlock,
  46. },
  47. }
  48. type Address struct {
  49. Address string `json:"address"` //the pubK of the user, to perform logins
  50. }
  51. func Index(w http.ResponseWriter, r *http.Request) {
  52. fmt.Fprintln(w, runningPeer.ID)
  53. }
  54. func GetPeers(w http.ResponseWriter, r *http.Request) {
  55. jResp, err := json.Marshal(outcomingPeersList)
  56. check(err)
  57. fmt.Fprintln(w, string(jResp))
  58. }
  59. func PostUser(w http.ResponseWriter, r *http.Request) {
  60. decoder := json.NewDecoder(r.Body)
  61. var address Address
  62. err := decoder.Decode(&address)
  63. if err != nil {
  64. panic(err)
  65. }
  66. defer r.Body.Close()
  67. fmt.Println(address)
  68. color.Blue(address.Address)
  69. //TODO add the verification of the address, to decide if it's accepted to create a new Block
  70. block := blockchain.createBlock(address)
  71. blockchain.addBlock(block)
  72. go propagateBlock(block)
  73. jResp, err := json.Marshal(blockchain)
  74. check(err)
  75. fmt.Fprintln(w, string(jResp))
  76. }
  77. func GenesisBlock(w http.ResponseWriter, r *http.Request) {
  78. var genesis Block
  79. if len(blockchain.Blocks) >= 0 {
  80. genesis = blockchain.Blocks[0]
  81. }
  82. jResp, err := json.Marshal(genesis)
  83. check(err)
  84. fmt.Fprintln(w, string(jResp))
  85. }
  86. func NextBlock(w http.ResponseWriter, r *http.Request) {
  87. vars := mux.Vars(r)
  88. blockhash := vars["blockhash"]
  89. currBlock, err := blockchain.getBlockByHash(blockhash)
  90. check(err)
  91. nextBlock, err := blockchain.getBlockByHash(currBlock.NextHash)
  92. check(err)
  93. jResp, err := json.Marshal(nextBlock)
  94. check(err)
  95. fmt.Fprintln(w, string(jResp))
  96. }
  97. func LastBlock(w http.ResponseWriter, r *http.Request) {
  98. var genesis Block
  99. if len(blockchain.Blocks) > 0 {
  100. genesis = blockchain.Blocks[len(blockchain.Blocks)-1]
  101. }
  102. jResp, err := json.Marshal(genesis)
  103. check(err)
  104. fmt.Fprintln(w, string(jResp))
  105. }