-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.go
154 lines (116 loc) · 2.96 KB
/
blockchain.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main
import (
"crypto"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
type Blockchain struct {
Chain []Block
CurrentTransactions []Transaction
Nodes map[string]bool
}
func NewBlockchain() Blockchain {
blockchain := Blockchain{Nodes: map[string]bool{}}
blockchain.NewBlock(100, "1")
return blockchain
}
func (b *Blockchain) NewBlock(proof int64, previousHash string) Block {
date := time.Now()
var hash string
if len(previousHash) > 0 {
hash = previousHash
} else {
hash = Hash(b.LastBlock())
}
block := Block{
Index: int64(len(b.Chain) + 1),
Timestamp: date.Unix(),
Transactions: b.CurrentTransactions,
Proof: proof,
PreviousHash: hash,
}
b.Chain = append(b.Chain, block)
return block
}
func (b *Blockchain) NewTransaction(sender string, recipient string, amount float64) int {
transaction := Transaction{Sender: sender, Recipient: recipient, Amount: amount}
b.CurrentTransactions = append(b.CurrentTransactions, transaction)
return len(b.Chain)
}
func Hash(block *Block) string {
hasher := crypto.SHA256.New()
hasher.Write([]byte(fmt.Sprintf("%v", block)))
return fmt.Sprintf("%x", hasher.Sum(nil))
}
func (b *Blockchain) LastBlock() *Block {
lastIndex := len(b.Chain)
return &b.Chain[lastIndex-1]
}
func (_ *Blockchain) ProofOfWork(lastProof int64) int64 {
var proof int64 = 0
for !ValidProof(lastProof, proof) {
proof++
}
return proof
}
func (b *Blockchain) RegisterNodes(address string) {
u, _ := url.ParseRequestURI(address)
hostPort := fmt.Sprintf("%s:%s", u.Hostname(), u.Port())
b.Nodes[hostPort] = true
}
func (b *Blockchain) ResolveConflicts() bool {
max_length := int64(len(b.Chain))
new_chain := []Block{}
for key := range b.Nodes {
url := fmt.Sprintf("http://%s/chain", key)
resp, err := http.Get(url)
if err != nil {
panic("Error trying get url")
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic("Error parsing json to content")
}
var content ChainResponse
json.Unmarshal([]byte(body), &content)
if content.Length > max_length && ValidChain(content.Chain) {
max_length = content.Length
new_chain = content.Chain
}
}
if len(new_chain) > 0 {
b.Chain = new_chain
return true
}
return false
}
func ValidChain(chain []Block) bool {
last_block := &chain[0]
current_index := 1
for current_index < len(chain) {
block := chain[current_index]
fmt.Printf("[last block] {%v}", last_block)
fmt.Printf("[current block] {%v}", block)
if block.PreviousHash != Hash(last_block) {
return false
}
if !ValidProof(last_block.Proof, block.Proof) {
return false
}
last_block = &block
current_index++
}
return true
}
func ValidProof(lastProof int64, proof int64) bool {
hasher := crypto.SHA256.New()
guess := fmt.Sprintf("%d%d", lastProof, proof)
hasher.Write([]byte(fmt.Sprintf("%v", guess)))
output := fmt.Sprintf("%x", hasher.Sum(nil))
return output[0:4] == "0000"
}