lessons period 2
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
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.blockHash = None
|
||||
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
|
@@ -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
|
@@ -0,0 +1,100 @@
|
||||
from gzip import READ
|
||||
from operator import truediv
|
||||
from optparse import AmbiguousOptionError
|
||||
|
||||
REWARD_VALUE = 25.0
|
||||
NORMAL = 0
|
||||
REWARD = 1
|
||||
|
||||
from Signature import *
|
||||
|
||||
class Tx:
|
||||
def __init__(self, type = NORMAL):
|
||||
|
||||
self.type = type
|
||||
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):
|
||||
|
||||
if self.type == REWARD:
|
||||
if len(self.inputs)!=0 and len(self.outputs)!=1:
|
||||
return False
|
||||
return True
|
||||
|
||||
else:
|
||||
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
|
@@ -0,0 +1,63 @@
|
||||
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_VALUE = 25.0
|
||||
leading_zeros = 2
|
||||
next_char_limit = 20
|
||||
|
||||
class TxBlock (CBlock):
|
||||
|
||||
def __init__(self, previousBlock):
|
||||
self.nonce = "A random nonce"
|
||||
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
|
||||
|
||||
if self.nonce != "A random nonce":
|
||||
if not self.good_nonce():
|
||||
return False
|
||||
|
||||
total_in, total_out = self.__count_totals()
|
||||
|
||||
Tx_Balance = round(total_out - total_in, 10)
|
||||
|
||||
if Tx_Balance > REWARD_VALUE:
|
||||
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()
|
||||
return this_hash[:leading_zeros] == b'\x00'*leading_zeros
|
||||
|
||||
def find_nonce(self):
|
||||
for i in range(10000000):
|
||||
self.nonce = i
|
||||
if self.good_nonce():
|
||||
return self.nonce
|
||||
return None
|
@@ -0,0 +1,11 @@
|
||||
import pickle
|
||||
import socket
|
||||
|
||||
PORT = 5005
|
||||
|
||||
def sendObj(ip_address, obj):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.connect((ip_address, PORT))
|
||||
sock.send(pickle.dumps(obj))
|
||||
sock.close()
|
||||
return False
|
@@ -0,0 +1,36 @@
|
||||
from TxBlock import *
|
||||
from Transaction import *
|
||||
from Signature import *
|
||||
|
||||
from client 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)
|
||||
|
||||
sendObj(SERVER, B1)
|
||||
|
||||
sendObj(SERVER, Tx2)
|
@@ -0,0 +1,21 @@
|
||||
import socket
|
||||
import pickle
|
||||
import TxBlock
|
||||
|
||||
PORT = 5050
|
||||
|
||||
def newConnection(ip_address):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.bind((ip_address, PORT))
|
||||
sock.listen(2)
|
||||
return sock
|
||||
|
||||
def recvObj(socket):
|
||||
new_sock, address = socket.accept()
|
||||
data = new_sock.recv(1024)
|
||||
print("Received: ", data)
|
||||
data = pickle.loads(data)
|
||||
new_sock.close()
|
||||
return data
|
||||
|
||||
|
@@ -0,0 +1,50 @@
|
||||
import TxBlock
|
||||
import socket
|
||||
import pickle
|
||||
|
||||
from server import *
|
||||
|
||||
SERVER = 'localhost'
|
||||
TCP_PORT = 5050
|
||||
# BUFFER_SIZE = 1024
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
server = newConnection(SERVER)
|
||||
|
||||
newB = recvObj(server)
|
||||
# print(newB.data[0])
|
||||
# print(newB.data[1])
|
||||
|
||||
if (newB.is_valid()):
|
||||
print("Success! Transaction is valid.")
|
||||
else:
|
||||
print("Error! Transaction invalid.")
|
||||
|
||||
if newB.data[0].inputs[0][1] == 2.3:
|
||||
print("Success! Input value matches.")
|
||||
else:
|
||||
print("Error! Wrong input value for block 1, transaction 1.")
|
||||
|
||||
if newB.data[0].outputs[1][1] == 1.1:
|
||||
print("Success! Output value matches.")
|
||||
else:
|
||||
print("Error! Wrong output value for block 1, transaction 1.")
|
||||
|
||||
if newB.data[1].inputs[0][1] == 2.3:
|
||||
print("Success! Input value matches.")
|
||||
else:
|
||||
print("Error! Wrong input value for block 1, transaction 1.")
|
||||
|
||||
if newB.data[1].inputs[1][1] == 1.0:
|
||||
print("Success! Input value matches.")
|
||||
else:
|
||||
print("Error! Wrong input value for block 1, transaction 1.")
|
||||
|
||||
if newB.data[1].outputs[0][1] == 3.1:
|
||||
print("Success! Output value matches.")
|
||||
else:
|
||||
print("Error! Wrong output value for block 1, transaction 1.")
|
||||
|
||||
newTx = recvObj(server)
|
||||
# print(newTx)
|
Reference in New Issue
Block a user