-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.py
69 lines (58 loc) · 2.05 KB
/
node.py
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
from blockChain import *
from transactions import *
# Initialize the transaction buffer and set the block size
blockSizeLimit = 3
txnBuffer = []
while(True):
command = input("> ").split()
if(command[0] == "transaction"):
if(len(command) == 1):
txn = randomTransaction();
else:
fr = command[1]
to = command[2]
amt = int(command[3])
txn = {fr: 0-amt,to: amt}
txnBuffer.append(txn)
# If we have enough transactions for a block, make one
if(len(txnBuffer)>blockSizeLimit-1):
print("Making a block...")
txnList = []
while (len(txnBuffer) > 0) & (len(txnList) < blockSizeLimit):
newTxn = txnBuffer.pop()
validTxn = isValidData(newTxn,state)
if validTxn:
txnList.append(newTxn)
state = updateState(newTxn,state)
else:
print("ignored transaction")
sys.stdout.flush()
continue # This was an invalid transaction; ignore it and move on
# Make a block
chain.makeBlock(txnList)
else:
print(txnBuffer)
elif(command[0] == "init"):
if(len(command)==1):
state={"Charlie":50, "Ada":50}
else:
state = {command[1]:int(command[2])}
chain = BlockChain(state,isValidData,updateState)
elif(command[0] == "save"):
f = open('BlockChain.json', 'w')
f.write(json.dumps(chain.chain,sort_keys=True))
f.close()
elif(command[0] == "import"):
f = open('BlockChain.json', 'r')
importChain = json.loads(f.read())
importBC = BlockChain(None,isValidData,updateState)
importBC.chain = importChain
f.close()
importState = importBC.checkChain()
if(importState):
chain = importBC
state = chain.checkChain()
elif(command[0] == "state"):
print(chain.checkChain())
else:
print("Not a valid command")