• R/O
  • HTTP
  • SSH
  • HTTPS

pybtm: 提交

Python3 implementation of the Bytom protocol. https://pypi.org/project/pybtm/


Commit MetaInfo

修订版f06db6b37304974d91ea84f647c3a9b93e88b6e8 (tree)
时间2019-03-26 16:59:51
作者Chengcheng Zhang <943420582@qq.c...>
CommiterChengcheng Zhang

Log Message

add get_seed, get_root_xprv, get_xpub

更改概述

差异

--- a/README.md
+++ b/README.md
@@ -5,6 +5,9 @@ pybtm
55 - [2 Usage](#2-usage)
66 - [2.1 Create entropy](#21-create-entropy)
77 - [2.2 Create mnemonics](#22-create-mnemonics)
8+ - [2.3 Create seed](#23-create-seed)
9+ - [2.4 Create root expanded private key](#24-create-root-expanded-private-key)
10+ - [2.5 Create expanded public key](#25-create-expanded-public-key)
811
912 Python3 implementation of the Bytom protocol.
1013
@@ -18,7 +21,7 @@ $ pip install pybtm
1821
1922 ### 2.1 Create entropy
2023
21-get_entropy() create 128bits entropy.
24+get_entropy() create 128 bits entropy.
2225
2326 ```python
2427 >>> from pybtm import key
@@ -36,4 +39,34 @@ get_mnemonic create 12 new mnemonics, if no paramater is specified, it will retu
3639 'nothing gate perfect glide wink lizard journey negative load quote wrong reason'
3740 >>> key.get_mnemonic('089fe9bf0cac76760bc4b131d938669e')
3841 'ancient young hurt bone shuffle deposit congress normal crack six boost despair'
42+```
43+
44+### 2.3 Create seed
45+
46+get_seed create 512 bits seed from 12 mnemonics.
47+
48+```python
49+>>> from pybtm import key
50+>>> key.get_seed('ancient young hurt bone shuffle deposit congress normal crack six boost despair')
51+'afa3a86bbec2f40bb32833fc6324593824c4fc7821ed32eac1f762b5893e56745f66a6c6f2588b3d627680aa4e0e50efd25065097b3daa8c6a19d606838fe7d4'
52+```
53+
54+### 2.4 Create root expanded private key
55+
56+get_root_xprv create root expanded private key.
57+
58+```python
59+>>> from pybtm import key
60+>>> key.get_root_xprv('afa3a86bbec2f40bb32833fc6324593824c4fc7821ed32eac1f762b5893e56745f66a6c6f2588b3d627680aa4e0e50efd25065097b3daa8c6a19d606838fe7d4')
61+'302a25c7c0a68a83fa043f594a2db8b44bc871fced553a8a33144b31bc7fb84887c9e75915bb6ba3fd0b9f94a60b7a5897ab9db6a48f888c2559132dba9152b0'
62+```
63+
64+### 2.5 Create expanded public key
65+
66+get_xpub create expanded public key.
67+
68+```
69+>>> from pybtm import key
70+>>> key.get_xpub('c003f4bcccf9ad6f05ad2c84fa5ff98430eb8e73de5de232bc29334c7d074759d513bc370335cac51d77f0be5dfe84de024cfee562530b4d873b5f5e2ff4f57c')
71+'1b0541a7664cee929edb54d9ef21996b90546918a920a77e1cd6015d97c56563d513bc370335cac51d77f0be5dfe84de024cfee562530b4d873b5f5e2ff4f57c'
3972 ```
\ No newline at end of file
--- a/pybtm/__init__.py
+++ b/pybtm/__init__.py
@@ -1,2 +1,2 @@
11 name = "pybtm"
2-version = "0.0.5"
\ No newline at end of file
2+version = "0.0.8"
\ No newline at end of file
--- /dev/null
+++ b/pybtm/edwards25519.py
@@ -0,0 +1,299 @@
1+# ed25519.py - Optimized version of the reference implementation of Ed25519
2+#
3+# Written in 2011? by Daniel J. Bernstein <djb@cr.yp.to>
4+# 2013 by Donald Stufft <donald@stufft.io>
5+# 2013 by Alex Gaynor <alex.gaynor@gmail.com>
6+# 2013 by Greg Price <price@mit.edu>
7+#
8+# To the extent possible under law, the author(s) have dedicated all copyright
9+# and related and neighboring rights to this software to the public domain
10+# worldwide. This software is distributed without any warranty.
11+#
12+# You should have received a copy of the CC0 Public Domain Dedication along
13+# with this software. If not, see
14+# <http://creativecommons.org/publicdomain/zero/1.0/>.
15+
16+"""
17+NB: This code is not safe for use with secret keys or secret data.
18+The only safe use of this code is for verifying signatures on public messages.
19+Functions for computing the public key of a secret key and for signing
20+a message are included, namely publickey_unsafe and signature_unsafe,
21+for testing purposes only.
22+The root of the problem is that Python's long-integer arithmetic is
23+not designed for use in cryptography. Specifically, it may take more
24+or less time to execute an operation depending on the values of the
25+inputs, and its memory access patterns may also depend on the inputs.
26+This opens it to timing and cache side-channel attacks which can
27+disclose data to an attacker. We rely on Python's long-integer
28+arithmetic, so we cannot handle secrets without risking their disclosure.
29+"""
30+
31+import hashlib
32+import operator
33+import sys
34+
35+
36+# __version__ = "1.0.dev0"
37+
38+
39+# Useful for very coarse version differentiation.
40+PY3 = sys.version_info[0] == 3
41+
42+if PY3:
43+ indexbytes = operator.getitem
44+ intlist2bytes = bytes
45+ int2byte = operator.methodcaller("to_bytes", 1, "big")
46+else:
47+ int2byte = chr
48+ range = xrange
49+
50+ def indexbytes(buf, i):
51+ return ord(buf[i])
52+
53+ def intlist2bytes(l):
54+ return b"".join(chr(c) for c in l)
55+
56+
57+b = 256
58+q = 2 ** 255 - 19
59+l = 2 ** 252 + 27742317777372353535851937790883648493
60+
61+
62+def H(m):
63+ return hashlib.sha512(m).digest()
64+
65+
66+def pow2(x, p):
67+ """== pow(x, 2**p, q)"""
68+ while p > 0:
69+ x = x * x % q
70+ p -= 1
71+ return x
72+
73+
74+def inv(z):
75+ """$= z^{-1} \mod q$, for z != 0"""
76+ # Adapted from curve25519_athlon.c in djb's Curve25519.
77+ z2 = z * z % q # 2
78+ z9 = pow2(z2, 2) * z % q # 9
79+ z11 = z9 * z2 % q # 11
80+ z2_5_0 = (z11 * z11) % q * z9 % q # 31 == 2^5 - 2^0
81+ z2_10_0 = pow2(z2_5_0, 5) * z2_5_0 % q # 2^10 - 2^0
82+ z2_20_0 = pow2(z2_10_0, 10) * z2_10_0 % q # ...
83+ z2_40_0 = pow2(z2_20_0, 20) * z2_20_0 % q
84+ z2_50_0 = pow2(z2_40_0, 10) * z2_10_0 % q
85+ z2_100_0 = pow2(z2_50_0, 50) * z2_50_0 % q
86+ z2_200_0 = pow2(z2_100_0, 100) * z2_100_0 % q
87+ z2_250_0 = pow2(z2_200_0, 50) * z2_50_0 % q # 2^250 - 2^0
88+ return pow2(z2_250_0, 5) * z11 % q # 2^255 - 2^5 + 11 = q - 2
89+
90+
91+d = -121665 * inv(121666) % q
92+I = pow(2, (q - 1) // 4, q)
93+
94+
95+def xrecover(y):
96+ xx = (y * y - 1) * inv(d * y * y + 1)
97+ x = pow(xx, (q + 3) // 8, q)
98+
99+ if (x * x - xx) % q != 0:
100+ x = (x * I) % q
101+
102+ if x % 2 != 0:
103+ x = q-x
104+
105+ return x
106+
107+
108+By = 4 * inv(5)
109+Bx = xrecover(By)
110+B = (Bx % q, By % q, 1, (Bx * By) % q)
111+ident = (0, 1, 1, 0)
112+
113+
114+def edwards_add(P, Q):
115+ # This is formula sequence 'addition-add-2008-hwcd-3' from
116+ # http://www.hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
117+ (x1, y1, z1, t1) = P
118+ (x2, y2, z2, t2) = Q
119+
120+ a = (y1-x1)*(y2-x2) % q
121+ b = (y1+x1)*(y2+x2) % q
122+ c = t1*2*d*t2 % q
123+ dd = z1*2*z2 % q
124+ e = b - a
125+ f = dd - c
126+ g = dd + c
127+ h = b + a
128+ x3 = e*f
129+ y3 = g*h
130+ t3 = e*h
131+ z3 = f*g
132+
133+ return (x3 % q, y3 % q, z3 % q, t3 % q)
134+
135+
136+def edwards_double(P):
137+ # This is formula sequence 'dbl-2008-hwcd' from
138+ # http://www.hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
139+ (x1, y1, z1, t1) = P
140+
141+ a = x1*x1 % q
142+ b = y1*y1 % q
143+ c = 2*z1*z1 % q
144+ # dd = -a
145+ e = ((x1+y1)*(x1+y1) - a - b) % q
146+ g = -a + b # dd + b
147+ f = g - c
148+ h = -a - b # dd - b
149+ x3 = e*f
150+ y3 = g*h
151+ t3 = e*h
152+ z3 = f*g
153+
154+ return (x3 % q, y3 % q, z3 % q, t3 % q)
155+
156+
157+def scalarmult(P, e):
158+ if e == 0:
159+ return ident
160+ Q = scalarmult(P, e // 2)
161+ Q = edwards_double(Q)
162+ if e & 1:
163+ Q = edwards_add(Q, P)
164+ return Q
165+
166+
167+# Bpow[i] == scalarmult(B, 2**i)
168+Bpow = []
169+
170+
171+def make_Bpow():
172+ P = B
173+ for i in range(253):
174+ Bpow.append(P)
175+ P = edwards_double(P)
176+make_Bpow()
177+
178+def scalarmultbase(e):
179+ return scalarmult_B(e)
180+
181+def scalarmult_B(e):
182+ """
183+ Implements scalarmult(B, e) more efficiently.
184+ """
185+ # scalarmult(B, l) is the identity
186+ e = e % l
187+ P = ident
188+ for i in range(253):
189+ if e & 1:
190+ P = edwards_add(P, Bpow[i])
191+ e = e // 2
192+ assert e == 0, e
193+ return P
194+
195+
196+def encodeint(y):
197+ bits = [(y >> i) & 1 for i in range(b)]
198+ return b''.join([
199+ int2byte(sum([bits[i * 8 + j] << j for j in range(8)]))
200+ for i in range(b//8)
201+ ])
202+
203+
204+def encodepoint(P):
205+ (x, y, z, t) = P
206+ zi = inv(z)
207+ x = (x * zi) % q
208+ y = (y * zi) % q
209+ bits = [(y >> i) & 1 for i in range(b - 1)] + [x & 1]
210+ return b''.join([
211+ int2byte(sum([bits[i * 8 + j] << j for j in range(8)]))
212+ for i in range(b // 8)
213+ ])
214+
215+
216+def bit(h, i):
217+ return (indexbytes(h, i // 8) >> (i % 8)) & 1
218+
219+
220+def publickey_unsafe(sk):
221+ """
222+ Not safe to use with secret keys or secret data.
223+ See module docstring. This function should be used for testing only.
224+ """
225+ h = H(sk)
226+ a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2))
227+ A = scalarmult_B(a)
228+ return encodepoint(A)
229+
230+
231+def Hint(m):
232+ h = H(m)
233+ return sum(2 ** i * bit(h, i) for i in range(2 * b))
234+
235+
236+def signature_unsafe(m, sk, pk):
237+ """
238+ Not safe to use with secret keys or secret data.
239+ See module docstring. This function should be used for testing only.
240+ """
241+ h = H(sk)
242+ a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2))
243+ r = Hint(
244+ intlist2bytes([indexbytes(h, j) for j in range(b // 8, b // 4)]) + m
245+ )
246+ R = scalarmult_B(r)
247+ S = (r + Hint(encodepoint(R) + pk + m) * a) % l
248+ return encodepoint(R) + encodeint(S)
249+
250+
251+def isoncurve(P):
252+ (x, y, z, t) = P
253+ return (z % q != 0 and
254+ x*y % q == z*t % q and
255+ (y*y - x*x - z*z - d*t*t) % q == 0)
256+
257+
258+def decodeint(s):
259+ return sum(2 ** i * bit(s, i) for i in range(0, b))
260+
261+
262+def decodepoint(s):
263+ y = sum(2 ** i * bit(s, i) for i in range(0, b - 1))
264+ x = xrecover(y)
265+ if x & 1 != bit(s, b-1):
266+ x = q - x
267+ P = (x, y, 1, (x*y) % q)
268+ if not isoncurve(P):
269+ raise ValueError("decoding point that is not on curve")
270+ return P
271+
272+
273+class SignatureMismatch(Exception):
274+ pass
275+
276+
277+def checkvalid(s, m, pk):
278+ """
279+ Not safe to use when any argument is secret.
280+ See module docstring. This function should be used only for
281+ verifying public signatures of public messages.
282+ """
283+ if len(s) != b // 4:
284+ raise ValueError("signature length is wrong")
285+
286+ if len(pk) != b // 8:
287+ raise ValueError("public-key length is wrong")
288+
289+ R = decodepoint(s[:b // 8])
290+ A = decodepoint(pk)
291+ S = decodeint(s[b // 8:b // 4])
292+ h = Hint(encodepoint(R) + pk + m)
293+
294+ (x1, y1, z1, t1) = P = scalarmult_B(S)
295+ (x2, y2, z2, t2) = Q = edwards_add(R, scalarmult(A, h))
296+
297+ if (not isoncurve(P) or not isoncurve(Q) or
298+ (x1*z2 - x2*z1) % q != 0 or (y1*z2 - y2*z1) % q != 0):
299+ raise SignatureMismatch("signature does not pass verification")
--- a/pybtm/key.py
+++ b/pybtm/key.py
@@ -1,13 +1,19 @@
11 import random
22 import hashlib
3+import pbkdf2
4+import hmac
5+from .edwards25519 import *
6+
37
48 def get_entropy():
59 entropy = random.randint(0, 2**128)
610 entropy_hexstr = entropy.to_bytes(16, byteorder='big').hex()
711 return entropy_hexstr
812
13+
914 word_list = ['abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract', 'absurd', 'abuse', 'access', 'accident', 'account', 'accuse', 'achieve', 'acid', 'acoustic', 'acquire', 'across', 'act', 'action', 'actor', 'actress', 'actual', 'adapt', 'add', 'addict', 'address', 'adjust', 'admit', 'adult', 'advance', 'advice', 'aerobic', 'affair', 'afford', 'afraid', 'again', 'age', 'agent', 'agree', 'ahead', 'aim', 'air', 'airport', 'aisle', 'alarm', 'album', 'alcohol', 'alert', 'alien', 'all', 'alley', 'allow', 'almost', 'alone', 'alpha', 'already', 'also', 'alter', 'always', 'amateur', 'amazing', 'among', 'amount', 'amused', 'analyst', 'anchor', 'ancient', 'anger', 'angle', 'angry', 'animal', 'ankle', 'announce', 'annual', 'another', 'answer', 'antenna', 'antique', 'anxiety', 'any', 'apart', 'apology', 'appear', 'apple', 'approve', 'april', 'arch', 'arctic', 'area', 'arena', 'argue', 'arm', 'armed', 'armor', 'army', 'around', 'arrange', 'arrest', 'arrive', 'arrow', 'art', 'artefact', 'artist', 'artwork', 'ask', 'aspect', 'assault', 'asset', 'assist', 'assume', 'asthma', 'athlete', 'atom', 'attack', 'attend', 'attitude', 'attract', 'auction', 'audit', 'august', 'aunt', 'author', 'auto', 'autumn', 'average', 'avocado', 'avoid', 'awake', 'aware', 'away', 'awesome', 'awful', 'awkward', 'axis', 'baby', 'bachelor', 'bacon', 'badge', 'bag', 'balance', 'balcony', 'ball', 'bamboo', 'banana', 'banner', 'bar', 'barely', 'bargain', 'barrel', 'base', 'basic', 'basket', 'battle', 'beach', 'bean', 'beauty', 'because', 'become', 'beef', 'before', 'begin', 'behave', 'behind', 'believe', 'below', 'belt', 'bench', 'benefit', 'best', 'betray', 'better', 'between', 'beyond', 'bicycle', 'bid', 'bike', 'bind', 'biology', 'bird', 'birth', 'bitter', 'black', 'blade', 'blame', 'blanket', 'blast', 'bleak', 'bless', 'blind', 'blood', 'blossom', 'blouse', 'blue', 'blur', 'blush', 'board', 'boat', 'body', 'boil', 'bomb', 'bone', 'bonus', 'book', 'boost', 'border', 'boring', 'borrow', 'boss', 'bottom', 'bounce', 'box', 'boy', 'bracket', 'brain', 'brand', 'brass', 'brave', 'bread', 'breeze', 'brick', 'bridge', 'brief', 'bright', 'bring', 'brisk', 'broccoli', 'broken', 'bronze', 'broom', 'brother', 'brown', 'brush', 'bubble', 'buddy', 'budget', 'buffalo', 'build', 'bulb', 'bulk', 'bullet', 'bundle', 'bunker', 'burden', 'burger', 'burst', 'bus', 'business', 'busy', 'butter', 'buyer', 'buzz', 'cabbage', 'cabin', 'cable', 'cactus', 'cage', 'cake', 'call', 'calm', 'camera', 'camp', 'can', 'canal', 'cancel', 'candy', 'cannon', 'canoe', 'canvas', 'canyon', 'capable', 'capital', 'captain', 'car', 'carbon', 'card', 'cargo', 'carpet', 'carry', 'cart', 'case', 'cash', 'casino', 'castle', 'casual', 'cat', 'catalog', 'catch', 'category', 'cattle', 'caught', 'cause', 'caution', 'cave', 'ceiling', 'celery', 'cement', 'census', 'century', 'cereal', 'certain', 'chair', 'chalk', 'champion', 'change', 'chaos', 'chapter', 'charge', 'chase', 'chat', 'cheap', 'check', 'cheese', 'chef', 'cherry', 'chest', 'chicken', 'chief', 'child', 'chimney', 'choice', 'choose', 'chronic', 'chuckle', 'chunk', 'churn', 'cigar', 'cinnamon', 'circle', 'citizen', 'city', 'civil', 'claim', 'clap', 'clarify', 'claw', 'clay', 'clean', 'clerk', 'clever', 'click', 'client', 'cliff', 'climb', 'clinic', 'clip', 'clock', 'clog', 'close', 'cloth', 'cloud', 'clown', 'club', 'clump', 'cluster', 'clutch', 'coach', 'coast', 'coconut', 'code', 'coffee', 'coil', 'coin', 'collect', 'color', 'column', 'combine', 'come', 'comfort', 'comic', 'common', 'company', 'concert', 'conduct', 'confirm', 'congress', 'connect', 'consider', 'control', 'convince', 'cook', 'cool', 'copper', 'copy', 'coral', 'core', 'corn', 'correct', 'cost', 'cotton', 'couch', 'country', 'couple', 'course', 'cousin', 'cover', 'coyote', 'crack', 'cradle', 'craft', 'cram', 'crane', 'crash', 'crater', 'crawl', 'crazy', 'cream', 'credit', 'creek', 'crew', 'cricket', 'crime', 'crisp', 'critic', 'crop', 'cross', 'crouch', 'crowd', 'crucial', 'cruel', 'cruise', 'crumble', 'crunch', 'crush', 'cry', 'crystal', 'cube', 'culture', 'cup', 'cupboard', 'curious', 'current', 'curtain', 'curve', 'cushion', 'custom', 'cute', 'cycle', 'dad', 'damage', 'damp', 'dance', 'danger', 'daring', 'dash', 'daughter', 'dawn', 'day', 'deal', 'debate', 'debris', 'decade', 'december', 'decide', 'decline', 'decorate', 'decrease', 'deer', 'defense', 'define', 'defy', 'degree', 'delay', 'deliver', 'demand', 'demise', 'denial', 'dentist', 'deny', 'depart', 'depend', 'deposit', 'depth', 'deputy', 'derive', 'describe', 'desert', 'design', 'desk', 'despair', 'destroy', 'detail', 'detect', 'develop', 'device', 'devote', 'diagram', 'dial', 'diamond', 'diary', 'dice', 'diesel', 'diet', 'differ', 'digital', 'dignity', 'dilemma', 'dinner', 'dinosaur', 'direct', 'dirt', 'disagree', 'discover', 'disease', 'dish', 'dismiss', 'disorder', 'display', 'distance', 'divert', 'divide', 'divorce', 'dizzy', 'doctor', 'document', 'dog', 'doll', 'dolphin', 'domain', 'donate', 'donkey', 'donor', 'door', 'dose', 'double', 'dove', 'draft', 'dragon', 'drama', 'drastic', 'draw', 'dream', 'dress', 'drift', 'drill', 'drink', 'drip', 'drive', 'drop', 'drum', 'dry', 'duck', 'dumb', 'dune', 'during', 'dust', 'dutch', 'duty', 'dwarf', 'dynamic', 'eager', 'eagle', 'early', 'earn', 'earth', 'easily', 'east', 'easy', 'echo', 'ecology', 'economy', 'edge', 'edit', 'educate', 'effort', 'egg', 'eight', 'either', 'elbow', 'elder', 'electric', 'elegant', 'element', 'elephant', 'elevator', 'elite', 'else', 'embark', 'embody', 'embrace', 'emerge', 'emotion', 'employ', 'empower', 'empty', 'enable', 'enact', 'end', 'endless', 'endorse', 'enemy', 'energy', 'enforce', 'engage', 'engine', 'enhance', 'enjoy', 'enlist', 'enough', 'enrich', 'enroll', 'ensure', 'enter', 'entire', 'entry', 'envelope', 'episode', 'equal', 'equip', 'era', 'erase', 'erode', 'erosion', 'error', 'erupt', 'escape', 'essay', 'essence', 'estate', 'eternal', 'ethics', 'evidence', 'evil', 'evoke', 'evolve', 'exact', 'example', 'excess', 'exchange', 'excite', 'exclude', 'excuse', 'execute', 'exercise', 'exhaust', 'exhibit', 'exile', 'exist', 'exit', 'exotic', 'expand', 'expect', 'expire', 'explain', 'expose', 'express', 'extend', 'extra', 'eye', 'eyebrow', 'fabric', 'face', 'faculty', 'fade', 'faint', 'faith', 'fall', 'false', 'fame', 'family', 'famous', 'fan', 'fancy', 'fantasy', 'farm', 'fashion', 'fat', 'fatal', 'father', 'fatigue', 'fault', 'favorite', 'feature', 'february', 'federal', 'fee', 'feed', 'feel', 'female', 'fence', 'festival', 'fetch', 'fever', 'few', 'fiber', 'fiction', 'field', 'figure', 'file', 'film', 'filter', 'final', 'find', 'fine', 'finger', 'finish', 'fire', 'firm', 'first', 'fiscal', 'fish', 'fit', 'fitness', 'fix', 'flag', 'flame', 'flash', 'flat', 'flavor', 'flee', 'flight', 'flip', 'float', 'flock', 'floor', 'flower', 'fluid', 'flush', 'fly', 'foam', 'focus', 'fog', 'foil', 'fold', 'follow', 'food', 'foot', 'force', 'forest', 'forget', 'fork', 'fortune', 'forum', 'forward', 'fossil', 'foster', 'found', 'fox', 'fragile', 'frame', 'frequent', 'fresh', 'friend', 'fringe', 'frog', 'front', 'frost', 'frown', 'frozen', 'fruit', 'fuel', 'fun', 'funny', 'furnace', 'fury', 'future', 'gadget', 'gain', 'galaxy', 'gallery', 'game', 'gap', 'garage', 'garbage', 'garden', 'garlic', 'garment', 'gas', 'gasp', 'gate', 'gather', 'gauge', 'gaze', 'general', 'genius', 'genre', 'gentle', 'genuine', 'gesture', 'ghost', 'giant', 'gift', 'giggle', 'ginger', 'giraffe', 'girl', 'give', 'glad', 'glance', 'glare', 'glass', 'glide', 'glimpse', 'globe', 'gloom', 'glory', 'glove', 'glow', 'glue', 'goat', 'goddess', 'gold', 'good', 'goose', 'gorilla', 'gospel', 'gossip', 'govern', 'gown', 'grab', 'grace', 'grain', 'grant', 'grape', 'grass', 'gravity', 'great', 'green', 'grid', 'grief', 'grit', 'grocery', 'group', 'grow', 'grunt', 'guard', 'guess', 'guide', 'guilt', 'guitar', 'gun', 'gym', 'habit', 'hair', 'half', 'hammer', 'hamster', 'hand', 'happy', 'harbor', 'hard', 'harsh', 'harvest', 'hat', 'have', 'hawk', 'hazard', 'head', 'health', 'heart', 'heavy', 'hedgehog', 'height', 'hello', 'helmet', 'help', 'hen', 'hero', 'hidden', 'high', 'hill', 'hint', 'hip', 'hire', 'history', 'hobby', 'hockey', 'hold', 'hole', 'holiday', 'hollow', 'home', 'honey', 'hood', 'hope', 'horn', 'horror', 'horse', 'hospital', 'host', 'hotel', 'hour', 'hover', 'hub', 'huge', 'human', 'humble', 'humor', 'hundred', 'hungry', 'hunt', 'hurdle', 'hurry', 'hurt', 'husband', 'hybrid', 'ice', 'icon', 'idea', 'identify', 'idle', 'ignore', 'ill', 'illegal', 'illness', 'image', 'imitate', 'immense', 'immune', 'impact', 'impose', 'improve', 'impulse', 'inch', 'include', 'income', 'increase', 'index', 'indicate', 'indoor', 'industry', 'infant', 'inflict', 'inform', 'inhale', 'inherit', 'initial', 'inject', 'injury', 'inmate', 'inner', 'innocent', 'input', 'inquiry', 'insane', 'insect', 'inside', 'inspire', 'install', 'intact', 'interest', 'into', 'invest', 'invite', 'involve', 'iron', 'island', 'isolate', 'issue', 'item', 'ivory', 'jacket', 'jaguar', 'jar', 'jazz', 'jealous', 'jeans', 'jelly', 'jewel', 'job', 'join', 'joke', 'journey', 'joy', 'judge', 'juice', 'jump', 'jungle', 'junior', 'junk', 'just', 'kangaroo', 'keen', 'keep', 'ketchup', 'key', 'kick', 'kid', 'kidney', 'kind', 'kingdom', 'kiss', 'kit', 'kitchen', 'kite', 'kitten', 'kiwi', 'knee', 'knife', 'knock', 'know', 'lab', 'label', 'labor', 'ladder', 'lady', 'lake', 'lamp', 'language', 'laptop', 'large', 'later', 'latin', 'laugh', 'laundry', 'lava', 'law', 'lawn', 'lawsuit', 'layer', 'lazy', 'leader', 'leaf', 'learn', 'leave', 'lecture', 'left', 'leg', 'legal', 'legend', 'leisure', 'lemon', 'lend', 'length', 'lens', 'leopard', 'lesson', 'letter', 'level', 'liar', 'liberty', 'library', 'license', 'life', 'lift', 'light', 'like', 'limb', 'limit', 'link', 'lion', 'liquid', 'list', 'little', 'live', 'lizard', 'load', 'loan', 'lobster', 'local', 'lock', 'logic', 'lonely', 'long', 'loop', 'lottery', 'loud', 'lounge', 'love', 'loyal', 'lucky', 'luggage', 'lumber', 'lunar', 'lunch', 'luxury', 'lyrics', 'machine', 'mad', 'magic', 'magnet', 'maid', 'mail', 'main', 'major', 'make', 'mammal', 'man', 'manage', 'mandate', 'mango', 'mansion', 'manual', 'maple', 'marble', 'march', 'margin', 'marine', 'market', 'marriage', 'mask', 'mass', 'master', 'match', 'material', 'math', 'matrix', 'matter', 'maximum', 'maze', 'meadow', 'mean', 'measure', 'meat', 'mechanic', 'medal', 'media', 'melody', 'melt', 'member', 'memory', 'mention', 'menu', 'mercy', 'merge', 'merit', 'merry', 'mesh', 'message', 'metal', 'method', 'middle', 'midnight', 'milk', 'million', 'mimic', 'mind', 'minimum', 'minor', 'minute', 'miracle', 'mirror', 'misery', 'miss', 'mistake', 'mix', 'mixed', 'mixture', 'mobile', 'model', 'modify', 'mom', 'moment', 'monitor', 'monkey', 'monster', 'month', 'moon', 'moral', 'more', 'morning', 'mosquito', 'mother', 'motion', 'motor', 'mountain', 'mouse', 'move', 'movie', 'much', 'muffin', 'mule', 'multiply', 'muscle', 'museum', 'mushroom', 'music', 'must', 'mutual', 'myself', 'mystery', 'myth', 'naive', 'name', 'napkin', 'narrow', 'nasty', 'nation', 'nature', 'near', 'neck', 'need', 'negative', 'neglect', 'neither', 'nephew', 'nerve', 'nest', 'net', 'network', 'neutral', 'never', 'news', 'next', 'nice', 'night', 'noble', 'noise', 'nominee', 'noodle', 'normal', 'north', 'nose', 'notable', 'note', 'nothing', 'notice', 'novel', 'now', 'nuclear', 'number', 'nurse', 'nut', 'oak', 'obey', 'object', 'oblige', 'obscure', 'observe', 'obtain', 'obvious', 'occur', 'ocean', 'october', 'odor', 'off', 'offer', 'office', 'often', 'oil', 'okay', 'old', 'olive', 'olympic', 'omit', 'once', 'one', 'onion', 'online', 'only', 'open', 'opera', 'opinion', 'oppose', 'option', 'orange', 'orbit', 'orchard', 'order', 'ordinary', 'organ', 'orient', 'original', 'orphan', 'ostrich', 'other', 'outdoor', 'outer', 'output', 'outside', 'oval', 'oven', 'over', 'own', 'owner', 'oxygen', 'oyster', 'ozone', 'pact', 'paddle', 'page', 'pair', 'palace', 'palm', 'panda', 'panel', 'panic', 'panther', 'paper', 'parade', 'parent', 'park', 'parrot', 'party', 'pass', 'patch', 'path', 'patient', 'patrol', 'pattern', 'pause', 'pave', 'payment', 'peace', 'peanut', 'pear', 'peasant', 'pelican', 'pen', 'penalty', 'pencil', 'people', 'pepper', 'perfect', 'permit', 'person', 'pet', 'phone', 'photo', 'phrase', 'physical', 'piano', 'picnic', 'picture', 'piece', 'pig', 'pigeon', 'pill', 'pilot', 'pink', 'pioneer', 'pipe', 'pistol', 'pitch', 'pizza', 'place', 'planet', 'plastic', 'plate', 'play', 'please', 'pledge', 'pluck', 'plug', 'plunge', 'poem', 'poet', 'point', 'polar', 'pole', 'police', 'pond', 'pony', 'pool', 'popular', 'portion', 'position', 'possible', 'post', 'potato', 'pottery', 'poverty', 'powder', 'power', 'practice', 'praise', 'predict', 'prefer', 'prepare', 'present', 'pretty', 'prevent', 'price', 'pride', 'primary', 'print', 'priority', 'prison', 'private', 'prize', 'problem', 'process', 'produce', 'profit', 'program', 'project', 'promote', 'proof', 'property', 'prosper', 'protect', 'proud', 'provide', 'public', 'pudding', 'pull', 'pulp', 'pulse', 'pumpkin', 'punch', 'pupil', 'puppy', 'purchase', 'purity', 'purpose', 'purse', 'push', 'put', 'puzzle', 'pyramid', 'quality', 'quantum', 'quarter', 'question', 'quick', 'quit', 'quiz', 'quote', 'rabbit', 'raccoon', 'race', 'rack', 'radar', 'radio', 'rail', 'rain', 'raise', 'rally', 'ramp', 'ranch', 'random', 'range', 'rapid', 'rare', 'rate', 'rather', 'raven', 'raw', 'razor', 'ready', 'real', 'reason', 'rebel', 'rebuild', 'recall', 'receive', 'recipe', 'record', 'recycle', 'reduce', 'reflect', 'reform', 'refuse', 'region', 'regret', 'regular', 'reject', 'relax', 'release', 'relief', 'rely', 'remain', 'remember', 'remind', 'remove', 'render', 'renew', 'rent', 'reopen', 'repair', 'repeat', 'replace', 'report', 'require', 'rescue', 'resemble', 'resist', 'resource', 'response', 'result', 'retire', 'retreat', 'return', 'reunion', 'reveal', 'review', 'reward', 'rhythm', 'rib', 'ribbon', 'rice', 'rich', 'ride', 'ridge', 'rifle', 'right', 'rigid', 'ring', 'riot', 'ripple', 'risk', 'ritual', 'rival', 'river', 'road', 'roast', 'robot', 'robust', 'rocket', 'romance', 'roof', 'rookie', 'room', 'rose', 'rotate', 'rough', 'round', 'route', 'royal', 'rubber', 'rude', 'rug', 'rule', 'run', 'runway', 'rural', 'sad', 'saddle', 'sadness', 'safe', 'sail', 'salad', 'salmon', 'salon', 'salt', 'salute', 'same', 'sample', 'sand', 'satisfy', 'satoshi', 'sauce', 'sausage', 'save', 'say', 'scale', 'scan', 'scare', 'scatter', 'scene', 'scheme', 'school', 'science', 'scissors', 'scorpion', 'scout', 'scrap', 'screen', 'script', 'scrub', 'sea', 'search', 'season', 'seat', 'second', 'secret', 'section', 'security', 'seed', 'seek', 'segment', 'select', 'sell', 'seminar', 'senior', 'sense', 'sentence', 'series', 'service', 'session', 'settle', 'setup', 'seven', 'shadow', 'shaft', 'shallow', 'share', 'shed', 'shell', 'sheriff', 'shield', 'shift', 'shine', 'ship', 'shiver', 'shock', 'shoe', 'shoot', 'shop', 'short', 'shoulder', 'shove', 'shrimp', 'shrug', 'shuffle', 'shy', 'sibling', 'sick', 'side', 'siege', 'sight', 'sign', 'silent', 'silk', 'silly', 'silver', 'similar', 'simple', 'since', 'sing', 'siren', 'sister', 'situate', 'six', 'size', 'skate', 'sketch', 'ski', 'skill', 'skin', 'skirt', 'skull', 'slab', 'slam', 'sleep', 'slender', 'slice', 'slide', 'slight', 'slim', 'slogan', 'slot', 'slow', 'slush', 'small', 'smart', 'smile', 'smoke', 'smooth', 'snack', 'snake', 'snap', 'sniff', 'snow', 'soap', 'soccer', 'social', 'sock', 'soda', 'soft', 'solar', 'soldier', 'solid', 'solution', 'solve', 'someone', 'song', 'soon', 'sorry', 'sort', 'soul', 'sound', 'soup', 'source', 'south', 'space', 'spare', 'spatial', 'spawn', 'speak', 'special', 'speed', 'spell', 'spend', 'sphere', 'spice', 'spider', 'spike', 'spin', 'spirit', 'split', 'spoil', 'sponsor', 'spoon', 'sport', 'spot', 'spray', 'spread', 'spring', 'spy', 'square', 'squeeze', 'squirrel', 'stable', 'stadium', 'staff', 'stage', 'stairs', 'stamp', 'stand', 'start', 'state', 'stay', 'steak', 'steel', 'stem', 'step', 'stereo', 'stick', 'still', 'sting', 'stock', 'stomach', 'stone', 'stool', 'story', 'stove', 'strategy', 'street', 'strike', 'strong', 'struggle', 'student', 'stuff', 'stumble', 'style', 'subject', 'submit', 'subway', 'success', 'such', 'sudden', 'suffer', 'sugar', 'suggest', 'suit', 'summer', 'sun', 'sunny', 'sunset', 'super', 'supply', 'supreme', 'sure', 'surface', 'surge', 'surprise', 'surround', 'survey', 'suspect', 'sustain', 'swallow', 'swamp', 'swap', 'swarm', 'swear', 'sweet', 'swift', 'swim', 'swing', 'switch', 'sword', 'symbol', 'symptom', 'syrup', 'system', 'table', 'tackle', 'tag', 'tail', 'talent', 'talk', 'tank', 'tape', 'target', 'task', 'taste', 'tattoo', 'taxi', 'teach', 'team', 'tell', 'ten', 'tenant', 'tennis', 'tent', 'term', 'test', 'text', 'thank', 'that', 'theme', 'then', 'theory', 'there', 'they', 'thing', 'this', 'thought', 'three', 'thrive', 'throw', 'thumb', 'thunder', 'ticket', 'tide', 'tiger', 'tilt', 'timber', 'time', 'tiny', 'tip', 'tired', 'tissue', 'title', 'toast', 'tobacco', 'today', 'toddler', 'toe', 'together', 'toilet', 'token', 'tomato', 'tomorrow', 'tone', 'tongue', 'tonight', 'tool', 'tooth', 'top', 'topic', 'topple', 'torch', 'tornado', 'tortoise', 'toss', 'total', 'tourist', 'toward', 'tower', 'town', 'toy', 'track', 'trade', 'traffic', 'tragic', 'train', 'transfer', 'trap', 'trash', 'travel', 'tray', 'treat', 'tree', 'trend', 'trial', 'tribe', 'trick', 'trigger', 'trim', 'trip', 'trophy', 'trouble', 'truck', 'true', 'truly', 'trumpet', 'trust', 'truth', 'try', 'tube', 'tuition', 'tumble', 'tuna', 'tunnel', 'turkey', 'turn', 'turtle', 'twelve', 'twenty', 'twice', 'twin', 'twist', 'two', 'type', 'typical', 'ugly', 'umbrella', 'unable', 'unaware', 'uncle', 'uncover', 'under', 'undo', 'unfair', 'unfold', 'unhappy', 'uniform', 'unique', 'unit', 'universe', 'unknown', 'unlock', 'until', 'unusual', 'unveil', 'update', 'upgrade', 'uphold', 'upon', 'upper', 'upset', 'urban', 'urge', 'usage', 'use', 'used', 'useful', 'useless', 'usual', 'utility', 'vacant', 'vacuum', 'vague', 'valid', 'valley', 'valve', 'van', 'vanish', 'vapor', 'various', 'vast', 'vault', 'vehicle', 'velvet', 'vendor', 'venture', 'venue', 'verb', 'verify', 'version', 'very', 'vessel', 'veteran', 'viable', 'vibrant', 'vicious', 'victory', 'video', 'view', 'village', 'vintage', 'violin', 'virtual', 'virus', 'visa', 'visit', 'visual', 'vital', 'vivid', 'vocal', 'voice', 'void', 'volcano', 'volume', 'vote', 'voyage', 'wage', 'wagon', 'wait', 'walk', 'wall', 'walnut', 'want', 'warfare', 'warm', 'warrior', 'wash', 'wasp', 'waste', 'water', 'wave', 'way', 'wealth', 'weapon', 'wear', 'weasel', 'weather', 'web', 'wedding', 'weekend', 'weird', 'welcome', 'west', 'wet', 'whale', 'what', 'wheat', 'wheel', 'when', 'where', 'whip', 'whisper', 'wide', 'width', 'wife', 'wild', 'will', 'win', 'window', 'wine', 'wing', 'wink', 'winner', 'winter', 'wire', 'wisdom', 'wise', 'wish', 'witness', 'wolf', 'woman', 'wonder', 'wood', 'wool', 'word', 'work', 'world', 'worry', 'worth', 'wrap', 'wreck', 'wrestle', 'wrist', 'write', 'wrong', 'yard', 'year', 'yellow', 'you', 'young', 'youth', 'zebra', 'zero', 'zone', 'zoo']
1015
16+
1117 # get_mnemonic create mnemonic from 128 bits entropy(the entropy_hexstr length is 32)
1218 # return 12 mnemonics
1319 # You can get more test data from: https://gist.github.com/zcc0721/63aeb5143807950f7b7051fadc08cef0
@@ -46,3 +52,79 @@ def get_mnemonic(entropy_hexstr=None):
4652 mnemonic_str += mnemonic_list[i]
4753 mnemonic_str += " "
4854 return mnemonic_str[:-1]
55+
56+
57+# get_seed create seed from mnemonic
58+# You can find more details from: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#from-mnemonic-to-seed
59+# You can get more test data from: https://gist.github.com/zcc0721/4918e891073a9ca6c444ec7490298e82
60+# test data 1:
61+# mnemonic_str: ancient young hurt bone shuffle deposit congress normal crack six boost despair
62+# seed_hexstr: afa3a86bbec2f40bb32833fc6324593824c4fc7821ed32eac1f762b5893e56745f66a6c6f2588b3d627680aa4e0e50efd25065097b3daa8c6a19d606838fe7d4
63+# test data 2:
64+# mnemonic_str: rich decrease live pluck friend recipe burden minor similar agent tired horror
65+# seed_hexstr: b435f948bd3748ede8f9d6f59728d669939e79c6c885667a5c138e05bbabde1de0dcfcbe0c6112022fbbf0da522f4e224a9c2381016380688b51886248b3156f
66+# test data 3:
67+# mnemonic_str: enough ginger just mutual fit trash loop mule peasant lady market hub
68+# seed_hexstr: ecc2bbb6c0492873cdbc81edf56bd896d3b644047879840e357be735b7fa7b6f4af1be7b8d71cc649ac4ca3816f9ccaf11bf49f4effb845f3c19e16eaf8bfcda
69+def get_seed(mnemonic_str):
70+ password_str = mnemonic_str
71+ salt_str = "mnemonic"
72+ seed_hexstr = pbkdf2.PBKDF2(password_str, salt_str, iterations=2048, digestmodule=hashlib.sha512, macmodule=hmac).hexread(64)
73+ return seed_hexstr
74+
75+
76+# s_str must be >= 32 bytes long and gets rewritten in place.
77+# This is NOT the same pruning as in Ed25519: it additionally clears the third
78+# highest bit to ensure subkeys do not overflow the second highest bit.
79+def prune_root_scalar(s_str):
80+ s_bytes = bytes.fromhex(s_str)
81+ s = bytearray(s_bytes)
82+ s[0] = s[0] & 248
83+ s[31] = s[31] & 31 # clear top 3 bits
84+ s[31] = s[31] | 64 # set second highest bit
85+ return s
86+
87+
88+# get_root_xprv create rootxprv from seed
89+# seed_hexstr length is 512 bits.
90+# root_xprv length is 512 bits.
91+# You can get more test data from: https://gist.github.com/zcc0721/0aa1b971f4bf93d8f67e25f57b8b97ee
92+# test data 1:
93+# seed_hexstr: afa3a86bbec2f40bb32833fc6324593824c4fc7821ed32eac1f762b5893e56745f66a6c6f2588b3d627680aa4e0e50efd25065097b3daa8c6a19d606838fe7d4
94+# root_xprv_hexstr: 302a25c7c0a68a83fa043f594a2db8b44bc871fced553a8a33144b31bc7fb84887c9e75915bb6ba3fd0b9f94a60b7a5897ab9db6a48f888c2559132dba9152b0
95+# test data 2:
96+# seed_hexstr: b435f948bd3748ede8f9d6f59728d669939e79c6c885667a5c138e05bbabde1de0dcfcbe0c6112022fbbf0da522f4e224a9c2381016380688b51886248b3156f
97+# root_xprv_hexstr: 6032adeb967ac5ccbf988cf8190817bf9040c8cfd9cdfe3d5e400effb2946946d478b61cc6be936f367ae769eb1dc65c473ee73cac2eb43cf6d5e7c62b7f0062
98+# test data 3:
99+# seed_hexstr: ecc2bbb6c0492873cdbc81edf56bd896d3b644047879840e357be735b7fa7b6f4af1be7b8d71cc649ac4ca3816f9ccaf11bf49f4effb845f3c19e16eaf8bfcda
100+# root_xprv_hexstr: a01d6b741b0e74b8d0836ac22b675bbf8e108148ef018d1b000aef1a899a134bd316c0f59e7333520ae1a429504073b2773869e95aa95bb3a4fa0ec76744025c
101+def get_root_xprv(seed_hexstr):
102+ hc_hexstr = hmac.HMAC(b'Root', bytes.fromhex(seed_hexstr), digestmod=hashlib.sha512).hexdigest()
103+ root_xprv_hexstr = prune_root_scalar(hc_hexstr[:64]).hex() + hc_hexstr[64:]
104+ return root_xprv_hexstr
105+
106+
107+# get_xpub derives new xpub from xprv
108+# xprv length is 64 bytes.
109+# xpub length is 64 bytes.
110+# You can get more test data from: https://gist.github.com/zcc0721/d872a219fa91621d60357278bc62a512
111+# PLEASE ATTENTION:
112+# xprv_bytes = bytes.fromhex(xprv_hexstr)
113+# xprv_bytes[31] <= 127
114+# This is the precondition. Please ref: https://github.com/bytom/bytom/blob/dev/crypto/ed25519/internal/edwards25519/edwards25519.go#L958-L963
115+# test data 1:
116+# xprv_hexstr: c003f4bcccf9ad6f05ad2c84fa5ff98430eb8e73de5de232bc29334c7d074759d513bc370335cac51d77f0be5dfe84de024cfee562530b4d873b5f5e2ff4f57c
117+# xpub_hexstr: 1b0541a7664cee929edb54d9ef21996b90546918a920a77e1cd6015d97c56563d513bc370335cac51d77f0be5dfe84de024cfee562530b4d873b5f5e2ff4f57c
118+# test data 2:
119+# xprv_hexstr: 36667587de27eec684fc4b222276f22a24d9a82e947ee0119148bedd4dec461dd4e1b1d95dfb0f78896677ea1026af7510b41fabd3bd5771311c0cb6968337b2
120+# xpub_hexstr: ef0b3a8b0d66523d88f214900101ddb08a2a2a6db28bd8002e5995c1f1cbbc4cd4e1b1d95dfb0f78896677ea1026af7510b41fabd3bd5771311c0cb6968337b2
121+# test data 3:
122+# xprv_hexstr: 74a49c698dbd3c12e36b0b287447d833f74f3937ff132ebff7054baa18623c35a705bb18b82e2ac0384b5127db97016e63609f712bc90e3506cfbea97599f46f
123+# xpub_hexstr: 522940d6440fdc45363df2097e9cac29a9a8a33ac339f8b7cff848c199db5a1ca705bb18b82e2ac0384b5127db97016e63609f712bc90e3506cfbea97599f46f
124+def get_xpub(xprv_hexstr):
125+ xprv_bytes = bytes.fromhex(xprv_hexstr)
126+ scalar = decodeint(xprv_bytes[:len(xprv_bytes)//2])
127+ buf = encodepoint(scalarmultbase(scalar))
128+ xpub = buf + xprv_bytes[len(xprv_bytes)//2:]
129+ xpub_hexstr = xpub.hex()
130+ return xpub_hexstr
\ No newline at end of file
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ with open("README.md", "r") as fh:
55
66 setuptools.setup(
77 name="pybtm",
8- version="0.0.5",
8+ version="0.0.8",
99 author="zcc0721",
1010 author_email="zcc0721@foxmail.com",
1111 description="Python3 implementation of the Bytom protocol.",
Show on old repository browser