本文整理汇总了Python中mnemonic.Mnemonic类的典型用法代码示例。如果您正苦于以下问题:Python Mnemonic类的具体用法?Python Mnemonic怎么用?Python Mnemonic使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Mnemonic类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_device_by_mnemonic
def load_device_by_mnemonic(self, mnemonic, pin, passphrase_protection, label, language, skip_checksum=False):
m = Mnemonic("english")
if not skip_checksum and not m.check(mnemonic):
raise Exception("Invalid mnemonic checksum")
# Convert mnemonic to UTF8 NKFD
mnemonic = Mnemonic.normalize_string(mnemonic)
# Convert mnemonic to ASCII stream
mnemonic = unicode(str(bytearray(mnemonic, "utf-8")), "utf-8")
if self.features.initialized:
raise Exception("Device is initialized already. Call wipe_device() and try again.")
resp = self.call(
proto.LoadDevice(
mnemonic=mnemonic,
pin=pin,
passphrase_protection=passphrase_protection,
language=language,
label=label,
skip_checksum=skip_checksum,
)
)
self.init_device()
return resp
示例2: test_utf8_nfkd
def test_utf8_nfkd(self):
# The same sentence in various UTF-8 forms
words_nfkd = u"Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a"
words_nfc = u"P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f"
words_nfkc = u"P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f"
words_nfd = u"Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a"
passphrase_nfkd = (
u"Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko"
)
passphrase_nfc = (
u"Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko"
)
passphrase_nfkc = (
u"Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko"
)
passphrase_nfd = (
u"Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko"
)
seed_nfkd = Mnemonic.to_seed(words_nfkd, passphrase_nfkd)
seed_nfc = Mnemonic.to_seed(words_nfc, passphrase_nfc)
seed_nfkc = Mnemonic.to_seed(words_nfkc, passphrase_nfkc)
seed_nfd = Mnemonic.to_seed(words_nfd, passphrase_nfd)
self.assertEqual(seed_nfkd, seed_nfc)
self.assertEqual(seed_nfkd, seed_nfkc)
self.assertEqual(seed_nfkd, seed_nfd)
示例3: _check_list
def _check_list(self, language, vectors):
mnemo = Mnemonic(language)
for v in vectors:
code = mnemo.to_mnemonic(unhexlify(v[0]))
seed = hexlify(Mnemonic.to_seed(code, passphrase = 'TREZOR'))
self.assertIs(mnemo.check(v[1]), True)
self.assertEqual(v[1], code)
self.assertEqual(v[2], seed)
示例4: test_to_entropy
def test_to_entropy(self):
data = [
bytearray((random.getrandbits(8) for _ in range(32))) for _ in range(1024)
]
data.append(b"Lorem ipsum dolor sit amet amet.")
m = Mnemonic("english")
for d in data:
self.assertEqual(m.to_entropy(m.to_mnemonic(d).split()), d)
示例5: restore
def restore(ctx):
""" Restore a wallet from a mnemonic
\b
If you accidently deleted your wallet file or the file
became corrupted, use this command to restore your wallet. You
must have your 12 word phrase (mnemonic) that was displayed
when you created your wallet.
"""
# Stop daemon if it's running.
d = None
try:
d = get_daemonizer()
except OSError as e:
pass
if d:
try:
d.stop()
except exceptions.DaemonizerError as e:
click.echo("ERROR: Couldn't stop daemon: %s" % e)
ctx.exit(code=4)
# Check to see if the current wallet path exists
if os.path.exists(ctx.obj['wallet_path']):
if click.confirm("Wallet file already exists and may have a balance. Do you want to delete it?"):
os.remove(ctx.obj['wallet_path'])
else:
click.echo("Not continuing.")
ctx.exit(code=4)
# Ask for mnemonic
mnemonic = click.prompt("Please enter the wallet's 12 word mnemonic")
# Sanity check the mnemonic
m = Mnemonic(language='english')
if not m.check(mnemonic):
click.echo("ERROR: Invalid mnemonic.")
ctx.exit(code=5)
if click.confirm("Did the wallet have a passphrase?"):
passphrase = get_passphrase()
else:
passphrase = ''
# Try creating the wallet
click.echo("\nRestoring...")
wallet = Two1Wallet.import_from_mnemonic(
data_provider=ctx.obj['data_provider'],
mnemonic=mnemonic,
passphrase=passphrase)
wallet.to_file(ctx.obj['wallet_path'])
if Two1Wallet.check_wallet_file(ctx.obj['wallet_path']):
click.echo("Wallet successfully restored.")
else:
click.echo("Wallet not restored.")
ctx.exit(code=6)
示例6: test_to_entropy
def test_to_entropy(self):
data = [bytearray((random.getrandbits(8) for _ in range(32))) for _ in
range(1024)]
data.append(
b" I'm a little teapot, short and stout. Here is my handle. "
b"Here is my spout. When I get all steamed up, hear me shout. "
b"Tip me over and pour me out!! ")
m = Mnemonic('english')
for d in data:
self.assertEqual(m.to_entropy(m.to_mnemonic(d).split()), d)
示例7: showDetails
def showDetails(mnemonic, passphrase="", i=1):
myMnemonic = mnemonic
passphrase = passphrase
mnemo = Mnemonic('english')
seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))
print 'Seed:\t\t\t\t', seed
priv = bitcoin.bip32_master_key(unhexlify(seed))
print 'Xpriv:\t\t\t\t', priv
key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv), 'wif_compressed')
print 'Key:\t\t\t\t', key
pub = bitcoin.bip32_privtopub(priv)
print 'Derived public key:\t', pub
pubHex = bitcoin.bip32_extract_key(pub)
print 'public key (hex):\t', pubHex
print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex)
print ""
print "TREZOR Keys:"
account = 0
derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account)
print 'Derived private key:', derivedPrivateKey
privateKey = bitcoin.encode_privkey(bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed')
print 'private key (wif):\t', privateKey
derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey)
print 'Derived public key:', derivedPublicKey
publicKeyHex = bitcoin.privtopub(privateKey)
print 'public key (hex):\t', publicKeyHex
address = bitcoin.pubtoaddr(publicKeyHex)
print 'address:\t\t\t', address
print ""
print "Account public keys (XPUB)"
xpubs = []
for i in range(0, i):
derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+i)
xpub = bitcoin.bip32_privtopub(derivedPrivateKey)
print 'Account', i, 'xpub:', xpub
xpubs.append(xpub)
return xpubs
示例8: _check_list
def _check_list(self, language, vectors):
mnemo = Mnemonic(language)
for v in vectors:
code = mnemo.to_mnemonic(unhexlify(v[0]))
seed = hexlify(Mnemonic.to_seed(code, passphrase="TREZOR"))
xprv = Mnemonic.to_hd_master_key(unhexlify(seed))
if sys.version >= "3":
seed = seed.decode("utf8")
self.assertIs(mnemo.check(v[1]), True)
self.assertEqual(v[1], code)
self.assertEqual(v[2], seed)
self.assertEqual(v[3], xprv)
示例9: _check_list
def _check_list(self, language, vectors):
mnemo = Mnemonic(language)
for v in vectors:
code = mnemo.encode(unhexlify(v[0]))
data = hexlify(mnemo.decode(code))
self.assertEqual(v[1], code)
self.assertEqual(v[0], data)
print "input: ", v[0], "(%d bits)" % len(v[0] * 4)
print "mnemonic:", code, "(%d words)" % len(code.split(' '))
print
示例10: restore_wallet
def restore_wallet(PIN):
if len(PIN) == 0:
PIN = choose_PIN_code()
retry = True
while retry:
userWords = []
print_screen_title("RESTORE AN EXISTING WALLET (step 2/3)")
print "Please type in your 24 words backup phrase."
print "Warning: BIP39 is " + term.bold("case-sensitive!") + "\n"
for i in range(1, 25):
validWord = False
while not validWord:
typedWord = raw_input("Word #" + str(i) + "? ")
typedWord = typedWord.lower()
if len(typedWord) > 0:
if typedWord in english_wordlist:
userWords.append(typedWord)
validWord = True
else:
print "This word is not in the official BIP39 english wordlist."
else:
print "Type a word a please."
bip39Seed = " ".join(userWords)
mnemo = Mnemonic("english")
if mnemo.check(bip39Seed) == False:
print ""
print "An " + term.bold("error occurred") + "."
print "Your BIP39 seed is invalid !\n"
question = "Try again to type the seed?"
retry = yes_or_no_question(question)
else:
retry = False
print "\nWe're almost done!"
print "Here is your BIP39 seed:\n"
print_wordlist(bip39Seed)
print "\nPlease check that it is correct."
question = "Continue and restore your wallet from this seed?"
choice = yes_or_no_question(question)
if choice == True:
start_flashing(PIN, bip39Seed)
else:
restore_wallet(PIN)
示例11: __init__
def __init__(self):
conf = read_config_file("ew.conf")
if conf['entropy']:
entropy = binascii.unhexlify(conf['entropy'])
else:
mnemo = Mnemonic('english')
entropy = mnemo.to_entropy(conf['passphrase'])
print("entropy=" + entropy.hex())
master = BIP32Node.from_master_secret(entropy, 'BTC')
print("master address=" + master.address())
# /m/4544288'/0'/0'/0/0 alias
alias = master.subkey(i=EW_DERIVATION, is_hardened=True).subkey(i=0, is_hardened=True).subkey(i=0, is_hardened=True).subkey(i=0, is_hardened=False).subkey(i=0, is_hardened=False)
self.address = alias.address()
print("alias address=" + self.address)
self.key = CBitcoinSecret(alias.wif())
示例12: testvectors
def testvectors():
"""
This function exercises the libraries and double checks that they are
returning expected data.
"""
print "Self Checking",
print_dot()
if "51477815b762e495e0f7deb01fb2969f2e15ba4615fa4a5aafc23ccf5c3c8bd2".decode('hex') != \
privkey_to_pubkey("12fab77add10bcabe1b62b3fe8b167e966e4beee38ccf0062fdd207b5906c841".decode('hex'), False):
return False
print_dot()
doublecheck_key_works("12fab77add10bcabe1b62b3fe8b167e966e4beee38ccf0062fdd207b5906c841".decode('hex'), \
"51477815b762e495e0f7deb01fb2969f2e15ba4615fa4a5aafc23ccf5c3c8bd2".decode('hex'), False)
print_dot()
if "51477815-b762e495-e0f7deb0-1fb2969f-2e15ba46-15fa4a5a-afc23ccf-5c3c8bd2-6c4cf980" != \
pubkey_to_send("51477815b762e495e0f7deb01fb2969f2e15ba4615fa4a5aafc23ccf5c3c8bd2".decode('hex'), False):
return False
print_dot()
if "Fs1Ts7PsKMwo4ftCYxQJ3rW4pLiRBXyGEjMrxtHycLu52aDgKGEy" != \
private_key_to_human("12fab77add10bcabe1b62b3fe8b167e966e4beee38ccf0062fdd207b5906c841".decode('hex'), False):
return False
print_dot()
if not onlyB58chars("Xw1"):
return False
if onlyB58chars("$"):
return False
print_dot()
if "4f4488c609552caf2c7a508108809518e9a1ab3ae6dc259a1e2e9989d053018d".decode('hex') != \
hashlib.sha256(hashlib.sha256("647812fab77add10bcabe1b62b3fe8b167e966e4beee38ccf0062fdd207b5906c841" \
.decode('hex')).digest()).digest():
return False
print_dot()
if True != verify_koinify_words("legal winner thank year wave sausage worth useful legal winner thank yellow"):
return False
print_dot()
if True == verify_koinify_words("legal winner thank year wave sausage worth useful legal winner thank thank"):
return False
print_dot()
if "878386efb78845b3355bd15ea4d39ef97d179cb712b77d5c12b6be415fffeffe5f377ba02bf3f8544ab800b955e51fbff09828f682052a20faa6addbbddfb096" \
.decode('hex') != Mnemonic.to_seed("legal winner thank year wave sausage worth useful legal winner thank yellow", ''):
return False
print_dot()
if "0488ade4000000000000000000598b4595ea72802756519e65a797234231d7d4f13d650cb06db15957c2368b1b007e56ecf5943d79e1f5f87e11c768253d7f3fcf30ae71335611e366c578b4564e"\
.decode('hex') != BIP32Key.fromEntropy("878386efb78845b3355bd15ea4d39ef97d179cb712b77d5c12b6be415fffeffe5f377ba02bf3f8544ab800b955e51fbff09828f682052a20faa6addbbddfb096"\
.decode('hex'), public=False).ExtendedKey(private=True, encoded=False):
return False
print_dot()
if "7999d61b8f5efc24b437244ff82b69ba474deeadbf144421f05d5b4b5ab20a8e".decode('hex') != \
koinify_words_to_private_key("legal winner thank year wave sausage worth useful legal winner thank yellow", False):
return False
print("\n")
# everything checks out ok
return True
示例13: processNext
def processNext(self):
self.persoData['seed'] = None
if self.ui.RestoreWalletButton.isChecked():
# Check if it's an hexa string
seedText = str(self.ui.seed.text())
if len(seedText) == 0:
QMessageBox.warning(self, "Error", "Please enter a seed", "OK")
return
if seedText[-1] == 'X':
seedText = seedText[0:-1]
try:
self.persoData['seed'] = seedText.decode('hex')
except:
pass
if self.persoData['seed'] == None:
if not MNEMONIC:
QMessageBox.warning(self, "Error", "Mnemonic API not available. Please install https://github.com/trezor/python-mnemonic", "OK")
return
if not self.mnemonic.check(seedText):
QMessageBox.warning(self, "Error", "Invalid mnemonic", "OK")
return
self.persoData['seed'] = Mnemonic.to_seed(seedText)
else:
if (len(self.persoData['seed']) < 32) or (len(self.persoData['seed']) > 64):
QMessageBox.warning(self, "Error", "Invalid seed length", "OK")
return
dialog = SecurityDialog(self.persoData, self)
self.hide()
dialog.exec_()
示例14: test_similarity
def test_similarity(self):
similar = (
('a', 'c'), ('a', 'e'), ('a', 'o'),
('b', 'd'), ('b', 'h'), ('b', 'p'), ('b', 'q'), ('b', 'r'),
('c', 'e'), ('c', 'g'), ('c', 'n'), ('c', 'o'), ('c', 'q'), ('c', 'u'),
('d', 'g'), ('d', 'h'), ('d', 'o'), ('d', 'p'), ('d', 'q'),
('e', 'f'), ('e', 'o'),
('f', 'i'), ('f', 'j'), ('f', 'l'), ('f', 'p'), ('f', 't'),
('g', 'j'), ('g', 'o'), ('g', 'p'), ('g', 'q'), ('g', 'y'),
('h', 'k'), ('h', 'l'), ('h', 'm'), ('h', 'n'), ('h', 'r'),
('i', 'j'), ('i', 'l'), ('i', 't'), ('i', 'y'),
('j', 'l'), ('j', 'p'), ('j', 'q'), ('j', 'y'),
('k', 'x'),
('l', 't'),
('m', 'n'), ('m', 'w'),
('n', 'u'), ('n', 'z'),
('o', 'p'), ('o', 'q'), ('o', 'u'), ('o', 'v'),
('p', 'q'), ('p', 'r'),
('q', 'y'),
('s', 'z'),
('u', 'v'), ('u', 'w'), ('u', 'y'),
('v', 'w'), ('v', 'y')
)
languages = Mnemonic.list_languages()
fail = False
for lang in languages:
mnemo = Mnemonic(lang)
for w1 in mnemo.wordlist:
for w2 in mnemo.wordlist:
if len(w1) != len(w2):
continue
if w1 == w2:
continue
if w1 > w2:
# No need to print warning twice
continue
diff = []
for i in range(len(w1)):
if w1[i] != w2[i]:
if w1[i] < w2[i]:
pair = (w1[i], w2[i])
else:
pair = (w2[i], w1[i])
diff.append(pair)
# pairs.update((pair,))
if len(diff) == 1:
if list(diff)[0] in similar:
fail = True
print("Similar words (%s): %s, %s" % (lang, w1, w2))
if fail:
self.assert_(False, "Similar words found")
示例15: test_lengths
def test_lengths(self):
# check if wordlists contain words between 3 and 8 characters
languages = Mnemonic.list_languages()
for lang in languages:
mnemo = Mnemonic(lang)
words = [w for w in mnemo.wordlist if len(w) < 3 or len(w) > 8]
print("Language '{}'".format(lang))
self.assertListEqual(words, [])