-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.go
70 lines (60 loc) · 1.46 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
package main
import (
"fmt"
"log"
"strings"
"time"
)
// Definition of the Block type
type Block struct {
nonce int
previousHash string
timestamp int64
transactions []string
}
func NewBlock(nonce int, previousHash string) *Block {
b := new(Block)
b.timestamp = time.Now().UnixNano()
b.nonce = nonce
b.previousHash = previousHash
return b
}
func (b *Block) Print() {
fmt.Printf("timestamp %d\n", b.timestamp)
fmt.Printf("nonce %d\n", b.nonce)
fmt.Printf("previousHash %s\n", b.previousHash)
fmt.Printf("transactions %s\n", b.transactions)
}
// Definition of the type Blockchain
type Blockchain struct {
transactionPool []string
chain []*Block
}
func NewBlockchain() *Blockchain {
bc := new(Blockchain)
bc.CreateBlock(0, "Sample Previous Hash")
return bc
}
func (bc *Blockchain) CreateBlock(nonce int, previousHash string) *Block {
b := NewBlock(nonce, previousHash)
bc.chain = append(bc.chain, b)
return b
}
func (bc *Blockchain) Print() {
for i, block := range bc.chain {
fmt.Printf("%s Chain: %d %s\n", strings.Repeat("=", 25), i, strings.Repeat("=", 25))
block.Print()
}
fmt.Printf("%s\n", strings.Repeat("*", 60))
}
func main() {
blockChain := NewBlockchain()
blockChain.Print()
blockChain.CreateBlock(5, "first block's hash")
blockChain.Print()
blockChain.CreateBlock(5, "second block's hash")
blockChain.Print()
}
func init() {
log.SetPrefix("SundeeepBlockchain ->> ")
}