Skip to content

Commit f9c8c84

Browse files
committed
GoBlockChain
Added simple blockchain
1 parent bb03f26 commit f9c8c84

File tree

4 files changed

+68
-0
lines changed

4 files changed

+68
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@
1919

2020
# Go workspace file
2121
go.work
22+
.vscode/settings.json

cmd/main.go

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package main
2+
3+
import (
4+
"Go_Blockchain/models"
5+
"crypto/sha256"
6+
"encoding/hex"
7+
"fmt"
8+
"strconv"
9+
"time"
10+
)
11+
12+
func calculateHash(b models.Block) string {
13+
record := strconv.Itoa(b.Index) + b.Timestamp + b.Data + b.PreviousHash
14+
h := sha256.New()
15+
h.Write([]byte(record))
16+
hashed := h.Sum(nil)
17+
return hex.EncodeToString(hashed)
18+
}
19+
20+
func generateBlock(oldBlock models.Block, data string) (models.Block, error) {
21+
var newBlock models.Block
22+
t := time.Now()
23+
newBlock.Index = oldBlock.Index + 1
24+
newBlock.Timestamp = t.String()
25+
newBlock.Data = data
26+
newBlock.PreviousHash = oldBlock.Hash
27+
newBlock.Hash = calculateHash(newBlock)
28+
29+
return newBlock, nil
30+
}
31+
32+
func isBlockValid(newBlock, oldBlock models.Block) bool {
33+
if oldBlock.Index+1 != newBlock.Index {
34+
return false
35+
}
36+
if oldBlock.Hash != newBlock.PreviousHash {
37+
return false
38+
}
39+
if calculateHash(newBlock) != newBlock.Hash {
40+
return false
41+
}
42+
return true
43+
}
44+
45+
func main() {
46+
genesisBlock := models.Block{}
47+
genesisBlock = models.Block{0, time.Now().String(), "Genesis Block", "", ""}
48+
genesisBlock.Hash = calculateHash(genesisBlock)
49+
fmt.Println(genesisBlock)
50+
51+
secondBlock, _ := generateBlock(genesisBlock, "Second Bock Data")
52+
fmt.Println(secondBlock)
53+
54+
fmt.Println(isBlockValid(secondBlock, genesisBlock))
55+
}

go.mod

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module Go_Blockchain
2+
3+
go 1.23.3

models/block.go

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package models
2+
3+
type Block struct {
4+
Index int
5+
Timestamp string
6+
Data string
7+
PreviousHash string
8+
Hash string
9+
}

0 commit comments

Comments
 (0)