-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.go
38 lines (34 loc) · 961 Bytes
/
block.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
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
)
// Block represents a single block in the blockchain
type Block struct {
Index int
Timestamp string
Data string
PreviousHash string
Hash string
}
// CalculateHash calculates the hash of a block
func CalculateHash(block Block) string {
record := fmt.Sprintf("%d%s%s%s", block.Index, block.Timestamp, block.Data, block.PreviousHash)
h := sha256.New()
h.Write([]byte(record))
return hex.EncodeToString(h.Sum(nil))
}
// CreateBlock creates a new block in the blockchain
func CreateBlock(previousBlock Block, data string) Block {
newIndex := previousBlock.Index + 1
timestamp := time.Now().String()
return Block{
Index: newIndex,
Timestamp: timestamp,
Data: data,
PreviousHash: previousBlock.Hash,
Hash: CalculateHash(Block{Index: newIndex, Timestamp: timestamp, Data: data, PreviousHash: previousBlock.Hash}),
}
}