forked from stx-labs/stacks.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
878 lines (638 loc) · 22.2 KB
/
proxy.py
File metadata and controls
878 lines (638 loc) · 22.2 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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Blockstack-client
~~~~~
copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
copyright: (c) 2016 by Blockstack.org
This file is part of Blockstack-client.
Blockstack-client is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Blockstack-client is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Blockstack-client. If not, see <http://www.gnu.org/licenses/>.
"""
import argparse
import sys
import json
import traceback
import types
import socket
import uuid
import os
import importlib
import pprint
import random
import time
import copy
import blockstack_profiles
import zone_file
import urllib
from xmlrpclib import ServerProxy, Transport
from defusedxml import xmlrpc
import httplib
# prevent the usual XML attacks
xmlrpc.monkey_patch()
import user as user_db
import storage
import pybitcoin
import bitcoin
import binascii
from utilitybelt import is_hex
import config
from config import get_logger, DEBUG, MAX_RPC_LEN, find_missing, BLOCKSTACKD_SERVER, \
BLOCKSTACKD_PORT, BLOCKSTACK_METADATA_DIR, BLOCKSTACK_DEFAULT_STORAGE_DRIVERS, \
FIRST_BLOCK_MAINNET, NAME_OPCODES, OPFIELDS, CONFIG_DIR, SPV_HEADERS_PATH, BLOCKCHAIN_ID_MAGIC, \
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_TRANSFER, NAMESPACE_PREORDER, NAME_IMPORT, \
USER_ZONEFILE_TTL, CONFIG_PATH
log = get_logger()
# borrowed with gratitude from Justin Cappos
# https://seattle.poly.edu/browser/seattle/trunk/demokit/timeout_xmlrpclib.py?rev=692
class TimeoutHTTPConnection(httplib.HTTPConnection):
def connect(self):
httplib.HTTPConnection.connect(self)
self.sock.settimeout(self.timeout)
class TimeoutHTTP(httplib.HTTP):
_connection_class = TimeoutHTTPConnection
def set_timeout(self, timeout):
self._conn.timeout = timeout
def getresponse(self, **kw):
return self._conn.getresponse(**kw)
class TimeoutTransport(Transport):
def __init__(self, *l, **kw):
self.timeout = kw.get('timeout', 10)
if 'timeout' in kw.keys():
del kw['timeout']
Transport.__init__(self, *l, **kw)
def make_connection(self, host):
conn = TimeoutHTTP(host)
conn.set_timeout(self.timeout)
return conn
class TimeoutServerProxy(ServerProxy):
def __init__(self, uri, *l, **kw):
kw['transport'] = TimeoutTransport(timeout=kw.get('timeout',10), use_datetime=kw.get('use_datetime', 0))
if 'timeout' in kw.keys():
del kw['timeout']
ServerProxy.__init__(self, uri, *l, **kw)
# default API endpoint proxy to blockstackd
default_proxy = None
class BlockstackRPCClient(object):
"""
RPC client for the blockstack server
"""
def __init__(self, server, port, max_rpc_len=MAX_RPC_LEN, timeout=config.DEFAULT_TIMEOUT ):
self.srv = TimeoutServerProxy( "http://%s:%s" % (server, port), timeout=timeout, allow_none=True )
self.server = server
self.port = port
def __getattr__(self, key):
try:
return object.__getattr__(self, key)
except AttributeError:
log.debug("RPC http://%s:%s %s" % (self.server, self.port, key))
def inner(*args, **kw):
func = getattr(self.srv, key)
res = func(*args, **kw)
if res is not None:
# lol jsonrpc within xmlrpc
res = json.loads(res)
return res
return inner
def get_default_proxy(config_path=CONFIG_PATH):
"""
Get the default API proxy to blockstack.
"""
global default_proxy
if default_proxy is None:
import client
if os.environ.get("BLOCKSTACK_CLIENT_TEST_ALTERNATIVE_CONFIG", None) == "1":
# feature test: make sure alternative config paths get propagated
if config_path.startswith("/home"):
print config_path
traceback.print_stack()
sys.exit(0)
# load
conf = config.get_config(config_path)
blockstack_server = conf['server']
blockstack_port = conf['port']
log.debug("Default proxy to %s:%s" % (blockstack_server, blockstack_port))
proxy = client.session(conf=conf, server_host=blockstack_server, server_port=blockstack_port)
return proxy
else:
return default_proxy
def set_default_proxy(proxy):
"""
Set the default API proxy
"""
global default_proxy
default_proxy = proxy
def json_traceback():
exception_data = traceback.format_exc().splitlines()
return {
"error": exception_data[-1],
"traceback": exception_data
}
def getinfo(proxy=None):
"""
getinfo
"""
resp = {}
if proxy is None:
proxy = get_default_proxy()
try:
resp = proxy.getinfo()
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
except Exception as e:
resp = json_traceback()
return resp
def ping(proxy=None):
"""
ping
"""
resp = {}
if proxy is None:
proxy = get_default_proxy()
try:
resp = proxy.ping()
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
except Exception as e:
resp['error'] = str(e)
return resp
def get_name_cost(name, proxy=None):
"""
name_cost
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_name_cost(name)
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
return resp
def get_namespace_cost(namespace_id, proxy=None):
"""
namespace_cost
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_namespace_cost(namespace_id)
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
return resp
def get_all_names(offset, count, proxy=None):
"""
get all names
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.get_all_names(offset, count)
def get_names_in_namespace(namespace_id, offset, count, proxy=None):
"""
Get names in a namespace
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.get_names_in_namespace(namespace_id, offset, count)
def get_names_owned_by_address(address, proxy=None):
"""
Get the names owned by an address.
Only works for p2pkh scripts.
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.get_names_owned_by_address(address)
def get_consensus_at(block_height, proxy=None):
"""
Get consensus at a block
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_consensus_at(block_height)
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
return resp
def get_consensus_range(block_id_start, block_id_end, proxy=None):
"""
Get a range of consensus hashes. The range is inclusive.
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_consensus_range(block_id_start, block_id_end)
return resp
def get_nameops_at(block_id, proxy=None):
"""
Get the set of records as they were at a particular block.
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_nameops_at(block_id)
return resp
def get_nameops_hash_at(block_id, proxy=None):
"""
Get the hash of a set of records as they were at a particular block.
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_nameops_hash_at(block_id)
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
return resp
def get_name_blockchain_record(name, proxy=None):
"""
get_name_blockchain_record
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_name_blockchain_record(name)
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
return resp
def get_namespace_blockchain_record(namespace_id, proxy=None):
"""
get_namespace_blockchain_record
"""
if proxy is None:
proxy = get_default_proxy()
ret = proxy.get_namespace_blockchain_record(namespace_id)
if type(ret) == list:
if len(ret) == 0:
ret = {'error': 'No data returned'}
return ret
else:
ret = ret[0]
if ret is not None:
# this isn't needed
if 'opcode' in ret:
del ret['opcode']
return ret
def get_namespace_reveal_blockchain_record(namespace_id, proxy=None):
"""
Get a revealed (but not readied) namespace's information
"""
if proxy is None:
proxy = get_default_proxy()
ret = proxy.get_namespace_reveal_blockchain_record(namespace_id)
if type(ret) == list:
if len(ret) == 0:
ret = {'error': 'No data returned'}
return ret
else:
ret = ret[0]
if ret is not None:
# this isn't needed
if 'opcode' in ret:
del ret['opcode']
return ret
def preorder(name, privatekey, register_addr=None, proxy=None, tx_only=False):
"""
preorder.
Generate a private key to derive a change address for the register,
if one is not given already.
"""
register_privkey_wif = None
if register_addr is None:
privkey = pybitcoin.BitcoinPrivateKey()
pubkey = privkey.public_key()
register_addr = pubkey.address()
register_privkey_wif = privkey.to_wif()
print register_privkey_wif
print register_addr
# make sure the reveal address is *not* the address of this private key
privkey = pybitcoin.BitcoinPrivateKey(privatekey)
if register_addr == privkey.public_key().address():
return {"error": "Register address derived from private key"}
resp = {}
if proxy is None:
proxy = get_default_proxy()
try:
if tx_only:
# get unsigned preorder
resp = proxy.preorder_tx(name, privatekey, register_addr)
else:
# send preorder
resp = proxy.preorder(name, privatekey, register_addr)
except Exception as e:
resp['error'] = str(e)
if 'error' in resp:
return resp
# give the client back the key to the addr we used
if register_privkey_wif is not None:
resp['register_privatekey'] = register_privkey_wif
return resp
def preorder_subsidized(name, register_addr, subsidy_key, proxy=None):
"""
preorder a name, but subsidize it with the given subsidy_key.
Return a SIGHASH_ANYONECANPAY transaction, where the client must sign each
input originating from register_addr
"""
resp = {}
if proxy is None:
proxy = get_default_proxy()
try:
# get preorder tx
resp = proxy.preorder_tx_subsidized(name, register_addr, subsidy_key)
except Exception as e:
resp['error'] = str(e)
return resp
def register(name, privatekey, register_addr, proxy=None, tx_only=False):
"""
register
"""
resp = {}
if proxy is None:
proxy = get_default_proxy()
try:
if tx_only:
# get unsigned preorder
resp = proxy.register_tx(name, privatekey, register_addr)
else:
# send preorder
resp = proxy.register(name, privatekey, register_addr)
except Exception as e:
resp['error'] = str(e)
return resp
def register_subsidized(name, public_key, register_addr, subsidy_key, proxy=None):
"""
make a transaction that will register a name, but subsidize it with the given subsidy_key.
Return a SIGHASH_ANYONECANPAY transaction, where the client must sign each
input originating from register_addr
"""
resp = {}
if proxy is None:
proxy = get_default_proxy()
try:
# get register tx
resp = proxy.register_tx_subsidized(name, public_key, register_addr, subsidy_key)
except Exception as e:
resp['error'] = str(e)
return resp
def update(name, user_zonefile_json_or_hash, privatekey, txid=None, proxy=None, tx_only=False, public_key=None, subsidy_key=None):
"""
Low-level update.
Update a name record. Send a new transaction that attaches the given zonefile JSON (or a hash of it) to the name.
Optionally supply a txid. The reason for doing so is to try to replicate user
data to new storage systems, or to recover from a transient error encountered
earlier.
"""
import profile
# sanity check
if privatekey is None and public_key is None:
return {'error': 'Missing public and private key'}
if proxy is None:
proxy = get_default_proxy()
user_zonefile_hash = None
user_zonefile = None
# 160-bit hex string?
if len(user_zonefile_json_or_hash) == 40 and len(user_zonefile_json_or_hash.translate(None, "0123456789ABCDEFabcdef")) == 0:
user_zonefile_hash = user_zonefile_json_or_hash.lower()
else:
# user zonefile. verify that it's wellformed
try:
if type(user_zonefile_json_or_hash) in [str, unicode]:
user_zonefile = json.loads(user_zonefile_json_or_hash)
else:
user_zonefile = copy.deepcopy(user_zonefile_json_or_hash)
assert user_db.is_user_zonefile( user_zonefile )
except Exception, e:
log.exception(e)
return {'error': 'User profile is unparseable JSON or unparseable hash'}
user_zonefile_txt = zone_file.make_zone_file( user_zonefile, origin=name, ttl=USER_ZONEFILE_TTL )
user_zonefile_hash = storage.get_name_zonefile_hash( user_zonefile_txt )
# must be blockchain data for this user
blockchain_result = get_name_blockchain_record( name, proxy=proxy )
if blockchain_result is None:
return {'error': 'No such user'}
if 'error' in blockchain_result:
return blockchain_result
if tx_only:
result = None
# only want a transaction
if privatekey is None and public_key is not None and subsidy_key is not None:
result = proxy.update_tx_subsidized( name, user_zonefile_hash, public_key, subsidy_key )
if privatekey is not None:
result = proxy.update_tx( name, user_zonefile_hash, privatekey )
if result is not None:
return result
if txid is None:
# send a new transaction
result = proxy.update( name, user_zonefile_hash, privatekey )
if result is None:
return {'error': 'No response from server'}
if 'error' in result:
return result
if 'transaction_hash' not in result:
# failed
print result
result['error'] = 'No transaction hash returned'
return result
txid = result['transaction_hash']
else:
# embed the txid into the result nevertheless
result['transaction_hash'] = txid
# store the zonefile, if given
if user_zonefile is not None:
rc, new_hash = profile.store_name_zonefile( name, user_zonefile, txid )
if not rc:
result['error'] = 'Failed to store user zonefile'
return result
# success!
result['status'] = True
result['value_hash'] = user_zonefile_hash
return result
def update_subsidized(name, user_zonefile_json_or_hash, public_key, subsidy_key, txid=None, proxy=None):
"""
update_subsidized
"""
return update(name, user_zonefile_json_or_hash, None, txid=txid, public_key=public_key, subsidy_key=subsidy_key, tx_only=True, proxy=proxy)
def transfer(name, address, keep_data, privatekey, proxy=None, tx_only=False):
"""
transfer
"""
if proxy is None:
proxy = get_default_proxy()
if tx_only:
return proxy.transfer_tx(name, address, keep_data, privatekey)
else:
return proxy.transfer(name, address, keep_data, privatekey)
def transfer_subsidized(name, address, keep_data, public_key, subsidy_key, proxy=None):
"""
transfer_subsidized
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.transfer_tx_subsidized(name, address, keep_data, public_key, subsidy_key)
def renew(name, privatekey, proxy=None, tx_only=False):
"""
renew
"""
if proxy is None:
proxy = get_default_proxy()
if tx_only:
return proxy.renew_tx(name, privatekey)
else:
return proxy.renew(name, privatekey)
def renew_subsidized(name, public_key, subsidy_key, proxy=None):
"""
renew_subsidized
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.renew_tx_subsidized(name, public_key, subsidy_key)
def revoke(name, privatekey, proxy=None, tx_only=False):
"""
revoke
"""
if proxy is None:
proxy = get_default_proxy()
if tx_only:
return proxy.revoke_tx(name, privatekey)
else:
return proxy.revoke(name, privatekey)
def revoke_subsidized(name, public_key, subsidy_key, proxy=None):
"""
revoke_subsidized
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.revoke_tx_subsidized(name, public_key, subsidy_key)
def send_subsidized(privatekey, subsidized_tx, proxy=None):
"""
send_subsidized
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.send_subsidized(privatekey, subsidized_tx)
def name_import(name, address, update_hash, privatekey, proxy=None):
"""
name import
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.name_import(name, address, update_hash, privatekey)
def namespace_preorder(namespace_id, privatekey, reveal_addr=None, proxy=None):
"""
namespace preorder
Generate a register change address private key, if not given
"""
if proxy is None:
proxy = get_default_proxy()
reveal_privkey_wif = None
if reveal_addr is None:
privkey = pybitcoin.BitcoinPrivateKey()
pubkey = privkey.public_key()
reveal_addr = pubkey.address()
reveal_privkey_wif = privkey.to_wif()
print reveal_privkey_wif
print reveal_addr
# make sure the reveal address is *not* the address of this private key
privkey = pybitcoin.BitcoinPrivateKey(privatekey)
if reveal_addr == privkey.public_key().address():
return {"error": "Reveal address derived from private key"}
result = proxy.namespace_preorder(namespace_id, reveal_addr, privatekey)
if 'error' in result:
return result
if reveal_privkey_wif is not None:
result['reveal_privatekey'] = reveal_privkey_wif
return result
def namespace_reveal(namespace_id, reveal_addr, lifetime, coeff, base_cost,
bucket_exponents, nonalpha_discount, no_vowel_discount,
privatekey, proxy=None):
"""
namesapce_reveal
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.namespace_reveal(namespace_id, reveal_addr, lifetime, coeff,
base_cost, bucket_exponents, nonalpha_discount,
no_vowel_discount, privatekey)
def namespace_ready(namespace_id, privatekey, proxy=None):
"""
namespace_ready
"""
if proxy is None:
proxy = get_default_proxy()
return proxy.namespace_ready(namespace_id, privatekey)
def is_name_registered(fqu, proxy=None):
"""
Return True if @fqu registered on blockchain
"""
if proxy is None:
proxy = get_default_proxy()
blockchain_record = get_name_blockchain_record( fqu, proxy=proxy )
if 'error' in blockchain_record:
log.debug("Failed to read blockchain record for %s" % fqu)
return False
if "first_registered" in blockchain_record:
return True
else:
return False
def has_zonefile_hash(fqu, proxy=None ):
"""
Return True if @fqu has a zonefile hash on the blockchain
"""
if proxy is None:
proxy = get_default_proxy()
blockchain_record = get_name_blockchain_record(fqu, proxy=proxy )
if 'error' in blockchain_record:
log.debug("Failed to read blockchain record for %s" % fqu)
return False
if 'value_hash' in blockchain_record and blockchain_record['value_hash'] is not None:
return True
else:
return False
def is_zonefile_current(fqu, zonefile_json, proxy=None):
"""
Return True if hash(@zonefile_json) published on blockchain
"""
from .profile import hash_zonefile
if proxy is None:
proxy = get_default_proxy()
blockchain_record = get_name_blockchain_record( fqu, proxy=proxy )
if 'error' in blockchain_record:
log.debug("Failed to read blockchain record for %s" % fqu)
return False
zonefile_hash = hash_zonefile(zonefile_json)
if 'value_hash' in blockchain_record and blockchain_record['value_hash'] == zonefile_hash:
# if hash of profile is in correct
return True
return False
def is_name_owner(fqu, address, proxy=None):
"""
return True if @btc_address owns @fqu
"""
if proxy is None:
proxy = get_default_proxy()
blockchain_record = get_name_blockchain_record( fqu, proxy=proxy )
if 'error' in blockchain_record:
log.debug("Failed to read blockchain record for %s" % fqu)
return False
if 'address' in blockchain_record and blockchain_record['address'] == address:
return True
else:
return False