-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.js
More file actions
165 lines (136 loc) · 3.75 KB
/
blockchain.js
File metadata and controls
165 lines (136 loc) · 3.75 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
const SHA256 = require('crypto-js/sha256')
const EC = require('elliptic').ec
const ec = new EC('secp256k1')
class Transaction {
constructor(fromAddress, toAddress, amount) {
this.fromAddress = fromAddress
this.toAddress = toAddress
this.amount = amount
}
calculateHash() {
return SHA256(this.fromAddress + this.toAddress + this.amount).toString()
}
signTransaction(signingKey) {
if (signingKey.getPublic('hex') !== this.fromAddress) {
throw new Error('You cannot sign transactions from other wallets!')
}
const hashTx = this.calculateHash()
const sig = signingKey.sign(hashTx, 'base64')
this.signature = sig.toDER('hex')
}
isValid() {
if (this.fromAddress === null) return true
if (!this.signature || this.signature.length === 0) {
throw new Error('No signature in this transaction')
}
const publicKey = ec.keyFromPublic(this.fromAddress, 'hex')
return publicKey.verify(this.calculateHash(), this.signature)
}
}
class Block {
constructor(timestamp, transactions, previousHash = '') {
this.timestamp = timestamp
this.transactions = transactions
this.previousHash = previousHash
this.hash = this.calculateHash()
this.nonce = 0
}
calculateHash() {
return SHA256(
this.index +
this.previousHash +
this.timestamp +
JSON.stringify(this.transactions) +
this.nonce
).toString()
}
mineBlock(difficulty) {
while (
this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')
) {
this.nonce++
this.hash = this.calculateHash()
}
console.log('Block mined: ' + this.hash)
}
hasValidTransactions() {
for (const tx of this.transactions) {
if (!tx.isValid()) {
return false
}
}
return true
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()]
this.difficulty = 2
this.pendingTransactions = []
this.miningReward = 100
}
createGenesisBlock() {
return new Block('01/01/2017', 'Genesis Block', '0')
}
getLatestBlock() {
return this.chain[this.chain.length - 1]
}
minePendingTransactions(miningRewardAddress) {
const rewardTx = new Transaction(
null,
miningRewardAddress,
this.miningReward
)
this.pendingTransactions.push(rewardTx)
let block = new Block(
Date.now(),
this.pendingTransactions,
this.getLatestBlock().hash
)
block.mineBlock(this.difficulty)
console.log('Block successfully mined!')
this.chain.push(block)
this.pendingTransactions = []
}
addTransaction(transaction) {
if (!transaction.fromAddress || !transaction.toAddress) {
throw new Error('Transaction must include from and to address')
}
if (!transaction.isValid()) {
throw new Error('Cannot add invalid transaction to chain')
}
this.pendingTransactions.push(transaction)
}
getBalanceOfAddress(address) {
let balance = 0
for (const block of this.chain) {
for (const trans of block.transactions) {
if (trans.fromAddress === address) {
balance -= trans.amount
}
if (trans.toAddress === address) {
balance += trans.amount
}
}
}
return balance
}
isChainValid() {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i]
const previousBlock = this.chain[i - 1]
if (!currentBlock.hasValidTransactions()) {
return false
}
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false
}
}
return true
}
}
module.exports.Blockchain = Blockchain
module.exports.Transaction = Transaction