-
Notifications
You must be signed in to change notification settings - Fork 2
/
crypto.py
1651 lines (1306 loc) · 54.5 KB
/
crypto.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
"""This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import math
import base58
import base64
import hashlib
import hmac
import bech32_addr
# from eth_keys import keys
from client_sdk_python.packages.platon_keys import keys
from mnemonic.mnemonic import Mnemonic
import random
from two1.bitcoin.utils import bytes_to_str
from two1.bitcoin.utils import address_to_key_hash
from two1.bitcoin.utils import rand_bytes
from two1.crypto.ecdsa_base import Point
from two1.crypto.ecdsa import ECPointAffine
from two1.crypto.ecdsa import secp256k1
from platon_utility import generate_keyfile_json
from client_sdk_python.packages.eth_utils import (
text_if_str,
to_bytes
)
bitcoin_curve = secp256k1()
from Crypto.Hash import keccak
sha3_256 = lambda x: keccak.new(digest_bits=256, data=x)
def sha3(seed):
return sha3_256(seed).digest()
def get_bytes(s):
"""Returns the byte representation of a hex- or byte-string."""
if isinstance(s, bytes):
b = s
elif isinstance(s, str):
b = bytes.fromhex(s)
else:
raise TypeError("s must be either 'bytes' or 'str'!")
return b
class PrivateKeyBase(object):
""" Base class for both PrivateKey and HDPrivateKey.
As this class is a base class it should not be used directly.
Args:
k (int): The private key.
Returns:
PrivateKey: The object representing the private key.
"""
@staticmethod
def from_b58check(private_key):
""" Decodes a Base58Check encoded private-key.
Args:
private_key (str): A Base58Check encoded private key.
Returns:
PrivateKey: A PrivateKey object
"""
raise NotImplementedError
def __init__(self, k):
self.key = k
self._public_key = None
@property
def public_key(self):
""" Returns the public key associated with this private key.
Returns:
PublicKey:
The PublicKey object that corresponds to this
private key.
"""
return self._public_key
def raw_sign(self, message, do_hash=True):
""" Signs message using this private key.
Args:
message (bytes): The message to be signed. If a string is
provided it is assumed the encoding is 'ascii' and
converted to bytes. If this is not the case, it is up
to the caller to convert the string to bytes
appropriately and pass in the bytes.
do_hash (bool): True if the message should be hashed prior
to signing, False if not. This should always be left as
True except in special situations which require doing
the hash outside (e.g. handling Bitcoin bugs).
Returns:
ECPointAffine:
a raw point (r = pt.x, s = pt.y) which is
the signature.
"""
raise NotImplementedError
def sign(self, message, do_hash=True):
""" Signs message using this private key.
Note:
This differs from `raw_sign()` since it returns a
Signature object.
Args:
message (bytes or str): The message to be signed. If a
string is provided it is assumed the encoding is
'ascii' and converted to bytes. If this is not the
case, it is up to the caller to convert the string to
bytes appropriately and pass in the bytes.
do_hash (bool): True if the message should be hashed prior
to signing, False if not. This should always be left as
True except in special situations which require doing
the hash outside (e.g. handling Bitcoin bugs).
Returns:
Signature: The signature corresponding to message.
"""
raise NotImplementedError
def sign_bitcoin(self, message, compressed=False):
""" Signs a message using this private key such that it
is compatible with bitcoind, bx, and other Bitcoin
clients/nodes/utilities.
Note:
0x18 + b\"Bitcoin Signed Message:" + newline + len(message) is
prepended to the message before signing.
Args:
message (bytes or str): Message to be signed.
compressed (bool): True if the corresponding public key will be
used in compressed format. False if the uncompressed version
is used.
Returns:
bytes: A Base64-encoded byte string of the signed message.
The first byte of the encoded message contains information
about how to recover the public key. In bitcoind parlance,
this is the magic number containing the recovery ID and
whether or not the key was compressed or not. (This function
always processes full, uncompressed public-keys, so the magic
number will always be either 27 or 28).
"""
raise NotImplementedError
def to_b58check(self, testnet=False):
""" Generates a Base58Check encoding of this private key.
Returns:
str: A Base58Check encoded string representing the key.
"""
raise NotImplementedError
def to_hex(self):
""" Generates a hex encoding of the serialized key.
Returns:
str: A hex encoded string representing the key.
"""
return bytes_to_str(bytes(self))
def get_private_key(self):
key_bytes = bytes(self)
assert len(key_bytes) == 32
pri = keys.PrivateKey(key_bytes)
return pri.to_hex()
def to_keyfile_json(self, password, hrp_type):
key_bytes = bytes(self)
password_bytes = text_if_str(to_bytes, password)
assert len(key_bytes) == 32
# return create_keyfile_json(key_bytes, password_bytes, kdf='scrypt')
return generate_keyfile_json(password_bytes, key_bytes, hrp_type)
def __bytes__(self):
raise NotImplementedError
def __int__(self):
raise NotImplementedError
class PublicKeyBase(object):
""" Base class for both PublicKey and HDPublicKey.
As this class is a base class it should not be used directly.
Args:
x (int): The x component of the public key point.
y (int): The y component of the public key point.
Returns:
PublicKey: The object representing the public key.
"""
@staticmethod
def from_bytes(key_bytes):
""" Generates a public key object from a byte (or hex) string.
Args:
key_bytes (bytes or str): A byte stream.
Returns:
PublicKey: A PublicKey object.
"""
raise NotImplementedError
@staticmethod
def from_private_key(private_key):
""" Generates a public key object from a PrivateKey object.
Args:
private_key (PrivateKey): The private key object from
which to derive this object.
Returns:
PublicKey: A PublicKey object.
"""
return private_key.public_key
def __init__(self):
pass
def hash160(self, compressed=True):
""" Return the RIPEMD-160 hash of the SHA-256 hash of the
public key.
Args:
compressed (bool): Whether or not the compressed key should
be used.
Returns:
bytes: RIPEMD-160 byte string.
"""
raise NotImplementedError
def address(self, compressed=True, testnet=False):
""" Address property that returns the Base58Check
encoded version of the HASH160.
Args:
compressed (bool): Whether or not the compressed key should
be used.
testnet (bool): Whether or not the key is intended for testnet
usage. False indicates mainnet usage.
Returns:
bytes: Base58Check encoded string
"""
raise NotImplementedError
def verify(self, message, signature, do_hash=True):
""" Verifies that message was appropriately signed.
Args:
message (bytes): The message to be verified.
signature (Signature): A signature object.
do_hash (bool): True if the message should be hashed prior
to signing, False if not. This should always be left as
True except in special situations which require doing
the hash outside (e.g. handling Bitcoin bugs).
Returns:
verified (bool): True if the signature is verified, False
otherwise.
"""
raise NotImplementedError
def to_hex(self):
""" Hex representation of the serialized byte stream.
Returns:
h (str): A hex-encoded string.
"""
return bytes_to_str(bytes(self))
def __bytes__(self):
raise NotImplementedError
def __int__(self):
raise NotImplementedError
@property
def compressed_bytes(self):
""" Byte string corresponding to a compressed representation
of this public key.
Returns:
b (bytes): A 33-byte long byte string.
"""
raise NotImplementedError
class PrivateKey(PrivateKeyBase):
""" Encapsulation of a Bitcoin ECDSA private key.
This class provides capability to generate private keys,
obtain the corresponding public key, sign messages and
serialize/deserialize into a variety of formats.
Args:
k (int): The private key.
Returns:
PrivateKey: The object representing the private key.
"""
TESTNET_VERSION = 0xEF
MAINNET_VERSION = 0x80
@staticmethod
def from_bytes(b):
""" Generates PrivateKey from the underlying bytes.
Args:
b (bytes): A byte stream containing a 256-bit (32-byte) integer.
Returns:
tuple(PrivateKey, bytes): A PrivateKey object and the remainder
of the bytes.
"""
if len(b) < 32:
raise ValueError('b must contain at least 32 bytes')
return PrivateKey(int.from_bytes(b[:32], 'big'))
@staticmethod
def from_hex(h):
""" Generates PrivateKey from a hex-encoded string.
Args:
h (str): A hex-encoded string containing a 256-bit
(32-byte) integer.
Returns:
PrivateKey: A PrivateKey object.
"""
return PrivateKey.from_bytes(bytes.fromhex(h))
@staticmethod
def from_int(i):
""" Initializes a private key from an integer.
Args:
i (int): Integer that is the private key.
Returns:
PrivateKey: The object representing the private key.
"""
return PrivateKey(i)
@staticmethod
def from_b58check(private_key):
""" Decodes a Base58Check encoded private-key.
Args:
private_key (str): A Base58Check encoded private key.
Returns:
PrivateKey: A PrivateKey object
"""
b58dec = base58.b58decode_check(private_key)
version = b58dec[0]
assert version in [PrivateKey.TESTNET_VERSION,
PrivateKey.MAINNET_VERSION]
return PrivateKey(int.from_bytes(b58dec[1:], 'big'))
@staticmethod
def from_random():
""" Initializes a private key from a random integer.
Returns:
PrivateKey: The object representing the private key.
"""
return PrivateKey(random.SystemRandom().randrange(1, bitcoin_curve.n))
def __init__(self, k):
self.key = k
self._public_key = None
@property
def public_key(self):
""" Returns the public key associated with this private key.
Returns:
PublicKey:
The PublicKey object that corresponds to this
private key.
"""
if self._public_key is None:
self._public_key = PublicKey.from_point(
bitcoin_curve.public_key(self.key))
return self._public_key
def raw_sign(self, message, do_hash=True):
""" Signs message using this private key.
Args:
message (bytes): The message to be signed. If a string is
provided it is assumed the encoding is 'ascii' and
converted to bytes. If this is not the case, it is up
to the caller to convert the string to bytes
appropriately and pass in the bytes.
do_hash (bool): True if the message should be hashed prior
to signing, False if not. This should always be left as
True except in special situations which require doing
the hash outside (e.g. handling Bitcoin bugs).
Returns:
ECPointAffine:
a raw point (r = pt.x, s = pt.y) which is
the signature.
"""
if isinstance(message, str):
msg = bytes(message, 'ascii')
elif isinstance(message, bytes):
msg = message
else:
raise TypeError("message must be either str or bytes!")
sig_pt, rec_id = bitcoin_curve.sign(msg, self.key, do_hash)
# Take care of large s:
# Bitcoin deals with large s, by subtracting
# s from the curve order. See:
# https://bitcointalk.org/index.php?topic=285142.30;wap2
if sig_pt.y >= (bitcoin_curve.n // 2):
sig_pt = Point(sig_pt.x, bitcoin_curve.n - sig_pt.y)
rec_id ^= 0x1
return (sig_pt, rec_id)
def sign(self, message, do_hash=True):
""" Signs message using this private key.
Note:
This differs from `raw_sign()` since it returns a Signature object.
Args:
message (bytes or str): The message to be signed. If a
string is provided it is assumed the encoding is
'ascii' and converted to bytes. If this is not the
case, it is up to the caller to convert the string to
bytes appropriately and pass in the bytes.
do_hash (bool): True if the message should be hashed prior
to signing, False if not. This should always be left as
True except in special situations which require doing
the hash outside (e.g. handling Bitcoin bugs).
Returns:
Signature: The signature corresponding to message.
"""
# Some BTC things want to have the recovery id to extract the public
# key, so we should figure that out.
sig_pt, rec_id = self.raw_sign(message, do_hash)
return Signature(sig_pt.x, sig_pt.y, rec_id)
def sign_bitcoin(self, message, compressed=False):
""" Signs a message using this private key such that it
is compatible with bitcoind, bx, and other Bitcoin
clients/nodes/utilities.
Note:
0x18 + b\"Bitcoin Signed Message:" + newline + len(message) is
prepended to the message before signing.
Args:
message (bytes or str): Message to be signed.
compressed (bool): True if the corresponding public key will be
used in compressed format. False if the uncompressed version
is used.
Returns:
bytes: A Base64-encoded byte string of the signed message.
The first byte of the encoded message contains information
about how to recover the public key. In bitcoind parlance,
this is the magic number containing the recovery ID and
whether or not the key was compressed or not.
"""
if isinstance(message, str):
msg_in = bytes(message, 'ascii')
elif isinstance(message, bytes):
msg_in = message
else:
raise TypeError("message must be either str or bytes!")
msg = b"\x18Bitcoin Signed Message:\n" + bytes([len(msg_in)]) + msg_in
msg_hash = hashlib.sha256(msg).digest()
sig = self.sign(msg_hash)
comp_adder = 4 if compressed else 0
magic = 27 + sig.recovery_id + comp_adder
return base64.b64encode(bytes([magic]) + bytes(sig))
def to_b58check(self, testnet=False):
""" Generates a Base58Check encoding of this private key.
Returns:
str: A Base58Check encoded string representing the key.
"""
version = self.TESTNET_VERSION if testnet else self.MAINNET_VERSION
return base58.b58encode_check(bytes([version]) + bytes(self))
def __bytes__(self):
return self.key.to_bytes(32, 'big')
def __int__(self):
return self.key
class PublicKey(PublicKeyBase):
""" Encapsulation of a Bitcoin ECDSA public key.
This class provides a high-level API to using an ECDSA public
key, specifically for Bitcoin (secp256k1) purposes.
Args:
x (int): The x component of the public key point.
y (int): The y component of the public key point.
Returns:
PublicKey: The object representing the public key.
"""
TESTNET_VERSION = 0x6F
MAINNET_VERSION = 0x00
@staticmethod
def from_point(p):
""" Generates a public key object from any object
containing x, y coordinates.
Args:
p (Point): An object containing a two-dimensional, affine
representation of a point on the secp256k1 curve.
Returns:
PublicKey: A PublicKey object.
"""
return PublicKey(p.x, p.y)
@staticmethod
def from_int(i):
""" Generates a public key object from an integer.
Note:
This assumes that the upper 32 bytes of the integer
are the x component of the public key point and the
lower 32 bytes are the y component.
Args:
i (Bignum): A 512-bit integer representing the public
key point on the secp256k1 curve.
Returns:
PublicKey: A PublicKey object.
"""
point = ECPointAffine.from_int(bitcoin_curve, i)
return PublicKey.from_point(point)
@staticmethod
def from_base64(b64str, testnet=False):
""" Generates a public key object from a Base64 encoded string.
Args:
b64str (str): A Base64-encoded string.
testnet (bool) (Optional): If True, changes the version that
is prepended to the key.
Returns:
PublicKey: A PublicKey object.
"""
return PublicKey.from_bytes(base64.b64decode(b64str))
@staticmethod
def from_bytes(key_bytes):
""" Generates a public key object from a byte (or hex) string.
The byte stream must be of the SEC variety
(http://www.secg.org/): beginning with a single byte telling
what key representation follows. A full, uncompressed key
is represented by: 0x04 followed by 64 bytes containing
the x and y components of the point. For compressed keys
with an even y component, 0x02 is followed by 32 bytes
containing the x component. For compressed keys with an
odd y component, 0x03 is followed by 32 bytes containing
the x component.
Args:
key_bytes (bytes or str): A byte stream that conforms to the above.
Returns:
PublicKey: A PublicKey object.
"""
b = get_bytes(key_bytes)
key_bytes_len = len(b)
key_type = b[0]
if key_type == 0x04:
# Uncompressed
if key_bytes_len != 65:
raise ValueError("key_bytes must be exactly 65 bytes long when uncompressed.")
x = int.from_bytes(b[1:33], 'big')
y = int.from_bytes(b[33:65], 'big')
elif key_type == 0x02 or key_type == 0x03:
if key_bytes_len != 33:
raise ValueError("key_bytes must be exactly 33 bytes long when compressed.")
x = int.from_bytes(b[1:33], 'big')
ys = bitcoin_curve.y_from_x(x)
# Pick the one that corresponds to key_type
last_bit = key_type - 0x2
for y in ys:
if y & 0x1 == last_bit:
break
else:
return None
return PublicKey(x, y)
@staticmethod
def from_hex(h):
""" Generates a public key object from a hex-encoded string.
See from_bytes() for requirements of the hex string.
Args:
h (str): A hex-encoded string.
Returns:
PublicKey: A PublicKey object.
"""
return PublicKey.from_bytes(h)
@staticmethod
def from_signature(message, signature):
""" Attempts to create PublicKey object by deriving it
from the message and signature.
Args:
message (bytes): The message to be verified.
signature (Signature): The signature for message.
The recovery_id must not be None!
Returns:
PublicKey:
A PublicKey object derived from the
signature, it it exists. None otherwise.
"""
if signature.recovery_id is None:
raise ValueError("The signature must have a recovery_id.")
msg = get_bytes(message)
pub_keys = bitcoin_curve.recover_public_key(msg,
signature,
signature.recovery_id)
for k, recid in pub_keys:
if signature.recovery_id is not None and recid == signature.recovery_id:
return PublicKey(k.x, k.y)
return None
@staticmethod
def verify_bitcoin(message, signature, address):
""" Verifies a message signed using PrivateKey.sign_bitcoin()
or any of the bitcoin utils (e.g. bitcoin-cli, bx, etc.)
Args:
message(bytes): The message that the signature corresponds to.
signature (bytes or str): A Base64 encoded signature
address (str): Base58Check encoded address.
Returns:
bool: True if the signature verified properly, False otherwise.
"""
magic_sig = base64.b64decode(signature)
magic = magic_sig[0]
sig = Signature.from_bytes(magic_sig[1:])
sig.recovery_id = (magic - 27) & 0x3
compressed = ((magic - 27) & 0x4) != 0
# Build the message that was signed
msg = b"\x18Bitcoin Signed Message:\n" + bytes([len(message)]) + message
msg_hash = hashlib.sha256(msg).digest()
derived_public_key = PublicKey.from_signature(msg_hash, sig)
if derived_public_key is None:
raise ValueError("Could not recover public key from the provided signature.")
ver, h160 = address_to_key_hash(address)
hash160 = derived_public_key.hash160(compressed)
if hash160 != h160:
return False
return derived_public_key.verify(msg_hash, sig)
def __init__(self, x, y):
p = ECPointAffine(bitcoin_curve, x, y)
if not bitcoin_curve.is_on_curve(p):
raise ValueError("The provided (x, y) are not on the secp256k1 curve.")
self.point = p
# RIPEMD-160 of SHA-256
r = hashlib.new('ripemd160')
r.update(hashlib.sha256(bytes(self)).digest())
self.ripe = r.digest()
r = hashlib.new('ripemd160')
r.update(hashlib.sha256(self.compressed_bytes).digest())
self.ripe_compressed = r.digest()
self.keccak = sha3(bytes(self)[1:])
def hash160(self, compressed=True):
""" Return the RIPEMD-160 hash of the SHA-256 hash of the
public key.
Args:
compressed (bool): Whether or not the compressed key should
be used.
Returns:
bytes: RIPEMD-160 byte string.
"""
return self.ripe_compressed if compressed else self.ripe
def address(self, hrp='atp', compressed=True):
""" Address property that returns the Base58Check
encoded version of the HASH160.
Args:
compressed (bool): Whether or not the compressed key should
be used.
Returns:
bytes: Base58Check encoded string
"""
return bech32_addr.encode(hrp, self.keccak[12:])
def verify(self, message, signature, do_hash=True):
""" Verifies that message was appropriately signed.
Args:
message (bytes): The message to be verified.
signature (Signature): A signature object.
do_hash (bool): True if the message should be hashed prior
to signing, False if not. This should always be left as
True except in special situations which require doing
the hash outside (e.g. handling Bitcoin bugs).
Returns:
verified (bool): True if the signature is verified, False
otherwise.
"""
msg = get_bytes(message)
return bitcoin_curve.verify(msg, signature, self.point, do_hash)
def to_base64(self):
""" Hex representation of the serialized byte stream.
Returns:
b (str): A Base64-encoded string.
"""
return base64.b64encode(bytes(self))
def __int__(self):
mask = 2 ** 256 - 1
return ((self.point.x & mask) << bitcoin_curve.nlen) | (self.point.y & mask)
def __bytes__(self):
return bytes(self.point)
@property
def compressed_bytes(self):
""" Byte string corresponding to a compressed representation
of this public key.
Returns:
b (bytes): A 33-byte long byte string.
"""
return self.point.compressed_bytes
class Signature(object):
""" Encapsulation of a ECDSA signature for Bitcoin purposes.
Args:
r (Bignum): r component of the signature.
s (Bignum): s component of the signature.
recovery_id (int) (Optional): Must be between 0 and 3 specifying
which of the public keys generated by the algorithm specified
in http://www.secg.org/sec1-v2.pdf Section 4.1.6 (Public Key
Recovery Operation) is the correct one for this signature.
Returns:
sig (Signature): A Signature object.
"""
@staticmethod
def from_der(der):
""" Decodes a Signature that was DER-encoded.
Args:
der (bytes or str): The DER encoding to be decoded.
Returns:
Signature: The deserialized signature.
"""
d = get_bytes(der)
# d must conform to (from btcd):
# [0 ] 0x30 - ASN.1 identifier for sequence
# [1 ] <1-byte> - total remaining length
# [2 ] 0x02 - ASN.1 identifier to specify an integer follows
# [3 ] <1-byte> - length of R
# [4.] <bytes> - R
# [..] 0x02 - ASN.1 identifier to specify an integer follows
# [..] <1-byte> - length of S
# [..] <bytes> - S
# 6 bytes + R (min. 1 byte) + S (min. 1 byte)
if len(d) < 8:
raise ValueError("DER signature string is too short.")
# 6 bytes + R (max. 33 bytes) + S (max. 33 bytes)
if len(d) > 72:
raise ValueError("DER signature string is too long.")
if d[0] != 0x30:
raise ValueError("DER signature does not start with 0x30.")
if d[1] != len(d[2:]):
raise ValueError("DER signature length incorrect.")
total_length = d[1]
if d[2] != 0x02:
raise ValueError("DER signature no 1st int marker.")
if d[3] <= 0 or d[3] > (total_length - 7):
raise ValueError("DER signature incorrect R length.")
# Grab R, check for errors
rlen = d[3]
s_magic_index = 4 + rlen
rb = d[4:s_magic_index]
if rb[0] & 0x80 != 0:
raise ValueError("DER signature R is negative.")
if len(rb) > 1 and rb[0] == 0 and rb[1] & 0x80 != 0x80:
raise ValueError("DER signature R is excessively padded.")
r = int.from_bytes(rb, 'big')
# Grab S, check for errors
if d[s_magic_index] != 0x02:
raise ValueError("DER signature no 2nd int marker.")
slen_index = s_magic_index + 1
slen = d[slen_index]
if slen <= 0 or slen > len(d) - (slen_index + 1):
raise ValueError("DER signature incorrect S length.")
sb = d[slen_index + 1:]
if sb[0] & 0x80 != 0:
raise ValueError("DER signature S is negative.")
if len(sb) > 1 and sb[0] == 0 and sb[1] & 0x80 != 0x80:
raise ValueError("DER signature S is excessively padded.")
s = int.from_bytes(sb, 'big')
if r < 1 or r >= bitcoin_curve.n:
raise ValueError("DER signature R is not between 1 and N - 1.")
if s < 1 or s >= bitcoin_curve.n:
raise ValueError("DER signature S is not between 1 and N - 1.")
return Signature(r, s)
@staticmethod
def from_base64(b64str):
""" Generates a signature object from a Base64 encoded string.
Args:
b64str (str): A Base64-encoded string.
Returns:
Signature: A Signature object.
"""
return Signature.from_bytes(base64.b64decode(b64str))
@staticmethod
def from_bytes(b):
""" Extracts the r and s components from a byte string.
Args:
b (bytes): A 64-byte long string. The first 32 bytes are
extracted as the r component and the second 32 bytes
are extracted as the s component.
Returns:
Signature: A Signature object.
Raises:
ValueError: If signature is incorrect length
"""
if len(b) != 64:
raise ValueError("from_bytes: Signature length != 64.")
r = int.from_bytes(b[0:32], 'big')
s = int.from_bytes(b[32:64], 'big')
return Signature(r, s)
@staticmethod
def from_hex(h):
""" Extracts the r and s components from a hex-encoded string.
Args:
h (str): A 64-byte (128 character) long string. The first
32 bytes are extracted as the r component and the
second 32 bytes are extracted as the s component.
Returns:
Signature: A Signature object.
"""
return Signature.from_bytes(bytes.fromhex(h))
def __init__(self, r, s, recovery_id=None):
self.r = r
self.s = s
self.recovery_id = recovery_id
@property
def x(self):
""" Convenience property for any method that requires
this object to provide a Point interface.
"""
return self.r
@property
def y(self):
""" Convenience property for any method that requires
this object to provide a Point interface.
"""
return self.s
def _canonicalize(self):
rv = []
for x in [self.r, self.s]:
# Compute minimum bytes to represent integer
bl = math.ceil(x.bit_length() / 8)
# Make sure it's at least one byte in length
if bl == 0:
bl += 1
x_bytes = x.to_bytes(bl, 'big')
# make sure there's no way it could be interpreted
# as a negative integer
if x_bytes[0] & 0x80:
x_bytes = bytes([0]) + x_bytes
rv.append(x_bytes)
return rv
def to_der(self):
""" Encodes this signature using DER
Returns:
bytes: The DER encoding of (self.r, self.s).
"""
# Output should be:
# 0x30 <length> 0x02 <length r> r 0x02 <length s> s
r, s = self._canonicalize()
total_length = 6 + len(r) + len(s)
der = bytes([0x30, total_length - 2, 0x02, len(r)]) + r + bytes([0x02, len(s)]) + s
return der
def to_hex(self):
""" Hex representation of the serialized byte stream.
Returns:
str: A hex-encoded string.
"""
return bytes_to_str(bytes(self))