-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.nim
65 lines (56 loc) · 1.53 KB
/
main.nim
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
import times
import strutils
import std/sha1
import jester
settings:
port = Port(5003)
bindAddr = "127.0.0.1"
type
Block = object
Index, BPM: int
Timestamp, Hash, PrevHash: string
var Blockchain: seq[Block]
proc calculateHash(b: Block): string =
var
record = intToStr(b.Index) & b.Timestamp & intToStr(b.BPM) & b.PrevHash
return $secureHash(record)
proc generateBlock(oldBlock: Block, BPM: int): Block =
var
newBlock: Block
newBlock.Index = oldBlock.Index + 1
newBlock.Timestamp = $getTime().toUnix()
newBlock.BPM = BPM
newBlock.PrevHash = oldBlock.Hash
newBlock.Hash = calculateHash(newBlock)
return newBlock
proc isBlockValid(newBlock, oldBlock: Block): bool =
if oldBlock.Index+1 != newBlock.Index:
return false
if oldBlock.Hash != newBlock.PrevHash:
return false
if calculateHash(newBlock) != newBlock.Hash:
return false
return true
proc replaceChain(newBlocks: seq[Block]) =
if len(newBlocks) > len(Blockchain):
Blockchain = newBlocks
var
genesisBlock: Block
genesisBlock.Index = 0
genesisBlock.Timestamp = $getTime().toUnix()
genesisBlock.BPM = 0
genesisBlock.PrevHash = ""
genesisBlock.Hash = ""
Blockchain.add genesisBlock
routes:
get "/":
resp $Blockchain
post "/":
var
bpm = @"BPM"
newBlock = generateBlock(Blockchain[len(Blockchain)-1], bpm.parseInt)
if isBlockValid(newBlock, Blockchain[len(Blockchain)-1]):
var newBlocks = deepCopy(Blockchain)
newBlocks.add newBlock
replaceChain(newBlocks)
resp Http201, $newBlock