-
Notifications
You must be signed in to change notification settings - Fork 53
/
banknetcoin.py
251 lines (192 loc) · 7.01 KB
/
banknetcoin.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
"""
BanknetCoin
Usage:
banknetcoin.py serve
banknetcoin.py ping
banknetcoin.py tx <from> <to> <amount>
banknetcoin.py balance <name>
Options:
-h --help Show this screen.
"""
import uuid, socketserver, socket, sys, argparse
from docopt import docopt
from copy import deepcopy
from ecdsa import SigningKey, SECP256k1
from utils import serialize, deserialize
from identities import user_public_key, user_private_key
def spend_message(tx, index):
outpoint = tx.tx_ins[index].outpoint
return serialize(outpoint) + serialize(tx.tx_outs)
class Tx:
def __init__(self, id, tx_ins, tx_outs):
self.id = id
self.tx_ins = tx_ins
self.tx_outs = tx_outs
def sign_input(self, index, private_key):
message = spend_message(self, index)
signature = private_key.sign(message)
self.tx_ins[index].signature = signature
def verify_input(self, index, public_key):
tx_in = self.tx_ins[index]
message = spend_message(self, index)
return public_key.verify(tx_in.signature, message)
class TxIn:
def __init__(self, tx_id, index, signature=None):
self.tx_id = tx_id
self.index = index
self.signature = signature
@property
def outpoint(self):
return (self.tx_id, self.index)
class TxOut:
def __init__(self, tx_id, index, amount, public_key):
self.tx_id = tx_id
self.index = index
self.amount = amount
self.public_key = public_key
@property
def outpoint(self):
return (self.tx_id, self.index)
class Bank:
def __init__(self):
self.utxo_set = {}
def update_utxo_set(self, tx):
for tx_out in tx.tx_outs:
self.utxo_set[tx_out.outpoint] = tx_out
for tx_in in tx.tx_ins:
del self.utxo_set[tx_in.outpoint]
def issue(self, amount, public_key):
id_ = str(uuid.uuid4())
tx_ins = []
tx_outs = [TxOut(tx_id=id_, index=0, amount=amount, public_key=public_key)]
tx = Tx(id=id_, tx_ins=tx_ins, tx_outs=tx_outs)
self.update_utxo_set(tx)
return tx
def validate_tx(self, tx):
in_sum = 0
out_sum = 0
for index, tx_in in enumerate(tx.tx_ins):
# TxIn spending unspent output
assert tx_in.outpoint in self.utxo_set
# Grab the tx_out
tx_out = self.utxo_set[tx_in.outpoint]
# Verify signature using public key of TxOut we're spending
public_key = tx_out.public_key
tx.verify_input(index, public_key)
# Sum up the total inputs
amount = tx_out.amount
in_sum += amount
for tx_out in tx.tx_outs:
out_sum += tx_out.amount
assert in_sum == out_sum
def handle_tx(self, tx):
# Save to self.utxo_set if it's valid
self.validate_tx(tx)
self.update_utxo_set(tx)
def fetch_utxos(self, public_key):
return [utxo for utxo in self.utxo_set.values()
if utxo.public_key == public_key]
def fetch_balance(self, public_key):
# Fetch utxos associated with this public key
utxos = self.fetch_utxos(public_key)
# Sum the amounts
return sum([tx_out.amount for tx_out in utxos])
def prepare_simple_tx(utxos, sender_private_key, recipient_public_key, amount):
sender_public_key = sender_private_key.get_verifying_key()
# Construct tx.tx_outs
tx_ins = []
tx_in_sum = 0
for tx_out in utxos:
tx_ins.append(TxIn(tx_id=tx_out.tx_id, index=tx_out.index, signature=None))
tx_in_sum += tx_out.amount
if tx_in_sum > amount:
break
# Make sure sender can afford it
assert tx_in_sum >= amount
# Construct tx.tx_outs
tx_id = uuid.uuid4()
change = tx_in_sum - amount
tx_outs = [
TxOut(tx_id=tx_id, index=0, amount=amount, public_key=recipient_public_key),
TxOut(tx_id=tx_id, index=1, amount=change, public_key=sender_public_key),
]
# Construct tx and sign inputs
tx = Tx(id=tx_id, tx_ins=tx_ins, tx_outs=tx_outs)
for i in range(len(tx.tx_ins)):
tx.sign_input(i, sender_private_key)
return tx
def prepare_message(command, data):
return {
"command": command,
"data": data,
}
class TCPHandler(socketserver.BaseRequestHandler):
def respond(self, command, data):
response = prepare_message(command, data)
return self.request.sendall(serialize(response))
def handle(self):
message_bytes = self.request.recv(5000).strip()
print(message_bytes)
message = deserialize(message_bytes)
command = message["command"]
data = message["data"]
print(command)
if command == "ping":
self.respond(command="pong", data="")
if command == "tx":
try:
bank.handle_tx(data)
self.respond(command="tx-response", data="accepted")
except:
self.respond(command="tx-response", data="rejected")
if command == "utxos":
balance = bank.fetch_utxos(data)
self.respond(command="utxos-response", data=balance)
if command == "balance":
balance = bank.fetch_balance(data)
self.respond(command="balance-response", data=balance)
HOST, PORT = 'localhost', 9006
ADDRESS = (HOST, PORT)
bank = Bank()
def serve():
server = socketserver.TCPServer(ADDRESS, TCPHandler)
server.serve_forever()
def send_message(address, command, data, response=False):
message = prepare_message(command, data)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(address)
s.sendall(serialize(message))
if response:
return deserialize(s.recv(5000))
def main(args):
if args["serve"]:
from identities import alice_public_key
bank.issue(1000, alice_public_key)
serve()
elif args["ping"]:
response = send_message(ADDRESS, "ping", "", response=True)
print(response)
elif args["balance"]:
name = args["<name>"]
public_key = user_public_key(name)
response = send_message(ADDRESS, "balance", public_key, response=True)
print(response)
elif args["tx"]:
# Grab parameters
sender_private_key = user_private_key(args["<from>"])
sender_public_key = sender_private_key.get_verifying_key()
recipient_private_key = user_private_key(args["<to>"])
recipient_public_key = recipient_private_key.get_verifying_key()
amount = int(args["<amount>"])
# Fetch utxos available to spend
response = send_message(ADDRESS, "utxos", sender_public_key, response=True)
utxos = response["data"]
# Prepare transaction
tx = prepare_simple_tx(utxos, sender_private_key, recipient_public_key, amount)
# send to bank
response = send_message(ADDRESS, "tx", tx, response=True)
print(response)
else:
print("Invalid commands")
if __name__ == '__main__':
main(docopt(__doc__))