Repository navigation
Expand file tree
/
Copy pathblockchain.go
More file actions
179 lines (143 loc) · 4.09 KB
/
Copy pathblockchain.go
File metadata and controls
179 lines (143 loc) · 4.09 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
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
174
175
176
177
178
179
package main
import (
"bytes"
"errors"
)
const difficulty = 3
const reward = 50
type Blockchain struct {
Blocks []*Block
}
func InitBlockchain(addr []byte) *Blockchain {
genesisTransaction := CoinbaseTx(addr)
genesisBlock := Block{Transactions: []*Transaction{genesisTransaction}}
genesisBlock.Mine()
chain := Blockchain{Blocks: []*Block{&genesisBlock}}
return &chain
}
func MineBlock(transactions []*Transaction, previousHash []byte) *Block {
newBlock := Block{Transactions: transactions, PreviousHash: previousHash}
newBlock.Mine()
return &newBlock
}
func (chain *Blockchain) AddMinedBlock(incomingBlock *Block) error {
incomingHash := incomingBlock.CalculateBlockHash(incomingBlock.Nonce)
previousBlock := chain.Blocks[len(chain.Blocks)-1]
for _, transaction := range incomingBlock.Transactions {
if !transaction.ValidateTransaction(chain) {
return errors.New("failed to validate incoming transactions")
}
}
if !bytes.Equal(incomingBlock.PreviousHash, previousBlock.Hash) {
return errors.New("failed to verify incoming block previous hash")
}
if !bytes.Equal(incomingHash, incomingBlock.Hash) {
return errors.New("failed to verify incoming block hash")
}
if verified := VerifyBlockHashDifficulty(incomingHash); !verified {
return errors.New("failed to verify incoming block PoW")
}
chain.Blocks = append(chain.Blocks, incomingBlock)
return nil
}
func (chain *Blockchain) IsValid() bool {
for i := len(chain.Blocks) - 1; i > 0; i-- {
currentBlock := chain.Blocks[i]
previousBlock := chain.Blocks[i-1]
if !bytes.Equal(currentBlock.PreviousHash, previousBlock.Hash) {
return false
}
if hash := currentBlock.CalculateBlockHash(currentBlock.Nonce); !bytes.Equal(hash, currentBlock.Hash) {
return false
}
}
return true
}
func (chain *Blockchain) Balance(owner []byte) int {
spentOutputs := chain.findSpentOutputs()
amount := 0
for _, block := range chain.Blocks {
for _, tx := range block.Transactions {
for i, output := range tx.Outputs {
isSpent := false
for _, spent := range spentOutputs[string(tx.ID)] {
if spent == i {
isSpent = true
break
}
}
if bytes.Equal(output.Owner, owner) && !isSpent {
amount += output.Amount
}
}
}
}
return amount
}
func (chain *Blockchain) GetBlockAt(height int) (*Block, error) {
if height >= len(chain.Blocks) || height < 0 {
return nil, errors.New("block doesn't exist on chain")
}
return chain.Blocks[height], nil
}
func (chain *Blockchain) GetBlock(hash []byte) (*Block, error) {
for _, block := range chain.Blocks {
if bytes.Equal(hash, block.Hash) {
return block, nil
}
}
return nil, errors.New("block hash not found!")
}
func (chain *Blockchain) findSpentOutputs() map[string][]int {
spentOutputs := make(map[string][]int)
for _, block := range chain.Blocks {
for _, tx := range block.Transactions {
for _, input := range tx.Inputs {
hash := string(input.TransactionHash)
spentOutputs[hash] = append(spentOutputs[hash], input.TxOutputIndex)
}
}
}
return spentOutputs
}
func (chain *Blockchain) findTransaction(txId []byte) (*Transaction, error) {
for _, block := range chain.Blocks {
for _, transaction := range block.Transactions {
if bytes.Equal(txId, transaction.ID) {
return transaction, nil
}
}
}
return nil, errors.New("transaction not found!")
}
func (chain *Blockchain) findSpendableInputs(from []byte, amount int, spentOutputs map[string][]int) ([]TxInput, int) {
accumulatedAmount := 0
var inputs []TxInput
Collect:
for _, block := range chain.Blocks {
for _, tx := range block.Transactions {
for i, output := range tx.Outputs {
if !bytes.Equal(from, output.Owner) {
continue
}
isSpent := false
for _, spent := range spentOutputs[string(tx.ID)] {
if spent == i {
isSpent = true
break
}
}
if isSpent {
continue
}
newInput := TxInput{TransactionHash: tx.ID, TxOutputIndex: i}
accumulatedAmount += output.Amount
inputs = append(inputs, newInput)
if accumulatedAmount >= amount {
break Collect
}
}
}
}
return inputs, accumulatedAmount
}