-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpychain.py
154 lines (109 loc) · 3.75 KB
/
pychain.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# PyChain Ledger
# Imports
import pwd
import streamlit as st
from dataclasses import dataclass
from typing import Any, List
import datetime as datetime
import pandas as pd
import hashlib
# Create a Record Data Class
# Create a Record Data Class that consists of the `sender`, `receiver`, and
# `amount` attributes
@dataclass
class Record:
sender: str
receiver: str
amount: float
# Modify the Existing Block Data Class to Store Record Data
# Set the data type of the `record` attribute to `Record`.
@dataclass
class Block:
record: Record
creator_id: int
prev_hash: str = "0"
timestamp: str = datetime.datetime.utcnow().strftime("%H:%M:%S")
nonce: int = 0
def hash_block(self):
sha = hashlib.sha256()
record = str(self.record).encode()
sha.update(record)
creator_id = str(self.creator_id).encode()
sha.update(creator_id)
timestamp = str(self.timestamp).encode()
sha.update(timestamp)
prev_hash = str(self.prev_hash).encode()
sha.update(prev_hash)
nonce = str(self.nonce).encode()
sha.update(nonce)
return sha.hexdigest()
# Create pychain data class
@dataclass
class PyChain:
chain: List[Block]
difficulty: int = 4
def proof_of_work(self, block):
calculated_hash = block.hash_block()
num_of_zeros = "0" * self.difficulty
while not calculated_hash.startswith(num_of_zeros):
block.nonce += 1
calculated_hash = block.hash_block()
print("Wining Hash", calculated_hash)
return block
def add_block(self, candidate_block):
block = self.proof_of_work(candidate_block)
self.chain += [block]
def is_valid(self):
block_hash = self.chain[0].hash_block()
for block in self.chain[1:]:
if block_hash != block.prev_hash:
print("Blockchain is invalid!")
return False
block_hash = block.hash_block()
print("Blockchain is Valid")
return True
# Adds the cache decorator for Streamlit
@st.cache(allow_output_mutation=True)
def setup():
print("Initializing Chain")
return PyChain([Block("Genesis", 0)])
# Add markdown on streamlit app
st.markdown("# PyChain")
st.markdown("## Store a Transaction Record in the PyChain")
pychain = setup()
# Add Relevant User Inputs to the Streamlit Interface
# Create these input areas to capture the sender, receiver, and
# amount for each transaction that you’ll store in the `Block` record.
# Add an input area where you can get a value for `sender` from the user.
sender = st.text_input("Sender")
# Add an input area where you can get a value for `receiver` from the user.
receiver = st.text_input("Receiver")
# Add an input area where you can get a value for `amount` from the user.
amount = st.text_input("Amount")
if st.button("Add Block"):
prev_block = pychain.chain[-1]
prev_block_hash = prev_block.hash_block()
# Update `new_block` so that `Block` consists of an attribute named `record`
new_block = Block(
record=Record,
creator_id=42,
prev_hash=prev_block_hash
)
pychain.add_block(new_block)
st.balloons()
# Streamlit Code for ledger dataframe
st.markdown("## The PyChain Ledger")
pychain_df = pd.DataFrame(pychain.chain).astype(str)
st.write(pychain_df)
# Set pychain difficulty
difficulty = st.sidebar.slider("Block Difficulty", 1, 5, 2)
pychain.difficulty = difficulty
# Create sidebar block inspector for the pychain
st.sidebar.write("# Block Inspector")
selected_block = st.sidebar.selectbox(
"Which block would you like to see?", pychain.chain
)
st.sidebar.write(selected_block)
# Create button to validate pychain
if st.button("Validate Chain"):
st.write(pychain.is_valid())