-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackend.py
1694 lines (1537 loc) · 64.8 KB
/
backend.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import copy
import io
import json
import os
import queue
import random
import threading
import time
import traceback
import typing
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Cipher.PKCS1_OAEP import PKCS1OAEP_Cipher
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from PIL import Image
from django.db import connection
class DBmanager:
# DATABASE_PATH = "./demo.db"
COLLECTIONS_TABLE_NAME = "collections"
USER_TABLE_NAME = "users"
TRANSACTIONS_TABLE_NAME = "transactions"
def __init__(self):
# init connection, db will be created if it doesn't exist
# self.conn = sqlite3.connect(self.DATABASE_PATH)
# self.cur = self.conn.cursor()
self.cur = connection.cursor()
# init tables
self.init_collections_table()
self.init_user_table()
self.init_transactions_table()
# init tables
def init_collections_table(self):
if (
len(
self.cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='{}';".format(
self.COLLECTIONS_TABLE_NAME
)
).fetchall()
)
> 0
):
print("Find '{}' table in db.".format(self.COLLECTIONS_TABLE_NAME))
return
# id | owner_id | price | encrypted_content | preview_path | status
self.cur.execute(
"CREATE TABLE {} "
"(ID TEXT, OWNER_ID TEXT, PRICE REAL, ENCRYPTED_CONTENT BOLB, PREVIEW_PATH TEXT, STATUS TEXT);".format(
self.COLLECTIONS_TABLE_NAME
)
)
# self.conn.commit()
print("Images table initialized.")
def init_user_table(self):
if (
len(
self.cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='{}';".format(
self.USER_TABLE_NAME
)
).fetchall()
)
> 0
):
print("Find '{}' table in db.".format(self.USER_TABLE_NAME))
return
# id | validation_file | pub_key | balance
self.cur.execute(
"CREATE TABLE {} (ID TEXT, VALIDATION_FILE TEXT, PUB_KEY TEXT, BALANCE REAL);".format(
self.USER_TABLE_NAME
)
)
# self.conn.commit()
print("Users table initialized.")
def init_transactions_table(self):
if (
len(
self.cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='{}';".format(
self.TRANSACTIONS_TABLE_NAME
)
).fetchall()
)
> 0
):
print("Find '{}' table in db.".format(self.TRANSACTIONS_TABLE_NAME))
return
# id | timestamp | type | content | collection_id | src_user_id | dest_user_id | status
self.cur.execute(
"CREATE TABLE {} (\
ID TEXT PRIMARY KEY, \
TIMESTAMP REAL, \
TYPE TEXT, \
CONTENT TEXT, \
COLLECTION_ID TEXT, \
SRC_USER_ID TEXT, \
DEST_USER_ID TEXT, \
STATUS TEXT, \
AMOUNT REAL);".format(
self.TRANSACTIONS_TABLE_NAME
)
)
# self.conn.commit()
print("Transaction table initialized.")
# manage collections TABLE
def add_collection(
self,
collection_id: str,
price: typing.Union[float, None] = None,
owner_id: typing.Union[str, None] = None,
encrypted_content: typing.Union[str, None] = None,
preview_path: typing.Union[str, None] = None,
status: typing.Union[str, None] = None,
):
self.cur.execute(
"INSERT INTO {} VALUES('{}', '{}', '{}', '{}', '{}', '{}')".format(
self.COLLECTIONS_TABLE_NAME,
collection_id,
owner_id,
price,
encrypted_content,
preview_path,
status,
)
)
# self.conn.commit()
'''
def remove_collection(self, collection_id):
self.cur.execute(
"DELETE FROM '{}' WHERE id = '{}'".format(
self.COLLECTIONS_TABLE_NAME, collection_id
)
)
# self.conn.commit()
'''
def update_collection(
self,
collection_id: str,
owner_id: str = None,
price: float = None,
encrypted_content: str = None,
preview_path: str = None,
status: str = None,
):
"""Update any field of the collection table in database."""
for field_name, field_value in zip(
[
f"{owner_id=}".split("=")[0],
f"{price=}".split("=")[0],
f"{encrypted_content=}".split("=")[0],
f"{preview_path=}".split("=")[0],
f"{status=}".split("=")[0],
],
[owner_id, price, encrypted_content, preview_path, status],
): # field_name is the name of the variable
if field_value:
'''
self.cur.execute(
"UPDATE '{}' SET '{}' = '{}' WHERE ID = '{}';".format(
self.COLLECTIONS_TABLE_NAME,
field_name,
field_value,
collection_id,
)
)
'''
sql = "UPDATE {} SET {} = '{}' WHERE ID = '{}';" \
.format(self.COLLECTIONS_TABLE_NAME, field_name, field_value, collection_id)
self.cur.execute(sql)
# self.conn.commit()
def get_all_collections(self):
self.cur.execute("SELECT * FROM {}".format(self.COLLECTIONS_TABLE_NAME))
return self.cur.fetchall()
def get_collection_by_id(self, collection_id):
"""
Find collection from database. Return the collection info if existed, otherwise None.
@return All data item of the collection: (id, owner_id, price, encrypted_content, preview_path, status)
"""
self.cur.execute(
"SELECT * FROM {} WHERE id = '{}'".format(
self.COLLECTIONS_TABLE_NAME, collection_id
)
)
res = self.cur.fetchall()
if len(res) > 1:
raise AssertionError("Fatal error, more than one collection have same id.")
if len(res) == 0:
return None
return res[0]
def get_collections_by_user_id(self, user_id):
"""
Find all collections belongs to user. Return the collection info list.
@return [(id, owner_id, price, encrypted_content, preview_path, status), ...]
"""
self.cur.execute(
"SELECT * FROM {} WHERE owner_id = '{}'".format(
self.COLLECTIONS_TABLE_NAME, user_id
)
)
res = self.cur.fetchall()
return res
# manage users TABLE`
def add_user(
self,
user_id: str,
validation_file: str = None,
pub_key: str = None,
balance: float = None,
):
self.cur.execute(
"INSERT INTO {} VALUES('{}', '{}', '{}', '{}')".format(
self.USER_TABLE_NAME,
user_id,
validation_file,
pub_key,
balance,
)
)
# self.conn.commit()
'''
def remove_user(self, user_id):
self.cur.execute(
"DELETE FROM '{}' WHERE id = '{}'".format(self.USER_TABLE_NAME, user_id)
)
# self.conn.commit()
'''
def update_user(
self,
user_id: str,
validation_file: bytes = None,
pub_key: str = None,
balance: float = None,
):
if balance is not None:
balance = round(balance, 2)
"""Update any field of the collection table in database."""
for field_name, field_value in zip(
[
f"{validation_file=}".split("=")[0],
f"{pub_key=}".split("=")[0],
f"{balance=}".split("=")[0],
],
[validation_file, pub_key, balance],
):
if field_value:
self.cur.execute(
"UPDATE {} SET {} = '{}' WHERE ID = '{}';".format(
self.USER_TABLE_NAME,
field_name,
field_value,
user_id,
)
)
# self.conn.commit()
def get_all_users(self):
self.cur.execute("SELECT * FROM {}".format(self.USER_TABLE_NAME))
return self.cur.fetchall()
def get_user_by_id(self, user_id) -> [typing.List, None]:
"""
Find user from database. Return the user info if existed, otherwise None.
@return All data item of the user: (id, validation_file, pub_key, balance)
"""
self.cur.execute(
"SELECT * FROM {} WHERE ID = '{}'".format(self.USER_TABLE_NAME, user_id)
)
res = self.cur.fetchall()
if len(res) > 1:
raise AssertionError("Fatal error, more than one user have same id.")
if len(res) == 0:
return None
return res[0]
# manage transactions TABLE
def get_transaction_by_id(self, transaction_id) -> [typing.List, None]:
"""
Find transaction from database. Return the user info if existed, otherwise None.
@return All data item of the transaction
"""
self.cur.execute(
"SELECT * FROM {} WHERE ID = '{}'".format(self.TRANSACTIONS_TABLE_NAME, transaction_id)
)
res = self.cur.fetchall()
if len(res) > 1:
raise AssertionError("Fatal error, more than one transaction have same id.")
if len(res) == 0:
return None
return res[0]
def add_transaction(
self,
id: str,
timestamp: float,
type: str,
content: str,
collection_id: str,
src_user_id: str,
dest_user_id: str,
status: str,
amount: float,
):
self.cur.execute(
"INSERT INTO {} (ID, TIMESTAMP, TYPE, CONTENT, COLLECTION_ID, SRC_USER_ID, DEST_USER_ID, STATUS, AMOUNT) "
"VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(
self.TRANSACTIONS_TABLE_NAME,
id,
timestamp,
type,
content.replace("'", ""),
collection_id,
src_user_id,
dest_user_id,
status,
amount,
)
)
# self.conn.commit()
def update_transaction_status(self, id: int, status: str):
self.cur.execute("UPDATE {} SET STATUS = '{}' WHERE ID = '{}';"
.format(self.TRANSACTIONS_TABLE_NAME, status, id))
# self.conn.commit()
pass
def get_all_transactions(self):
self.cur.execute("SELECT * FROM {}".format(self.TRANSACTIONS_TABLE_NAME))
return self.cur.fetchall()
def get_transactions_by_user_id(self, user_id):
"""
Find all transactions related to user (either src_user_id or dest_user_id). Return the transactions' info list.
@return [(id, owner_id, price, encrypted_content, preview_path, status), ...]
"""
self.cur.execute(
"SELECT * FROM {} WHERE dest_user_id = '{}'".format(self.TRANSACTIONS_TABLE_NAME, user_id)
)
res = self.cur.fetchall()
return res
# general function
def destroy(self):
self.cur.close()
# self.conn.close()
print("Db connection closed.")
class User:
"""
If we want to User class, must first call User.connect_db() first.
Note:
1. Constructors and public methods should check User.db == None first,
since connect to db first is the **Code of Conduct**.
2. When use db, always call User.db (cls.db is also acceptable but to
unify we don't use), and check User.db==None at the beginning.
"""
DEFAULT_BALANCE = 3 # user default balance
SYSTEM_USER_ID = "System"
db = None
def __init__(
self,
id: str,
validation_file: bytes,
pub_key: str,
balance: float,
collections: list,
transactions: list,
):
"""
id: username, must be unique, thus can be view as ID
pub_key: user's RSA public key
validation_file: json serialized file (contains user_id & AES key)
after being encrypted with user's RSA private key
balance: user's balance of XAV coin
collections: user's all collections
transactions: user's all transactions
"""
if User.db is None:
raise RuntimeError(
"Please connect User class to DBmanager by calling User.connect_db() first."
)
self.id = id
self.pub_key = pub_key
self.validation_file = validation_file
self.balance = balance
self.collections = collections
self.transactions = transactions
@classmethod
def fromID(cls, id):
"""
Load a user by fetching the info from database using user id.
@AttributeError raise exception if user id doesn't exist.
"""
if User.db is None:
raise RuntimeError(
"Please connect User class to DBmanager by calling connect_db() first."
)
if not User.if_id_exist(id):
raise AttributeError("User doesn't exist with id={}.".format(id))
_, validation_file, pub_key, balance = User.db.get_user_by_id(id)
collections = cls._get_collections(id)
transactions = cls._get_transactions(id)
return cls(id, validation_file, pub_key, balance, collections, transactions)
@classmethod
def new(cls, id):
"""
Create a new user with an id.
@AttributeError raise exception if id already exist.
@return user instance and the RSA private key of user.
"""
if User.db is None:
raise RuntimeError(
"Please connect User class to DBmanager by calling connect_db() first."
)
if cls.if_id_exist(id):
raise AttributeError("User id already exists with id={}.".format(id))
priv_key, pub_key, aes_key = cls._gen_keys()
validation_file = cls._gen_validation_file(id, pub_key, aes_key)
balance = float(cls.DEFAULT_BALANCE)
user = cls(id, validation_file, pub_key, balance, [], [])
user._add_to_db()
return user, priv_key
@classmethod
def connect_db(cls, db: DBmanager) -> None:
"""Connect DBmanager to User class. Won't instantiate."""
if User.db is not None:
print("Connect failed: User class already has a DBmanager.")
else:
User.db = db
@staticmethod
def if_id_exist(user_id):
"""
Return whether or not the user's id already exists in database.
@RuntimeError raise exception if haven't connect a DBmanager instance to User class.
TODO: put the detailed logic into a method in DBmanager, and call the method here.
"""
if User.db is None:
raise RuntimeError(
"Please connect User class to DBmanager by calling connect_db() first."
)
User.db.cur.execute(
"SELECT * FROM {} WHERE id = '{}'".format(
User.db.USER_TABLE_NAME, user_id
)
)
return len(User.db.cur.fetchall()) > 0
@staticmethod
def _gen_keys() -> typing.Tuple[str, str, str]:
"""
Generate:
1. a pair of keys using EEC algorithm (P-256 curve)
2. a key using AES algorithm (CTR mode, 32-bytes random VI)
All keys are in bytes form, but is decoded using utf-8 system to strings.
The AES key (bytes) is also encoded using base64 since the bytes don't follow utf-8 system.
"""
priv_key_bytes, pub_key_bytes = User._get_rsa_keys()
priv_key, pub_key = (
priv_key_bytes.decode("utf-8"),
pub_key_bytes.decode("utf-8"),
)
aes_key_bytes = User.get_aes_key()
aes_key = base64.b64encode(aes_key_bytes).decode("utf-8")
return priv_key, pub_key, aes_key
def _gen_validation_file(id, pub_key: str, aes_key: str) -> str:
data = json.dumps({"user_id": id, "aes_key": aes_key}) # str
encrypted_data_bytes = User._rsa_encrypt(
data.encode("utf-8"), pub_key.encode("utf-8")
) # bytes -> bytes
encrypted_data = base64.b64encode(encrypted_data_bytes).decode(
"utf-8"
) # bytes -> str
return encrypted_data
def decrypt_validation_file(self, priv_key: str) -> typing.Tuple[str, str]:
"""
Decrypt the validation file and return the file content.
@return `user_id` contained in the validation file and `aes_key` of user's (base64 encoded string)
"""
encrypted_data_bytes = base64.b64decode(
self.validation_file.encode("utf-8")
) # str -> bytes
decrypted_data_bytes = User._rsa_decrypt(
encrypted_data_bytes, priv_key.encode("utf-8")
) # bytes -> bytes
decrypted_data = decrypted_data_bytes.decode("utf-8") # bytes -> str
data = json.loads(decrypted_data)
user_id, aes_key = data["user_id"], data["aes_key"]
return user_id, aes_key
def encrypt_temp_collection(self, raw_data: bytes) -> bytes:
"""Encrypt the temporarily decrypted collection's raw data using user's RSA public key."""
return User._rsa_encrypt(raw_data, self.pub_key.encode("utf-8"))
@staticmethod
def decrypt_temp_collection(rsa_encrypted_data: bytes, priv_key: str) -> bytes:
"""Decrypt the temporarily encrypted collection's data using user's RSA private key."""
return User._rsa_decrypt(rsa_encrypted_data, priv_key.encode("utf-8"))
def update_db(
self,
validation_file: bytes = None,
pub_key: str = None,
balance: float = None,
):
User.db.update_user(self.id, validation_file, pub_key, balance)
def _add_to_db(self):
"""
- id: user name, must be unique, thus can be view as ID
- pub_key: user's RSA public key
- validation_file: json serialized file (2 fields: user_id & AES key) being encrypted using user's RSA private key
- balance: user's balance of XAV coin
- transactions: user's all transactions
"""
if User.db is None:
raise RuntimeError(
"Please connect User class to DBmanager by calling User.connect_db() first."
)
User.db.add_user(
self.id,
self.validation_file,
self.pub_key,
round(self.balance, 2),
)
@staticmethod
def _get_collections(id):
# retrieve user's collections from database
if User.db is None:
raise RuntimeError(
"Please connect User class to DBmanager by calling User.connect_db() first."
)
return User.db.get_collections_by_user_id(id)
@staticmethod
def _get_transactions(id):
# retrieve user's transactions from database
if User.db is None:
raise RuntimeError(
"Please connect User class to DBmanager by calling User.connect_db() first."
)
tuple_transactions = User.db.get_transactions_by_user_id(id)
transactions = []
for tuple_transaction in tuple_transactions:
transactions.append(Transaction(tuple_transaction[0], tuple_transaction[1], tuple_transaction[2],
tuple_transaction[3], tuple_transaction[4], tuple_transaction[5],
tuple_transaction[6], tuple_transaction[7], tuple_transaction[8]))
return transactions
@staticmethod
def _get_rsa_keys() -> typing.Tuple[bytes, bytes]:
"""Get a pair of RSA keys in bytes format. Using the safest 2048 length of random bits to generate keys."""
random_generator = Random.new().read
rsa = RSA.generate(2048, random_generator)
return rsa.exportKey(), rsa.publickey().exportKey()
@staticmethod
def get_aes_key() -> bytes:
"""Get an AES key in bytes format. Using the safest 32-bytes (256-bits) length."""
return get_random_bytes(32)
@staticmethod
def _rsa_encrypt(data: bytes, pub_key: bytes) -> bytes:
"""Encrypt with RSA public key. All operation are in bytes format."""
pub_key = RSA.import_key(pub_key)
cipher_rsa = PKCS1_OAEP.new(pub_key)
encrypted_data_bytes_ls = []
for i in range(0, len(data), 200):
encrypted_data_bytes_ls.append(cipher_rsa.encrypt(data[i:i + 200]))
return b"".join(encrypted_data_bytes_ls)
@staticmethod
def _rsa_decrypt(data: bytes, priv_key: bytes) -> bytes:
"""
Decrypt with RSA private key. In a multi-thread way. Improving the decryption duration from 5+ mins to 90s for a
10 MB data. But it is dangerous for a large users' website with a not enough powerful server. Here is to speed
up the procedure for demonstration.
"""
priv_key = RSA.import_key(priv_key)
cipher_rsa = PKCS1_OAEP.new(priv_key)
decrypted_data_bytes_ls = []
task_queue = queue.Queue(int(len(data) / 256) + 1)
for i in range(0, len(data), 256):
decrypted_data_bytes_ls.append(b'')
task_queue.put((data[i:i + 256], cipher_rsa, decrypted_data_bytes_ls, int(i / 256)))
lock = threading.Lock()
thread_ls = []
for i in range(10):
thread_ls.append(User.DecryptThread(str(i), task_queue, lock))
thread_ls[-1].start()
time.sleep(0.2)
for i in range(10):
if thread_ls[i].hasException:
raise Exception("Repeated request.")
thread_ls[i].join()
return b"".join(decrypted_data_bytes_ls)
@staticmethod
def _rsa_decrypt_subtask(data_slice: bytes, cipher: PKCS1OAEP_Cipher, bytes_ls: list, idx: int):
bytes_ls[idx] = cipher.decrypt(data_slice)
# Thread for decrypt the rsa encrypted content
class DecryptThread(threading.Thread):
def __init__(self, name: str, task_queue: queue.Queue, lock: threading.Lock):
threading.Thread.__init__(self, name=name)
self.task_queue = task_queue
self.lock = lock
self.hasException = False
def run(self) -> None:
while True:
self.lock.acquire()
if self.task_queue.empty():
self.lock.release()
break
task = self.task_queue.get()
self.lock.release()
try:
User._rsa_decrypt_subtask(task[0], task[1], task[2], task[3])
except:
self.hasException = True
break
def add_transaction(self, transaction):
self.transactions.append(transaction)
def __repr__(self):
return """
User:\n\tid={}\n\tpub_key={}\n\tvalidation_file={}\n\tbalance={}\n\tcollections={
}\n\ttransactions={}
""".format(
self.id,
self.pub_key,
self.validation_file,
self.balance,
self.collections,
self.transactions,
)
class Collection:
"""
If we want to Collection class, must first call Collection.connect_db() first.
Note:
1. Constructors and public methods should check Collection.db == None first,
since connect to db first is the **Code of Conduct**.
2. When use db, always call Collection.db (cls.db is also acceptable but to
unify we don't use), and check Collection.db==None at the beginning.
"""
_DEFAULT_PRICE = 0.1 # default price of a collection
STATUS_CONFIRMED = "confirmed" # default status
STATUS_PENDING = "pending" # collection on processing, will be confirmed once seller accept and buyer be online
# after seller accepted
db = None # database
def __init__(
self,
id: str,
owner_id: str,
price: float,
encrypted_content: str,
preview_path: str,
status: str,
):
"""
@params
- id: collection unique name
- owner_id: id of collection's owner
- price: price of the collection, auto increase by 1 after each transaction
- encrypted_content: raw data of the collection after encrypted with owner's AES key (in json serialized format)
- preview_path: low resolution version of the image
- status: pending if in the middle of a transaction, otherwise confirmed
"""
if Collection.db is None:
raise RuntimeError(
"Please connect Collection class to DBmanager by calling Collection.connect_db() first."
)
self.id = id
self.owner_id = owner_id
self.price = price
self.encrypted_content = encrypted_content
self.preview_path = preview_path
self.status = status
@classmethod
def fromID(cls, id):
"""Load a collection by fetching data from database using collection id."""
if Collection.db is None:
raise RuntimeError(
"Please connect Collection class to DBmanager by calling Collection.connect_db() first."
)
if not cls.if_id_exist(id):
raise AttributeError("Collection doesn't exist with id={}.".format(id))
(
_,
owner_id,
price,
encrypted_content,
preview_path,
status,
) = cls.db.get_collection_by_id(id)
return cls(id, owner_id, price, encrypted_content, preview_path, status)
@classmethod
def new(cls, id, owner_id, price, image: Image, aes_key: str):
"""Create a new collection and add to database."""
if Collection.db is None:
raise RuntimeError(
"Please connect Collection class to DBmanager by calling Collection.connect_db() first."
)
if cls.if_id_exist(id):
raise AttributeError("Collection id already exists, please use another id.")
# price = cls._DEFAULT_PRICE
aes_bytes = base64.b64decode(aes_key.encode("utf-8"))
# Check the file type of the image
suffix = id.split('.')[-1]
img_format = "PNG"
if suffix == "png" or suffix == "PNG":
if not image.mode == "RGBA":
image = image.convert("RGBA")
if suffix == "jpg" or suffix == "JPG":
img_format = "JPEG"
if not image.mode == "RGB":
image = image.convert("RGB")
# Covert the image to bytes for en/decrypt and store
img_bytes = io.BytesIO()
image.save(img_bytes, format=img_format)
img_bytes.seek(0)
# encrypt the data and save the preview
encrypted_content = cls.encrypt_content(img_bytes.read(), aes_bytes)
out_path = os.path.join(Controller.preview_store_path, id)
cls._gen_save_preview(image, out_path)
# Add new collection
status = cls.STATUS_CONFIRMED
collection = cls(id, owner_id, price, encrypted_content, out_path, status)
collection._add_to_db()
return collection
@classmethod
def connect_db(cls, db: DBmanager) -> None:
"""Connect DBmanager to Collection class."""
if Collection.db is not None:
print("Connect failed: Collection class already has a DBmanager.")
else:
cls.db = db
@staticmethod
def if_id_exist(collection_id):
"""Return whether the collection's id already exists in database or not."""
if Collection.db is None:
raise RuntimeError(
"Please connect Collection class to DBmanager by calling Collection.connect_db() first."
)
Collection.db.cur.execute(
"SELECT * FROM {} WHERE id = '{}'".format(
Collection.db.COLLECTIONS_TABLE_NAME, collection_id
)
)
return len(Collection.db.cur.fetchall()) > 0
def _add_to_db(self):
"""
Add this user to database.
- id: collection unique name
- price: price of the collection, auto increase by 1 after each transaction
- owner_id: id of collection's owner
- encrypted_content: raw data of the collection after encrypted with owner's AES key
- preview_path: low resolution version of the image
- status: pending if in the middle of a transaction, otherwise confirmed
"""
if Collection.db is None:
raise RuntimeError(
"Please connect Collection class to DBmanager by calling Collection.connect_db() first."
)
Collection.db.add_collection(
self.id,
self.price,
self.owner_id,
self.encrypted_content,
self.preview_path,
self.status,
)
@staticmethod
def encrypt_content(data: bytes, aes_key: bytes) -> str:
"""
Encrypt content using AES (CTR mode, allow arbitrary length of data).
@param data: raw data of image in bytes
@param aes_key: the aes key of the user
@return **serialized json string** (e.g., {"nonce": '4Sa\we', "ciphertext": 'wgS2F=D3'})
"""
cipher = AES.new(aes_key, AES.MODE_CTR)
ct_bytes = cipher.encrypt(data)
nonce = base64.b64encode(cipher.nonce).decode("utf-8")
ct = base64.b64encode(ct_bytes).decode("utf-8")
result = json.dumps({"nonce": nonce, "ciphertext": ct})
# print("Encrypt result:", result)
return result
def decrypt_content(self, aes_key: str) -> typing.Union[bytes, None]:
"""
Decrypt content using AES (CTR mode, allow arbitrary length of data).
@param self: json serialized string (e.g., {"nonce": '4Sa\we', "ciphertext": 'wgS2F=D3'})
@return decrypted bytes data if successfully decrypt, otherwise None.
"""
aes_key_bytes = base64.b64decode(aes_key.encode("utf-8"))
try:
b64 = json.loads(self.encrypted_content)
nonce = base64.b64decode(b64["nonce"])
ct = base64.b64decode(b64["ciphertext"])
cipher = AES.new(aes_key_bytes, AES.MODE_CTR, nonce=nonce)
pt = cipher.decrypt(ct)
# print("Decrypt result:", pt)
return pt
except Exception as e:
traceback.print_exc()
return None
def get_raw_data(self, owner: typing.Union[str, User], priv_key: str) -> bytes:
"""
<high level API> Decrypt the collection and return raw data.
@param owner: collection owner id or an owner's User instance. Pass a User instance will make it
faster, otherwise need to search database using user id to get the user.
@param priv_key: collection owner's private key.
@return [bytes]: raw
data of the collection.
"""
if isinstance(owner, str):
owner = Collection.db.get_user_by_id(owner)
_, aes_key = owner.decrypt_validation_file(priv_key)
return self.decrypt_content(aes_key)
@staticmethod
def _gen_save_preview(raw_data, path):
"""Generate low resolution thumbnail and return its data in bytes."""
PREVIEW_SIZE = (210, 294) # default collection thumbnail size (width, height)
img = raw_data # Image.open(io.BytesIO(image))
img.thumbnail((int(img.width * 0.5), int(img.height * 0.5)))
img.save(path)
# img_byte_buffer = io.BytesIO()
# img.save(img_byte_buffer, format=img.format)
# return img_byte_buffer.getvalue()
def update_db(
self,
owner_id=None,
price=None,
encrypted_content=None,
preview_path=None,
status=None,
):
self.db.update_collection(
collection_id=self.id,
owner_id=owner_id,
price=price,
encrypted_content=encrypted_content,
preview_path=preview_path,
status=status,
)
def release_pending_status(self, mew_encrypted_content):
self.encrypted_content = mew_encrypted_content
self.status = Collection.STATUS_CONFIRMED
self.update_db(encrypted_content=mew_encrypted_content, status=Collection.STATUS_CONFIRMED)
def update_owner(self, old_owner: User, new_owner: User, priv_key: str):
"""
Change the collection's owner.
Procedure:\n 1. change collection's owner_id 2. decrypt collection's encrypted_content and get raw data 3.
check whether new owner is online: - if online: 1. encrypt collection's raw data using new owner's AES key -
if not online: 1. encrypted collection's raw data using new owner's RSA public key 2. set the status of the
collection as PENDING (when user online again, all collections will be checked. if anyone is in PENDING,
AES unlock it and RSA lock it using private key.) 4. store the new collection's encrypted_content into
database and update corresponding instances
"""
# 1. change collection's owner_id
self.owner_id = new_owner.id
self.update_db(owner_id=new_owner.id)
# 2. decrypt collection's encrypted_content and get raw data
_, aes_key = old_owner.decrypt_validation_file(priv_key)
raw_data = self.decrypt_content(aes_key)
# 3. check whether new owner is online
# if new_owner.is_online():
# # 1) encrypt collection's raw data using new owner's AES key
# aes_key = new_owner.get_aes_key()
# encrypted_content = self.encrypt_content(image, aes_key)
# else:
# 1) encrypt collection's raw data using new owner's RSA public key
encrypted_content = new_owner.encrypt_temp_collection(raw_data)
encrypted_content = base64.b64encode(encrypted_content).decode("utf-8")
# 2) set the status of the collection as PENDING (when user online again,
# all collections will be checked. if anyone is in PENDING, AES unlock
# it and RSA lock it using private key.)
self.status = Collection.STATUS_PENDING
self.encrypted_content = encrypted_content
# 4. store the new collection's encrypted_content into database
self.update_db(encrypted_content=encrypted_content, status=Collection.STATUS_PENDING)
class Transaction:
"""
If we want to Transaction class, must first call Transaction.connect_db() first.
Note:
1. Constructors and public methods should check Transaction.db == None first,
since connect to db first is the **Code of Conduct**.
2. When use db, always call Transaction.db (cls.db is also acceptable but to
unify we don't use), and check Transaction.db==None at the beginning.
"""
db = None
TYPE_REQUEST = (
"request" # the transaction is a request to a user send by another user
)
TYPE_NOTICE = "notice" # the transaction is a notice to a user lead by the behavior of another user
STATUS_PENDING = (
"pending" # the transaction (request) is waiting to be accepted/rejected
)
STATUS_ACCEPTED = (
"accepted" # the transaction (request) which was in pending status is accepted
)
STATUS_REJECTED = (
"rejected" # the transaction (request) which was in pending status is rejected
)
STATUS_CLOSED = (
"closed" # the transaction (request) which was in accepted/rejected status is closed
)
STATUS_UNSEEN = (
"unseen" # the transaction (notice) is sent but unseen by the receiver
)
STATUS_SEEN = "seen" # the transaction (notice) is sent and seen by the receiver
def __init__(
self,
id,
timestamp,
type,
content,
collection_id,
src_user_id,
dest_user_id,
status,
amount,
):
"""Internal use only! Please use Transaction.new()."""
if Transaction.db is None:
raise RuntimeError(