当前位置: 首页>>代码示例>>Python>>正文


Python Mnemonic.check方法代码示例

本文整理汇总了Python中mnemonic.Mnemonic.check方法的典型用法代码示例。如果您正苦于以下问题:Python Mnemonic.check方法的具体用法?Python Mnemonic.check怎么用?Python Mnemonic.check使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mnemonic.Mnemonic的用法示例。


在下文中一共展示了Mnemonic.check方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_device_by_mnemonic

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
    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
开发者ID:kyuupichan,项目名称:python-keepkey,代码行数:28,代码来源:client.py

示例2: _check_list

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
 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)
开发者ID:Jud,项目名称:python-mnemonic,代码行数:10,代码来源:test_mnemonic.py

示例3: restore

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
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)
开发者ID:SamvitJ,项目名称:21BC-lib,代码行数:60,代码来源:cli.py

示例4: _check_list

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
 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)
开发者ID:trezor,项目名称:python-mnemonic,代码行数:14,代码来源:test_mnemonic.py

示例5: SeedDialog

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
class SeedDialog(QtGui.QDialog):

	def __init__(self, persoData, parent = None):
		QDialog.__init__(self, parent)
		self.persoData = persoData
		self.ui = ui.personalization01seed.Ui_Dialog()
		self.ui.setupUi(self)
		self.ui.seed.setEnabled(False)
		self.ui.RestoreWalletButton.toggled.connect(self.restoreWalletToggled)
		self.ui.NextButton.clicked.connect(self.processNext)
		self.ui.CancelButton.clicked.connect(self.processCancel)
		if MNEMONIC:
			self.mnemonic = Mnemonic('english')
			self.ui.mnemonicNotAvailableLabel.hide()

	def restoreWalletToggled(self, toggled):
		self.ui.seed.setEnabled(toggled)

	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_()

	def processCancel(self):
		self.reject()
		self.persoData['main'].reject()
开发者ID:smartqubit,项目名称:btchip-python,代码行数:53,代码来源:btchipPersoWizard.py

示例6: restore_wallet

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
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)
开发者ID:LedgerHQ,项目名称:ledger-starter-iso,代码行数:52,代码来源:init.py

示例7: verify_koinify_words

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
def verify_koinify_words(words):
    """
    This function checks to make sure there are multiple words and
    that the first word is in the english wordlist.
    Both of these errors would crash the Mnemonic library, so they should be checked before using it.
    The Mnemonic library checks for other errors.
    """
    if ' ' in words:
        wordchecker = Mnemonic('english')
        firstword = words.split(' ')[0]
        if firstword in wordchecker.wordlist:
            check = wordchecker.check(words)
            return check
        else:
            return False
    else:
        return False
开发者ID:FactomProject,项目名称:factoidGenesisManager,代码行数:19,代码来源:factoidGenesisManager.py

示例8: load_device_by_mnemonic

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
def load_device_by_mnemonic(
    client,
    mnemonic,
    pin,
    passphrase_protection,
    label,
    language="english",
    skip_checksum=False,
    expand=False,
):
    # Convert mnemonic to UTF8 NKFD
    mnemonic = Mnemonic.normalize_string(mnemonic)

    # Convert mnemonic to ASCII stream
    mnemonic = mnemonic.encode()

    m = Mnemonic("english")

    if expand:
        mnemonic = m.expand(mnemonic)

    if not skip_checksum and not m.check(mnemonic):
        raise ValueError("Invalid mnemonic checksum")

    if client.features.initialized:
        raise RuntimeError(
            "Device is initialized already. Call device.wipe() and try again."
        )

    resp = client.call(
        proto.LoadDevice(
            mnemonic=mnemonic,
            pin=pin,
            passphrase_protection=passphrase_protection,
            language=language,
            label=label,
            skip_checksum=skip_checksum,
        )
    )
    client.init_device()
    return resp
开发者ID:trezor,项目名称:python-trezor,代码行数:43,代码来源:debuglink.py

示例9: test_failed_checksum

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
 def test_failed_checksum(self):
     code = ('bless cloud wheel regular tiny venue bird web grief security '
             'dignity zoo')
     mnemo = Mnemonic('english')
     self.assertFalse(mnemo.check(code))
开发者ID:ghtdak,项目名称:python-mnemonic,代码行数:7,代码来源:test_mnemonic.py

示例10: PollyAudit

# 需要导入模块: from mnemonic import Mnemonic [as 别名]
# 或者: from mnemonic.Mnemonic import check [as 别名]
class PollyAudit():
    """
    Auditing tests and utilities for Polly.
    """
    
    
    def __init__(self, wordfile = 'wordlist.txt'):
        
        # Read create the mnemonic wordlist object
        self.mnemonic = Mnemonic("english")
    
        # Set up a default reference wallet
        self.wallet = Wallet.from_master_secret(bytes(0))
        
        # Set up a Polly communication pipe
        self.polly = PollyCom()
        
        # Default print padding
        self.PAD = "{:35}"
        
    #
    # Tests
    #
        
    def test_set_seed(self, wordlist):
        """
        Sets the wallet seed for Polly and the reference wallet.
        
        Note: Subsequent tests will use the seed set by this routine.
        
        wordlist -  a space separated string of 18 mnemonic words from the Polly wordlist.
                    Note: the checksum must be correct (part of the 18th word) - see BIP0039.
                    gen_wordlist can be used to generate a wordlist including the proper checksum.
        """
        
        assert len(wordlist.split(" ")) == 18, "expecting 18 words"
        assert self.mnemonic.check(wordlist) == True, "invalid word list"
        
        print (self.PAD.format("Set seed"), end='')
        
        # Set polly
        self.polly.send_set_master_seed(wordlist)
        print (self.__outok())
        
        # Set the reference wallet
        seed = self.mnemonic.to_seed(wordlist)
        self.wallet = Wallet.from_master_secret(seed)
        
        
    def test_key(self, keytype, account = 0, chain = 0, address = 0):
        """
        Performs a public key retrieval test, comparing Polly's key against the reference wallet.
       
        keytype - Type of key to retrieve, valid values are KEY_MASTER, KEY_ACCOUNT, KEY_CHAIN, or KEY_ADDRESS.
        account - Account to use for type KEY_ACCOUNT, KEY_CHAIN, KEY_ADDRESS.
        chain   - Chain to use for type KEY_CHAIN, KEY_ADDRESS.
        address - Index (0 - 0x7FFFFFFF) to use for type KEY_ADDRESS.
        """
        
        assert address < 0x80000000, "hardened address keys are not supported"
        
        if keytype == PollyCom.KEY_MASTER:
            print(self.PAD.format("Get master key"), end='')
            refkey = self.wallet
            check_chaincode = False
            
        elif keytype == PollyCom.KEY_ACCOUNT:
            print(self.PAD.format("Get account key m/" + str(account) + "h"), end='')
            refkey = self.wallet.subkey(account, is_hardened = True)
            check_chaincode = True
            
        elif keytype == PollyCom.KEY_CHAIN:
            print(self.PAD.format("Get chain key   m/" + str(account) + "h/" + str(chain)), end='')
            refkey = self.wallet.subkey(account, is_hardened = True).subkey(chain)
            check_chaincode = True
            
        else: # keytype == PollyCom.KEY_ADDRESS
            print(self.PAD.format("Get address key m/" + str(account) + "h/" + str(chain) + "/" + str(address)), end='')
            refkey = self.wallet.subkey(account, is_hardened = True).subkey(chain).subkey(address)
            check_chaincode = False
    
        # Get keypair from Polly 
        (pubx, puby, chaincode) = self.polly.send_get_public_key(keytype, account, chain, address)

        print (self.__outok())

        # Check against reference wallet
        addr       = encoding.public_pair_to_hash160_sec((pubx, puby))
        addr_check = encoding.public_pair_to_hash160_sec(refkey.public_pair)
        
        assert addr == addr_check, "public key mismatch\nexpected: " + self.hexstr(addr_check) + "\nactual:   " + self.hexstr(addr) 
        
        if check_chaincode == True :
            assert refkey.chain_code == chaincode, "chain code mismatch\nexpected: " + self.hexstr(refkey.chain_code) + "\nactual:   " + self.hexstr(chaincode) 
            
        


    def test_sign(self, keynums_satoshi, out_addr, out_satoshi, change_keynum, change_satoshi, prevtx_keynums, prevtx_outputs, prevtx_inputs):
        """
#.........这里部分代码省略.........
开发者ID:ngburke,项目名称:pollyaudit,代码行数:103,代码来源:audit.py


注:本文中的mnemonic.Mnemonic.check方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。