-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathapi.py
More file actions
2026 lines (1549 loc) · 67.8 KB
/
api.py
File metadata and controls
2026 lines (1549 loc) · 67.8 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
from cryptos import (
ecdsa_raw_sign,
ecdsa_raw_verify,
der_decode_sig,
compress,
privkey_to_pubkey,
pubkey_to_address,
der_encode_sig,
)
from .utils import (
is_valid_hash,
is_valid_block_representation,
is_valid_coin_symbol,
is_valid_wallet_name,
is_valid_address_for_coinsymbol,
coin_symbol_from_mkey,
double_sha256,
compress_txn_outputs,
get_txn_outputs_dict,
uses_only_hash_chars,
)
from .constants import COIN_SYMBOL_MAPPINGS
from dateutil import parser
from posixpath import join as urljoin
import requests
import logging
try:
from json.decoder import JSONDecodeError as JSONError
except ImportError: # pragma: no cover
JSONError = ValueError
BLOCKCYPHER_DOMAIN = 'https://api.blockcypher.com'
ENDPOINT_VERSION = 'v1'
TIMEOUT_IN_SECONDS = 10
logger = logging.getLogger(__name__)
'''
# For debugging:
# https://docs.python.org/3/howto/logging.html#configuring-logging
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
'''
class RateLimitError(RuntimeError):
''' Raised when the library makes too many API calls '''
pass
def get_valid_json(request, allow_204=False):
if request.status_code == 429:
raise RateLimitError('Status Code 429', request.text)
elif request.status_code == 204 and allow_204:
return True
try:
return request.json()
except JSONError as error:
msg = 'JSON deserialization failed: {}'.format(str(error))
raise requests.exceptions.ContentDecodingError(msg)
def get_token_info(api_key):
assert api_key
url = '%s/%s/tokens/%s' % (BLOCKCYPHER_DOMAIN, ENDPOINT_VERSION, api_key)
r = requests.get(url, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)
def _clean_tx(response_dict):
''' Pythonize a blockcypher API response '''
confirmed_txrefs = []
for confirmed_txref in response_dict.get('txrefs', []):
confirmed_txref['confirmed'] = parser.parse(confirmed_txref['confirmed'])
confirmed_txrefs.append(confirmed_txref)
response_dict['txrefs'] = confirmed_txrefs
unconfirmed_txrefs = []
for unconfirmed_txref in response_dict.get('unconfirmed_txrefs', []):
unconfirmed_txref['received'] = parser.parse(unconfirmed_txref['received'])
unconfirmed_txrefs.append(unconfirmed_txref)
response_dict['unconfirmed_txrefs'] = unconfirmed_txrefs
return response_dict
def _clean_block(response_dict):
''' Pythonize a blockcypher API response '''
response_dict['received_time'] = parser.parse(response_dict['received_time'])
response_dict['time'] = parser.parse(response_dict['time'])
return response_dict
def get_address_details(address, coin_symbol='btc', txn_limit=None, api_key=None, before_bh=None, after_bh=None, unspent_only=False, show_confidence=False, confirmations=0, include_script=False):
'''
Takes an address and coin_symbol and returns the address details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
For batching a list of addresses, see get_addresses_details
'''
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
url = make_url(coin_symbol, **dict(addrs=address))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return _clean_tx(response_dict=r)
def get_addresses_details(address_list, coin_symbol='btc', txn_limit=None, api_key=None,
before_bh=None, after_bh=None, unspent_only=False, show_confidence=False,
confirmations=0, include_script=False):
'''
Batch version of get_address_details method
'''
for address in address_list:
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
kwargs = dict(addrs=';'.join([str(addr) for addr in address_list]))
url = make_url(coin_symbol, **kwargs)
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r]
def get_address_full(address, coin_symbol='btc', txn_limit=None, inout_limit=None,
api_key=None, before_bh=None, after_bh=None, show_confidence=False, confirmations=0):
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
url = make_url(coin_symbol, 'addrs', **{address: 'full'})
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if show_confidence:
params['includeConfidence'] = 'true'
if inout_limit:
params['txlimit'] = inout_limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
txs = []
for tx in response_dict['txs']:
if 'confirmed' in tx:
tx['confirmed'] = parser.parse(tx['confirmed'])
if 'received' in tx:
tx['received'] = parser.parse(tx['received'])
txs.append(tx)
response_dict['txs'] = txs
return response_dict
def get_wallet_transactions(wallet_name, api_key, coin_symbol='btc',
before_bh=None, after_bh=None, txn_limit=None, omit_addresses=False,
unspent_only=False, show_confidence=False, confirmations=0):
'''
Takes a wallet, api_key, coin_symbol and returns the wallet's details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
'''
assert len(wallet_name) <= 25, wallet_name
assert api_key
assert is_valid_coin_symbol(coin_symbol=coin_symbol)
assert isinstance(show_confidence, bool), show_confidence
assert isinstance(omit_addresses, bool), omit_addresses
url = make_url(coin_symbol, **dict(addrs=wallet_name))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if omit_addresses:
params['omitWalletAddresses'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return _clean_tx(get_valid_json(r))
def get_address_overview(address, coin_symbol='btc', api_key=None):
'''
Takes an address and coin_symbol and return the address details
'''
assert is_valid_address_for_coinsymbol(b58_address=address,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, 'addrs', **{address: 'balance'})
params = {}
if api_key:
params['token'] = api_key
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)
def get_total_balance(address, coin_symbol='btc', api_key=None):
'''
Balance including confirmed and unconfirmed transactions for this address,
in satoshi.
'''
return get_address_overview(address=address,
coin_symbol=coin_symbol, api_key=api_key)['final_balance']
def get_unconfirmed_balance(address, coin_symbol='btc', api_key=None):
'''
Balance including only unconfirmed (0 block) transactions for this address,
in satoshi.
'''
return get_address_overview(address=address,
coin_symbol=coin_symbol, api_key=api_key)['unconfirmed_balance']
def get_confirmed_balance(address, coin_symbol='btc', api_key=None):
'''
Balance including only confirmed (1+ block) transactions for this address,
in satoshi.
'''
return get_address_overview(address=address,
coin_symbol=coin_symbol, api_key=api_key)['balance']
def get_num_confirmed_transactions(address, coin_symbol='btc', api_key=None):
'''
Only transactions that have made it into a block (confirmations > 0)
'''
return get_address_overview(address=address,
coin_symbol=coin_symbol, api_key=api_key)['n_tx']
def get_num_unconfirmed_transactions(address, coin_symbol='btc', api_key=None):
'''
Only transactions that have note made it into a block (confirmations == 0)
'''
return get_address_overview(address=address,
coin_symbol=coin_symbol, api_key=api_key)['unconfirmed_n_tx']
def get_total_num_transactions(address, coin_symbol='btc', api_key=None):
'''
All transaction, regardless if they have made it into any blocks
'''
return get_address_overview(address=address,
coin_symbol=coin_symbol, api_key=api_key)['final_n_tx']
def generate_new_address(coin_symbol='btc', api_key=None):
'''
Takes a coin_symbol and returns a new address with it's public and private keys.
This method will create the address server side, which is inherently insecure and should only be used for testing.
If you want to create a secure address client-side using python, please check out bitmerchant:
from bitmerchant.wallet import Wallet
Wallet.new_random_wallet()
https://github.com/sbuss/bitmerchant
'''
assert api_key, 'api_key required'
assert is_valid_coin_symbol(coin_symbol)
if coin_symbol not in ('btc-testnet', 'bcy'):
WARNING_MSG = [
'Generating private key details server-side.',
'You really should do this client-side.',
'See https://github.com/sbuss/bitmerchant for an example.',
]
print(' '.join(WARNING_MSG))
url = make_url(coin_symbol, 'addrs')
params = {'token': api_key}
r = requests.post(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)
def derive_hd_address(api_key=None, wallet_name=None, num_addresses=1,
subchain_index=None, coin_symbol='btc'):
'''
Returns a new address (without access to the private key) and adds it to
your HD wallet (previously created using create_hd_wallet).
This method will traverse/discover a new address server-side from your
previously supplied extended public key, the server will never see your
private key. It is therefor safe for production use.
You may also include a subchain_index directive if your wallet has multiple
subchain_indices and you'd like to specify which one should be traversed.
'''
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
assert wallet_name, wallet_name
assert isinstance(num_addresses, int), num_addresses
url = make_url(coin_symbol, 'wallets/hd', **{wallet_name: 'addresses/derive'})
params = {'token': api_key}
if subchain_index:
params['subchain_index'] = subchain_index
if num_addresses > 1:
params['count'] = num_addresses
r = requests.post(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)
def get_transaction_details(tx_hash, coin_symbol='btc', limit=None, tx_input_offset=None, tx_output_offset=None,
include_hex=False, show_confidence=False, confidence_only=False, api_key=None):
"""
Takes a tx_hash, coin_symbol, and limit and returns the transaction details
Optional:
- limit: # inputs/ouputs to include (applies to both)
- tx_input_offset: input offset
- tx_output_offset: output offset
- include_hex: include the raw TX hex
- show_confidence: adds confidence information to unconfirmed TXRefs.
- confidence_only: show only the confidence statistics and don't return the rest of the endpoint details (faster)
"""
assert is_valid_hash(tx_hash), tx_hash
assert is_valid_coin_symbol(coin_symbol), coin_symbol
added = 'txs/{}{}'.format(tx_hash, '/confidence' if confidence_only else '')
url = make_url(coin_symbol, added)
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
if tx_input_offset:
params['instart'] = tx_input_offset
if tx_output_offset:
params['outstart'] = tx_output_offset
if include_hex:
params['includeHex'] = 'true'
if show_confidence and not confidence_only:
params['includeConfidence'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' not in response_dict and not confidence_only:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
response_dict['block_height'] = None
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
return response_dict
def get_transactions_details(tx_hash_list, coin_symbol='btc', limit=None, api_key=None):
"""
Takes a list of tx_hashes, coin_symbol, and limit and returns the transaction details
Limit applies to both num inputs and num outputs.
TODO: add offsetting once supported
"""
for tx_hash in tx_hash_list:
assert is_valid_hash(tx_hash)
assert is_valid_coin_symbol(coin_symbol)
if len(tx_hash_list) == 0:
return []
elif len(tx_hash_list) == 1:
return [get_transaction_details(tx_hash=tx_hash_list[0],
coin_symbol=coin_symbol,
limit=limit,
api_key=api_key
)]
url = make_url(coin_symbol, **dict(txs=';'.join(tx_hash_list)))
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict_list = get_valid_json(r)
cleaned_dict_list = []
for response_dict in response_dict_list:
if 'error' not in response_dict:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
response_dict['block_height'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
cleaned_dict_list.append(response_dict)
return cleaned_dict_list
def get_num_confirmations(tx_hash, coin_symbol='btc', api_key=None):
'''
Given a tx_hash, return the number of confirmations that transactions has.
Answer is going to be from 0 - current_block_height.
'''
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
limit=1, api_key=api_key).get('confirmations')
def get_confidence(tx_hash, coin_symbol='btc', api_key=None):
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
show_confidence=True, api_key=api_key).get('confidence')
def get_miner_preference(tx_hash, coin_symbol='btc', api_key=None):
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
show_confidence=True, api_key=api_key).get('preference')
def get_receive_count(tx_hash, coin_symbol='btc', api_key=None):
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
show_confidence=True, api_key=api_key).get('receive_count')
def get_satoshis_transacted(tx_hash, coin_symbol='btc', api_key=None):
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
limit=1, api_key=api_key)['total']
def get_satoshis_in_fees(tx_hash, coin_symbol='btc', api_key=None):
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
limit=1, api_key=api_key)['fees']
def get_broadcast_transactions(coin_symbol='btc', limit=10, api_key=None):
"""
Get a list of broadcast but unconfirmed transactions
Similar to bitcoind's getrawmempool method
"""
url = make_url(coin_symbol, 'txs')
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
unconfirmed_txs = []
for unconfirmed_tx in response_dict:
unconfirmed_tx['received'] = parser.parse(unconfirmed_tx['received'])
unconfirmed_txs.append(unconfirmed_tx)
return unconfirmed_txs
def get_broadcast_transaction_hashes(coin_symbol='btc', api_key=None, limit=10):
'''
Warning, slow!
'''
transactions = get_broadcast_transactions(
coin_symbol=coin_symbol,
api_key=api_key,
limit=limit,
)
return [tx['hash'] for tx in transactions]
def get_block_overview(block_representation, coin_symbol='btc', txn_limit=None,
txn_offset=None, api_key=None):
"""
Takes a block_representation, coin_symbol and txn_limit and gets an overview
of that block, including up to X transaction ids.
Note that block_representation may be the block number or block hash
"""
assert is_valid_coin_symbol(coin_symbol)
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, **dict(blocks=block_representation))
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
if txn_offset:
params['txstart'] = txn_offset
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' in response_dict:
return response_dict
return _clean_block(response_dict=response_dict)
def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None):
'''
Batch request version of get_blocks_overview
'''
for block_representation in block_representation_list:
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
assert is_valid_coin_symbol(coin_symbol)
blocks = ';'.join([str(x) for x in block_representation_list])
url = make_url(coin_symbol, **dict(blocks=blocks))
logger.info(url)
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r]
def get_merkle_root(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the merkle root
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['mrkl_root']
def get_bits(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the number of bits
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits']
def get_nonce(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the nonce
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits']
def get_prev_block_hash(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the previous block hash
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['prev_block']
def get_block_hash(block_height, coin_symbol='btc', api_key=None):
'''
Takes a block_height and returns the block_hash
'''
return get_block_overview(block_representation=block_height,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['hash']
def get_block_height(block_hash, coin_symbol='btc', api_key=None):
'''
Takes a block_hash and returns the block_height
'''
return get_block_overview(block_representation=block_hash,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['height']
def get_block_details(block_representation, coin_symbol='btc', txn_limit=None,
txn_offset=None, in_out_limit=None, api_key=None):
"""
Takes a block_representation, coin_symbol and txn_limit and
1) Gets the block overview
2) Makes a separate API call to get specific data on txn_limit transactions
Note: block_representation may be the block number or block hash
WARNING: using a high txn_limit will make this *extremely* slow.
"""
assert is_valid_coin_symbol(coin_symbol)
block_overview = get_block_overview(
block_representation=block_representation,
coin_symbol=coin_symbol,
txn_limit=txn_limit,
txn_offset=txn_offset,
api_key=api_key,
)
if 'error' in block_overview:
return block_overview
txids_to_lookup = block_overview['txids']
txs_details = get_transactions_details(
tx_hash_list=txids_to_lookup,
coin_symbol=coin_symbol,
limit=in_out_limit,
api_key=api_key,
)
if 'error' in txs_details:
return txs_details
# build comparator dict to use for fast sorting of batched results later
txids_comparator_dict = {}
for cnt, tx_id in enumerate(txids_to_lookup):
txids_comparator_dict[tx_id] = cnt
# sort results using comparator dict
block_overview['txids'] = sorted(
txs_details,
key=lambda k: txids_comparator_dict.get(k.get('hash'), 9999), # anything that fails goes last
)
return block_overview
def get_blockchain_overview(coin_symbol='btc', api_key=None):
assert is_valid_coin_symbol(coin_symbol)
url = make_url(coin_symbol)
params = {}
if api_key:
params['token'] = api_key
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
response_dict['time'] = parser.parse(response_dict['time'])
return response_dict
def get_latest_block_height(coin_symbol='btc', api_key=None):
'''
Get the latest block height for a given coin
'''
return get_blockchain_overview(coin_symbol=coin_symbol,
api_key=api_key)['height']
def get_latest_block_hash(coin_symbol='btc', api_key=None):
'''
Get the latest block hash for a given coin
'''
return get_blockchain_overview(coin_symbol=coin_symbol,
api_key=api_key)['hash']
def get_blockchain_fee_estimates(coin_symbol='btc', api_key=None):
"""
Returns high, medium, and low fee estimates for a given blockchain.
"""
overview = get_blockchain_overview(coin_symbol=coin_symbol, api_key=api_key)
if coin_symbol == 'eth':
return {
'high_fee_per_kb': overview['high_gas_price'],
'medium_fee_per_kb': overview['medium_gas_price'],
'low_fee_per_kb': overview['low_gas_price'],
}
else:
return {
'high_fee_per_kb': overview['high_fee_per_kb'],
'medium_fee_per_kb': overview['medium_fee_per_kb'],
'low_fee_per_kb': overview['low_fee_per_kb'],
}
def get_blockchain_high_fee(coin_symbol='btc', api_key=None):
"""
Returns high fee estimate per kilobyte for a given blockchain.
"""
return get_blockchain_overview(coin_symbol, api_key)['high_fee_per_kb']
def get_blockchain_medium_fee(coin_symbol='btc', api_key=None):
"""
Returns medium fee estimate per kilobyte for a given blockchain.
"""
return get_blockchain_overview(coin_symbol, api_key)['medium_fee_per_kb']
def get_blockchain_low_fee(coin_symbol='btc', api_key=None):
"""
Returns low fee estimate per kilobyte for a given blockchain.
"""
return get_blockchain_overview(coin_symbol, api_key)['low_fee_per_kb']
def make_url(coin_symbol='btc'):
"""
Used for creating, listing and deleting payments
"""
assert is_valid_coin_symbol(coin_symbol)
return make_url(coin_symbol, 'payments')
def get_forwarding_address_details(destination_address, api_key, callback_url=None, coin_symbol='btc'):
"""
Give a destination address and return the details of the input address
that will automatically forward to the destination address
Note: a blockcypher api_key is required for this method
"""
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'payments')
logger.info(url)
params = {'token': api_key}
data = {
'destination': destination_address,
}
if callback_url:
data['callback_url'] = callback_url
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)
def get_forwarding_address(destination_address, api_key, callback_url=None, coin_symbol='btc'):
"""
Give a destination address and return an input address that will
automatically forward to the destination address. See
get_forwarding_address_details if you also need the forwarding address ID.
Note: a blockcypher api_key is required for this method
"""
assert api_key, 'api_key required'
resp_dict = get_forwarding_address_details(
destination_address=destination_address,
api_key=api_key,
callback_url=callback_url,
coin_symbol=coin_symbol
)
return resp_dict['input_address']
# came up with better names after it was already released
create_forwarding_address = get_forwarding_address
create_forwarding_address_with_details = get_forwarding_address_details
def list_forwarding_addresses(api_key, offset=None, coin_symbol='btc'):
'''
List the forwarding addresses for a certain api key
(and on a specific blockchain)
'''
assert is_valid_coin_symbol(coin_symbol)
assert api_key
url = make_url(coin_symbol, 'payments')
params = {'token': api_key}
if offset:
params['start'] = offset
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)
def delete_forwarding_address(payment_id, coin_symbol='btc', api_key=None):
'''
Delete a forwarding address on a specific blockchain, using its
payment id
'''
assert payment_id, 'payment_id required'
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
params = {'token': api_key}
url = make_url(**dict(payments=payment_id))
r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=True)
def subscribe_to_address_webhook(callback_url, subscription_address, event='tx-confirmation', confirmations=0, confidence=0.00, coin_symbol='btc', api_key=None):
'''
Subscribe to transaction webhooks on a given address.
Webhooks for transaction broadcast and each confirmation (up to 6).
Returns the blockcypher ID of the subscription
'''
assert is_valid_coin_symbol(coin_symbol)
assert is_valid_address_for_coinsymbol(subscription_address, coin_symbol)
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'hooks')
params = {'token': api_key}
data = {
'event': event,
'url': callback_url,
'address': subscription_address,
}
if event == 'tx-confirmation' and confirmations:
data['confirmations'] = confirmations
elif event == 'tx-confidence' and confidence:
data['confidence'] = confidence
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
return response_dict['id']
def subscribe_to_wallet_webhook(callback_url, wallet_name,
event='tx-confirmation', coin_symbol='btc', api_key=None):
'''
Subscribe to transaction webhooks on a given address.
Webhooks for transaction broadcast and each confirmation (up to 6).
Returns the blockcypher ID of the subscription
'''
assert is_valid_coin_symbol(coin_symbol)
assert is_valid_wallet_name(wallet_name), wallet_name
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'hooks')
params = {'token': api_key}
data = {
'event': event,
'url': callback_url,
'wallet_name': wallet_name,
}
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
return response_dict['id']
def list_webhooks(api_key, coin_symbol='btc'):
assert api_key, api_key
assert is_valid_coin_symbol(coin_symbol), coin_symbol
url = make_url(coin_symbol, 'hooks')
params = {'token': api_key}
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)
def get_webhook_info(webhook_id, api_key=None, coin_symbol='btc'):
assert is_valid_coin_symbol(coin_symbol), coin_symbol
url = make_url(coin_symbol, **dict(hooks=webhook_id))
if api_key:
params = {'token': api_key}
else:
params = {}
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r)