Что такое derivation path
HD Wallets and Derivation Paths: Explained
When accessing the blockchain with a hardware wallet or mnemonic phrase, you have the ability to interact with a seemingly infinite amount of addresses. But where do they come from? What do you do with them? How do you choose?
The path most traveled
Wallets that carry the functionality to derive many different addresses from a single access point are called HD wallets, which stands for Hierarchical Deterministic wallets. When these wallets are first generated, a root seed/key is derived. This is the foundation seed from which all branches and addresses will stem from in that particular wallet. In most cases, this key is derived from an entropy standard of 128 or 256 bits. The higher the entropy, the more randomized and secure this seed is.
From there, the wallet uses BIPs, which stands for ‘Bitcoin Improvement Protocol’, to determine how the seed will branch out into different addresses or cryptocurrencies. Even though this standard has the word Bitcoin in it, BIP 44 allows the protocols to be used on different cryptos. There are other BIPs as well, such as BIP 32, 39, and 43. These are often mentioned in the crypto-space, and each carries their own value to the entire system. For example, BIP 39 is used to generate mnemonic phrases across the board, taken from a long list of words shown here. These protocols are important, but are not necessary to understand for the general public.
A wide variety of wallets use these protocols, although the full extent of it often remains undercover. For example, MEWconnect uses an HD wallet, but we only show the first address from the vast list of addresses to the user, simplifying their process.
This can be confusing for users who go to restore their mnemonic phrase on a web interface like MEW, only to be shown millions of unused, empty addresses. In these scenarios, your expected address should populate as the first address you see in the list.
In all other cases, such as hardware wallets or raw mnemonic phrases, the user is able to choose which address they’d like to interact with each time they access their wallet. There’s no real benefit or detriment to this method, it just allows the user more choice. But all addresses are made equally, and the first one is usually easiest for keeping track down the road.
Same standard, different sequence
When you connect through your HD wallet, some wallets use slightly different paths for connection. Each path will generate a completely new list of addresses, relative to your root private key. That’s why it’s important to keep derivation paths in mind when troubleshooting issues regarding addresses accessed with hardware wallets.
For example, the general path for connecting to the base Ethereum set of addresses looks like this: m/44’/60’/0’/0. Trezor, MetaMask, Digital Bitbox, Jaxx, and Exodus, MEWconnect are just a few HD wallets that use this path.
This sequence is broken down into different sections and changes based on what you’re working with. The sequence goes:
m’ / purpose’ / coin_type’ / account’ / change / address_index
Any change to that path number or sequence will completely alter the addresses you expect to see. Ethereum Classic takes a different path, using this sequence: m/44’/61’/0’/0. Then hardware wallets like Ledger take an even more varied sequence specific to Ethereum Classic: m/44’/60’/160720’/0.
As you can see, not only can different cryptocurrencies have different sequences for deriving addresses, but hardware wallets and extensions can also take different paths than the norm, making room for a lot of variation.
Common paths
Here is a list of the paths we offer for connection with MyEtherWallet:
Ethereum Classic — m’/44’/61’/0’/0
Ethereum Testnet (Ropsten) — m’/44’/1’/0’/0
Ethereum (Ledger) — m’/44’/60’/0’
Ethereum Classic (Ledger) — m’/44’/60’/160720’/0
Ethereum Classic (Ledger, Vintage MEW) — m’/44’/60’/160720’/0’
Ethereum (Ledger Live) — m’/44’/60’
Ethereum Classic (Ledger Live) — m’/44’/61’
Ethereum (KeepKey) — m’/44’/60’
Ethereum Classic (KeepKey) — m’/44’/61’
WTF Is A Derivation Path?
How does one address turn into UNLIMITED addresses?
Using a wallet in the land of crypto is far different than the traditional world. There are new words, new concepts, and, depending on the type of account you make, the process can be confusing. You can create a private key, a keystore file (a private key protected by a password), or a mnemonic phrase (a string of words that can access multiple private keys).
Aside from having different security features, the biggest difference between each of these is that a private key or keystore file only creates one account. Creating a mnemonic phrase gives you control of many accounts, all accessible with that same phrase.
How does a single phrase create more than one address?
A mnemonic phrase — otherwise known as a “Hierarchical Deterministic Wallet” — generates addresses by taking the phrase and combining it with a piece of information called a derivation path. Together, they create any number of accounts, using Complex Math™ aka cryptography.
So, what is a derivation path?
Before we try to understand what a derivation path is, let’s look at what the word derive means. The standard definition of derive is “to obtain something from a specified source.” In a mathematical context, the definition is a bit more specific: “To obtain [a function or equation] from another by a sequence of logical steps, for example by differentiation.”
This, put more simply, is to obtain something, from something else, in a very specific way. “Derivation Path” is just a fancy way of saying “this is the thing you use to get all your accounts from your mnemonic phrase.”
The anatomy of a derivation path
This is what a derivation path looks like: m/44’/60’/0’/0’/0
Address #1: m/44’/60’/0’/0’/0
Address #2: m/44’/60’/0’/0’/1
Address #3: m/44’/60’/0’/0’/2
….
Address #99: m/44’/60’/0’/0’/98
(In programming, you start counting at 0. 0…1…2…3… rather than 1…2….3….This different than how we count in our day-to-day lives, so it can be confusing at first.)
History lesson: Addresses in Bitcoin (UTXO) versus Ethereum
Bitcoin and Ethereum operate differently whenever you send a transaction. On the Bitcoin network, when you send coins from one address to another, you typically send your entire balance. Part of what you send goes to a receiver address, and the remainder goes to a secondary, or “change,” address. This is called “UTXO” or “Unspent Transaction Output.” In order to know the balance, you actually have to add up all the UTXO’s. A technical explanation of this can be found here.
Ethereum, on the other hand, uses an account-based system, which operates more like a traditional banking system would. This means that each account, or address, directly spends or receives value. There are several advantages to using this system, such as ease of tracing transactions and how double spending is prevented. It also allows for smart contracts to hold a balance in the same way a “normal” account would. Because of this, each Ethereum address can have a balance, contract code, and data storage, and the system allows the balance to change for any address with each transaction.
The complexity and robustness of the Ethereum Virtual Machine, which executes the contract code, is more easily served by the account method. Having the value, contract, and storage information bound to a single address saves space in the current state of the chain. A more in-depth article on these differences can be found here.
Regardless, the reason behind the mnemonic phrase, derivation path, and seemingly unnecessary complexity comes from Bitcoin. The specification was made before Ethereum even existed and helped solve a very specific problem: it allowed you to send bitcoin to the receiver and send all the “change” to a new address that you controlled without having to create, backup, and secure a new private key each time. Nifty, right?
Derivation paths and HD Wallets in general are a great example of how, slowly but surely, we are improving how we interact with the blockchain. You might have seen one when accessing a wallet via mnemonic phrase or when using a Ledger or a Trezor. Hopefully when you look at a derivation path now, it’s less meaningless numbers and more awe-inspiring technology.
Derivation Paths
How HD wallets derive keys.
The cool thing about extended keys is that they can derive children, and these child keys can derive more children, and so on. This allows you to create a tree of extended keys, with each key having its own unique derivation path from the master key.
You can derive keys in any way you want. But to help with compatibility between wallets, we have a set structure for how we derive keys for use in a hierarchical deterministic wallet.
The most common derivation paths used are:
1. Notation
First of all, we have a basic notation for describing the derivation path for a specific extended key. For example:
The slashes / indicate a new level in the tree (a new child). The numbers (e.g. 0 ) indicate the child number from the parent.
The only other thing you need to know about the notation is that a ‘ or h indicates a hardened child extended private key (which means that the public keys it creates cannot be derived by the extended public key ):
Tip: You can derive up to 4294967296 children from a single extended key. The first half are for normal children, and the second half are for hardened children.
Note: Deriving hardened children is the default. Normal children are only derived when it would be useful to have a corresponding extended public key for deriving the same public keys.
2. Wallet Structure
To help with consistency between wallets, BIP 44 introduced the following structure:
The levels in the tree have a meaning. m : Master
The master key (created from a seed).
m/44′ : Purpose (hardened)
This specifies the upcoming wallet structure.
There are three schemes currently being used by wallets:
m/44’/0′ : Coin Type (hardened)
The cryptocurrency the keys will be used for.
Different cryptocurrencies can use the same private keys and public keys derived from a seed. So instead of having separate seeds for different currencies (or using the same public keys on different chains), we can use the same seed with different derivation paths instead.
This is useful in hardware wallets, where you can have a single seed and use it for holding a variety of different coins.
m/44’/0’/0′ : Account (hardened)
For example, you can use the same seed yet still create separate “pots” for receiving payments. The coins in these separate accounts will never be mixed.
Tip: You could obviously create many different accounts at various indexes at this level. But to keep recovery simple, a wallet should create accounts in sequential order, and not create a new account if a previous one has not been used.
m/44’/0’/0’/0 : Change
The keys and addresses we use are separated in to “Receiving” and “Change”.
This means you will always be able to identify the coins that arrived from external payments.
m/44’/0’/0’/0/0 : Index
These are the extended keys that you use for their private keys and public keys for actual usage in the wallet.
So as you can see, the first few levels in the path are just used to structure the hierarchical deterministic wallet in a practical way.
The actual keys used for addresses are in lowest level of the tree.
3. Derivation Paths
Here are some actual derivation paths used by wallets.
BIP 32: m/0’/0/0 (deprecated)
This is the original derivation path specification in BIP 32.
This is a nice and simple derivation path, but it doesn’t allow for the option of creating alternative derivation path schemes.
This is where BIP 44, BIP 49, and BIP 84 come in.
BIP 44: m/44’/0’/0’/0/0
BIP 44 builds upon the original BIP 32 scheme to include a purpose 1 (which is like a version number to identify the upcoming scheme), as well as a coin type so that the same seed can be used to generate keys for different cryptocurrencies.
The public keys are encoded to 1addresses ( P2PKH ).
BIP 49: m/49’/0’/0’/0/0
BIP 49 uses the same structure as BIP 44, but is used to indicate that the public keys should be encoded in to 3addresses ( P2WPKH-P2SH ).
BIP 49 Serialization
The extended keys in the BIP 49 derivation path use the version bytes 049d7878 “yprv” or 049d7cb2 “ypub” during serialization. This allows you to identify an extended key when it is part of the BIP 49 scheme.
BIP 84: m/84’/0’/0’/0/0
BIP 84 uses the same structure as BIP 44, but is used to indicate that the public keys should be encoded in to bc1addresses ( P2WPKH ).
BIP 84 Serialization
The extended keys in the BIP 84 derivation path use the version bytes 04b2430c “zprv” or 04b24746 “zpub” during serialization. This allows you to identify an extended key when it is part of the BIP 84 scheme.
4. Example
The following takes a seed (mnemonic sentence or hex) and derivation path, and shows you the address for the private extended key in that path (along with the next few children too).
Gap Limit: When recovering a wallet from a seed, you should only check the first 20 receiving addresses for a balance. If none have been used in the past, you can consider the account as unused.
Never enter your actual seed in to a website. Websites can save what you enter and use it to steal your coins.
5. Code
To save on code, these snippets use handy libraries (bitcoin-ruby, hdkeychain) for deriving extended keys.
Использование аппаратного кошелька с кастомным путем деривации
1 мин. чтения
При выполнении доступа к аппаратному кошельку вам предоставляется выбор, какой путь деривации использовать. В большинстве случаев предпочтительно для удобства использовать путь по умолчанию, поскольку каждый путь ведет к разному набору адресов. Однако бывают случаи, когда необходим другой путь. Мы предоставили возможность добавлять кастомные пути деривации, чтобы вы могли выполнить подключение с помощью любого пути. Посмотрите нашу статью для более подробной информации о путях деривации.
Шаг 1. Направляйтесь на главную страницу MEW и нажмите “Доступ к кошельку”, затем выберите “Аппаратный кошелек”.
Шаг 2. После выбора вашего аппаратного кошелька должно появиться окно, как показано ниже. Нажмите на маленькую стрелку, чтобы развернуть большой список путей деривации.
Шаг 3. Выберите “Кастомный путь” внизу правого столбца и введите данные кастомного пути, который вы хотите использовать.
Готово! После добавления вашего кастомного пути вы должны увидеть другой список адресов, к которым можно подключиться.
Использование аппаратного кошелька Ledger на Android-устройстве
Использование аппаратного кошелька Trezor с MEW
Использование аппаратного кошелька Secalot с MEW
Использование аппаратного кошелька KeepKey с MEW
Использование аппаратного кошелька CoolWallet с MEW
Использование аппаратного кошелька BC Vault с MEW
Использование аппаратного кошелька Digital BitBox с MEW
Использование аппаратного кошелька Ledger с MEW
Использование аппаратного кошелька с кастомным узлом
Использование аппаратного кошелька с кастомным путем деривации
Использование аппаратного кошелька Ledger на Android-устройстве
Не удается подключиться к аппаратному кошельку
Использование аппаратного кошелька с кастомным путем деривации
1 мин. чтения
При выполнении доступа к аппаратному кошельку вам предоставляется выбор, какой путь деривации использовать. В большинстве случаев предпочтительно для удобства использовать путь по умолчанию, поскольку каждый путь ведет к разному набору адресов. Однако бывают случаи, когда необходим другой путь. Мы предоставили возможность добавлять кастомные пути деривации, чтобы вы могли выполнить подключение с помощью любого пути. Посмотрите нашу статью для более подробной информации о путях деривации.
Шаг 1. Направляйтесь на главную страницу MEW и нажмите “Доступ к кошельку”, затем выберите “Аппаратный кошелек”.
Шаг 2. После выбора вашего аппаратного кошелька должно появиться окно, как показано ниже. Нажмите на маленькую стрелку, чтобы развернуть большой список путей деривации.
Шаг 3. Выберите “Кастомный путь” внизу правого столбца и введите данные кастомного пути, который вы хотите использовать.
Готово! После добавления вашего кастомного пути вы должны увидеть другой список адресов, к которым можно подключиться.
Как узнать приватный ключ из seed-фразы
Обычно в некастодиальных кошельках для восстановления доступа к средствам используется seed-фраза. Seed — это последовательность из 12, 18 или 24 слов, стандарта BIP39. Данный стандарт содержит словарь из 2048 слов и протоколы генерации ключей BIP32-44-49-84-141. Имея сид-фразу от кошелька вы можете получить доступ к средствам практически в любом некастодиальном приложении-кошельке. Соответственно надежность хранения сид-фразы — это первоочередная задача для пользователя криптовалют. О способах ее хранения мы ранее уже говорили в этой статье.
В некоторых кошельках доступ к средствам осуществляется посредством Private Key (приватный ключ), он представляет собой последовательность буквенно-цифровых символов. Стоит отметить, что приватный ключ обеспечивает доступ только к одному конкретному адресу монеты, в то время как seed-фраза дает полный контроль над всеми адресами монет, которые были сгенерированы в кошельке. Простыми словами — seed-фраза содержит в себе сразу все приватные ключи от всех адресов в кошельке.
Команда Trustee Wallet заведомо убрала функцию импорта/экспорта приватного ключа из приложения. Связано это как с определенными правилами безопасности, так и с комфортом использования — намного легче импортировать один seed, чем множество приватных ключей. Однако, процесс извлечения приватного ключа из seed-фразы достаточно прост, давайте рассмотрим его на примере монеты Ripple (XRP).
Внимание! Дальнейшие операции будут производиться с вашей seed-фразой. Продолжая следовать инструкции вы берете на себя полную ответственность за сохранность ваших активов.
Данный способ можно использовать для получения приватных ключей из seed-фразы любой монеты, при этом важно соблюдать правила “цифровой гигиены”. Заметьте, что правила обращения и хранения с приватным ключом сравнимы с правилами относительно seed-фразы — никому не передавать, надежно хранить и т. д.