-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwallet.py
More file actions
78 lines (67 loc) · 2.89 KB
/
wallet.py
File metadata and controls
78 lines (67 loc) · 2.89 KB
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
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
import Crypto.Random
import binascii
import ast
class Wallet:
def __init__(self, node_id):
private_key, public_key = self.generate_keys()
self.private_key = None
self.public_key = None
self.node_id = node_id
def create_keys(self):
private_key, public_key = self.generate_keys()
self.private_key = private_key
self.public_key = public_key
def save_keys(self):
if self.public_key != None and self.private_key != None:
data = {'public': self.public_key, 'private': self.private_key}
print(str(data))
try:
with open("wallet-{}.txt".format(self.node_id), "a") as f:
f.write(str(data) + "\n")
# f.write("\n")
# f.write(self.private_key)
return True
except(IOError, IndexError):
print("Saving wallet failed...")
return False
def load_keys(self):
try:
with open("wallet-{}.txt".format(self.node_id), "r") as f:
lines = f.read().splitlines()
key = lines[-1]
keys = ast.literal_eval(key)
public_key = keys['public']
private_key = keys['private']
self.public_key = public_key
self.private_key = private_key
return True
except(IOError, IndexError):
print("Loading wallet failed...")
return False
def show_keys(self):
try:
with open("wallet-{}.txt".format(self.node_id), "r") as f:
lines = f.read().splitlines()
# keys =ast.literal_eval(lines)
return lines
except(IOError, IndexError):
print("Loading wallet failed...")
return False
def generate_keys(self):
private_key = RSA.generate(1024, Crypto.Random.new().read)
public_key = private_key.publickey()
return (binascii.hexlify(private_key.exportKey(format='DER')).decode('ascii'), binascii.hexlify(public_key.exportKey(format='DER')).decode('ascii'))
def sign_transaction(self, sender, recipient, amount):
signer = PKCS1_v1_5.new(RSA.importKey(binascii.unhexlify(self.private_key)))
h = SHA256.new((str(sender) + str(recipient) + str(amount)).encode('utf8'))
signature = signer.sign(h)
return binascii.hexlify(signature).decode('ascii')
@staticmethod
def verify_transaction(transaction):
public_key = RSA.importKey(binascii.unhexlify(transaction.sender))
verifier = PKCS1_v1_5.new(public_key)
h = SHA256.new((str(transaction.sender) + str(transaction.recipient) + str(transaction.amount)).encode('utf8'))
return verifier.verify(h, binascii.unhexlify(transaction.signature))