-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.go
More file actions
179 lines (153 loc) · 4.09 KB
/
blockchain.go
File metadata and controls
179 lines (153 loc) · 4.09 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
//Following tutorial to learn a bit of Go and blockchain for a project
package main
import (
"fmt"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"time"
"github.com/gorilla/mux"
"io"
"log"
"net/http"
"crypto/md5"
)
type Block struct {
Pos int
Data BookCheckout
Timestamp string
Hash string
PrevHash string
}
type BookCheckout struct {
BookID string `json:"book_id"`
User string `json:"user"`
CheckoutDate string `json:"checkout_date"`
IsGenesis bool `json:"is_genesis"`
}
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
PublishDate string `json:"publish_date"`
ISBN string `json:"isbn"`
}
// Blockchain is an ordered list of blocks
type Blockchain struct {
blocks []*Block
}
var BlockChain *Blockchain
func (bc *Blockchain) AddBlock (data BookCheckout) {
prevBlock := bc.blocks[len(bc.blocks)-1]
block := CreateBlock(prevBlock, data)
if validBlock(block, prevBlock) {
bc.blocks = append(bc.blocks, block)
}
}
func GenesisBlock() *Block {
return CreateBlock(&Block{}, BookCheckout{IsGenesis: true})
}
func NewBlockchain() *Blockchain {
return &Blockchain{[]*Block{GenesisBlock()}}
}
func validBlock(block, prevBlock *Block) bool {
if prevBlock.Hash != block.PrevHash {
return false
}
if !block.validateHash(block.Hash) {
return false
}
if prevBlock.Pos + 1 != block.Pos {
return false
}
return true
}
func (b *Block) validateHash(hash string) bool {
b.generateHash()
if b.Hash != hash {
return false
}
return true
}
func (b *Block) generateHash() {
bytes, _ := json.Marshal(b.Data) //get json encoding, drop error
data := string(b.Pos) + b.Timestamp + string(bytes) + b.PrevHash
hash := sha256.New()
hash.Write([]byte(data))
b.Hash = hex.EncodeToString(hash.Sum(nil))
}
func CreateBlock(prevBlock *Block, checkoutItem BookCheckout) *Block {
block := &Block{}
block.Pos = prevBlock.Pos + 1
block.Timestamp = time.Now().String()
block.Data = checkoutItem
block.PrevHash = prevBlock.Hash
block.generateHash()
return block
}
func getBlockchain(w http.ResponseWriter, r *http.Request) {
jbytes, err := json.MarshalIndent(BlockChain.blocks, "", " ")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(err)
return
}
io.WriteString(w, string(jbytes))
}
func writeBlock(w http.ResponseWriter, r *http.Request) {
var checkoutItem BookCheckout
if err := json.NewDecoder(r.Body).Decode(&checkoutItem); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Could not write block: %v", err)
w.Write([]byte("Could not write block"))
return
}
BlockChain.AddBlock(checkoutItem)
resp, err := json.MarshalIndent(checkoutItem, "", " ")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Could not marshal payload: %v", err)
w.Write([]byte("Could not write block"))
return
}
w.WriteHeader(http.StatusOK)
w.Write(resp)
}
func newBook(w http.ResponseWriter, r *http.Request) {
var book Book
if err := json.NewDecoder(r.Body).Decode(&book); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Could not create: %v", err)
w.Write([]byte("Could not create new book"))
}
h := md5.New()
io.WriteString(h, book.ISBN+book.PublishDate)
book.ID = fmt.Sprintf("%x", h.Sum(nil))
resp, err := json.MarshalIndent(book, "", " ")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Could not marshal payload: %v", err)
w.Write([]byte("Could not save book data"))
return
}
w.WriteHeader(http.StatusOK)
w.Write(resp)
}
func main() {
BlockChain = NewBlockchain()
r := mux.NewRouter()
r.HandleFunc("/", getBlockchain).Methods("GET")
r.HandleFunc("/", writeBlock).Methods("POST")
r.HandleFunc("/new", newBook).Methods("POST")
go func() {
for _, block := range BlockChain.blocks {
fmt.Printf("Prev. hash: %x\n", block.PrevHash)
bytes, _ := json.MarshalIndent(block.Data, "", " ")
fmt.Printf("Data: %v\n", string(bytes))
fmt.Printf("Hash: %x\n", block.Hash)
fmt.Println()
}
}()
log.Println("Listening on port 3000")
log.Fatal(http.ListenAndServe(":3000", r))
}