forked from OpenBazaar/OpenBazaar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multisig.py
executable file
·276 lines (231 loc) · 8.95 KB
/
multisig.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
import logging
from twisted.internet import reactor
import obelisk
import urllib2
import re
import random
# import pybitcointools
# Create new private key:
#
# $ sx newkey > key1
#
# Show private secret:
#
# $ cat key1 | sx wif-to-secret
#
# Show compressed public key:
#
# $ cat key1 | sx pubkey
#
# You will need 3 keys for buyer, seller and arbitrer
def build_output_info_list(unspent_rows):
unspent_infos = []
for row in unspent_rows:
assert len(row) == 4
outpoint = obelisk.OutPoint()
outpoint.hash = row[0]
outpoint.index = row[1]
value = row[3]
unspent_infos.append(
obelisk.OutputInfo(outpoint, value))
return unspent_infos
class Multisig:
def __init__(self, client, number_required, pubkeys):
if number_required > len(pubkeys):
raise Exception("number_required > len(pubkeys)")
self.client = client
self.number_required = number_required
self.pubkeys = pubkeys
self._log = logging.getLogger(self.__class__.__name__)
@property
def script(self):
# return pybitcointools.mk_multisig_script(self.pubkeys, 2, 3)
result = chr(80 + self.number_required)
for pubkey in self.pubkeys:
result += chr(33) + pubkey
result += chr(80 + len(self.pubkeys))
# checkmultisig
result += "\xae"
return result
@property
def address(self):
# script = self.script
# print 'multisig-script',script
#
# address = pybitcointools.scriptaddr(script)
# return address
raw_addr = obelisk.hash_160(self.script)
return obelisk.hash_160_to_bc_address(raw_addr, addrtype=0x05)
#
def create_unsigned_transaction(self, destination, finished_cb):
def fetched(ec, history):
if ec is not None:
self._log.error("Error fetching history: %s" % ec)
return
self._fetched(history, destination, finished_cb)
self.client.fetch_history(self.address, fetched)
#
def _fetched(self, history, destination, finished_cb):
unspent = [row[:4] for row in history if row[4] is None]
tx = self._build_actual_tx(unspent, destination)
finished_cb(tx)
#
@staticmethod
def _build_actual_tx(unspent, destination):
# Send all unspent outputs (everything in the address) minus the fee
tx = obelisk.Transaction()
total_amount = 0
for row in unspent:
assert len(row) == 4
outpoint = obelisk.OutPoint()
outpoint.hash = row[0]
outpoint.index = row[1]
value = row[3]
total_amount += value
add_input(tx, outpoint)
# Constrain fee so we don't get negative amount to send
fee = min(total_amount, 10000)
send_amount = total_amount - fee
add_output(tx, destination, send_amount)
return tx
def sign_all_inputs(self, tx, secret):
signatures = []
key = obelisk.EllipticCurveKey()
key.set_secret(secret)
for i, input in enumerate(tx.inputs):
sighash = generate_signature_hash(tx, i, self.script)
# Add sighash::all to end of signature.
signature = key.sign(sighash) + "\x01"
signatures.append(signature.encode('hex'))
return signatures
@staticmethod
def make_request(*args):
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0' + str(random.randrange(1000000)))]
try:
return opener.open(*args).read().strip()
except Exception as e:
try:
p = e.read().strip()
except:
p = e
raise Exception(p)
@staticmethod
def eligius_pushtx(tx):
print 'FINAL TRANSACTION: %s' % tx
s = Multisig.make_request('http://eligius.st/~wizkid057/newstats/pushtxn.php', 'transaction=' + tx + '&send=Push')
strings = re.findall('string[^"]*"[^"]*"', s)
for string in strings:
quote = re.findall('"[^"]*"', string)[0]
if len(quote) >= 5:
return quote[1:-1]
@staticmethod
def broadcast(tx):
raw_tx = tx.serialize().encode("hex")
Multisig.eligius_pushtx(raw_tx)
# gateway_broadcast(raw_tx)
# bci_pushtx(raw_tx)
def add_input(tx, prevout):
input = obelisk.TxIn()
input.previous_output.hash = prevout.hash
input.previous_output.index = prevout.index
tx.inputs.append(input)
def add_output(tx, address, value):
output = obelisk.TxOut()
output.value = value
output.script = obelisk.output_script(address)
tx.outputs.append(output)
def generate_signature_hash(parent_tx, input_index, script_code):
tx = obelisk.copy_tx(parent_tx)
if input_index >= len(tx.inputs):
return None
for input in tx.inputs:
input.script = ""
tx.inputs[input_index].script = script_code
raw_tx = tx.serialize() + "\x01\x00\x00\x00"
return obelisk.Hash(raw_tx)
class Escrow:
def __init__(self, client, buyer_pubkey, seller_pubkey, arbit_pubkey):
pubkeys = (buyer_pubkey, seller_pubkey, arbit_pubkey)
self.multisig = Multisig(client, 2, pubkeys)
# 1. BUYER: Deposit funds for seller
@property
def deposit_address(self):
return self.multisig.address
# 2. BUYER: Send unsigned tx to seller
def initiate(self, destination_address, finished_cb):
self.multisig.create_unsigned_transaction(
destination_address, finished_cb)
# ...
# 3. BUYER: Release funds by sending signature to seller
def release_funds(self, tx, secret):
return self.multisig.sign_all_inputs(tx, secret)
# 4. SELLER: Claim your funds by generating a signature.
def claim_funds(self, tx, secret, buyer_sigs):
seller_sigs = self.multisig.sign_all_inputs(tx, secret)
return Escrow.complete(tx, buyer_sigs, seller_sigs,
self.multisig.script)
@staticmethod
def complete(tx, buyer_sigs, seller_sigs, script_code):
for i, input in enumerate(tx.inputs):
sigs = (buyer_sigs[i], seller_sigs[i])
script = "\x00"
for sig in sigs:
script += chr(len(sig)) + sig
script += "\x4c"
assert len(script_code) < 255
script += chr(len(script_code)) + script_code
tx.inputs[i].script = script
return tx
def main():
##########################################################
# ESCROW TEST
##########################################################
pubkeys = [
"035b175132eeb8aa6e8455b6f1c1e4b2784bea1add47a6ded7fc9fc6b7aff16700".decode("hex"),
"0351e400c871e08f96246458dae79a55a59730535b13d6e1d4858035dcfc5f16e2".decode("hex"),
"02d53a92e3d43db101db55e351e9b42b4f711d11f6a31efbd4597695330d75d250".decode("hex")
]
client = obelisk.ObeliskOfLightClient("tcp://85.25.198.97:8081")
escrow = Escrow(client, pubkeys[0], pubkeys[1], pubkeys[2])
def finished(tx):
buyer_sigs = escrow.release_funds(tx,
"b28c7003a7b6541cd1cd881928863abac0eff85f5afb40ff5561989c9fb95fb2".decode(
"hex"))
completed_tx = escrow.claim_funds(tx,
"5b05667dac199c48051932f14736e6f770e7a5917d2994a15a1508daa43bc9b0".decode(
"hex"),
buyer_sigs)
print 'COMPLETED TX: ', completed_tx.serialize().encode("hex")
# TODO: Send to the bitcoin network
escrow.initiate("1Fufjpf9RM2aQsGedhSpbSCGRHrmLMJ7yY", finished)
##########################################################
# MULTISIGNATURE TEST
##########################################################
msig = Multisig(client, 2, pubkeys)
print "Multisig address: ", msig.address
def finished(tx):
print tx
print ''
print tx.serialize().encode("hex")
print ''
sigs1 = msig.sign_all_inputs(tx,
"b28c7003a7b6541cd1cd881928863abac0eff85f5afb40ff5561989c9fb95fb2".decode("hex"))
sigs3 = msig.sign_all_inputs(tx,
"b74dbef0909c96d5c2d6971b37c8c71d300e41cad60aeddd6b900bba61c49e70".decode("hex"))
for i, input in enumerate(tx.inputs):
sigs = (sigs1[i], sigs3[i])
script = "\x00"
for sig in sigs:
script += chr(len(sig)) + sig
script += "\x4c"
assert len(msig.script) < 255
script += chr(len(msig.script)) + msig.script
print "Script:", script.encode("hex")
tx.inputs[i].script = script
print tx
print tx.serialize().encode("hex")
msig.create_unsigned_transaction("1Fufjpf9RM2aQsGedhSpbSCGRHrmLMJ7yY", finished)
reactor.run()
if __name__ == "__main__":
main()