-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssignment 2.go
173 lines (146 loc) · 4.78 KB
/
Assignment 2.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"crypto/sha256"
"encoding/json"
"fmt"
"strings"
"time"
)
// Structure of Block
type Block struct {
Timestamp string
Nonce int
PreviousHash string
CurrentHash string
Transactions string
}
// Structure of Transaction
type Transaction struct {
TransactionId string `json:"transaction_id"`
SenderBlockchainAddress string `json:"sender_blockchain_address"`
RecipientBlockchainAddress string `json:"recipient_blockchain_address"`
Value float32 `json:"value"`
}
// List of Blocks
type Blockchain struct {
Chain []*Block
TransactionPool []*Transaction
}
// Calculate Hash of Block
func calculateHash(stringValue1 string, numericValue int, stringValue2 string) string {
data := fmt.Sprintf("%s%d%s", stringValue1, numericValue, stringValue2)
hash := sha256.Sum256([]byte(data))
return fmt.Sprintf("%x", hash)
}
// Add new block
func newBlock(nonce int, previousHash string) *Block {
b := new(Block)
now := time.Now().String()
b.Timestamp = now
b.Nonce = nonce
b.PreviousHash = previousHash
b.CurrentHash = calculateHash(b.Timestamp, nonce, previousHash)
return b
}
// Append the block in the List
func (bl *Blockchain) appendBlock(difficulty int) *Block {
//for previous hash of block
var previousHash string
if len(bl.Chain) > 0 {
previousHash = bl.Chain[len(bl.Chain)-1].CurrentHash
} else {
previousHash = "0000"
}
nonce := proofOfWork(previousHash, difficulty)
//adding new block
addBlock := newBlock(nonce, previousHash)
//Add transactions in the Block in JSON format
transactionsData, err := json.Marshal(bl.TransactionPool)
if err != nil {
fmt.Println("Error in adding marshall transactions: ", err)
}
//adding transactions in the block
addBlock.Transactions = string(transactionsData)
//clear the transaction pool
bl.TransactionPool = nil
//append the block
bl.Chain = append(bl.Chain, addBlock)
return addBlock
}
// List all Blocks
func (bl *Blockchain) listBlocks() {
for i, block := range bl.Chain {
fmt.Printf("%s Block %d %s\n", strings.Repeat("=", 40), i, strings.Repeat("=", 40))
fmt.Printf("Timestamp: %s \n", block.Timestamp)
fmt.Printf("Nonce: %d \n", block.Nonce)
fmt.Printf("Previous Block Hash: %s \n", block.PreviousHash)
fmt.Printf("Current Block Hash: %s \n", block.CurrentHash)
fmt.Println(strings.Repeat("-", 89))
fmt.Printf("Transactions: \n%s\n", block.Transactions)
fmt.Println(strings.Repeat("=", 89))
fmt.Println("\n")
}
}
// Print a specific Block by index
func (bl *Blockchain) printBlock(index int) {
// Check if the index is within bounds
if index < 0 || index >= len(bl.Chain) {
fmt.Println("Error: Block index out of range.")
return
}
// Retrieve the block at the specified index
block := bl.Chain[index]
// Print the block's details
fmt.Printf("%s Block %d %s\n", strings.Repeat("=", 40), index, strings.Repeat("=", 40))
fmt.Printf("Timestamp: %s \n", block.Timestamp)
fmt.Printf("Nonce: %d \n", block.Nonce)
fmt.Printf("Previous Block Hash: %s \n", block.PreviousHash)
fmt.Printf("Current Block Hash: %s \n", block.CurrentHash)
fmt.Println(strings.Repeat("-", 89))
fmt.Printf("Transactions: \n%s\n", block.Transactions)
fmt.Println(strings.Repeat("=", 89))
fmt.Println("\n")
}
// New transaction
func newTransaction(sender string, recipient string, value float32) *Transaction {
tr := new(Transaction)
tr.SenderBlockchainAddress = sender
tr.RecipientBlockchainAddress = recipient
tr.Value = value
tr.TransactionId = calculateHash(sender, int(value), recipient)
return tr
}
// append transaction
func (bl *Blockchain) appendTransaction(sender string, recipient string, value float32) *Transaction {
addTransaction := newTransaction(sender, recipient, value)
bl.TransactionPool = append(bl.TransactionPool, addTransaction)
return addTransaction
}
// Proof of Work: find nonce
func proofOfWork(previousHash string, difficulty int) int {
nonce := 0
prefix := strings.Repeat("0", difficulty)
for {
hash := calculateHash(time.Now().String(), nonce, previousHash)
if strings.HasPrefix(hash, prefix) {
break
}
nonce++
}
return nonce
}
func main() {
blockchain := new(Blockchain)
//add some transactions
blockchain.appendTransaction("Alice", "Bob", 10.5)
blockchain.appendTransaction("Bob", "Charlie", 20.0)
//append block with proof of work difficulty level 2
blockchain.appendBlock(2)
//add new transactions for new block
blockchain.appendTransaction("Charlie", "John", 10.5)
blockchain.appendTransaction("John", "Alice", 20.0)
//append block with proof of work difficulty level 2
blockchain.appendBlock(2)
//blockchain.listBlocks()
blockchain.printBlock(1)
}