-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUuMChain.js
More file actions
38 lines (34 loc) · 1.07 KB
/
UuMChain.js
File metadata and controls
38 lines (34 loc) · 1.07 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
'use strict'
const Block = require('./Block')
const fs = require('fs')
const uumChainFile = 'uumChain.json'
module.exports = class BlockChain {
constructor(difficulty) {
var newBlock = new Block('Genesis', '0x01')
newBlock.calcHash()
this._chain = [newBlock]
this.getChainFromFile()
this.difficulty = difficulty
console.log('BlockChain: difficulty: ' + this.difficulty)
}
addBlock(data) {
const lastBlock = this._chain[this._chain.length - 1]
var block = new Block(data, lastBlock.hash)
block.id = lastBlock.id + 1
block.calcHash()
block.mineBlock(this.difficulty)
this._chain.push(block)
this.saveChainToFile()
}
// https://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-file-into-server-memory
getChainFromFile(){
const uumChainString = fs.readFileSync(uumChainFile, 'utf8')
if (uumChainString){
this._chain = JSON.parse(uumChainString)
}
}
saveChainToFile(){
fs.writeFileSync(uumChainFile, JSON.stringify(this._chain))
console.log("The file was saved!");
}
}