Skip to content

Commit d3270b9

Browse files
#9 Creating a Block part Three
1 parent 4de9345 commit d3270b9

File tree

3 files changed

+47
-2
lines changed

3 files changed

+47
-2
lines changed

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,8 @@
1111
},
1212
"devDependencies": {
1313
"tsc-watch": "^1.0.17"
14+
},
15+
"dependencies": {
16+
"crypto-js": "^3.1.9-1"
1417
}
1518
}

src/index.ts

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,20 @@
1+
import * as CryptoJS from "crypto-js";
2+
13
class Block {
24
public index: number;
35
public hash: string;
46
public previousHash: string;
57
public data: string;
68
public timestamp: number;
9+
10+
static calculateBlockHash = (
11+
index: number,
12+
previousHash: string,
13+
timestamp: number,
14+
data: string
15+
): string =>
16+
CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
17+
718
constructor(
819
index: number,
920
hash: string,
@@ -21,8 +32,35 @@ class Block {
2132

2233
const genesisBlock: Block = new Block(0, "2020202020202", "", "Hello", 123456);
2334

24-
let blockchain: [Block] = [genesisBlock];
35+
let blockchain: Block[] = [genesisBlock];
36+
37+
const getBlockchain = (): Block[] => blockchain;
38+
39+
const getLatestBlock = (): Block => blockchain[blockchain.length - 1];
40+
41+
const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);
42+
43+
const createNewBlock = (data: string): Block => {
44+
const previosBlock: Block = getLatestBlock();
45+
const newIndex: number = previosBlock.index + 1;
46+
const newTimestamp: number = getNewTimeStamp();
47+
const newHash: string = Block.calculateBlockHash(
48+
newIndex,
49+
previosBlock.hash,
50+
newTimestamp,
51+
data
52+
);
53+
const newBlock: Block = new Block(
54+
newIndex,
55+
newHash,
56+
previosBlock.hash,
57+
data,
58+
newTimestamp
59+
);
60+
return newBlock;
61+
};
2562

26-
console.log(blockchain);
63+
console.log(createNewBlock("hello"));
64+
console.log(createNewBlock("bye bye"));
2765

2866
export {};

yarn.lock

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ cross-spawn@^5.1.0:
3434
shebang-command "^1.2.0"
3535
which "^1.2.9"
3636

37+
crypto-js@^3.1.9-1:
38+
version "3.1.9-1"
39+
resolved "https://registry.yarnpkg.com/crypto-js/-/crypto-js-3.1.9-1.tgz#fda19e761fc077e01ffbfdc6e9fdfc59e8806cd8"
40+
3741
duplexer@~0.1.1:
3842
version "0.1.1"
3943
resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1"

0 commit comments

Comments
 (0)