-
Notifications
You must be signed in to change notification settings - Fork 53
/
blockcoin.py
351 lines (272 loc) · 9.89 KB
/
blockcoin.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
"""
BlockCoin
Usage:
blockcoin.py serve
blockcoin.py ping [--node <node>]
blockcoin.py tx <from> <to> <amount> [--node <node>]
blockcoin.py balance <name> [--node <node>]
Options:
-h --help Show this screen.
--node=<node> Hostname of node [default: node0]
"""
import uuid, socketserver, socket, sys, argparse, time, os, logging, threading, pickle
from docopt import docopt
from copy import deepcopy
from ecdsa import SigningKey, SECP256k1
from utils import serialize, deserialize
from identities import user_private_key, user_public_key, bank_private_key, bank_public_key, airdrop_tx
NUM_BANKS = 3
BLOCK_TIME = 5 # in seconds
PORT = 10000
bank = None
logging.basicConfig(
level="INFO",
format='%(asctime)-15s %(levelname)s %(message)s',
)
logger = logging.getLogger(__name__)
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 Block:
def __init__(self, txns, timestamp=None, signature=None):
if timestamp == None:
timestamp = time.time()
self.timestamp = timestamp
self.signature = signature
self.txns = txns
@property
def message(self):
return serialize([self.timestamp, self.txns])
def sign(self, private_key):
self.signature = private_key.sign(self.message)
class Bank:
def __init__(self, id, private_key):
self.id = id
self.blocks = []
self.utxo_set = {}
self.mempool = []
self.private_key = private_key
self.peer_addresses = {(p, PORT) for p in os.environ.get('PEERS', '').split(',') if p}
@property
def next_id(self):
return len(self.blocks) % NUM_BANKS
@property
def our_turn(self):
return self.id == self.next_id
@property
def mempool_outpoints(self):
return [tx_in.outpoint for tx in self.mempool for tx_in in tx.tx_ins]
def fetch_utxos(self, public_key):
return [tx_out for tx_out in self.utxo_set.values()
if tx_out.public_key == public_key]
def update_utxo_set(self, tx):
# Remove utxos that were just spent
for tx_in in tx.tx_ins:
del self.utxo_set[tx_in.outpoint]
# Save utxos which were just created
for tx_out in tx.tx_outs:
self.utxo_set[tx_out.outpoint] = tx_out
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 validate_tx(self, tx):
in_sum = 0
out_sum = 0
for index, tx_in in enumerate(tx.tx_ins):
# TxIn spending an unspent output
assert tx_in.outpoint in self.utxo_set
# No pending transactions spending this same output
assert tx_in.outpoint not in self.mempool_outpoints
# 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:
# Sum up the total outpouts
out_sum += tx_out.amount
# Check no value created or destroyed
assert in_sum == out_sum
def handle_tx(self, tx):
self.validate_tx(tx)
self.mempool.append(tx)
def handle_block(self, block):
# Genesis block has no signature
if len(self.blocks) > 0:
public_key = bank_public_key(self.next_id)
public_key.verify(block.signature, block.message)
# Check the transactions are valid
for tx in block.txns:
self.validate_tx(tx)
# If they're all good, update self.blocks and self.utxo_set
for tx in block.txns:
self.update_utxo_set(tx)
# Add the block and increment the id of bank who will report next block
self.blocks.append(block)
# Schedule submisison of next block
self.schedule_next_block()
def make_block(self):
# Reset mempool
txns = deepcopy(self.mempool)
self.mempool = []
block = Block(txns=txns)
block.sign(self.private_key)
return block
def submit_block(self):
# Make the block
block = self.make_block()
# Save locally
self.handle_block(block)
# Tell peers
for address in self.peer_addresses:
send_message(address, "block", block)
def schedule_next_block(self):
if self.our_turn:
threading.Timer(5, self.submit_block, []).start()
def airdrop(self, tx):
assert len(self.blocks) == 0
# Update utxo set
self.update_utxo_set(tx)
# Update blockchain
block = Block(txns=[tx])
self.blocks.append(block)
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(1024*4).strip()
message = deserialize(message_bytes)
command = message["command"]
data = message["data"]
logger.info(f"received {command}")
if command == "ping":
self.respond(command="pong", data="")
if command == "block":
bank.handle_block(data)
if command == "tx":
bank.handle_tx(data)
if command == "balance":
balance = bank.fetch_balance(data)
self.respond(command="balance-response", data=balance)
if command == "utxos":
utxos = bank.fetch_utxos(data)
self.respond(command="utxos-response", data=utxos)
def external_address(node):
i = int(node[-1])
port = PORT + i
return ('localhost', port)
def serve():
server = socketserver.TCPServer(("0.0.0.0", PORT), 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"]:
global bank
bank_id = int(os.environ["BANK_ID"])
bank = Bank(
id=bank_id,
private_key=bank_private_key(bank_id)
)
# Airdrop starting balances
bank.airdrop(airdrop_tx())
# Start producing blocks
bank.schedule_next_block()
serve()
elif args["ping"]:
address = address_from_host(args["--node"])
send_message(address, "ping", "")
elif args["balance"]:
public_key = user_public_key(args["<name>"])
address = external_address(args["--node"])
response = send_message(address, "balance", public_key, response=True)
print(response["data"])
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>"])
address = external_address(args["--node"])
# 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
send_message(address, "tx", tx)
else:
print("Invalid command")
if __name__ == '__main__':
main(docopt(__doc__))