forked from itsfuad/BlockChain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
74 lines (60 loc) · 1.62 KB
/
Copy pathmain.go
File metadata and controls
74 lines (60 loc) · 1.62 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
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
)
type Block struct {
Index int64
Timestamp int64
Data string
PreviousHash string
Hash string
}
func calculateHash(block Block) string {
record := string(block.Index) + string(block.Timestamp) + block.Data + block.PreviousHash
h := sha256.New()
h.Write([]byte(record))
hashed := h.Sum(nil)
return hex.EncodeToString(hashed)
}
func generateBlock(previousBlock Block, data string) Block {
var newBlock Block
newBlock.Index = previousBlock.Index + 1
newBlock.Timestamp = time.Now().Unix()
newBlock.Data = data
newBlock.PreviousHash = previousBlock.Hash
newBlock.Hash = calculateHash(newBlock)
return newBlock
}
func isBlockValid(newBlock, previousBlock Block) bool {
if previousBlock.Index+1 != newBlock.Index {
return false
}
if previousBlock.Hash != newBlock.PreviousHash {
return false
}
if calculateHash(newBlock) != newBlock.Hash {
return false
}
return true
}
func main() {
var blockchain []Block
// Generate the genesis block
genesisBlock := Block{0, time.Now().Unix(), "Genesis Block", "", ""}
genesisBlock.Hash = calculateHash(genesisBlock)
blockchain = append(blockchain, genesisBlock)
// Add some more blocks to the blockchain
blockchain = append(blockchain, generateBlock(genesisBlock, "First Block"))
blockchain = append(blockchain, generateBlock(blockchain[1], "Second Block"))
// Verify the blockchain
for i := 1; i < len(blockchain); i++ {
if isBlockValid(blockchain[i], blockchain[i-1]) {
fmt.Printf("Block %d is valid\n", i)
} else {
fmt.Printf("Block %d is invalid\n", i)
}
}
}