forked from stx-labs/stacks.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
2528 lines (1865 loc) · 77.5 KB
/
client.py
File metadata and controls
2528 lines (1865 loc) · 77.5 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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/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 parsing, schemas, storage, drivers, config, spv, utils
import user as user_db
from spv import SPVClient
import pybitcoin
import bitcoin
import binascii
from utilitybelt import is_hex
from config import log, 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
import virtualchain
# default API endpoint proxy to blockstackd
default_proxy = None
# ancillary storage providers
STORAGE_IMPL = None
class BlockstackRPCClient(object):
"""
Not-quite-JSONRPC client for Blockstack.
Blockstack's not-quite-JSONRPC server expects a raw Netstring that encodes
a JSON object with a "method" string and an "args" list. It will ignore
"id" and "version", and will not accept keyword arguments. It also does
not guarantee that the "result" and "error" keywords will be present.
"""
def __init__(self, server, port,
max_rpc_len=MAX_RPC_LEN,
timeout=config.DEFAULT_TIMEOUT):
self.server = server
self.port = port
self.sock = None
self.max_rpc_len = max_rpc_len
self.timeout = timeout
def __getattr__(self, key):
try:
return object.__getattr__(self, key)
except AttributeError:
return self.dispatch(key)
def socket():
return self.sock
def default(self, *args):
self.params = args
return self.request()
def dispatch(self, key):
self.method = key
return self.default
def ensure_connected(self):
if self.sock is None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
self.sock.settimeout(self.timeout)
self.sock.connect((self.server, self.port))
return True
def request(self):
self.ensure_connected()
request_id = str(uuid.uuid4())
parameters = {
'id': request_id,
'method': self.method,
'params': self.params,
'version': '2.0'
}
data = json.dumps(parameters)
data_netstring = str(len(data)) + ":" + data + ","
# send request
try:
self.sock.sendall(data_netstring)
except Exception, e:
self.sock.close()
self.sock = None
raise e
# get response: expect comma-ending netstring
# get the length first
len_buf = ""
while True:
c = self.sock.recv(1)
if len(c) == 0:
# connection closed
self.sock.close()
self.sock = None
raise Exception("Server closed remote connection")
c = c[0]
if c == ':':
break
else:
len_buf += c
buf_len = 0
# ensure it's an int
try:
buf_len = int(len_buf)
except Exception, e:
# invalid
self.sock.close()
self.sock = None
raise Exception("Invalid response: invalid netstring length")
# ensure it's not too big
if buf_len >= self.max_rpc_len:
self.sock.close()
self.sock = None
raise Exception("Invalid response: message too big")
# receive message
num_received = 0
response = ""
while num_received < buf_len+1:
buf = self.sock.recv(4096)
num_received += len(buf)
response += buf
# ensure that the message is terminated with a comma
if response[-1] != ',':
self.sock.close()
self.sock = None
raise Exception("Invalid response: invalid netstring termination")
# trim ','
response = response[:-1]
result = None
# parse the response
try:
result = json.loads(response)
# Netstrings responds with [{}] instead of {}
result = result[0]
return result
except Exception, e:
# try to clean up
self.sock.close()
self.sock = None
raise Exception("Invalid response: not a JSON string")
def session(conf=None, server_host=BLOCKSTACKD_SERVER, server_port=BLOCKSTACKD_PORT,
storage_drivers=BLOCKSTACK_DEFAULT_STORAGE_DRIVERS,
metadata_dir=BLOCKSTACK_METADATA_DIR, spv_headers_path=SPV_HEADERS_PATH, set_global=False):
"""
Create a blockstack session:
* validate the configuration
* load all storage drivers
* initialize all storage drivers
* load an API proxy to blockstack
conf's fields override specific keyword arguments.
Returns the API proxy object.
"""
global default_proxy
if conf is not None:
missing = find_missing(conf)
if len(missing) > 0:
log.error("Missing blockstack configuration fields: %s" % (", ".join(missing)))
sys.exit(1)
server_host = conf['server']
server_port = conf['port']
storage_drivers = conf['storage_drivers']
metadata_dir = conf['metadata']
if storage_drivers is None:
log.error("No storage driver(s) defined in the config file. Please set 'storage=' to a comma-separated list of %s" % ", ".join(drivers.DRIVERS))
sys.exit(1)
# create proxy
proxy = BlockstackRPCClient(server_host, server_port)
# load all storage drivers
for storage_driver in storage_drivers.split(","):
storage_impl = load_storage(storage_driver)
if storage_impl is None:
log.error("Failed to load storage driver '%s'" % (storage_driver))
sys.exit(1)
rc = register_storage(storage_impl)
if not rc:
log.error("Failed to initialize storage driver '%s'" % (storage_driver))
sys.exit(1)
# initialize SPV
SPVClient.init(spv_headers_path)
proxy.spv_headers_path = spv_headers_path
proxy.conf = conf
if set_global:
default_proxy = proxy
return proxy
def get_default_proxy():
"""
Get the default API proxy to blockstack.
"""
global default_proxy
return default_proxy
def set_default_proxy(proxy):
"""
Set the default API proxy
"""
global default_proxy
default_proxy = proxy
def load_storage(module_name):
"""
Load a storage implementation, given its module name.
Valid options can be found in blockstack.drivers.DRIVERS
"""
if module_name not in drivers.DRIVERS:
raise Exception("Unrecognized storage driver. Valid options are %s" % (", ".join(drivers.DRIVERS)))
try:
storage_impl = importlib.import_module("blockstack_client.drivers.%s" % module_name)
except ImportError, ie:
raise Exception("Failed to import blockstack.drivers.%s. Please verify that it is accessible via your PYTHONPATH" % module_name)
return storage_impl
def register_storage(storage_impl):
"""
Register a storage implementation.
"""
rc = storage.register_storage(storage_impl)
if rc:
rc = storage_impl.storage_init()
return rc
def load_user(record_hash):
"""
Load a user record from the storage implementation with the given hex string hash,
The user record hash should have been loaded from the blockchain, and thereby be the
authentic hash.
Return the user record on success
Return None on error
"""
user_json = storage.get_immutable_data(record_hash)
if user_json is None:
log.error("Failed to load user record '%s'" % record_hash)
return None
# verify integrity
user_record_hash = storage.get_data_hash(user_json)
if user_record_hash != record_hash:
log.error("Profile hash mismatch: expected '%s', got '%s'" % (record_hash, user_record_hash))
return None
user = user_db.parse_user(user_json)
return user
def get_zone_file(name):
# or whatever else we're going to call this
return get_name_record(name)
def get_create_diff(blockchain_record):
"""
Given a blockchain record, find its earliest history diff and its creation block number.
"""
preorder_block_number = blockchain_record['preorder_block_number']
history = blockchain_record['history']
create_block_number = None
if str(preorder_block_number) in history.keys():
# was preordered
create_block_number = preorder_block_number
else:
# was imported
create_block_number = int(sorted(history.keys())[0])
create_diff = history[str(create_block_number)][0]
return (create_block_number, create_diff)
def get_reveal_txid(blockchain_record):
"""
Given a blockchain record, find the transaction ID that revealed it
as well as the associated block number.
"""
history = blockchain_record['history']
reveal_block_number = None
# find the earliest history record with NAME_IMPORT or NAME_REGISTRATION
for block_number_str in sorted(history.keys()):
for i in xrange(0, len(history[block_number_str])):
if history[block_number_str][i].has_key('opcode'):
if str(history[block_number_str][i]['opcode']) in ['NAME_IMPORT', 'NAME_REGISTRATION']:
reveal_block_number = int(block_number_str)
return reveal_block_number, str(history[block_number_str][i]['txid'])
return (None, None)
def get_serial_number(blockchain_record):
"""
Calculate the serial number from a name's blockchain record.
* If the name was preordered, then this is first such $preorder_block-$vtxindex
* If the name was imported, then this is the first such $import_block-$vtxindex
"""
create_block_number, create_diff = get_create_diff(blockchain_record)
create_tx_index = create_diff['vtxindex']
history = blockchain_record['history']
serial_number = None
if str(create_diff['opcode']) == "NAME_PREORDER":
# name was preordered; use preorder block_id/tx_index
# find the oldest registration
update_order = sorted(history.keys())
for block_num in update_order:
for tx_op in history[block_num]:
if tx_op['opcode'] == "NAME_PREORDER":
serial_number = str(tx_op['block_number']) + '-' + str(tx_op['vtxindex'])
break
if serial_number is None:
raise Exception("No NAME_REGISTRATION found for '%s'" % blockchain_record.get('name', 'UNKNOWN_NAME'))
else:
# name was imported.
# serial number is the first NAME_IMPORT block + txindex
serial_number = str(create_block_number) + '-' + str(create_tx_index)
return serial_number
def get_block_from_consensus(consensus_hash, proxy=None):
"""
Get a block ID from a consensus hash
"""
if proxy is None:
proxy = get_default_proxy()
resp = proxy.get_block_from_consensus(consensus_hash)
if type(resp) == list:
if len(resp) == 0:
resp = {'error': 'No data returned'}
else:
resp = resp[0]
return resp
def txid_to_block_data(txid, bitcoind_proxy, proxy=None):
"""
Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, txdata) on success
Return (None, None, None) on error
"""
if proxy is None:
proxy = get_default_proxy()
timeout = 1.0
while True:
try:
untrusted_tx_data = bitcoind_proxy.getrawtransaction(txid, 1)
untrusted_block_hash = untrusted_tx_data['blockhash']
untrusted_block_data = bitcoind_proxy.getblock(untrusted_block_hash)
break
except Exception, e:
log.exception(e)
log.error("Unable to obtain block data; retrying...")
time.sleep(timeout)
timeout = timeout * 2 + random.random() * timeout
# first, can we trust this block? is it in the SPV headers?
untrusted_block_header_hex = virtualchain.block_header_to_hex(untrusted_block_data, untrusted_block_data['previousblockhash'])
block_id = SPVClient.block_header_index(proxy.spv_headers_path, (untrusted_block_header_hex + "00").decode('hex'))
if block_id < 0:
# bad header
log.error("Block header '%s' is not in the SPV headers" % untrusted_block_header_hex)
return (None, None, None)
# block header is trusted. Is the transaction data consistent with it?
if not virtualchain.block_verify(untrusted_block_data):
log.error("Block transaction IDs are not consistent with the trusted header's Merkle root")
return (None, None, None)
# verify block hash
if not virtualchain.block_header_verify(untrusted_block_data, untrusted_block_data['previousblockhash'], untrusted_block_hash):
log.error("Block hash is not consistent with block header")
return (None, None, None)
# we trust the block hash, block data, and txids
block_hash = untrusted_block_hash
block_data = untrusted_block_data
tx_data = untrusted_tx_data
return (block_hash, block_data, tx_data)
def txid_to_serial_number(txid, bitcoind_proxy, proxy=None):
"""
Given a transaction ID, convert it into a serial number
(defined as $block_id-$tx_index).
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the serial number on success
Return None on error
"""
if proxy is None:
proxy = get_default_proxy()
block_hash, block_data, _ = txid_to_block_data(txid, bitcoind_proxy, proxy=proxy)
if block_hash is None or block_data is None:
return None
# What's the tx index?
try:
tx_index = block_data['tx'].index(txid)
except:
# not actually present
log.error("Transaction %s is not present in block %s (%s)" % (txid, block_id, block_hash))
return "%s-%s" % (block_id, tx_index)
def serial_number_to_tx(serial_number, bitcoind_proxy, proxy=None):
"""
Convert a serial number into its transaction in the blockchain.
Use an untrusted bitcoind connection to get the list of transactions,
and use trusted SPV headers to ensure that the transaction obtained is on the main chain.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the SPV-verified transaction object (as a dict) on success
Return None on error
"""
if proxy is None:
proxy = get_default_proxy()
parts = serial_number.split("-")
block_id = int(parts[0])
tx_index = int(parts[1])
timeout = 1.0
while True:
try:
block_hash = bitcoind_proxy.getblockhash(block_id)
block_data = bitcoind_proxy.getblock(block_hash)
break
except Exception, e:
log.error("Unable to obtain block data; retrying...")
time.sleep(timeout)
timeout = timeout * 2 + random.random() * timeout
rc = SPVClient.sync_header_chain(proxy.spv_headers_path, bitcoind_proxy.opts['bitcoind_server'], block_id)
if not rc:
log.error("Failed to synchronize SPV header chain up to %s" % block_id)
return None
# verify block header
rc = SPVClient.block_header_verify(proxy.spv_headers_path, block_id, block_hash, block_data)
if not rc:
log.error("Failed to verify block header for %s against SPV headers" % block_id)
return None
# verify block txs
rc = SPVClient.block_verify(block_data, block_data['tx'])
if not rc:
log.error("Failed to verify block transaction IDs for %s against SPV headers" % block_id)
return None
# sanity check
if tx_index >= len(block_data['tx']):
log.error("Serial number %s references non-existant transaction %s (out of %s txs)" % (serial_number, tx_index, len(block_data['tx'])))
return None
# obtain transaction
txid = block_data['tx'][tx_index]
tx = bitcoind_proxy.getrawtransaction(txid, 1)
# verify tx
rc = SPVClient.tx_verify(block_data['tx'], tx)
if not rc:
log.error("Failed to verify block transaction %s against SPV headers" % txid)
return None
# verify tx index
if tx_index != SPVClient.tx_index(block_data['tx'], tx):
log.error("TX index mismatch: serial number identifies transaction number %s (%s), but got transaction %s" % \
(tx_index, block_data['tx'][tx_index], block_data['tx'][ SPVClient.tx_index(block_data['tx'], tx) ]))
return None
# success!
return tx
def parse_tx_op_return(tx):
"""
Given a transaction, locate its OP_RETURN and parse
out its opcode and payload.
Return (opcode, payload) on success
Return (None, None) if there is no OP_RETURN, or if it's not a blockchain ID operation.
"""
# find OP_RETURN output
op_return = None
outputs = tx['vout']
for out in outputs:
if int(out["scriptPubKey"]['hex'][0:2], 16) == pybitcoin.opcodes.OP_RETURN:
op_return = out['scriptPubKey']['hex'].decode('hex')
break
if op_return is None:
pp = pprint.PrettyPrinter()
pp.pprint(tx)
log.error("transaction has no OP_RETURN output")
return (None, None)
# [0] is OP_RETURN, [1] is the length; [2:4] are 'id', [4] is opcode
magic = op_return[2:4]
if magic != BLOCKCHAIN_ID_MAGIC:
# not a blockchain ID operation
#print SPVClient.tx_hash(tx)
#print op_return.encode('hex')
log.error("OP_RETURN output does not encode a blockchain ID operation")
return (None, None)
opcode = op_return[4]
payload = op_return[5:]
return (opcode, payload)
def get_consensus_hash_from_tx(tx):
"""
Given an SPV-verified transaction, extract its consensus hash.
Only works of the tx encodes a NAME_PREORDER, NAMESPACE_PREORDER,
or NAME_TRANSFER.
Return hex-encoded consensus hash on success.
Return None on error.
"""
opcode, payload = parse_tx_op_return(tx)
if opcode is None or payload is None:
return None
# only present in NAME_PREORDER, NAMESPACE_PREORDER, NAME_TRANSFER
if opcode not in [NAME_PREORDER, NAMESPACE_PREORDER, NAME_TRANSFER]:
log.error("Blockchain ID transaction is not a NAME_PREORDER, NAMESPACE_PROERDER or NAME_TRANSFER")
return None
else:
consensus_hash = payload[-16:].encode('hex')
return consensus_hash
def verify_consensus_hash_from_tx(tx, fqname, candidate_consensus_hash):
"""
Given the SPV-verified transaction that encodes a consensus hash-bearing OP_RETURN,
the fully qualified name, and the list of candidate consensus hashes from Blockstack,
verify the consensus hash against the transaction.
Return the consensus hash on success
Return None if there was no OP_RETURN output in the tx, or the OP_RETURN output
does not encode one of the valid opcodes, or there is a mismatch.
"""
opcode, payload = parse_tx_op_return(tx)
if opcode is None or payload is None:
return None
if opcode not in [NAME_PREORDER, NAMESPACE_PREORDER, NAME_UPDATE, NAME_TRANSFER]:
# no consensus hash will be present
log.error("Blockchain ID transaction is not a NAME_PREORDER, NAMESPACE_PROERDER, NAME_UPDATE, or NAME_TRANSFER")
return None
elif opcode != NAME_UPDATE:
# in all but NAME_UPDATE, the consensus hash is the last 16 bytes
consensus_hash = payload[-16:].encode('hex')
if str(consensus_hash) == str(candidate_consensus_hash):
return consensus_hash
else:
# nope
log.error("Consensus hash mismatch: expected %s, got %s" % (candidate_consensus_hash, consensus_hash))
return None
else:
# In NAME_UPDATE, the consensus hash *at the time of the operation* is mixed with the name,
# truncated to 16 bytes, and appended after the opcode.
name_consensus_hash_mix = pybitcoin.hash.bin_sha256(fqname + candidate_consensus_hash)[0:16]
tx_name_consensus_hash_mix = payload[0:16]
if name_consensus_hash_mix == tx_name_consensus_hash_mix:
return candidate_consensus_hash
log.error("NAME_UPDATE consensus hash mix mismatch: expected %s from %s, got %s" % (name_consensus_hash_mix.encode('hex'), candidate_consensus_hash, tx_name_consensus_hash_mix.encode('hex')))
return None
def get_name_creation_consensus_info(name, blockchain_record, bitcoind_proxy, proxy=None, serial_number=None):
"""
Given the result of a call to get_name_blockchain_record,
obtain the creation consensus hash, type, and block number.
Verify them with SPV.
On success, return a dict with:
* type: if the name was preordered, then this is NAME_PREORDER. If the name was instead
imported, then this is NAME_IMPORT.
* block_id: the block ID of the NAME_PREORDER or NAME_IMPORT
* anchor: an object containing:
* consensus_hash: if the name was preordered, then this is the consensus hash at the time
the preorder operation was issued. Otherwise, if the name was imported, then this is
the consensus hash at the time the namespace preorder of the namespace into which the
was imported was issued. Note that in both cases, this is the consensus hash
from the block *at the time of issue*--this is NOT the block at which the name
operation was incorporated into the blockchain.
* block_id: the block id from which the consensus hash was taken. Note that this
is *not* the block at which the name operation was incorporated into the blockchain
(i.e. this block ID may *not* match the serial number).
* txid: the transaction ID that contains the consensus hash
'anchor' will not be given on NAMESPACE_PREORDER
On error, return a dict with 'error' defined as a key, mapped to an error message.
"""
create_block_number, create_diff = get_create_diff(blockchain_record)
create_consensus_tx = None
# consensus info for when the name was created (NAMESPACE_PREORDER or NAME_PREORDER)
creation_consensus_hash = None
creation_consensus_type = str(create_diff['opcode'])
# find preorder consensus hash, if preordered
if creation_consensus_type == "NAME_PREORDER":
creation_consensus_hash = create_diff['consensus_hash']
# transaction with the consensus hash comes from the NAME_PREORDER
preorder_serial_number = None
if serial_number is None:
preorder_serial_number = get_serial_number(blockchain_record)
else:
preorder_serial_number = serial_number
create_consensus_tx = serial_number_to_tx(preorder_serial_number, bitcoind_proxy, proxy=proxy)
if create_consensus_tx is None:
return {'error': 'Failed to verify name creation consensus-bearing transaction against SPV headers'}
# we can trust that the consensus-bearing transaction is on the blockchain.
# now, what's the creation consensus hash's block number?
# (NOTE: this trusts Blockstack)
creation_consensus_block_id = get_block_from_consensus(creation_consensus_hash, proxy=proxy)
if type(creation_consensus_hash_id) == dict and 'error' in ret:
return ret
# verify that the given consensus hash is present in the trusted consensus-bearing transaction
tx_consensus_hash = verify_consensus_hash_from_tx(create_consensus_tx, name, creation_consensus_hash)
if tx_consensus_hash is None:
# !!! Blockstackd lied to us--we got the wrong consensus hash
return {'error': 'Blockstack consensus hash does not match the SPV block headers'}
creation_info = {
'type': creation_consensus_type,
'block_id': create_block_number,
}
if creation_consensus_type == 'NAME_PREORDER':
# have trust anchor
creation_info['anchor'] = {
'consensus_hash': creation_consensus_hash,
'block_id': creation_consensus_block_id,
'txid': create_consensus_tx['txid']
}
return creation_info
def get_name_reveal_consensus_info(name, blockchain_record, bitcoind_proxy, proxy=None):
"""
Given a name, its blockchain record, and a bitcoind proxy, get information
about the name's revelation (i.e. the Blockstack state transition that exposed
the name's plaintext). That is, get information about a name's NAME_REGISTRATION,
or its NAME_IMPORT.
The transaction that performed the revelation will be fetched
from the underlying blockchain, and verified with SPV.
Return a dict with the following:
* type: either NAME_REGISTRATION or NAME_IMPORT
* block_id: the block ID of the name op that revealed the name
* txid: the transaction ID of the revelation
"""
reveal_block_number, reveal_txid = get_reveal_txid(blockchain_record)
# consensus info for when the name was revealed to the world (NAME_IMPORT or NAME_REGISTRATION)
reveal_consensus_tx = None
reveal_consensus_hash = None
reveal_consensus_type = None
# get verified name revelation data
reveal_block_hash, reveal_block_data, reveal_tx = txid_to_block_data(reveal_txid, bitcoind_proxy, proxy=proxy)
if reveal_block_hash is None or reveal_block_data is None:
return {'error': 'Failed to look up name revelation information'}
reveal_op, reveal_payload = parse_tx_op_return(reveal_tx)
if reveal_op is None or reveal_payload is None:
return {'error': 'Transaction is not a valid Blockstack operation'}
if reveal_op not in [NAME_REGISTRATION, NAME_IMPORT]:
return {'error': 'Transaction is not a NAME_REGISTRATION or a NAME_IMPORT'}
if reveal_payload != name:
log.error("Reveal payload is '%s'; expected '%s'" % (reveal_payload, name))
return {'error': 'Transaction does not reveal the given name'}
# NOTE: trusts Blockstack
if reveal_op == NAME_REGISTRATION:
reveal_op = "NAME_REGISTRATION"
elif reveal_op == NAME_IMPORT:
reveal_op = "NAME_IMPORT"
else:
return {'error': 'Unrecognized reveal opcode'}
ret = {
'type': reveal_op,
'block_id': reveal_block_number,
'txid': reveal_tx['txid']
}
return ret
def find_last_historical_op(history, opcode):
"""
Given the blockchain history of a name, and the desired opcode name,
find the last history record for the opcode. This returns a dict of the
old values for the fields.
Return (block number, dict of records that changed at that block number) on success.
block number will be -1 if the dict of records is the oldest historical record, which
indicates that the caller should use the preorder_block_number field as the block to
which the history record applies.
Return (None, None) on error
"""
prev_blocks = sorted(history.keys())[::-1] + [-1]
prev_opcode = None
for i in xrange(0, len(prev_blocks)-1):
prev_block = prev_blocks[i]
prev_ops = history[prev_block]
for prev_op in reversed(prev_ops):
if prev_op.has_key('opcode'):
prev_opcode = str(prev_op['opcode'])
if prev_opcode == opcode:
return (int(prev_blocks[i + 1]), prev_op)
return (None, None)
def get_name_update_consensus_info(name, blockchain_record, bitcoind_proxy, proxy=None):
"""
Given the result of a call to get_name_blockchain_record (an untrusted database record for a name),
obtain the last-modification consensus hash, type, and block number. Use SPV to verify that
(1) the consensus hash is in the blockchain,
(2)
On success, and the name was modified since it was registered, return a dict with:
* type: NAME_UPDATE
* anchor: an object with:
* consensus_hash: the consensus hash obtained from the NAME_UPDATE transaction. Note
that this is the consensus hash *at the time of issue*--it is *not* guaranteed to
correspond to the block at which the NAME_UPDATE was incorporated into the blockchain.
* block_id: the block id at which the operation was issued (*not* the block ID
at which the NAME_UPDATE was incorporated into the blockchain).
If the name has never been updated, then return None.
On error, return a dict with 'error' defined as a key, mapped to an error message.
"""
update_consensus_hash = None
update_record = None
update_block_id = None
update_consensus_block_id = None
# find the latest NAME_UPDATE
if str(blockchain_record['opcode']) == "NAME_UPDATE":
update_consensus_hash = str(blockchain_record['consensus_hash'])
update_record = blockchain_record
update_block_id = int(sorted(blockchain_record['history'].keys())[-1])
else:
update_block_id, update_record = find_last_historical_op(blockchain_record['history'], "NAME_UPDATE")
if update_record is not None:
update_consensus_hash = str(update_record['consensus_hash'])
if update_consensus_hash is None:
# never updated
return None
# get update tx data and verify it via SPV
update_serial = "%s-%s" % (update_block_id, update_record['vtxindex'])
update_tx = serial_number_to_tx(update_serial, bitcoind_proxy, proxy=proxy)
# update_tx is now known to be on the main blockchain.
tx_consensus_hash = None
# the consensus hash will be between when we accepted the update (update_block_id), and up to BLOCKS_CONSENSUS_HASH_IS_VALID blocks in the past.
candidate_consensus_hashes = get_consensus_range(update_block_id, update_block_id - virtualchain.lib.BLOCKS_CONSENSUS_HASH_IS_VALID)
for i in xrange(0, len(candidate_consensus_hashes)):
ch = candidate_consensus_hashes[i]
tx_consensus_hash = verify_consensus_hash_from_tx(update_tx, name, ch)
if tx_consensus_hash is not None:
# the update_tx contains the untrusted consensus hash.
# success!
update_consensus_block_id = update_block_id + i
break
if tx_consensus_hash is None:
# !!! Blockstackd lied to us--we got the wrong consensus hash
return {'error': 'Blockstack consensus hash does not match the SPV block headers'}
else:
update_info = {
'type': 'NAME_UPDATE',
'block_id': update_block_id,
'anchor': {
'consensus_hash': update_consensus_hash,
'block_id': update_consensus_block_id,
'txid': update_tx['txid']
}
}
return update_info
def lookup(name, proxy=None):
"""
Get the name and (some) blockchain data:
* zone file
* serial number
* consensus hash at block of creation (NAME_IMPORT or NAME_PREORDER)
* consensus hash at block of last modification
* address
Use SPV to verify that we're getting the right consensus hash.
"""
if proxy is None:
proxy = get_default_proxy()
bitcoind_proxy = virtualchain.connect_bitcoind(proxy.conf)
# get zonefile data
zone_file = get_zone_file(name)
if 'error' in zone_file:
return zone_file
# get blockchain-obtained data
blockchain_result = get_name_blockchain_record(name, proxy=proxy)
# get creation consensus data
creation_info = get_name_creation_consensus_info(name, blockchain_result, bitcoind_proxy, proxy=proxy)
if 'error' in creation_info:
return creation_info
# get revelation consensus data
reveal_info = get_name_reveal_consensus_info(name, blockchain_result, bitcoind_proxy, proxy=proxy)
if reveal_info is not None and 'error' in reveal_info:
return reveal_info
# get update consensus data
update_info = get_name_update_consensus_info(name, blockchain_result, bitcoind_proxy, proxy=proxy)
if update_info is not None and 'error' in update_info:
return update_info
# get serial number
serial_number = get_serial_number(blockchain_result)
# fill in serial number, address
result = {
'blockchain_id': name,
'zone_file': zone_file,
'serial_number': serial_number,
'address': blockchain_result.get('address', None),
'created': creation_info
}
if reveal_info is not None:
result['revealed'] = reveal_info
if update_info is not None:
result['updated'] = update_info
return result
def get_name_record(name, create_if_absent=False, proxy=None,
check_only_blockchain=False):
"""
Given the name of the user, look up the user's record hash,
and then get the record itself from storage.