forked from justinmoon/digital-cash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bankutxocoin.py
97 lines (72 loc) · 2.51 KB
/
bankutxocoin.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
import uuid
from copy import deepcopy
from ecdsa import SigningKey, SECP256k1
from utils import serialize
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):
signature = private_key.sign(self.tx_ins[index].spend_message)
self.tx_ins[index].signature = signature
class TxIn:
def __init__(self, tx_id, index, signature=None):
self.tx_id = tx_id
self.index = index
self.signature = signature
@property
def spend_message(self):
return f"{self.tx_id}:{self.index}".encode()
@property
def outpoint(self):
return (self.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.id, self.index)
class Bank:
def __init__(self):
self.utxo = {}
def update_utxo(self, tx):
for tx_out in tx.tx_outs:
self.utxo[tx_out.outpoint] = tx_out
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(self, tx)
return tx
def validate_tx(self, tx):
in_sum = 0
out_sum = 0
for tx_in in tx.tx_ins:
assert tx_in.outpoint in self.utxo
tx_out = self.utxo[tx_in.outpoint]
# Verify signature using public key of TxOut we're spending
public_key = tx_out.public_key
public_key.verify(tx_in.signature, tx_in.spend_message)
# 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 if it's valid
self.validate_tx(tx)
self.update_utxo(self, tx)
def fetch_utxo(self, public_key):
return [utxo for utxo in self.utxo.values()
if utxo.public_key == public_key]
def fetch_balance(self, public_key):
# Fetch utxo associated with this public key
unspents = self.fetch_utxo(public_key)
# Sum the amounts
return sum([tx_out.amount for tx_out in unspents])