-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathsecp256k1.py
1248 lines (1205 loc) · 65.5 KB
/
secp256k1.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
# -*- coding: utf-8 -*-
"""
@author: iceland
"""
import platform
import os
import sys
import ctypes
import math
import pickle
import base64
###############################################################################
N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
Zero=b'\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
#==============================================================================
if platform.system().lower().startswith('win'):
dir_path = os.path.dirname(os.path.realpath(__file__))
dllfile = dir_path + '/ice_secp256k1.dll'
if os.path.isfile(dllfile) == True:
pathdll = os.path.realpath(dllfile)
ice = ctypes.CDLL(pathdll)
else:
print('File {} not found'.format(dllfile))
elif platform.system().lower().startswith('lin'):
dir_path = os.path.dirname(os.path.realpath(__file__))
dllfile = dir_path + '/ice_secp256k1.so'
if os.path.isfile(dllfile) == True:
pathdll = os.path.realpath(dllfile)
ice = ctypes.CDLL(pathdll)
else:
print('File {} not found'.format(dllfile))
else:
print('[-] Unsupported Platform currently for ctypes dll method. Only [Windows and Linux] is working')
sys.exit()
###############################################################################
#==============================================================================
# Coin type
COIN_BTC = 0
COIN_BSV = 1
COIN_BTCD = 2
COIN_ARG = 3
COIN_AXE = 4
COIN_BC = 5
COIN_BCH = 6
COIN_BSD = 7
COIN_BTDX = 8
COIN_BTG = 9
COIN_BTX = 10
COIN_CHA = 11
COIN_DASH = 12
COIN_DCR = 13
COIN_DFC = 14
COIN_DGB = 15
COIN_DOGE = 16
COIN_FAI = 17
COIN_FTC = 18
COIN_GRS = 19
COIN_JBS = 20
COIN_LTC = 21
COIN_MEC = 22
COIN_MONA = 23
COIN_MZC = 24
COIN_PIVX = 25
COIN_POLIS= 26
COIN_RIC = 27
COIN_STRAT= 28
COIN_SMART= 29
COIN_VIA = 30
COIN_XMY = 31
COIN_ZEC = 32
COIN_ZCL = 33
COIN_ZERO = 34
COIN_ZEN = 35
COIN_TENT = 36
COIN_ZEIT = 37
COIN_VTC = 38
COIN_UNO = 39
COIN_SKC = 40
COIN_RVN = 41
COIN_PPC = 42
COIN_OMC = 43
COIN_OK = 44
COIN_NMC = 45
COIN_NLG = 46
COIN_LBRY = 47
COIN_DNR = 48
COIN_BWK = 49
#==============================================================================
# Mnem Lang [Only English is Enabled. No other Language Actiavted yet]
MNEM_EN = 0 # English
MNEM_JP = 1 # Japanese
MNEM_KR = 2 # Korean
MNEM_SP = 3 # Spanish
MNEM_CS = 4 # Chinese_simplified
MNEM_CT = 5 # Chinese_traditional
MNEM_FR = 6 # French
MNEM_IT = 7 # Italian
MNEM_CZ = 8 # Czech
MNEM_PT = 9 # Portuguese
#==============================================================================
ice.scalar_multiplication.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # pvk,ret
#==============================================================================
ice.scalar_multiplications.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # pvk,len,ret
#==============================================================================
ice.get_x_to_y.argtypes = [ctypes.c_char_p, ctypes.c_bool, ctypes.c_char_p] # x,even,ret
#==============================================================================
ice.point_increment.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # upub,ret
#==============================================================================
ice.point_negation.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # upub,ret
#==============================================================================
ice.point_doubling.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # upub,ret
#==============================================================================
ice.privatekey_to_coinaddress.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_bool, ctypes.c_char_p] # intcoin,012,comp,pvk
ice.privatekey_to_coinaddress.restype = ctypes.c_void_p
#==============================================================================
ice.pubkey_to_coinaddress.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_bool, ctypes.c_char_p] # intcoin,012,comp,upub
ice.pubkey_to_coinaddress.restype = ctypes.c_void_p
#==============================================================================
ice.privatekey_to_address.argtypes = [ctypes.c_int, ctypes.c_bool, ctypes.c_char_p] # 012,comp,pvk
ice.privatekey_to_address.restype = ctypes.c_void_p
#==============================================================================
ice.pubkey_to_p2wsh_address.argtypes = [ctypes.c_char_p] # upub
ice.pubkey_to_p2wsh_address.restype = ctypes.c_void_p
#==============================================================================
ice.hash_to_address.argtypes = [ctypes.c_int, ctypes.c_bool, ctypes.c_char_p] # 012,comp,hash
ice.hash_to_address.restype = ctypes.c_void_p
#==============================================================================
ice.pubkey_to_address.argtypes = [ctypes.c_int, ctypes.c_bool, ctypes.c_char_p] # 012,comp,upub
ice.pubkey_to_address.restype = ctypes.c_void_p
#==============================================================================
ice.privatekey_to_h160.argtypes = [ctypes.c_int, ctypes.c_bool, ctypes.c_char_p, ctypes.c_char_p] # 012,comp,pvk,ret
#==============================================================================
ice.privatekey_loop_h160.argtypes = [ctypes.c_ulonglong, ctypes.c_int, ctypes.c_bool, ctypes.c_char_p, ctypes.c_char_p] # num,012,comp,pvk,ret
#==============================================================================
ice.privatekey_loop_h160_sse.argtypes = [ctypes.c_ulonglong, ctypes.c_int, ctypes.c_bool, ctypes.c_char_p, ctypes.c_char_p] # num,012,comp,pvk,ret
#==============================================================================
ice.pubkey_to_h160.argtypes = [ctypes.c_int, ctypes.c_bool, ctypes.c_char_p, ctypes.c_char_p] # 012,comp,upub,ret
#==============================================================================
ice.pbkdf2_hmac_sha512_dll.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] # ret, words, len
#==============================================================================
ice.pbkdf2_hmac_sha512_list.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_int, ctypes.c_ulonglong] # ret,words,len,mnem_size,total
#==============================================================================
ice.pub_endo1.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # upub,ret
#==============================================================================
ice.pub_endo2.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # upub,ret
#==============================================================================
ice.pubkey_isvalid.argtypes = [ctypes.c_char_p] #upub
ice.pubkey_isvalid.restype = ctypes.c_bool #True or False
#==============================================================================
ice.b58_encode.argtypes = [ctypes.c_char_p] # _h
ice.b58_encode.restype = ctypes.c_void_p
#==============================================================================
ice.b58_decode.argtypes = [ctypes.c_char_p] # addr
ice.b58_decode.restype = ctypes.c_void_p
#==============================================================================
ice.bech32_address_decode.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p] # coin,b32_addr,h160
#==============================================================================
ice.get_hmac_sha512.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # k, klen, mess, mess_len, ret
#==============================================================================
ice.get_sha512.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # input, len, ret
#==============================================================================
ice.rmd160.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # input, len, ret
#==============================================================================
ice.hash160.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # input, len, ret
#==============================================================================
ice.mnem_to_masternode.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] # words, len, ret
#==============================================================================
ice.create_valid_mnemonics.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] # rbytes,len, lang
ice.create_valid_mnemonics.restype = ctypes.c_void_p
#==============================================================================
ice.get_sha256.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p] # input, len, ret
#==============================================================================
ice.get_sha256_iter.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_ulonglong] # input, len, ret, iter
#==============================================================================
ice.create_baby_table.argtypes = [ctypes.c_ulonglong, ctypes.c_ulonglong, ctypes.c_char_p] # start,end,ret
#==============================================================================
ice.point_addition.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] # upub1,upub2,ret
#==============================================================================
ice.point_subtraction.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] # upub1,upub2,ret
#==============================================================================
ice.point_loop_subtraction.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] # k,upub1,upub2,ret
#==============================================================================
ice.point_loop_addition.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] # k,upub1,upub2,ret
#==============================================================================
ice.point_vector_addition.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] # num,upubs1,upubs2,ret
#==============================================================================
ice.point_sequential_increment_P2.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_char_p] # num,upub1,ret
#==============================================================================
ice.point_sequential_increment_P2_mcpu.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # num,upub1,mcpu,ret
#==============================================================================
ice.point_sequential_increment_P2X_mcpu.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # num,upub1,mcpu,retX
#==============================================================================
ice.point_sequential_increment.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_char_p] # num,upub1,ret
#==============================================================================
ice.point_sequential_decrement.argtypes = [ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_char_p] # num,upub1,ret
#==============================================================================
ice.pubkeyxy_to_ETH_address.argtypes = [ctypes.c_char_p] # upub_xy
ice.pubkeyxy_to_ETH_address.restype = ctypes.c_void_p
#==============================================================================
ice.pubkeyxy_to_ETH_address_bytes.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # upub_xy, ret
#==============================================================================
ice.privatekey_to_ETH_address.argtypes = [ctypes.c_char_p] # pvk
ice.privatekey_to_ETH_address.restype = ctypes.c_void_p
#==============================================================================
ice.privatekey_to_ETH_address_bytes.argtypes = [ctypes.c_char_p, ctypes.c_char_p] # pvk, ret
#==============================================================================
ice.privatekey_group_to_ETH_address.argtypes = [ctypes.c_char_p, ctypes.c_int] # pvk, m
ice.privatekey_group_to_ETH_address.restype = ctypes.c_void_p
#==============================================================================
ice.privatekey_group_to_ETH_address_bytes.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] # pvk,m,ret
#==============================================================================
ice.init_P2_Group.argtypes = [ctypes.c_char_p] # upub
#==============================================================================
ice.free_memory.argtypes = [ctypes.c_void_p] # pointer
#==============================================================================
ice.bloom_check_add.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong, ctypes.c_ubyte, ctypes.c_char_p] #buff, len, 0_1, _bits, _hashes, _bf
ice.bloom_check_add.restype = ctypes.c_int
#==============================================================================
ice.bloom_batch_add.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong, ctypes.c_ubyte, ctypes.c_char_p] #chunk, buff, len, 0_1, _bits, _hashes, _bf
#==============================================================================
ice.bloom_check_add_mcpu.argtypes = [ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong, ctypes.c_ubyte, ctypes.c_char_p] #buff, num_items, found_array, len, mcpu, 0_1, _bits, _hashes, _bf
#==============================================================================
ice.test_bit_set_bit.argtypes = [ctypes.c_char_p, ctypes.c_ulonglong, ctypes.c_int] #_bf, _bits, 0_1
#==============================================================================
ice.create_bsgs_bloom_mcpu.argtypes = [ctypes.c_int, ctypes.c_ulonglong, ctypes.c_ulonglong, ctypes.c_ubyte, ctypes.c_char_p] #mcpu, num_items, _bits, _hashes, _bf
#==============================================================================
ice.bsgs_2nd_check_prepare.argtypes = [ctypes.c_ulonglong] # bP_elem
#==============================================================================
ice.dump_bsgs_state.argtypes = [ctypes.c_char_p, ctypes.c_bool] # binary_dump_file_out, verbose
#==============================================================================
ice.load_bsgs_state.argtypes = [ctypes.c_char_p, ctypes.c_bool] # binary_dump_file_in, verbose
#==============================================================================
ice.bsgs_2nd_check.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] # upub, z1, bP_elem, ret
ice.bsgs_2nd_check.restype = ctypes.c_bool #True or False
#==============================================================================
ice.Load_data_to_memory.argtypes = [ctypes.c_char_p, ctypes.c_bool] #sorted_bin_file_h160, verbose
#==============================================================================
ice.check_collision.argtypes = [ctypes.c_char_p] #h160
ice.check_collision.restype = ctypes.c_bool #True or False
#==============================================================================
ice.check_collision_mcpu.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_char_p] #h160_array, num_items, mcpu, found_array
#==============================================================================
ice.xor_filter_add.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_uint64, ctypes.c_uint8, ctypes.c_char_p] #buff, len, _bits, _hashes, _xf
#==============================================================================
ice.xor_filter_check.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_uint64, ctypes.c_uint8, ctypes.c_char_p] #buff, len, _bits, _hashes, _xf
ice.xor_filter_check.restype = ctypes.c_int
#==============================================================================
ice.xor_filter_check_mcpu.argtypes = [ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_int, ctypes.c_int, ctypes.c_uint64, ctypes.c_uint8, ctypes.c_char_p, ctypes.c_char_p] #buff, num_items, len, mcpu, _bits, _hashes, _xf, found_array
#==============================================================================
ice.bsgs_xor_create_mcpu.argtypes = [ctypes.c_int, ctypes.c_ulonglong, ctypes.c_uint64, ctypes.c_uint8, ctypes.c_char_p] #mcpu, total_entries, _bits, _hashes, _xf
ice.init_secp256_lib()
#==============================================================================
###############################################################################
# For Operator Overloading Purpose. Like P + Q, Q * 20, P / 5 etc etc.
class UpubData:
def __init__(self, data):
if len(data) != 65:
raise ValueError("Data must be 65 bytes")
self.data = data
def __add__(self, other):
if not isinstance(other, UpubData):
return NotImplemented
return UpubData(point_addition(self.data, other.data))
def __sub__(self, other):
if not isinstance(other, UpubData):
return NotImplemented
return UpubData(point_subtraction(self.data, other.data))
def __neg__(self):
return UpubData(point_negation(self.data))
def __mul__(self, other):
if isinstance(other, int):
return UpubData(point_multiplication(self.data, other))
return NotImplemented
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
if isinstance(other, int):
return UpubData(point_division(self.data, other))
return NotImplemented
def to_bytes(self):
return self.data
def __repr__(self):
return f"UpubData({self.data})"
def __str__(self):
return f"{self.data.hex()}"
def upub(data):
if isinstance(data, UpubData):
return data
return UpubData(data)
# Example. Q = (((P * 160 )-P) /77).to_bytes()
###############################################################################
#==============================================================================
def version():
ice.version()
#==============================================================================
def _scalar_multiplication(pvk_int):
''' Integer value passed to function. 65 bytes uncompressed pubkey output '''
res = (b'\x00') * 65
pass_int_value = fl(pvk_int).encode('utf8')
ice.scalar_multiplication(pass_int_value, res)
return res
def scalar_multiplication(pvk_int):
if pvk_int < 0: pvk_int = N+pvk_int
res = _scalar_multiplication(pvk_int)
return bytes(bytearray(res))
#==============================================================================
def _scalar_multiplications(pvk_int_list):
''' Integer list passed to function. 65*len bytes uncompressed pubkey output. No Zero Point handling '''
sz = len(pvk_int_list)
res = (b'\x00') * (65 * sz)
pvks = b''.join(pvk_int_list)
ice.scalar_multiplications(pvks, sz, res)
return res
def scalar_multiplications(pvk_int_list):
pvk_int_list = [bytes.fromhex(fl(N+i)) if i < 0 else bytes.fromhex(fl(i)) for i in pvk_int_list]
res = _scalar_multiplications(pvk_int_list)
return bytes(bytearray(res))
#==============================================================================
# =============================================================================
# def point_multiplication(k, P):
# ''' k=scalar. P = Input Point. Output is 65 bytes uncompressed pubkey '''
# if type(P) == int: k,P = P,k
# def bits(k):
# while k:
# yield k & 1
# k >>= 1
# result = Zero
# addend = P
# for bit in bits(k):
# if bit == 1: result=point_addition(result,addend)
# addend=point_doubling(addend)
# return result
# =============================================================================
#==============================================================================
def _point_multiplication(pubkey_bytes, kk):
''' Input Point and Integer value passed to function. 65 bytes uncompressed pubkey output '''
res = (b'\x00') * 65
bytes_value = bytes.fromhex(hex(kk)[2:].zfill(64)) # strict 32 bytes scalar
ice.point_multiplication(pubkey_bytes, bytes_value, res)
return res
def point_multiplication(P, k):
if type(P) == int: k,P = P,k
res = _point_multiplication(P, k)
return bytes(bytearray(res))
#==============================================================================
def point_division(P, k):
''' Input Point and Integer value passed to function. 65 bytes uncompressed pubkey output '''
kk = inv(k)
res = point_multiplication(P, kk)
return bytes(bytearray(res))
#==============================================================================
def _get_x_to_y(x_hex, is_even):
''' Input x_hex encoded as bytes and bool is_even. 32 bytes y of point output '''
res = (b'\x00') * 32
ice.get_x_to_y(x_hex.encode('utf8'), is_even, res)
return res
def get_x_to_y(x_hex, is_even):
res = _get_x_to_y(x_hex, is_even)
return bytes(bytearray(res))
#==============================================================================
def _point_increment(pubkey_bytes):
res = (b'\x00') * 65
ice.point_increment(pubkey_bytes, res)
return res
def point_increment(pubkey_bytes):
res = _point_increment(pubkey_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_negation(pubkey_bytes):
res = (b'\x00') * 65
ice.point_negation(pubkey_bytes, res)
return res
def point_negation(pubkey_bytes):
res = _point_negation(pubkey_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_doubling(pubkey_bytes):
res = (b'\x00') * 65
ice.point_doubling(pubkey_bytes, res)
return res
def point_doubling(pubkey_bytes):
res = _point_doubling(pubkey_bytes)
return bytes(bytearray(res))
#==============================================================================
def init_P2_Group(pubkey_bytes):
ice.init_P2_Group(pubkey_bytes)
#==============================================================================
def privatekey_to_coinaddress(coin_type, addr_type, iscompressed, pvk_int):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
if pvk_int < 0: pvk_int = N+pvk_int
pass_int_value = fl(pvk_int).encode('utf8')
res = ice.privatekey_to_coinaddress(coin_type, addr_type, iscompressed, pass_int_value)
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def pubkey_to_coinaddress(coin_type, addr_type, iscompressed, pubkey_bytes):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
res = ice.pubkey_to_coinaddress(coin_type, addr_type, iscompressed, pubkey_bytes)
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def privatekey_to_address(addr_type, iscompressed, pvk_int):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
if pvk_int < 0: pvk_int = N+pvk_int
pass_int_value = fl(pvk_int).encode('utf8')
res = ice.privatekey_to_address(addr_type, iscompressed, pass_int_value)
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def hash_to_address(addr_type, iscompressed, hash160_bytes):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
res = ice.hash_to_address(addr_type, iscompressed, hash160_bytes)
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def pubkey_to_address(addr_type, iscompressed, pubkey_bytes):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
res = ice.pubkey_to_address(addr_type, iscompressed, pubkey_bytes)
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def pubkey_to_p2wsh_address(pubkey_bytes):
# [bech32 p2wsh]
res = ice.pubkey_to_p2wsh_address(pubkey_bytes)
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def _privatekey_to_h160(addr_type, iscompressed, pvk_int):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
if pvk_int < 0: pvk_int = N+pvk_int
pass_int_value = fl(pvk_int).encode('utf8')
res = (b'\x00') * 20
ice.privatekey_to_h160(addr_type, iscompressed, pass_int_value, res)
return res
def privatekey_to_h160(addr_type, iscompressed, pvk_int):
res = _privatekey_to_h160(addr_type, iscompressed, pvk_int)
return bytes(bytearray(res))
#==============================================================================
def _privatekey_loop_h160(num, addr_type, iscompressed, pvk_int):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
if pvk_int < 0: pvk_int = N+pvk_int
pass_int_value = fl(pvk_int).encode('utf8')
res = (b'\x00') * (20 * num)
ice.privatekey_loop_h160(num, addr_type, iscompressed, pass_int_value, res)
return res
def privatekey_loop_h160(num, addr_type, iscompressed, pvk_int):
if num <= 0: num = 1
res = _privatekey_loop_h160(num, addr_type, iscompressed, pvk_int)
return bytes(bytearray(res))
#==============================================================================
def _privatekey_loop_h160_sse(num, addr_type, iscompressed, pvk_int):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
if pvk_int < 0: pvk_int = N+pvk_int
pass_int_value = fl(pvk_int).encode('utf8')
res = (b'\x00') * (20 * num)
ice.privatekey_loop_h160_sse(num, addr_type, iscompressed, pass_int_value, res)
return res
def privatekey_loop_h160_sse(num, addr_type, iscompressed, pvk_int):
if num <= 0: num = 1
res = _privatekey_loop_h160_sse(num, addr_type, iscompressed, pvk_int)
return bytes(bytearray(res))
#==============================================================================
def _pubkey_to_h160(addr_type, iscompressed, pubkey_bytes):
# type = 0 [p2pkh], 1 [p2sh], 2 [bech32]
res = (b'\x00') * 20
ice.pubkey_to_h160(addr_type, iscompressed, pubkey_bytes, res)
return res
def pubkey_to_h160(addr_type, iscompressed, pubkey_bytes):
res = _pubkey_to_h160(addr_type, iscompressed, pubkey_bytes)
return bytes(bytearray(res))
#==============================================================================
def _pub_endo1(pubkey_bytes):
res = (b'\x00') * 65
ice.pub_endo1(pubkey_bytes, res)
return res
def pub_endo1(pubkey_bytes):
res = _pub_endo1(pubkey_bytes)
return bytes(bytearray(res))
#==============================================================================
def _pub_endo2(pubkey_bytes):
res = (b'\x00') * 65
ice.pub_endo2(pubkey_bytes, res)
return res
def pub_endo2(pubkey_bytes):
res = _pub_endo2(pubkey_bytes)
return bytes(bytearray(res))
#==============================================================================
def pubkey_isvalid(pubkey_bytes):
''' check if the pubkey is on the curve '''
is_valid = ice.pubkey_isvalid(pubkey_bytes)
return is_valid
#==============================================================================
def one_to_6pubkey(pubkey_bytes):
# Pubkey = [x,y] [x*beta%p, y] [x*beta2%p, y] [x,p-y] [x*beta%p, p-y] [x*beta2%p, p-y]
# beta = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee
# beta2 = 0x851695d49a83f8ef919bb86153cbcb16630fb68aed0a766a3ec693d68e6afa40 # beta*beta
P1 = pubkey_bytes
P2 = pub_endo1(pubkey_bytes)
P3 = pub_endo2(pubkey_bytes)
P4 = point_negation(pubkey_bytes)
P5 = pub_endo1(P4)
P6 = pub_endo2(P4)
return P1, P2, P3, P4, P5, P6
#==============================================================================
def one_to_6privatekey(pvk_int):
lmda = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72
lmda2 = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283ce # lmda*lmda
#print('PVK1 : ', hex(pvk_int)[2:].zfill(64))
#print('PVK2 : ', hex(pvk_int*lmda%N)[2:].zfill(64))
#print('PVK3 : ', hex(pvk_int*lmda2%N)[2:].zfill(64))
#print('PVK4 : ', hex(N-pvk_int)[2:].zfill(64))
#print('PVK5 : ', hex(N-pvk_int*lmda%N)[2:].zfill(64))
#print('PVK6 : ', hex(N-pvk_int*lmda2%N)[2:].zfill(64))
return pvk_int, pvk_int*lmda%N, pvk_int*lmda2%N, N-pvk_int, N-pvk_int*lmda%N, N-pvk_int*lmda2%N
#==============================================================================
def b58py(data):
B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
if data[0] == 0:
return "1" + b58py(data[1:])
x = sum([v * (256 ** i) for i, v in enumerate(data[::-1])])
ret = ""
while x > 0:
ret = B58[x % 58] + ret
x = x // 58
return ret
#==============================================================================
def b58_encode(inp_bytes):
res = ice.b58_encode(inp_bytes, len(inp_bytes))
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def b58_decode(inp):
res = ice.b58_decode(inp.encode("utf-8"))
addr = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return addr
#==============================================================================
def bech32_address_decode(addr, coin_type=0):
''' Input address in String format. Output h160 in hex string format
[Note] p2wsh = bech32(sha256(21 + pubkey + ac)). So Decoding it not Needed '''
if len(addr) > 50:
h160 = (b'\x00') * 32 # Bech32 p2wsh case
else: h160 = (b'\x00') * 20 # Bech32 p2wpkh case
ice.bech32_address_decode(coin_type, addr.encode("utf-8"), h160)
return bytes(bytearray(h160)).hex()
#==============================================================================
def address_to_h160(p2pkh):
''' Input address in String format. Output h160 in hex string format'''
h1 = b58_decode(p2pkh)
return h1[2:-8]
#==============================================================================
def create_burn_address(vanity = 'iceLand', filler = 'x'):
# create_burn_address('ADayWiLLcomeWheniceLandisGoingToSoLvebitCoinPuzzLe', 'X')
out = []
bs58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
for i in vanity:
if i not in bs58:
return "invalid char found in vanity --> : " + i
vanity = [vanity[i:i+25] for i in range(0,len(vanity),25)] # For longer text make many address
for t in vanity:
s = t.ljust(30, filler) if t[0] == '1' else ('1'+t).ljust(30, filler) + '111'
h = address_to_h160(s)
out.append(hash_to_address(0, True, bytes.fromhex(h)))
if len(out) == 1: return out[0]
else: return out
#==============================================================================
def btc_wif_to_pvk_hex(wif):
pvk = ''
if wif[0] == '5':
pvk = b58_decode(wif)[2:-8]
elif wif[0] in ['L', 'K']:
pvk = b58_decode(wif)[2:-10]
else: print('[Error] Incorrect WIF Key')
return pvk
#==============================================================================
def btc_wif_to_pvk_int(wif):
pvk = ''
pvk_hex = btc_wif_to_pvk_hex(wif)
if pvk_hex != '': pvk = int(pvk_hex, 16)
return pvk
#==============================================================================
def btc_pvk_to_wif(pvk, is_compressed=True):
''' Input Privatekey can in any 1 of these [Integer] [Hex] [Bytes] form'''
inp = ''
suff = '01' if is_compressed == True else ''
if type(pvk) in [int, str]: inp = bytes.fromhex('80' + fl(pvk) + suff)
elif type(pvk) == bytes: inp = b'\x80' + fl(pvk) + bytes.fromhex(suff)
else: print("[Error] Input Privatekey format [Integer] [Hex] [Bytes] allowed only")
if inp != '':
res = get_sha256(inp)
res2 = get_sha256(res)
return b58_encode(inp + res2[:4])
else: return inp
#==============================================================================
def checksum(inp):
''' Input string output double sha256 checksum 4 bytes'''
res = get_sha256(inp)
res2 = get_sha256(res)
return res2[:4]
#==============================================================================
def chunks(s, sz=65):
for start in range(0, len(s), sz):
yield s[start : start + sz]
#==============================================================================
def inv(a):
return pow(a, N - 2, N)
#==============================================================================
def msg_magic(message):
lm = len(message)
a = ((lm.to_bytes(1, 'little') if lm < 0xFD else b'\xFD' + lm.to_bytes(2, 'little'))
if lm <= 0xFFFF else b'\xFE' + lm.to_bytes(4, 'little')) if lm <=0xFFFFFFFF else b'\xFF' + lm.to_bytes(8, 'little')
return b'\x18Bitcoin Signed Message:\n' + a + message.encode('utf-8')
#==============================================================================
def verify_message(address, signature, message):
out = _verify_message(address, signature, message)
if out == False:
print(f"Message Failed to verify from Address: {address}")
else:
r, s, z, is_compress, RP, pubkey = out
print(f'Rpoint: {RP.hex()}')
print(f'r : {hex(r)[2:]}')
print(f's : {hex(s)[2:]}')
print(f'z : {hex(z)[2:]}')
print(f'PubKey : {pubkey}')
print(f'Address : {address}')
print('\nsignature is Valid and Address is Verified.\n')
print('-----BEGIN BITCOIN SIGNED MESSAGE-----')
print(message)
print('-----BEGIN BITCOIN SIGNATURE-----')
print(address)
print(signature)
print('-----END BITCOIN SIGNATURE-----')
#==============================================================================
def _verify_message(address, signature, message):
""" See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
sig = base64.b64decode(signature)
_, r, s = sig[0], int.from_bytes(sig[1:33], 'big'), int.from_bytes(sig[33:], 'big')
msb = msg_magic(message)
z = int.from_bytes(get_sha256(get_sha256(msb)), 'big')
RP1 = pub2upub('02' + hex(r)[2:].zfill(64))
RP2 = pub2upub('03' + hex(r)[2:].zfill(64))
sdr = (s * inv(r)) % N
zdr = (z * inv(r)) % N
FF1 = point_subtraction( point_multiplication(RP1, sdr),
scalar_multiplication(zdr) )
FF2 = point_subtraction( point_multiplication(RP2, sdr),
scalar_multiplication(zdr) )
if address[0] == '1': #p2pkh compressed or uncompressed
if address == pubkey_to_address(0, True, FF1):
return r, s, z, True, RP1, point_to_cpub(FF1)
if address == pubkey_to_address(0, False, FF1):
return r, s, z, False, RP1, FF1.hex()[2:]
if address[0] == '3': #p2sh compressed
if address == pubkey_to_address(1, True, FF1):
return r, s, z, True, RP1, point_to_cpub(FF1)
if address[0] == 'b': #bech32 compressed
if address == pubkey_to_address(2, True, FF1):
return r, s, z, True, RP1, point_to_cpub(FF1)
if address[0] == '1': #p2pkh compressed or uncompressed
if address == pubkey_to_address(0, True, FF2):
return r, s, z, True, RP2, point_to_cpub(FF2)
if address == pubkey_to_address(0, False, FF2):
return r, s, z, False, RP2, FF2.hex()[2:]
if address[0] == '3': #p2sh compressed
if address == pubkey_to_address(1, True, FF2):
return r, s, z, True, RP2, point_to_cpub(FF2)
if address[0] == 'b': #bech32 compressed
if address == pubkey_to_address(2, True, FF2):
return r, s, z, True, RP2, point_to_cpub(FF2)
return False
#==============================================================================
def fl(sstr, length=64):
''' Fill input to exact 32 bytes. If input is int or str the return is str. if input is bytes return is bytes'''
if type(sstr) == int: fixed = hex(sstr%N)[2:].zfill(length)
elif type(sstr) == str: fixed = sstr[2:].zfill(length) if sstr[:2].lower() == '0x' else sstr.zfill(length)
elif type(sstr) == bytes: fixed = (b'\x00') * (32 - len(sstr)) + sstr
else: print("[Error] Input format [Integer] [Hex] [Bytes] allowed only. Detected : ", type(sstr))
return fixed
#==============================================================================
def create_valid_mnemonics(strength = 128, lang = MNEM_EN):
# valid_entropy_bits = [128, 160, 192, 224, 256]
if strength not in [128, 160, 192, 224, 256]:
return 'Invalid strength'
rbytes = os.urandom(strength // 8)
res = ice.create_valid_mnemonics(rbytes, len(rbytes), lang)
mnem = (ctypes.cast(res, ctypes.c_char_p).value).decode('utf8')
ice.free_memory(res)
return mnem
#==============================================================================
def pbkdf2_hmac_sha512_dll(words):
seed_bytes = (b'\x00') * 64
# words = 'good push broken people salad bar mad squirrel joy dismiss merge jeans token wear boring manual doll near sniff turtle sunset lend invest foil'
ice.pbkdf2_hmac_sha512_dll(seed_bytes, words.encode("utf-8"), len(words))
return bytes(bytearray(seed_bytes))
#==============================================================================
def pbkdf2_hmac_sha512_list(words_list):
''' strength is [12, 18, 24]. words_list is a list of strings with each line having valid mnemonics'''
wl = len(words_list)
strength = len(words_list[0].split())
words = ' '.join(words_list)
seed_bytes = (b'\x00') * (64 * wl)
# words = 'good push broken people salad bar mad squirrel joy dismiss merge jeans token wear boring manual doll near sniff turtle sunset lend invest foil'
ice.pbkdf2_hmac_sha512_list(seed_bytes, words.encode("utf-8"), len(words), strength, wl)
return bytes(bytearray(seed_bytes))
#==============================================================================
def mnemonics_to_bip32masternode(words):
digest_bytes = (b'\x00') * 64
ice.mnem_to_masternode(words.encode("utf-8"), len(words), digest_bytes)
key, chain_code = digest_bytes[:32], digest_bytes[32:]
return key, chain_code
#==============================================================================
def bip39seed_to_bip32masternode(seed):
h = hmac_sha512(b'Bitcoin seed', seed)
key, chain_code = h[:32], h[32:]
return key, chain_code
#==============================================================================
def _p2i(x = "44'"):
if "'" in x: return 0x80000000 + int(x[:-1])
else: return int(x)
def _parse_derivation_path(str_derivation_path="m/44'/60'/0'/0/0"): # 60' is for ETH 0' is for BTC
path = []
sdp = str_derivation_path.replace(" ", "")
if sdp[0:2] != 'm/':
raise ValueError("Can't recognize derivation path. It should look like \"m/44'/0'/0'/0\".")
for i in sdp.lstrip('m/').split('/'):
path.append(_p2i(i))
return [path] # return a list of list
def parse_derivation_path(str_derivation_path_range="m/44'/60'/0'/0/(0-5)"): # 60' is for ETH 0' is for BTC
if str_derivation_path_range.count("(") == 0: # No range, only single value
return _parse_derivation_path(str_derivation_path_range)
def deplist(i = "(0-3)"):
if i[0] == '(': # It is a range of values
flgh = False
if i[-1] == "'":
flgh = True
dr = [int(x) for x in i.lstrip('(').rstrip(")'").split('-')]
else:
dr = [int(x) for x in i.lstrip('(').rstrip(')').split('-')]
return [str(i)+"'" if flgh else str(i) for i in range(dr[0], dr[1]+1)] # +1 to include the last element
sdp = str_derivation_path_range.replace(" ", "")
og = sdp.lstrip('m/').split('/')
path = [_p2i(x) for x in og[:-1]] # Leaving last element of range childpath
return path, deplist( og[-1] ) # A tuple of (first 4 values and list for last value range)
#==============================================================================
def derive_bip32childkey(parent_key, parent_chain_code, i):
assert len(parent_key) == 32
assert len(parent_chain_code) == 32
k = parent_chain_code
if (i & 0x80000000) != 0:
key = b'\x00' + parent_key
else:
key = bytes.fromhex(point_to_cpub(scalar_multiplication(int.from_bytes(parent_key, byteorder='big'))))
d = key + bytes.fromhex(hex(i)[2:].zfill(8))
while True:
h = hmac_sha512(k, d)
key, chain_code = h[:32], h[32:]
a = int.from_bytes(key, byteorder='big')
b = int.from_bytes(parent_key, byteorder='big')
key = (a + b) % N
if a < N and key != 0:
key = key.to_bytes(32, byteorder='big')
break
d = b'\x01' + h[32:] + bytes.fromhex(hex(i)[2:].zfill(8))
return key, chain_code
#==============================================================================
def bip39seed_to_privatekey(bip39seed, str_derivation_path = "m/44'/0'/0'/0/0"): # ' is Hardened otherwise Normal
# suports single "m/44'/0'/0'/0/0" and range of child "m/44'/0'/0'/0/(11-21)"
derivation_path = parse_derivation_path(str_derivation_path)
master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed)
private_key, chain_code = master_private_key, master_chain_code
for i in derivation_path[0]: # All values for single case. In case of range Except last element.
# parent_fingerprint = fingerprint_from_pvk(int(private_key.hex(), 16))
# child_number_bytes = bytes.fromhex(hex(i)[2:])
# depth_byte : starts from 1 2 3 4 5
private_key, chain_code = derive_bip32childkey(private_key, chain_code, i)
if len(derivation_path) == 2: # check if range case
pvklist = []
for i in derivation_path[1]:
# parent_fingerprint = fingerprint_from_pvk(int(private_key.hex(), 16))
# child_number_bytes = bytes.fromhex(hex(i)[2:])
# depth_byte = b'\05' # this one is Last
tpvk, _ = derive_bip32childkey(private_key, chain_code, _p2i(i))
pvklist.append(tpvk)
return pvklist # list of bytes
return private_key # bytes
#==============================================================================
def mnem_to_privatekey(words, str_derivation_path = "m/44'/0'/0'/0/0"): # ' is Hardened otherwise Normal
# suports single "m/44'/0'/0'/0/0" and range of child "m/44'/0'/0'/0/(11-21)"
seed = pbkdf2_hmac_sha512_dll(words)
return bip39seed_to_privatekey(seed, str_derivation_path) # either bytes or list of bytes
#==============================================================================
def mnem_to_address(words, addr_type, iscompressed, str_derivation_path = "m/44'/0'/0'/0/0"): # ' is Hardened otherwise Normal
# suports single "m/44'/0'/0'/0/0" and range of child "m/44'/0'/0'/0/(11-21)"
seed = pbkdf2_hmac_sha512_dll(words)
pvks = bip39seed_to_privatekey(seed, str_derivation_path) # either bytes or list of bytes
if type(pvks) == list:
return [privatekey_to_address(addr_type, iscompressed, int(line.hex(), 16)) for line in pvks] # list of addresses
return privatekey_to_address(addr_type, iscompressed, int(pvks.hex(), 16)) # single address
#==============================================================================
def fingerprint_from_pvk(k): # input int key
return privatekey_to_h160(0, True, k)[:4]
#==============================================================================
def root_key(master_private_key, master_chain_code, version = '0488ade4'):
'''This same function can be modified for getting xprv, xpub of extended keys.
Need to return also the parent_fingerprint, child_number_bytes, depth_byte to use here
'''
version_bytes = bytes.fromhex(version) # Mainnet [Private: '0488ade4'] [Public: '0488b21e']
key_bytes = b'\x00' + master_private_key
# version_bytes, depth_byte, parent_fingerprint, child_number_bytes, master_chain_code, key_bytes
inp = version_bytes + b'\x00' + b'\x00' * 4 + b'\x00' * 4 + master_chain_code + key_bytes
xp = b58_encode(inp + checksum(inp))
return xp
#==============================================================================
def hmac_sha512(key_bytes, message_bytes):
digest_bytes = (b'\x00') * 64
if type(key_bytes) == str: key_bytes = key_bytes.encode("utf-8")
if type(message_bytes) == str: message_bytes = message_bytes.encode("utf-8")
ice.get_hmac_sha512(key_bytes, len(key_bytes), message_bytes, len(message_bytes), digest_bytes)
return bytes(bytearray(digest_bytes))
#==============================================================================
def sha512(input_bytes):
digest_bytes = (b'\x00') * 64
if type(input_bytes) == str: input_bytes = input_bytes.encode("utf-8")
ice.get_sha512(input_bytes, len(input_bytes), digest_bytes)
return bytes(bytearray(digest_bytes))
#==============================================================================
def hash160(input_bytes):
digest_bytes = (b'\x00') * 20
if type(input_bytes) == str: input_bytes = input_bytes.encode("utf-8")
ice.hash160(input_bytes, len(input_bytes), digest_bytes)
return bytes(bytearray(digest_bytes))
#==============================================================================
def rmd160(input_bytes):
digest_bytes = (b'\x00') * 20
ice.rmd160(input_bytes, len(input_bytes), digest_bytes)
return bytes(bytearray(digest_bytes))
#==============================================================================
def get_sha256(input_bytes):
digest_bytes = (b'\x00') * 32
if type(input_bytes) == str: input_bytes = input_bytes.encode("utf-8")
# MiniKey example
ice.get_sha256(input_bytes, len(input_bytes), digest_bytes)
return bytes(bytearray(digest_bytes))
#==============================================================================
def get_sha256_iter(input_bytes, iteration = 1):
digest_bytes = (b'\x00') * 32
if type(input_bytes) == str: input_bytes = input_bytes.encode("utf-8")
ice.get_sha256_iter(input_bytes, len(input_bytes), digest_bytes, iteration)
return bytes(bytearray(digest_bytes))
#==============================================================================
def create_baby_table(start_value, end_value):
res = (b'\x00') * ((1+end_value-start_value) * 32)
ice.create_baby_table(start_value, end_value, res)
return bytes(bytearray(res))
#==============================================================================
def _point_addition(pubkey1_bytes, pubkey2_bytes):
res = (b'\x00') * 65
ice.point_addition(pubkey1_bytes, pubkey2_bytes, res)
return res
def point_addition(pubkey1_bytes, pubkey2_bytes):
res = _point_addition(pubkey1_bytes, pubkey2_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_subtraction(pubkey1_bytes, pubkey2_bytes):
res = (b'\x00') * 65
ice.point_subtraction(pubkey1_bytes, pubkey2_bytes, res)
return res
def point_subtraction(pubkey1_bytes, pubkey2_bytes):
res = _point_subtraction(pubkey1_bytes, pubkey2_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_loop_subtraction(num, pubkey1_bytes, pubkey2_bytes):
res = (b'\x00') * (65 * num)
ice.point_loop_subtraction(num, pubkey1_bytes, pubkey2_bytes, res)
return res
def point_loop_subtraction(num, pubkey1_bytes, pubkey2_bytes):
''' Continuously subtracting point2 into point1 in a loop of num times.
Output is array of pubkeys P1-P2, P1-2P2, P1-3P2, P1-4P2....'''
if num <= 0: num = 1
res = _point_loop_subtraction(num, pubkey1_bytes, pubkey2_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_loop_addition(num, pubkey1_bytes, pubkey2_bytes):
res = (b'\x00') * (65 * num)
ice.point_loop_addition(num, pubkey1_bytes, pubkey2_bytes, res)
return res
def point_loop_addition(num, pubkey1_bytes, pubkey2_bytes):
''' Continuously adding point2 into point1 in a loop of num times.
Output is array of pubkeys P1+P2, P1+2P2, P1+3P2, P1+4P2....'''
if num <= 0: num = 1
res = _point_loop_addition(num, pubkey1_bytes, pubkey2_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_vector_addition(num, pubkeys1_bytes, pubkeys2_bytes):
res = (b'\x00') * (65 * num)
ice.point_vector_addition(num, pubkeys1_bytes, pubkeys2_bytes, res)
return res
def point_vector_addition(num, pubkeys1_bytes, pubkeys2_bytes):
''' Adding two array of points of equal length. '''
if num <= 0: num = 1
res = _point_vector_addition(num, pubkeys1_bytes, pubkeys2_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_sequential_increment_P2(num, pubkey1_bytes):
res = (b'\x00') * (65 * num)
ice.point_sequential_increment_P2(num, pubkey1_bytes, res)
return res
def point_sequential_increment_P2(num, pubkey1_bytes):
''' Use init_P2_Group(P2) to initialize it just once.
This is the fastest implementation to add point P2 in the given Point sequentially.'''
if num <= 0: num = 1
res = _point_sequential_increment_P2(num, pubkey1_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_sequential_increment_P2_mcpu(num, pubkey1_bytes, mcpu):
res = (b'\x00') * (65 * num)
ice.point_sequential_increment_P2_mcpu(num, pubkey1_bytes, mcpu, res)
return res
def point_sequential_increment_P2_mcpu(num, pubkey1_bytes, mcpu=os.cpu_count()):
''' Use init_P2_Group(P2) to initialize it just once.
This is the fastest multi CPU implementation to add point P2 in the given Point sequentially. Threads are Not optimised yet'''
if num <= 0: num = 1
res = _point_sequential_increment_P2_mcpu(num, pubkey1_bytes, mcpu)
return bytes(bytearray(res))
#==============================================================================
def _point_sequential_increment_P2X_mcpu(num, pubkey1_bytes, mcpu):
res = (b'\x00') * (32 * num) # only X is returned from pubkeys
ice.point_sequential_increment_P2X_mcpu(num, pubkey1_bytes, mcpu, res)
return res
def point_sequential_increment_P2X_mcpu(num, pubkey1_bytes, mcpu=os.cpu_count()):
''' Use init_P2_Group(P2) to initialize it just once.
This is the fastest multi CPU implementation to add point P2 in the given Point sequentially. Threads are Not optimised yet'''
if num <= 0: num = 1
res = _point_sequential_increment_P2X_mcpu(num, pubkey1_bytes, mcpu)
return bytes(bytearray(res))
#==============================================================================
def _point_sequential_increment(num, pubkey1_bytes):
res = (b'\x00') * (65 * num)
ice.point_sequential_increment(num, pubkey1_bytes, res)
return res
def point_sequential_increment(num, pubkey1_bytes):
''' This is the fastest implementation using G'''
if num <= 0: num = 1
res = _point_sequential_increment(num, pubkey1_bytes)
return bytes(bytearray(res))
#==============================================================================
def _point_sequential_decrement(num, pubkey1_bytes):
res = (b'\x00') * (65 * num)
ice.point_sequential_decrement(num, pubkey1_bytes, res)
return res
def point_sequential_decrement(num, pubkey1_bytes):
''' This is the fastest implementation using -G.'''
if num <= 0: num = 1
res = _point_sequential_decrement(num, pubkey1_bytes)
return bytes(bytearray(res))
#==============================================================================
def pubkey_to_ETH_address(pubkey_bytes):
''' 65 Upub bytes input. Output is 20 bytes ETH address lowercase with 0x as hex string'''
xy = pubkey_bytes[1:]