I am trying to create my own blockchain using python.
I took this source code and I am trying to tweak it to fit what I need.
My code:
import datetime
import hashlib
class Block:
def __init__(
self,
previous_block_hash,
data,
timestamp,
sender,
):
self.previous_block_hash = previous_block_hash
self.data = data
self.timestamp = timestamp
self.hash = self.get_hash()
self.sender = self.get_sender()
#staticmethod
def create_genesis_block():
return Block('0', '0', datetime.datetime.now(), '')
def get_sender(self):
self.sender = input('Enter senders ID number: ')
return self.sender
def get_hash(self):
header_bin = str(self.previous_block_hash) + str(self.data) \
+ str(self.timestamp) + str(self.sender)
inner_hash = \
hashlib.sha256(header_bin.encode()).hexdigest().encode()
outer_hash = hashlib.sha256(inner_hash).hexdigest()
return outer_hash
blockchain = [Block.create_genesis_block()]
length_of_blockchain = len(blockchain)
print ('The genesis block has been created.')
print ('Hash: %s' % blockchain[0].hash)
blockchain.append(Block(blockchain[length_of_blockchain - 1].hash,
'Blockchain Number: '[length_of_blockchain - 1],
datetime.datetime.now(), Block.get_sender()))
I want to add a sender and receiver to the Block. So, I started out with one first and that is the sender. I keep getting this error here and I am not sure how to fix it. Everything is being tested locally to make sure everything checks out then I will add react native to it. Hoping someone can help me
You're trying to access self.sender before initializing it. Reordering initialization might help us here.
import datetime
import hashlib
class Block:
def __init__(
self,
previous_block_hash,
data,
timestamp,
sender,
):
self.previous_block_hash = previous_block_hash
self.data = data
self.timestamp = timestamp
#reordering self.hash and self.sender as self.get_sender() references to self.sender
self.sender = self.get_sender()
self.hash = self.get_hash()
#staticmethod
def create_genesis_block():
return Block('0', '0', datetime.datetime.now(), '')
def get_sender(self):
self.sender = input('Enter senders ID number: ')
return self.sender
def get_hash(self):
header_bin = str(self.previous_block_hash) + str(self.data) \
+ str(self.timestamp) + str(self.sender)
inner_hash = \
hashlib.sha256(header_bin.encode()).hexdigest().encode()
outer_hash = hashlib.sha256(inner_hash).hexdigest()
return outer_hash
hope this helps
Related
I am trying to set up a multithreaded server and client, and am currently sending information wrapped in a TCP module class. I am sending the data using pickle, and have run in to a problem where attempting to access instance variables after unpickling the data leads to "Property object at 0x", instead of the instance variable.
Here is the relevant server code:
data = self.clientSocket.recv(2048)
print(data)
message = pickle.loads(data)
header = message.header
self.currUser = message.user
if header == 'user-login':
print("[recv] New login request")
self.userLogin()
client code:
username = input("Username: ")
password = input("Password: ")
message = TCPmodule().withSocket("user-login", password, self.clientSocket)
message.user = username
print(message.header)
data = pickle.dumps(message)
self.clientSocket.send(data)
Class (classmethod used and getters/setters):
def withSocket(self, header, content, socket):
self.header = header
self.content = content
self.socket = socket
self.user = ""
self.port = 0
return self
#property
def header(self):
return self._header
#header.setter
def header(self,value):
self._header = value
#property
def content(self):
return self._content
#content.setter
def content(self,content):
self._content = content
#property
def user(self):
return self._user
#user.setter
def user(self,user):
self._user = user
property object message when I print (message.header) server side
Am somewhat new to python, so I'm not sure if I'm missing something here.
Thanks
I coded this in python 3 and it is showing an attribute error.code is
as following:
import datetime
class MessageUser():
User_Details = []
Messages = []
base_message = """Hi {name}!
Thank you for the purchase on {date}.
We hope you are exicted about using it. Just as a
reminder the purcase total was ${total}.
Have a great time!
from Pritom_Mazhi
"""
def add_user(self, name, amount, email=None):
name = name[0].upper() + name[1:].lower() #Capitalizing the first letter of all names - formatted name
amount = "%.2f" %(amount) #formatted amount
detail = {
"name" : name,
"amount" : amount,
}
today = datetime.date.today()
date_text = '{tday.day}/{tday.month}/{tday.year}'.format(tday=today) #formatted date
detail["date"] = date_text
if email is not None:
detail["email"] = email
self.User_Details.append(detail)
def get_details(self):
return self.User_Details
def make_message(self):
if len(self.User_Details) > 0:
for detail in self.get_details(): #for detail in self.User_Details
name = detail["name"]
amount = detail["amount"]
date = detail["date"]
email = detail["email"]
message = self.base_message
formatted_message = message.format(
name = name,
total = amount,
date = date,
)
self.Messages.append(formatted_message)
return self.Messages
else:
return []
obj = MessageUser()
obj.add_user("Pritom", 123.32, email='hello#teamcfe.com')
obj.add_user("jon Snow", 94.23)
obj.add_user("Sean", 93.23)
obj.add_user("Emilee", 193.23)
obj.add_user("Marie", 13.23)
obj.get_details()
obj.make_message()
when i run it i get this error:
File "Class_StringFormat.py", line 57, in <module>
obj.get_details()
AttributeError: 'MessageUser' object has no attribute 'get_details'
i simply can't find what wrong i did there and so can't manage to fix it.
If your indentation is reproduced correctly in the question, get_details is defined inside add_user and is not visible from outside.
You should unindent the definition of get_details and make_message to be on the same level as add_user:
def add_user(self, name, amount, email=None):
# method body...
def get_details(self):
return self.User_Details
def make_message(self):
# method body
class Person:
def __init__(self, name):
self.name = name
self.bucket = []
def announce(self, *args):
# ???
pass
def put(self, item):
self.bucket.append(item)
p1 = Person("ya")
p2 = Person("yu")
p1.put("apple")
now I want to somehow announce to all Person() objects that I have an apple in my bucket, they should put one apple in their bucket too if they want.
Simple implementation could be:
class Person:
persons = set()
def __init__(self, name):
self.name = name
self.bucket = []
self.persons.add(self)
def announce(self, msg):
print("[{}]: {}".format(self.name,msg))
#classmethod
def broadcast(cls, person, msg):
for p in cls.persons:
if not p is person:
p.announce(msg)
def put(self, item):
self.bucket.append(item)
self.broadcast(self, '{}: got {} in my bucket!'.format(self.name, item))
p1 = Person("ya")
p2 = Person("yu")
p1.put("apple")
Person.broadcast(None, "Hey! Everybody can broadcast message!")
Output:
[yu]: "ya: got apple in my bucket!
[ya]: Hey! Everybody can broadcast message!
[yu]: Hey! Everybody can broadcast message!
That implementation lacks in
No deregister implementation
No thread save
Just Person and it's subclass can be informed
It is just a toy, you need to adapt it to your real case
Maybe is better you implement an Observer pattern better than that simple one.
Implementing the observer-pattern in python is quite simple,
The basic idea "I want Object A, object B, Object C to get notifications from a specified messaging Object". Therefore you somehow have to connect them, in observer Pattern this process is called "subscription". So your Object A, B, C (Observers) are subscribing to the Object that delivers messages (Subject)
This example is a basic implementation. I didn't addapt it to your code, but alice and bob would be Persons in your case.
class Mailbox :
def __init__(self, ownersName):
self.owner = ownersName
self.messages = []
self.newMessageObservers = []
def deliverMessage(self, message):
self.messages.append(message)
for notifyNewMessage in self.newMessageObservers:
notifyNewMessage(message, self.owner)
def subscribe(self, observer):
self.newMessageObservers.append(observer)
class MailboxObserver :
def __init__(self, observerName):
self.name = observerName
def newMessageHandler(self, contents, owner):
print self.name + " observed a new message in " +\
owner + "'s mailbox"
print "The message said: " + contents
# create the observers
alice = MailboxObserver("alice")
bob = MailboxObserver("bob")
# create a mailbox
alicesMailbox = Mailbox("alice")
# have bob and alice subscribe to alice's mailbox
# registering their 'newMessageHandler' method
alicesMailbox.subscribe(bob.newMessageHandler)
alicesMailbox.subscribe(alice.newMessageHandler)
# put a new message into alice's mailbox
alicesMailbox.deliverMessage("Hello, world!")
source: http://www.philipuren.com/serendipity/index.php?/archives/4-Simple-Observer-Pattern-in-Python.html
Just keep a normal variable in your class (Not a member), and update it whenever you want to "announce" something to all classes.
class Person:
bApple = False
def __init__(self, name):
self.name = name
self.bucket = []
def announce(self, *args):
# ???
pass
def put(self, item):
self.bucket.append(item)
def hasApple(self):
if Person.bApple:
return "True"
else:
return "False"
p1 = Person("ya")
p2 = Person("yu")
p1.put("apple")
print "p1 has Apple? " + p1.hasApple()
print "p2 has Apple? " + p2.hasApple()
Person.bApple = True
print "p1 has Apple? " + p1.hasApple()
print "p2 has Apple? " + p2.hasApple()
I need to simulate the requests and responses being processed by a network of routers and began small by creating a server class:
class NBServer:
"""Name based content server"""
def __init__(self, _id):
self.id = _id
self.requests = deque('x')
self.responses = deque('x')
self.req_load = 0
self.res_load = 0
self.color = ''
self.forwarding_table = {}
self.content_store = {}
self.pending_table = {}
def __str__(self):
return 'current load: ' + str(req_load + req_load)
def request(self, content_name, requester_id):
self.requests.append((content_name, requester_ids))
self.req_load += 1
def response(self, content_name, content_url):
self.responses.append((content_url, destination_ids))
return ((content_url, destination_ids))
def process(self):
for req in self.requests:
# Case 1: content in cache
if content_name in self.content_store:
return self.content_name[content_name]
# Case 2: duplicate request exists
elif content_name in self.pending_table:
self.pending_table[content_name].append(requester_id)
# Case 3: add to PT, forward to next router
else:
self.pending_table[content_name] = [requester_id]
response = response.popleft()
if response:
for dest_id in self.pending_table[content_name]:
nodes[dest_id].response(content_name, content_url)
del self.pending_table[content_name]
However, now I am getting confused on how the communication between the routers can be represented:
Any advice on how to do this with NumPy?
Any help is greatly appreciated!
from datetime import datetime
class sms_store:
store = []
read = []
def add_new_arrival(self,number,time,text):
sms_store.read.append(len(sms_store.store))
sms_store.store.append(("From: {}, Recieved: {}, Msg: {}".format(number,time,text)))
def delete(self,i):
try:
del sms_store.store[i]
except IndexError:
print("Index is out of range. Cannot delete")
def message_count(self):
return print("Amt of messages in inbox: {}".format(len(sms_store.store)))
def viewall(self):
print(sms_store.store)
def get_unread_indexes(self):
#### ###################################I need help for this method.
def get_message(self,i)
print(sms_store.store[i])
### tests ####
time = datetime.now().strftime('%H:%M:%S')
my_inbox = sms_store() #instantiate an object 'store' for class
my_inbox.add_new_arrival("12345",time,"Hello how are you?") #instance of store object
my_inbox.add_new_arrival("1111111",time,"BYE BYE BYE")
my_inbox.viewall()
my_inbox.msgcount()
Thanks for viewing this.
This is what I need to do:
my_inbox.add_new_arrival()
When adding a new message, its has_been_viewed status is set False.
my_inbox.get_unread_indexes()
Returns list of indexes of all not-yet-viewed SMS messages
my_inbox.get_message(i)**
Return (from_number, time_arrived, text_of_sms) for message[i]
Also change its state to "has been viewed".
If there is no message at position i, return None
Please help me on those above methods!?
Thank you so much!
Hi I tweaked your code a bit, I think I have done this before in the "How to think like a computer Scientist Book", Hope it works for you.
from datetime import datetime
and
class SMS_store:
then
def __init__(self):
self.store = []
def __str__(self):
return ("{0}".format(self))
def add_new_arrival(self, number, time, text ):
self.store.append(("Read: False", "From: "+number, "Recieved: "+time, "Msg: "+text))
def message_count(self):
return (len(self.store))
def get_unread_indexes(self):
result = []
for (i, v) in enumerate(self.store):
if v[0] == "Read: False":
result.append(i)
return (result)
def get_message(self, i):
msg = self.store[i]
msg = ("Read: True",) + msg[1:]
self.store[i] = (msg)
return (self.store[i][1:])
def delete(self, i):
del self.store[i]
def clear(self):
self.store = []
Why don't you add another list to your class called unread. Change add_new_arrival to add the message to unread.
Then under the get_message method move the specified message from unread to read.
Lastly your get_unread method just lists the indexes of the unread list.
Python SMS store program using class and methods - has_been_viewed status
import time
class SMS_store:
def __init__(self):
self.inbox = []
def add_new_arrival(self, from_number, text_of_sms,read_status = False):
number = str(from_number)
time_received = time.strftime("%D %T")
self.inbox.append([time_received, number, text_of_sms, read_status])
def message_count(self):
return "There are {0} messages in your Inbox".format(len(self.inbox))
def get_unread_indexes(self):
unread = []
for index, message in enumerate(self.inbox):
if False in message:
unread.append(index)
return "Unread Messages in:", unread
def get_message(self, index):
message = self.inbox[index]
message[3] = "Read"
return message[ : 3]
def delete(self, index):
del self.inbox[index]
return "Deleted Message", index
def clear(self):
self.inbox = []
return "Empty Inbox"