forked from Abhimanyu121/simple_blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
140 lines (133 loc) · 3.19 KB
/
main.go
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
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
)
//lalallala
type Block struct{
Index int
Timestamp string
data string
Hash string
PrevHash string
}
var Blockchain []Block
func calculateHash(block Block) string{
record := string(block.Index)+block.Timestamp+block.data+block.PrevHash
h := sha256.New()
h.Write([]byte(record))
hashed := h.Sum(nil)
return hex.EncodeToString(hashed)
}
func generateBlock(oldblock Block,data string)(Block ,error){
var newBlock Block
t:=time.Now()
newBlock.Index=oldblock.Index +1
newBlock.Timestamp=t.String()
newBlock.data=data
newBlock.PrevHash=oldblock.Hash
newBlock.Hash=calculateHash(newBlock)
return newBlock,nil
}
func isBlockValid(newBlock,oldblock Block)bool{
if oldblock.Index+1 !=newBlock.Index{
return false
}
if oldblock.Hash != newBlock.PrevHash{
return false
}
if(calculateHash(newBlock)!=newBlock.Hash){
return false
}
return true
}
func replaceChain(newBlocks [] Block){
if len(newBlocks)>len(Blockchain){
Blockchain= newBlocks
}
}
func run() error {
mux := makeMuxRouter()
httpAddr := os.Getenv("ADDR")
log.Println("Listening on ", os.Getenv("ADDR"))
s := &http.Server{
Addr: ":" + httpAddr,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if err := s.ListenAndServe(); err != nil {
return err
}
return nil
}
func makeMuxRouter() http.Handler{
muxRouter:=mux.NewRouter()
muxRouter.HandleFunc("/",handleGetBlockchain).Methods("GET")
muxRouter.HandleFunc("/",handleWriteBlock).Methods("POST")
return muxRouter
}
func handleGetBlockchain(w http.ResponseWriter,r *http.Request){
bytes, err := json.MarshalIndent(Blockchain, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.WriteString(w, string(bytes))
}
type message struct{
data string
}
func handleWriteBlock(w http.ResponseWriter, r *http.Request){
var m message
decoder:=json.NewDecoder(r.Body)
if err:=decoder.Decode(&m);err!=nil{
respondWithJSON(w, r, http.StatusBadRequest, r.Body)
return
}
defer r.Body.Close()
newBlock, err := generateBlock(Blockchain[len(Blockchain)-1], m.data)
if err != nil {
respondWithJSON(w, r, http.StatusInternalServerError, m)
return
}
if isBlockValid(newBlock, Blockchain[len(Blockchain)-1]) {
newBlockchain := append(Blockchain, newBlock)
replaceChain(newBlockchain)
spew.Dump(Blockchain)
}
respondWithJSON(w, r, http.StatusCreated, newBlock)
}
func respondWithJSON(w http.ResponseWriter, r *http.Request, code int, payload interface{}){
response,err:=json.MarshalIndent(payload,""," ")
if err!=nil{
w.WriteHeader(http.StatusInternalServerError)
//w.Write(byte[]("HTTP 500: Internal Server Error"))
return
}
w.WriteHeader(code)
w.Write(response)
}
func main(){
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
go func(){
t:=time.Now()
genesisBlock:= Block{0,t.String(),"bleh","",""}
spew.Dump(genesisBlock)
Blockchain = append(Blockchain, genesisBlock)
}()
log.Fatal(run())
}