-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathblockchain.js
261 lines (191 loc) · 5.72 KB
/
blockchain.js
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
var sha256 = require('sha256');
const EC = require('elliptic').ec;
const config = require('./config');
const wallet = require('./wallet');
// Blockchain class
class Blockchain {
constructor() {
this.pool = []
this.chain = new Array();
this.nodes = new Set(config.NODE_ADDRESSES);
}
genesis() {
/*
@description
Creates a genesis block in the blockchain
: return: True if created
*/
this.chain.push({
index: 1,
timestamp: Date.now(),
transactions: [{
sender: 'genesis',
recipient: '0',
amount: config.INITIAL_BALANCE
}],
nonce: 0,
previous_hash: 0
});
return true
}
lastBlock() {
return this.chain.slice(-1)[0]
}
registerNode(address) {
/*
@description
Add a new node to the list of nodes
:param address: Address of node. Eg. 'http://192.168.0.5:5000'
*/
parsed_url = parse(address)
this.nodes.push(parsed_url.host)
}
validChain(chain) {
/*
@description
Determine if a given blockchain is valid
: param chain: A blockchain
: return: True if valid, False if not
*/
var lastBlock = chain[0]
var currentIndex = 1
while (currentIndex < chain.length) {
var block = chain[currentIndex]
console.log(`${lastBlock}`)
console.log(`${block}`)
console.log("\n------------\n")
// Check that the hash of the block is correct
if (block['previous_hash'] != this.constructor.hash(lastBlock)) {
return false
}
// Check that the Proof of Work is correct
if (!(this.constructor.validProof(lastBlock['nonce'], block['nonce']))) {
return false
}
lastBlock = block
currentIndex += 1
}
return true
}
static hash(block) {
/*
@description
Creates a SHA-256 hash of a Block
: param block: Block
*/
// We must make sure that the Object is Ordered, or we'll have inconsistent hashes
const blockString = JSON.stringify(block, Object.keys(block).sort())
return sha256(blockString)
}
resolveConflicts() {
/*
@description
This is our consensus algorithm, it resolves conflicts
by replacing our chain with the longest blocks in the network.
: return: True if our chain was replaced, False if not
*/
var neighbours = this.nodes
var newChain = null
// We're only looking for chains longer than ours
var max_length = this.chain.length
// Grab and verify the chains from all the nodes in our network
neighbours.forEach(function (node) {
response = requests.get(`http://${node}/chain`)
.on('response', function (res) {
if (res.statusCode == 200) {
var length = res.json()['length']
var chain = res.json()['chain']
// Check if the length is longer and the chain is valid
if (length > max_length && this.validChain(chain)) {
max_length = length
newChain = chain
}
}
})
});
if (newChain) {
this.chain = newChain;
return true
}
return false;
}
newBlock(nonce, previous_hash) {
/*
@description
Create a new Block in the Blockchain
This is where the information is stored
: param proof: The proof given by the Proof of Work algorithm
: param previous_hash: Hash of previous Block
: return: New Block
*/
const block = {
'index': this.chain == undefined ? 1 : this.chain.length + 1,
'timestamp': Date.now(),
'transactions': this.pool,
'nonce': nonce,
'previous_hash': previous_hash !== undefined ? previous_hash : 0,
}
this.pool = []
this.chain.push(block)
return block
}
newTransaction(sender, recipient, amount) {
/*
@description
Use eliptic curve keys to verify user's transaction
source : https://github.com/indutny/elliptic
then envoke a new transaction to go into the next mined Block's pool
: param sender: Address of the Sender
: param recipient: Address of the Recipient
: param amount: Amount
: return: The index of the Block that will hold this transaction
*/
// create a new transaction to go into the next mined Block
this.pool.push({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return this.lastBlock()['index'] + 1
}
proofOfWork(lastNonce) {
/*
@description
Simple Proof of Work Algorithm:
- Find a nonce p', proof such that hash(pp') contains leading 4 zeroes, where p is the previous p'
- p is the previous proof, and p' is the new proof
: param lastNonce: Nonce from previous block in the blockchain
*/
var nonce = 0
while (this.constructor.validProof(lastNonce, nonce) == false) {
nonce += 1
}
return nonce
}
static validProof(lastNonce, nonce) {
/*
@description
Validates the Proof
: param lastNonce: Nonce from previous block in the blockchain
: param nonce: Current Nonce
: return: True if correct, False if not.
*/
const guess = sha256(`${lastNonce}${nonce}`)
return guess.slice(0, config.DIFFICULTY) === "0".repeat(config.DIFFICULTY);
}
mineSelf() {
/*
@description
Self-mining for the private blockchain(solo model)
*/
// Get lastblock's nonce for mining
var lastBlock = this.lastBlock();
var lastNonce = lastBlock.nonce;
var nonce = this.proofOfWork(lastNonce);
// Forge the new Block by adding it to the chain
var previousHash = this.constructor.hash(lastBlock);
var block = this.newBlock(nonce, previousHash);
console.log(this.chain);
}
}
module.exports = Blockchain;