-
Notifications
You must be signed in to change notification settings - Fork 659
/
storage.py
1266 lines (945 loc) · 36.7 KB
/
storage.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
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 python2
# -*- 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/>.
"""
# this module contains the high-level methods for talking to ancillary storage.
import os
import sys
from keylib import ECPrivateKey, ECPublicKey
import bitcoin
import ecdsa
import pybitcoin
import keylib
import types
import re
import base64
import json
import hashlib
import urllib
import urllib2
import blockstack_zones
from collections import defaultdict
import blockstack_profiles
from config import LENGTH_MAX_NAME, get_logger, CONFIG_PATH
from scripts import is_name_valid
import keys
log = get_logger()
import string
B40_CHARS = string.digits + string.lowercase + '-_.+'
B40_CLASS = '[a-z0-9\-_.+]'
B40_NO_PERIOD_CLASS = '[a-z0-9\-_+]'
B40_REGEX = '^%s*$' % B40_CLASS
URLENCODED_CLASS = '[a-zA-Z0-9\-_.~%]'
# global list of registered data handlers
storage_handlers = []
def is_b40(s):
return (isinstance(s, str) and (re.match(B40_REGEX, s) is not None))
class UnhandledURLException( Exception ):
def __init__(self, url):
super( UnhandledURLException, self ).__init__()
self.unhandled_url = url
def is_valid_hash( value ):
"""
Is this string a valid 32-byte hash?
"""
if type(value) not in [str, unicode]:
return False
strvalue = str(value)
if re.match(r"^[a-fA-F0-9]+$", strvalue ) is None:
return False
if len(strvalue) != 64:
return False
return True
def get_data_hash( data_txt ):
"""
Generate a hash over data for immutable storage.
Return the hex string.
"""
h = hashlib.sha256()
h.update(data_txt)
return h.hexdigest()
def get_zonefile_data_hash( data_txt ):
"""
Generate a hash over a user's zonefile.
Return the hex string.
"""
return pybitcoin.hex_hash160( data_txt )
def get_blockchain_compat_hash( data_txt ):
"""
Generate a hash suitable for embedding into
the blockchain (e.g. for user zonefiles and
announcements).
"""
return pybitcoin.hex_hash160( data_txt )
def hash_zonefile( zonefile_json ):
"""
Given a JSON-ized zonefile, calculate its hash
"""
assert "$origin" in zonefile_json.keys(), "Missing $origin"
assert "$ttl" in zonefile_json.keys(), "Missing $ttl"
user_zonefile_txt = blockstack_zones.make_zone_file( zonefile_json )
data_hash = get_zonefile_data_hash( user_zonefile_txt )
return data_hash
def verify_zonefile( zonefile_str, value_hash ):
"""
Verify that a zonefile hashes to the given value hash
@zonefile_str must be the zonefile as a serialized string
"""
zonefile_hash = get_zonefile_data_hash( zonefile_str )
if zonefile_hash != value_hash:
log.debug("Zonefile hash mismatch: expected %s, got %s" % (value_hash, zonefile_hash))
return False
return True
def get_storage_handlers():
"""
Get the list of loaded storage handler instances
"""
global storage_handlers
return storage_handlers
def make_mutable_data_urls( data_id, use_only=None ):
"""
Given a data ID for mutable data, get a list of URLs to it
by asking the storage handlers.
"""
global storage_handlers
use_only = [] if use_only is None else use_only
urls = []
for handler in storage_handlers:
if not hasattr(handler, "make_mutable_url"):
continue
if len(use_only) > 0 and handler.__name__ not in use_only:
# not requested
continue
new_url = None
try:
new_url = handler.make_mutable_url( data_id )
except Exception, e:
log.exception(e)
continue
if new_url is not None:
urls.append( new_url )
return urls
def serialize_mutable_data( data_json, privatekey ):
"""
Generate a serialized mutable data record from the given information.
Sign it with privatekey.
Return the serialized data (as a string) on success
"""
tokenized_data = blockstack_profiles.sign_token_records( [data_json], privatekey )
del tokenized_data[0]['decodedToken']
serialized_data = json.dumps( tokenized_data, sort_keys=True )
return serialized_data
def parse_mutable_data( mutable_data_json_txt, public_key, public_key_hash=None ):
"""
Given the serialized JSON for a piece of mutable data,
parse it into a JSON document. Verify that it was
signed by public_key's or public_key_hash's private key.
Try to verify with both keys, if given.
Return the parsed JSON dict on success
Return None on error
"""
assert public_key is not None or public_key_hash is not None, "need a public key or public key hash"
mutable_data_jwt = None
try:
mutable_data_jwt = json.loads(mutable_data_json_txt)
assert type(mutable_data_jwt) in [dict, list]
except:
log.error("Invalid JSON")
return None
mutable_data_json = None
# try pubkey, if given
if public_key is not None:
mutable_data_json = blockstack_profiles.get_profile_from_tokens( mutable_data_jwt, public_key )
if len(mutable_data_json) > 0:
return mutable_data_json
else:
log.warn("Failed to verify with public key '%s'" % public_key)
# try pubkey address
if public_key_hash is not None:
# NOTE: these should always have version byte 0
public_key_hash_0 = keylib.address_formatting.bin_hash160_to_address( keylib.address_formatting.address_to_bin_hash160( str(public_key_hash) ), version_byte=0 )
mutable_data_json = blockstack_profiles.get_profile_from_tokens( mutable_data_jwt, public_key_hash_0 )
if len(mutable_data_json) > 0:
log.debug("Verified with %s" % public_key_hash)
return mutable_data_json
else:
log.warn("Failed to verify with public key hash '%s' ('%s')" % (public_key_hash, public_key_hash_0))
return None
def register_storage( storage_impl ):
"""
Given a class, module, etc. with the methods,
register the mutable and immutable data handlers.
The given argument--storage_impl--must persist for
as long as the application will be using its methods.
Return True on success
Return False on error
"""
global storage_handlers
if storage_impl in storage_handlers:
return True
storage_handlers.append( storage_impl )
# sanity check
for expected_method in ["make_mutable_url", "get_immutable_handler", "get_mutable_handler", \
"put_immutable_handler", "put_mutable_handler", \
"delete_immutable_handler", "delete_mutable_handler" ]:
if not hasattr( storage_impl, expected_method ):
log.warning("Storage implementation is missing a '%s' method" % expected_method )
return True
def get_immutable_data( data_hash, data_url=None, hash_func=get_data_hash, fqu=None, data_id=None, zonefile=False, deserialize=True, drivers=None ):
"""
Given the hash of the data, go through the list of
immutable data handlers and look it up.
Optionally pass the fully-qualified name (@fqu), human-readable data ID (data_id),
and whether or not this is a zonefile request (zonefile) as hints to the driver.
Return the data (as a dict) on success.
Return None on failure
"""
global storage_handlers
if len(storage_handlers) == 0:
log.debug("No storage handlers registered")
return None
handlers_to_use = []
if drivers is not None and len(drivers) > 0:
# whitelist of drivers to try
for d in drivers:
for h in storage_handlers:
if h.__name__ == d:
handlers_to_use.append(h)
else:
handlers_to_use = storage_handlers
log.debug("get_immutable %s" % data_hash)
for handler in [data_url] + handlers_to_use:
if handler is None:
continue
data = None
data_dict = None
if handler == data_url:
# url hint
try:
# assume it's something we can urlopen
urlh = urllib2.urlopen( data_url )
data = urlh.read()
urlh.close()
except Exception, e:
log.exception(e)
log.error("Failed to load profile from '%s'" % data_url)
continue
else:
# handler
if not hasattr( handler, "get_immutable_handler" ):
log.debug("No method: %s.get_immutable_handler(%s)" % (handler, data_hash))
continue
log.debug("Try %s (%s)" % (handler.__name__, data_hash))
try:
data = handler.get_immutable_handler( data_hash, data_id=data_id, zonefile=zonefile, fqu=fqu )
except Exception, e:
log.exception( e )
log.debug("Method failed: %s.get_immutable_handler(%s)" % (handler, data_hash))
continue
if data is None:
log.debug("No data: %s.get_immutable_handler(%s)" % (handler.__name__, data_hash))
continue
# validate
dh = hash_func(data)
if dh != data_hash:
# nope
if handler == data_url:
log.error("Invalid data hash from '%s'" % data_url)
else:
log.error("Invalid data hash from %s.get_immutable_handler" % (handler.__name__))
continue
# deserialize
if deserialize:
try:
data_dict = json.loads(data)
except ValueError:
log.error("Invalid JSON for %s" % data_hash)
continue
else:
data_dict = data
log.debug("loaded %s with %s" % (data_hash, handler.__name__))
return data_dict
return None
def sign_raw_data(raw_data, privatekey):
"""
Sign a string of data.
Returns signature as a base64 string
"""
data_hash = get_data_hash(raw_data)
pk = ECPrivateKey(privatekey)
pk_hex = pk.to_hex()
# force uncompressed
if len(pk_hex) > 64:
pk = ECPrivateKey(privkey[:64])
priv = pk.to_hex()
pub = pk.public_key().to_hex()
assert len(pub[2:].decode('hex')) == ecdsa.SECP256k1.verifying_key_length, "BUG: Invalid key decoding"
sk = ecdsa.SigningKey.from_string(priv.decode('hex'), curve=ecdsa.SECP256k1)
sig_bin = sk.sign_digest(data_hash.decode('hex'), sigencode=ecdsa.util.sigencode_der)
# enforce low-s
sig_r, sig_s = ecdsa.util.sigdecode_der( sig_bin, ecdsa.SECP256k1.order )
if sig_s * 2 >= ecdsa.SECP256k1.order:
log.debug("High-S to low-S")
sig_s = ecdsa.SECP256k1.order - sig_s
sig_bin = ecdsa.util.sigencode_der( sig_r, sig_s, ecdsa.SECP256k1.order )
# sanity check
vk = ecdsa.VerifyingKey.from_string(pub[2:].decode('hex'), curve=ecdsa.SECP256k1)
assert vk.verify_digest(sig_bin, data_hash.decode('hex'), sigdecode=ecdsa.util.sigdecode_der), "Failed to verify signature ({}, {})".format(sig_r, sig_s)
return base64.b64encode( bitcoin.encode_sig( None, sig_r, sig_s ).decode('hex') )
def secp256k1_compressed_pubkey_to_uncompressed_pubkey( pubkey ):
"""
convert a secp256k1 compressed public key into an uncompressed public key.
taken from https://bitcointalk.org/index.php?topic=644919.msg7205689#msg7205689
"""
pubk = ECPublicKey(pubkey).to_hex()
assert len(pubk) == 66, "Not a compressed hex public key"
def pow_mod(x, y, z):
"Calculate (x ** y) % z efficiently."
number = 1
while y:
if y & 1:
number = number * x % z
y >>= 1
x = x * x % z
return number
p = ecdsa.SECP256k1.curve.p()
b = ecdsa.SECP256k1.curve.b()
y_parity = int(pubk[:2]) - 2
x = int(pubk[2:], 16)
a = (pow_mod(x, 3, p) + b) % p
y = pow_mod(a, (p+1)//4, p)
if y % 2 != y_parity:
y = -y % p
uncompressed_pubk = '04{:x}{:x}'.format(x, y)
return uncompressed_pubk
def verify_raw_data(raw_data, pubkey, sigb64):
"""
Verify the signature over a string, given the public key
and base64-encode signature.
Return True on success.
Return False on error.
"""
data_hash = get_data_hash(raw_data)
pubk = ECPublicKey(pubkey).to_hex()
if len(pubk) == 66:
pubk = secp256k1_compressed_pubkey_to_uncompressed_pubkey( pubkey )
sig_bin = base64.b64decode(sigb64)
vk = ecdsa.VerifyingKey.from_string( pubk[2:].decode('hex'), curve=ecdsa.SECP256k1 )
return vk.verify_digest(sig_bin, data_hash.decode('hex'), sigdecode=ecdsa.util.sigdecode_der)
def get_drivers_for_url( url ):
"""
Which drivers can handle this url?
"""
global storage_drivers
ret = []
for h in storage_handlers:
if not hasattr(h, "handles_url"):
continue
if h.handles_url(url):
ret.append( h )
return ret
def get_mutable_data( fq_data_id, data_pubkey, urls=None, data_address=None, owner_address=None, drivers=None, decode=True ):
"""
Given a mutable data's zonefile, go fetch the data.
Return a mutable data dict on success
Return None on error
"""
global storage_handlers
fq_data_id = str(fq_data_id)
assert is_fq_data_id( fq_data_id ) or is_name_valid( fq_data_id ), "Need either a fully-qualified data ID or a blockchain ID: '%s'" % fq_data_id
fqu = None
if is_fq_data_id(fq_data_id):
fqu = fq_data_id.split(":")[0]
else:
fqu = fq_data_id
handlers_to_use = []
if drivers is not None and len(drivers) > 0:
# whitelist of drivers to try
for d in drivers:
for h in storage_handlers:
if h.__name__ == d:
handlers_to_use.append(h)
else:
handlers_to_use = storage_handlers
log.debug("get_mutable %s" % fq_data_id)
for storage_handler in handlers_to_use:
if not hasattr(storage_handler, "get_mutable_handler"):
continue
# which URLs to attempt?
try_urls = []
if urls is None:
# make one on-the-fly
if not hasattr(storage_handler, "make_mutable_url"):
log.warning("Storage handler %s does not support `make_mutable_url`" % storage_handler.__name__)
continue
new_url = None
try:
new_url = storage_handler.make_mutable_url( fq_data_id )
except Exception, e:
log.exception(e)
continue
try_urls = [new_url]
else:
# find the set that this handler can manage
for url in urls:
if not hasattr(storage_handler, "handles_url"):
log.warning("Storage handler %s does not support `handles_url`" % storage_handler.__name__)
continue
if storage_handler.handles_url( url ):
try_urls.append(url)
for url in try_urls:
data_json = None
data = None
log.debug("Try %s (%s)" % (storage_handler.__name__, url))
try:
data_json = storage_handler.get_mutable_handler( url, fqu=fqu )
except UnhandledURLException, uue:
# handler doesn't handle this URL
log.debug("Storage handler %s does not handle URLs like %s" % (storage_handler.__name__, url ))
continue
except Exception, e:
log.exception( e )
continue
if data_json is None:
# no data
log.debug("No data from %s (%s)" % (storage_handler.__name__, url))
continue
# parse it, if desired
if decode:
data = parse_mutable_data( data_json, data_pubkey, public_key_hash=data_address )
if data is None:
# maybe try owner address?
if owner_address is not None:
data = parse_mutable_data( data_json, data_pubkey, public_key_hash=owner_address )
if data is None:
log.error("Unparseable data from '%s'" % url)
continue
log.debug("loaded '%s' with %s" % (url, storage_handler.__name__))
else:
data = data_json
log.debug("fetched (but did not decode) '%s' with '%s'" % (url, storage_handler.__name__))
return data
return None
def serialize_immutable_data( data_json ):
"""
Serialize a piece of immutable data
"""
assert type(data_json) in [dict,list,defaultdict], "Invalid immutable data: must be a dict or list(got type %s)" % type(data_json)
return json.dumps(data_json, sort_keys=True)
def put_immutable_data( data_json, txid, data_hash=None, data_text=None, required=None ):
"""
Given a string of data (which can either be data or a zonefile), store it into our immutable data stores.
Do so in a best-effort manner--this method only fails if *all* storage providers fail.
Return the hash of the data on success
Return None on error
"""
global storage_handlers
required = [] if required is None else required
assert (data_hash is None and data_text is None and data_json is not None) or \
(data_hash is not None and data_text is not None), "Need data hash and text, or just JSON"
if data_text is None:
data_text = serialize_immutable_data( data_json )
if data_hash is None:
data_hash = get_data_hash( data_text )
else:
data_hash = str(data_hash)
successes = 0
log.debug("put_immutable_data(%s), required=%s" % (data_hash, ",".join(required)))
for handler in storage_handlers:
if not getattr(handler, "put_immutable_handler"):
# this one failed
if handler.__name__ in required:
# fatal
log.debug("Failed to replicate to required storage provider '%s'" % handler.__name__)
return None
else:
continue
rc = False
try:
log.debug("Try '%s'" % handler.__name__)
rc = handler.put_immutable_handler( data_hash, data_text, txid )
except Exception, e:
log.exception(e)
if handler.__name__ in required:
# fatal
log.debug("Failed to replicate to required storage provider '%s'" % handler.__name__)
return None
else:
continue
if not rc:
log.debug("Failed to replicate with '%s'" % handler.__name__)
else:
log.debug("Replication succeeded with '%s'" % handler.__name__)
successes += 1
if successes == 0:
# failed everywhere
return None
else:
# succeeded somewhere
return data_hash
def put_mutable_data( fq_data_id, data_json, privatekey, required=None, use_only=None ):
"""
Given the unserialized data, store it into our mutable data stores.
Do so in a best-effort way. This method only fails if all storage providers fail.
@fq_data_id is the fully-qualified data id. It must be prefixed with the username,
to avoid collisions in shared mutable storage.
Return True on success
Return False on error
"""
global storage_handlers
required = [] if required is None else required
use_only = [] if use_only is None else use_only
# sanity check: only support single-sig private keys
if not keys.is_singlesig(privatekey):
log.error("Only single-signature data private keys are supported")
return False
fq_data_id = str(fq_data_id)
assert is_fq_data_id( fq_data_id ) or is_name_valid(fq_data_id), "Data ID must be fully qualified or must be a valid blockchain ID (got %s)" % fq_data_id
assert privatekey is not None
fqu = None
if is_fq_data_id(fq_data_id):
fqu = fq_data_id.split(":")[0]
else:
fqu = fq_data_id
serialized_data = serialize_mutable_data( data_json, privatekey )
successes = 0
log.debug("put_mutable_data(%s), required=%s" % (fq_data_id, ",".join(required)))
for handler in storage_handlers:
if not hasattr( handler, "put_mutable_handler" ):
if handler.__name__ in required:
log.debug("Failed to replicate with required storage provider '%s'" % handler.__name__)
return None
else:
continue
if len(use_only) > 0 and handler.__name__ not in use_only:
log.debug("Skipping storage driver '%s'" % handler.__name__)
continue
rc = False
try:
log.debug("Try '%s'" % handler.__name__)
rc = handler.put_mutable_handler( fq_data_id, serialized_data, fqu=fqu )
except Exception, e:
log.exception( e )
if handler.__name__ in required:
log.debug("Failed to replicate with required storage provider '%s'" % handler.__name__)
return None
else:
continue
if not rc:
if handler.__name__ in required:
log.debug("Failed to replicate with required storage provider '%s'" % handler.__name__)
return None
else:
log.debug("Failed to replicate with '%s'" % handler.__name__)
continue
else:
successes += 1
if successes == 0:
# failed everywhere
return False
else:
# succeeded somewhere
return True
def delete_immutable_data( data_hash, txid, privkey ):
"""
Given the hash of the data, the private key of the user,
and the txid that deleted the data's hash from the blockchain,
delete the data from all immutable data stores.
"""
global storage_handlers
# sanity check
if not keys.is_singlesig(privkey):
log.error("Only single-signature data private keys are supported")
return False
data_hash = str(data_hash)
txid = str(txid)
sigb64 = sign_raw_data( data_hash + txid, privkey )
for handler in storage_handlers:
if not hasattr( handler, "delete_immutable_handler" ):
continue
try:
handler.delete_immutable_handler( data_hash, txid, sigb64 )
except Exception, e:
log.exception( e )
return False
return True
def delete_mutable_data( fq_data_id, privatekey, only_use=None ):
"""
Given the data ID and private key of a user,
go and delete the associated mutable data.
"""
global storage_handlers
only_use = [] if only_use is None else only_use
# sanity check
if not keys.is_singlesig(privatekey):
log.error("Only single-signature data private keys are supported")
return False
fq_data_id = str(fq_data_id)
assert is_fq_data_id( fq_data_id ) or is_name_valid(fq_data_id), "Data ID must be fully qualified or must be a valid blockchain ID (got %s)" % fq_data_id
sigb64 = sign_raw_data( fq_data_id, privatekey )
# remove data
for handler in storage_handlers:
if not hasattr( handler, "delete_mutable_handler" ):
continue
if len(only_use) > 0 and handler.__name__ in only_use:
log.debug("Skip storage driver %s" % handler.__name__)
continue
try:
handler.delete_mutable_handler( fq_data_id, sigb64 )
except Exception, e:
log.exception( e )
return False
return True
def get_announcement( announcement_hash ):
"""
Go get an announcement's text, given its hash.
Use the blockstack client library, so we can get at
the storage drivers for the storage systems the sender used
to host it.
Return the data on success
"""
data = get_immutable_data( announcement_hash, hash_func=get_blockchain_compat_hash, deserialize=False )
if data is None:
log.error("Failed to get announcement '%s'" % (announcement_hash))
return None
return data
def put_announcement( announcement_text, txid ):
"""
Go put an announcement into back-end storage.
Use the blockstack client library, so we can get at
the storage drivers for the storage systems this host
is configured to use.
Return the data's hash
"""
data_hash = get_blockchain_compat_hash(announcement_text)
res = put_immutable_data( None, txid, data_hash=data_hash, data_text=announcement_text )
if res is None:
log.error("Failed to put announcement '%s'" % (data_hash))
return None
return data_hash
def make_fq_data_id( name, data_id ):
"""
Make a fully-qualified data ID, prefixed by the name.
"""
return str("%s:%s" % (name, data_id))
def is_fq_data_id( fq_data_id ):
"""
Is a data ID is fully qualified?
"""
if len(fq_data_id.split(":")) < 2:
return False
# name must be valid
name = fq_data_id.split(":")[0]
if not is_name_valid(name):
return False
return True
def blockstack_mutable_data_url( blockchain_id, data_id, version ):
"""
Make a blockstack:// URL for mutable data
"""
if version is not None:
if type(version) not in [int, long]:
raise ValueError("Verison must be an int or long")
return "blockstack://%s/%s#%s" % (urllib.quote(blockchain_id), urllib.quote(data_id), str(version))
else:
return "blockstack://%s/%s" % (urllib.quote(blockchain_id), urllib.quote(data_id))
def blockstack_immutable_data_url( blockchain_id, data_id, data_hash ):
"""
Make a blockstack:// URL for immutable data
"""
if data_hash is not None and not is_valid_hash( data_hash ):
raise ValueError("Invalid hash: %s" % data_hash)
if data_hash is not None:
return "blockstack://%s.%s/#%s" % (urllib.quote(data_id), urllib.quote(blockchain_id), data_hash)
else:
return "blockstack://%s.%s" % (urllib.quote(data_id), urllib.quote(blockchain_id))
def blockstack_app_data_url( blockchain_id, service_id, account_id, data_id, version ):
"""
Make a blockstack:// URL for application data
"""
if version is not None:
if type(version) not in [int, long]:
raise ValueError("Version must be an int or a long")
# don't allow periods in the service ID
service_id = service_id.replace(".", "\\x2e")
# don't allow '@' in either the service or account IDs
service_id = service_id.replace("@", "\\x40")
account_id = account_id.replace("@", "\\x40")
return "blockstack://%s.%s@%s/%s#%s" % (urllib.quote(account_id), urllib.quote(service_id), urllib.quote(blockchain_id), urllib.quote(data_id), str(version))
else:
return "blockstack://%s.%s@%s/%s" % (urllib.quote(account_id), urllib.quote(service_id), urllib.quote(blockchain_id), urllib.quote(data_id))
def blockstack_mutable_data_url_parse( url ):
"""
Parse a blockstack:// URL for mutable data
Return (blockchain ID, data ID, data version, account ID, service ID) on success
* The version may be None if not given (in which case, the latest value is requested).
* The data ID may be None, in which case, a listing of mutable data is requested.
* account ID and service ID will be None for mutable data in the profile, but will be defined for app-specific mutable data
Raise on bad data
"""
url = str(url)
mutable_url_data_regex = r"blockstack://(%s+)[/]+(%s+)(#[0-9]+)?" % (B40_CLASS, URLENCODED_CLASS)
app_url_data_regex = r"blockstack://(%s+)\.(%s+)@(%s+)[/]+(%s+)(#[0-9]+)?" % (URLENCODED_CLASS, URLENCODED_CLASS, B40_CLASS, URLENCODED_CLASS)
mutable_url_listing_regex = r"blockstack://(%s+)[/]+#mutable" % (B40_CLASS)
blockchain_id = None
data_id = None
version = None
# app?
m = re.match( app_url_data_regex, url )
if m:
account_id, service_id, blockchain_id, data_id, version = m.groups()
if not is_name_valid( blockchain_id ):
raise ValueError("Invalid blockchain ID '%s'" % blockchain_id)
# version?
if version is not None:
version = version.strip("#")
version = int(version)
return urllib.unquote(blockchain_id), urllib.unquote(data_id), version, urllib.unquote(account_id), urllib.unquote(service_id)
# mutable?
m = re.match( mutable_url_data_regex, url )
if m:
blockchain_id, data_id, version = m.groups()
if not is_name_valid( blockchain_id ):
raise ValueError("Invalid blockchain ID '%s'" % blockchain_id)
# version?
if version is not None:
version = version.strip("#")
version = int(version)
return urllib.unquote(blockchain_id), urllib.unquote(data_id), version, None, None
else:
# maybe a listing?
m = re.match( mutable_url_listing_regex, url )
if not m:
raise ValueError("Invalid URL: %s" % url)
blockchain_id = m.groups()[0]
return urllib.unquote(blockchain_id), None, None, None, None
def blockstack_immutable_data_url_parse( url ):
"""
Parse a blockstack:// URL for immutable data
Return (blockchain ID, data ID, data hash)
* The hash may be None if not given, in which case, the hash should be looked up from the blockchain ID's profile.
* The data ID may be None, in which case, the list of immutable data is requested.
Raise on bad data
"""
url = str(url)
immutable_data_regex = r"blockstack://(%s+)\.(%s+)\.(%s+)([/]+#[a-fA-F0-9]+)?" % (URLENCODED_CLASS, B40_NO_PERIOD_CLASS, B40_NO_PERIOD_CLASS)
immutable_listing_regex = r"blockstack://(%s+)[/]+#immutable" % (B40_CLASS)
m = re.match( immutable_data_regex, url )