forked from dongyuanxin/node-blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
64 lines (50 loc) · 1.32 KB
/
test.js
File metadata and controls
64 lines (50 loc) · 1.32 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
const CryptoJS = require('crypto-js')
const {
getLength,
generateNextBlock,
addBlock,
addChain,
getBlock,
checkBlock,
Block
} = require('./main')
function generateBlock(blockData, previousBlock) {
const nextIndex = previousBlock.index + 1
const nextTimeStamp = new Date().getTime()
const nextHash = CryptoJS.SHA256(nextIndex + previousBlock.hash + nextTimeStamp + blockData) + ''
return new Block(nextIndex, previousBlock.hash, nextTimeStamp, blockData, nextHash)
}
function printBlockChain() {
let length = getLength(),
blocks = []
for(let i = 0; i < length; ++i) {
blocks.push(getBlock(i))
}
console.table(blocks)
}
/*
addBlock(generateNextBlock('a'))
addBlock(generateNextBlock('b'))
console.log('区块链长度是', getLength())
console.log('起源块是', getBlock(0))
// 打印区块链
printBlockChain()
let newBlock = generateNextBlock('c')
// 是否合法
console.log(checkBlock(newBlock))
*/
let aBlock = null;
addBlock(generateNextBlock('a'))
aBlock = getBlock(getLength() - 1)
addBlock(generateNextBlock('b'))
printBlockChain()
setTimeout(() => {
let blockchain = [],
newBlock = null
newBlock = generateBlock('B', aBlock)
blockchain.push(newBlock)
newBlock = generateBlock('C', newBlock)
blockchain.push(newBlock)
addChain(blockchain)
printBlockChain()
}, 1000)