-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddress_utils.py
102 lines (76 loc) · 2.28 KB
/
address_utils.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
import os
import hashlib
def sha256(data):
digest = hashlib.new("sha256")
digest.update(data)
return digest.digest()
def ripemd160(x):
d = hashlib.new("ripemd160")
d.update(x)
return d.digest()
def b58(data):
B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
if data[0] == 0:
return "1" + b58(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
class Point:
def __init__(self,
x=0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
y=0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
p=2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 1):
self.x = x
self.y = y
self.p = p
def __add__(self, other):
return self.__radd__(other)
def __mul__(self, other):
return self.__rmul__(other)
def __rmul__(self, other):
n = self
q = None
for i in range(256):
if other & (1 << i):
q = q + n
n = n + n
return q
def __radd__(self, other):
if other is None:
return self
x1 = other.x
y1 = other.y
x2 = self.x
y2 = self.y
p = self.p
if self == other:
l = pow(2 * y2 % p, p-2, p) * (3 * x2 * x2) % p
else:
l = pow(x1 - x2, p-2, p) * (y1 - y2) % p
newX = (l ** 2 - x2 - x1) % p
newY = (l * x2 - l * newX - y2) % p
return Point(newX, newY)
def toBytes(self):
x = self.x.to_bytes(32, "big")
y = self.y.to_bytes(32, "big")
return b"\x04" + x + y
def getPublicKey(privkey):
SPEC256k1 = Point()
if SPEC256k1.y == 1 :
return b'\x03' + SPEC256k1.x.to_bytes(32, "big")
else:
return b'\x02' + SPEC256k1.x.to_bytes(32, "big")
def getAddress(privkey):
SPEC256k1 = Point()
pk = int.from_bytes(privkey, "big")
hash160 = ripemd160(sha256((SPEC256k1 * pk).toBytes()))
address = b"\x19" + hash160
address = b58(address + sha256(sha256(address))[:4])
return address
def getWif(privkey):
wif = b"\x9E" + privkey
wif = b58(wif + sha256(sha256(wif))[:4])
return wif