lessons period 2
This commit is contained in:
24
period_2/02-sockets/902/BlockChain.py
Normal file
24
period_2/02-sockets/902/BlockChain.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
|
||||
class CBlock:
|
||||
|
||||
data = None
|
||||
previousHash = None
|
||||
previousBlock = None
|
||||
def __init__(self, data, previousBlock):
|
||||
self.data = data
|
||||
self.previousBlock = previousBlock
|
||||
if previousBlock != None:
|
||||
self.previousHash = previousBlock.computeHash()
|
||||
|
||||
def computeHash(self):
|
||||
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
|
||||
digest.update(bytes(str(self.data),'utf8'))
|
||||
digest.update(bytes(str(self.previousHash),'utf8'))
|
||||
return digest.finalize()
|
||||
|
||||
def is_valid(self):
|
||||
if self.previousBlock == None:
|
||||
return True
|
||||
return self.previousBlock.computeHash() == self.previousHash
|
65
period_2/02-sockets/902/Client_test.py
Normal file
65
period_2/02-sockets/902/Client_test.py
Normal file
@@ -0,0 +1,65 @@
|
||||
from TxBlock import *
|
||||
from Transaction import *
|
||||
from Signature import *
|
||||
|
||||
from SocketUtil import *
|
||||
|
||||
SERVER = 'localhost'
|
||||
TCP_PORT = 5050
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
alex_prv, alex_pbc = generate_keys()
|
||||
mike_prv, mike_pbc = generate_keys()
|
||||
rose_prv, rose_pbc = generate_keys()
|
||||
mara_prv, mara_pbc = generate_keys()
|
||||
|
||||
Tx1 = Tx()
|
||||
Tx1.add_input(alex_pbc, 2.3)
|
||||
Tx1.add_output(mike_pbc, 1.0)
|
||||
Tx1.add_output(rose_pbc, 1.1)
|
||||
Tx1.sign(alex_prv)
|
||||
|
||||
Tx2 = Tx()
|
||||
Tx2.add_input(rose_pbc, 2.3)
|
||||
Tx2.add_input(mike_pbc, 1.0)
|
||||
Tx2.add_output(alex_pbc, 3.1)
|
||||
Tx2.sign(mike_prv)
|
||||
Tx2.sign(rose_prv)
|
||||
|
||||
B1 = TxBlock(None)
|
||||
B1.addTx(Tx1)
|
||||
B1.addTx(Tx2)
|
||||
|
||||
server = newServerSocket(SERVER)
|
||||
|
||||
print('A connection to the server is established.')
|
||||
|
||||
# -------------------------------------
|
||||
sendObj(SERVER, Tx2)
|
||||
print('Server is in Receiving mode ...')
|
||||
Obj = recvObj(server)
|
||||
if Obj:
|
||||
print('Data: ', type(Obj),'\n')
|
||||
else:
|
||||
print('No object received')
|
||||
|
||||
# -------------------------------------
|
||||
sendObj(SERVER, B1)
|
||||
print('Server is in Receiving mode ...')
|
||||
Obj = recvObj(server)
|
||||
if Obj:
|
||||
print('Data: ', type(Obj),'\n')
|
||||
else:
|
||||
print('No object received')
|
||||
|
||||
# -------------------------------------
|
||||
print('Server is in Receiving mode ...')
|
||||
Obj = recvObj(server)
|
||||
if Obj:
|
||||
print(Obj)
|
||||
else:
|
||||
print('No object received')
|
||||
|
||||
print("Success! The connection is released.") # If returns after time, then successful
|
||||
server.close()
|
41
period_2/02-sockets/902/Signature.py
Normal file
41
period_2/02-sockets/902/Signature.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from cryptography.exceptions import *
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
def generate_keys():
|
||||
private_key = rsa.generate_private_key(public_exponent=65537,key_size=2048)
|
||||
public_key = private_key.public_key()
|
||||
|
||||
pbc_ser = public_key.public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
return private_key, pbc_ser
|
||||
|
||||
def sign(message, private_key):
|
||||
message = bytes(str(message), 'utf-8')
|
||||
signature = private_key.sign(
|
||||
message,
|
||||
padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),
|
||||
hashes.SHA256()
|
||||
)
|
||||
return signature
|
||||
|
||||
def verify(message, signature, pbc_ser):
|
||||
message = bytes(str(message), 'utf-8')
|
||||
public_key = serialization.load_pem_public_key(pbc_ser)
|
||||
try:
|
||||
public_key.verify(
|
||||
signature,
|
||||
message,
|
||||
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
|
||||
salt_length=padding.PSS.MAX_LENGTH),
|
||||
hashes.SHA256()
|
||||
)
|
||||
return True
|
||||
except InvalidSignature:
|
||||
return False
|
||||
except:
|
||||
print("Error executing 'public_key.verify'")
|
||||
return False
|
38
period_2/02-sockets/902/SocketUtil.py
Normal file
38
period_2/02-sockets/902/SocketUtil.py
Normal file
@@ -0,0 +1,38 @@
|
||||
import socket
|
||||
import pickle
|
||||
import select
|
||||
|
||||
TCP_PORT = 5050
|
||||
BUFFER_SIZE = 1024
|
||||
|
||||
|
||||
def newServerSocket(ip_addr):
|
||||
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
server_socket.bind((ip_addr, TCP_PORT))
|
||||
server_socket.listen()
|
||||
return server_socket
|
||||
|
||||
|
||||
def recvObj(socket):
|
||||
ready_to_read, ready_to_write, in_error = select.select([socket], [], [socket], 20)
|
||||
if socket in ready_to_read:
|
||||
print('Server is ready to receive data ...')
|
||||
connected_socket, addr = socket.accept()
|
||||
print('Server is receiving data ...')
|
||||
all_data = b''
|
||||
while True:
|
||||
data = connected_socket.recv(BUFFER_SIZE)
|
||||
if not data:
|
||||
break
|
||||
all_data = all_data + data
|
||||
return pickle.loads(all_data)
|
||||
return None
|
||||
|
||||
|
||||
def sendObj(ip_addr, obj):
|
||||
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
soc.connect((ip_addr, TCP_PORT))
|
||||
data = pickle.dumps(obj)
|
||||
soc.send(data)
|
||||
soc.close()
|
||||
return False
|
18
period_2/02-sockets/902/SocketUtil_t.py
Normal file
18
period_2/02-sockets/902/SocketUtil_t.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from TxBlock import *
|
||||
from Transaction import *
|
||||
from Signature import *
|
||||
|
||||
from SocketUtil import *
|
||||
|
||||
TCP_PORT = 5050
|
||||
BUFFER_SIZE = 1024
|
||||
SERVER = 'localhost'
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
server = newServerSocket(SERVER)
|
||||
print('A connection to the server is established.')
|
||||
Obj = recvObj(server)
|
||||
|
||||
print("Success! The connection is released.") # If returns after time, then successful
|
||||
server.close()
|
88
period_2/02-sockets/902/Transaction.py
Normal file
88
period_2/02-sockets/902/Transaction.py
Normal file
@@ -0,0 +1,88 @@
|
||||
from Signature import *
|
||||
|
||||
class Tx:
|
||||
inputs = None
|
||||
outputs =None
|
||||
sigs = None
|
||||
reqd = None
|
||||
def __init__(self):
|
||||
self.inputs = []
|
||||
self.outputs = []
|
||||
self.sigs = []
|
||||
self.reqd = []
|
||||
|
||||
def add_input(self, from_addr, amount):
|
||||
self.inputs.append((from_addr, amount))
|
||||
|
||||
def add_output(self, to_addr, amount):
|
||||
self.outputs.append((to_addr, amount))
|
||||
|
||||
def add_reqd(self, addr):
|
||||
self.reqd.append(addr)
|
||||
|
||||
def sign(self, private):
|
||||
message = self.__gather()
|
||||
newsig = sign(message, private)
|
||||
self.sigs.append(newsig)
|
||||
|
||||
def is_valid(self):
|
||||
total_in = 0
|
||||
total_out = 0
|
||||
message = self.__gather()
|
||||
for addr,amount in self.inputs:
|
||||
found = False
|
||||
for s in self.sigs:
|
||||
if verify(message, s, addr):
|
||||
found = True
|
||||
if not found:
|
||||
# print ("No good sig found for " + str(message))
|
||||
return False
|
||||
if amount < 0:
|
||||
return False
|
||||
total_in = total_in + amount
|
||||
for addr in self.reqd:
|
||||
found = False
|
||||
for s in self.sigs:
|
||||
if verify(message, s, addr):
|
||||
found = True
|
||||
if not found:
|
||||
return False
|
||||
for addr,amount in self.outputs:
|
||||
if amount < 0:
|
||||
return False
|
||||
total_out = total_out + amount
|
||||
|
||||
# if total_out > total_in:
|
||||
# # print("Outputs exceed inputs")
|
||||
# return False
|
||||
|
||||
return True
|
||||
|
||||
def __gather(self):
|
||||
data=[]
|
||||
data.append(self.inputs)
|
||||
data.append(self.outputs)
|
||||
data.append(self.reqd)
|
||||
return data
|
||||
|
||||
def __repr__(self):
|
||||
|
||||
repr_str = "INPUTS:\n"
|
||||
for addr, amt in self.inputs:
|
||||
repr_str = repr_str + str(amt) + "from" + str(addr) + "\n"
|
||||
|
||||
repr_str += "OUTPUTS:\n"
|
||||
for addr, amt in self.outputs:
|
||||
repr_str = repr_str + str(amt) + "to" + str(addr) + "\n"
|
||||
|
||||
repr_str += "EXTRA REQUIRED SIGNATURES:\n"
|
||||
for req_sig in self.reqd:
|
||||
repr_str = repr_str + str(req_sig) + "\n"
|
||||
|
||||
repr_str += "SIGNATURES:\n"
|
||||
for sig in self.sigs:
|
||||
repr_str = repr_str + str(sig) + "\n"
|
||||
|
||||
repr_str += "END\n"
|
||||
|
||||
return repr_str
|
60
period_2/02-sockets/902/TxBlock.py
Normal file
60
period_2/02-sockets/902/TxBlock.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from BlockChain import CBlock
|
||||
from Signature import generate_keys, sign, verify
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
import random
|
||||
|
||||
reward = 25.0
|
||||
leading_zeros = 2
|
||||
next_char_limit = 20
|
||||
|
||||
class TxBlock(CBlock):
|
||||
|
||||
nonce = "A random nonce"
|
||||
|
||||
def __init__(self, previousBlock):
|
||||
super(TxBlock, self).__init__([], previousBlock)
|
||||
|
||||
def addTx(self, Tx_in):
|
||||
self.data.append(Tx_in)
|
||||
|
||||
def __count_totals(self):
|
||||
total_in = 0
|
||||
total_out = 0
|
||||
for tx in self.data:
|
||||
for addr, amt in tx.inputs:
|
||||
total_in = total_in + amt
|
||||
for addr, amt in tx.outputs:
|
||||
total_out = total_out + amt
|
||||
return total_in, total_out
|
||||
|
||||
def is_valid(self):
|
||||
if not super(TxBlock, self).is_valid():
|
||||
return False
|
||||
for tx in self.data:
|
||||
if not tx.is_valid():
|
||||
return False
|
||||
total_in, total_out = self.__count_totals()
|
||||
if total_out - total_in - reward > 0.000000000001:
|
||||
return False
|
||||
return True
|
||||
|
||||
def good_nonce(self):
|
||||
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
|
||||
digest.update(bytes(str(self.data), 'utf8'))
|
||||
digest.update(bytes(str(self.previousHash), 'utf8'))
|
||||
digest.update(bytes(str(self.nonce), 'utf8'))
|
||||
this_hash = digest.finalize()
|
||||
|
||||
if this_hash[:leading_zeros] != bytes(''.join(['\x4f' for i in range(leading_zeros)]), 'utf8'):
|
||||
return False
|
||||
return int(this_hash[leading_zeros]) < next_char_limit
|
||||
|
||||
def find_nonce(self):
|
||||
for i in range(1000000):
|
||||
self.nonce = ''.join([
|
||||
chr(random.randint(0, 255)) for i in range(10*leading_zeros)])
|
||||
if self.good_nonce():
|
||||
return self.nonce
|
||||
return None
|
Reference in New Issue
Block a user