Что такое xpub и xprv?
Xpub (extended public key/master public key — расширенный открытый ключ) вместе с xprv (extended private key/master private key — расширенный закрытый ключ) позволяет вам генерировать почти бесконечное количество Биткоин-адресов без необходимости хранить и защищать отдельные закрытые ключи для каждого отдельно.
Чтобы защитить вашу конфиденциальность, рекомендуется использовать новый Биткоин-адрес для каждой транзакции. Но для каждого нового адреса требуется собственный закрытый ключ. В старые времена (до 2013 г.) Биткоин кошельки генерировали и хранили новый приватный ключ для каждого нового адреса. Представьте себе популярную биржу, использующую миллионы адресов. Бирже придется хранить и защищать миллионы индивидуальных закрытых ключей. Для биржи это превратится в головную боль! Должен быть способ получше.
В 2013 г. Питер Вилле один из основных разработчиков Bitcoin Core и стал автором BIP-32, который определяет стандарт для HD-кошельков (Hierarchical Deterministic — иерархически-детерминированных кошельков) — это кошельки, которые используют древообразную структуру, которая генерирует новую пару ключей из пары главных ключей для каждой крипто-транзакции, чтобы повысить конфиденциальность и безопасность. Этот тип кошелька позволяет вам генерировать тонну адресов, используя только мнемоническую Seed фразу. Это и называется xprv (extended private key/master private key — расширенный закрытый ключ) — https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
По сути, xprv — это закрытый ключ, а xpub — его открытый ключ, и каждый из них дополняется дополнительными данными. Эти дополнительные данные, называемые "chain code", помогают генерировать почти бесконечное количество дополнительных ключей. Все эти дополнительные ключи генерируются с использованием стандартного шаблона, поэтому их можно пересчитать в любое время. Почему это полезно? Допустим, у вас был кошелек с миллионами адресов, и, к сожалению, все данные были уничтожены. Пока у вас все еще есть исходная Seed фраза (xprv), вы сможете повторно сгенерировать все свои адреса, следуя стандартному шаблону, и вы сможете восстановить весь свой кошелек.
Так что же это за особый шаблон, который позволяет сгенерировать так много адресов из начальной Seed фразы? Математика включает в себя некоторое хеширование, о котором я не буду вдаваться в подробности. Но вы должны быть знакомы с одной концепцией, с которой вам следует ознакомиться — это Derivation path (Путь деривации). Derivation path похож на инструкции, которые говорят вам, как сгенерировать адрес. Пример, как выглядит Derivation path как на скрине ниже я взял из генератора seed фраз iancolemen.io/bip39:
Каждый путь деривации предоставляет все инструкции, необходимые для вычисления адреса и соответствующего ему закрытого ключа. Применяя путь деривации к xpub, вы получаете адрес. А, применяя путь деривации к xprv, вы получаете закрытый ключ.
Использование HD-кошельков — хороший способ организовать ваши адреса, поскольку разные числа в Пути позволяют вам организовать ваши адреса в древовидной структуре. Типичный вариант использования — поместить все получающие адреса в одну ветку, и все меняют адреса в другой ветке.
Это может ввести в заблуждение пользователей, которые восстанавливают свою мнемоническую фразу в веб-интерфейсе, например MEW (MyEtherWallet), только для того, чтобы увидеть свой баланс. В этих сценариях ваш ожидаемый адрес должен заполняться как первый адрес, который вы видите в списке. И вы можете просто не увидеть ваш баланс, т.к. средства могут храниться не на первом по нумерации адресе.
Во всех других случаях, таких как аппаратные кошельки, пользователь может выбирать, с каким адресом он хотел бы взаимодействовать при каждом доступе к своему кошельку. В этом методе нет никакой реальной выгоды или вреда, он просто предоставляет пользователю больший выбор. Но все адреса сгенерированы одинаково, и первый, как правило, проще всего отслеживать в будущем.
Вы можете задаться вопросом: если каждый раз использовать новый адрес для отправки и получения Биткоина, то их накопиться довольно большое количество и как таким образом отслеживать свои балансы на каждом из них?
Ответ: для этого вам достаточно знать Xpub (extended public key/master public key) — расширенный публичный мастер ключи открытый ключ. Из публичного мастер ключа появляются все ваши Биткоин адреса, относящиеся к вашей Seed фразе. Публичный мастер ключ не содержит приватных ключей и вообще не имеет внутри себя ничего кроме Биткоин адресов. Чтобы отслеживать все ваши Биткоин адреса, относящиеся к вашей Seed фразе достаточно загрузить ваш публичный мастер ключ Xpub в кошельки, которые это позволяют сделать, практически все известнве кошельки, поддерживающие генерацмю seed фраз: аппаратные кошельки, Electrum, Wassabi Wallet, Blockstream Green Wallet, Trust Wallet, BlueWallet, Armory и др. Как я уже писал выше, аппаратные кошельки уже сами предоставляют возможность выбрать самому адрес для работы.
xpub — это открытый ключ с некоторыми дополнительными данными, который позволяет вам генерировать тонну адресов.
xprv — это закрытый ключ, который позволяет вам генерировать тонну закрытых ключей, которые соответствуют этим адресам.
Вместе они составляют основу HD-кошельков, которые представляют собой удобный способ организовать ваш кошелек без необходимости хранить кучу индивидуальных закрытых ключей.
Публичные ключи и приватные ключи: что это и как они работают
Без приватных и публичных ключей не получится переводить и получать криптовалюту. Они также нужны для обеспечения конфиденциальности и защиты цифровых активов. Их можно использовать из любого устройства и любого криптокошелька, без привязки к месту.
Что такое публичные и приватные ключи
Для работы с криптовалютой используются специальные программы-кошельки. Чтобы переводить и обменивать цифровые деньги, нужно иметь два вида ключей шифрования:
Оба ключа привязываются к программному кошельку и могут быть импортированы в другой кошелек по желанию пользователя.
Сами монеты имеют форму данных о неизрасходованной транзакции и хранятся в распределенном реестре – блокчейне. Именно для получения доступа к этому реестру и нужны ключи. Без них перевести криптовалюту другому пользователю не получится. То есть основная функция публичного и приватного ключа сводится к обеспечению безопасных транзакций.
Открытый ключ является адресом (счетом), на который пересылаются цифровые деньги. Его могут видеть другие пользователи, поэтому он и называется публичным. При помощи открытого ключа выполняется процесс шифрования – создания транзакции.
Но перевод не будет одобрен администраторами сети, если в нем отсутствует цифровая подпись. Для создания такой подписи используется приватный ключ. Без него пользователь не сможет отправлять криптовалюту на другие кошельки. По этой причине его важно хранить в надежном месте. Желательно на устройстве, которое не подключено к интернету.
Если закрытый ключ шифрования будет утерян, владелец кошелька не сможет получить доступ к своим средствам. Даже если кто-то отправит ему цифровые деньги, у него не получится их использовать.
Также приватный ключ важно защищать и по причине высокой активности мошенников. Если злоумышленники узнают его, они смогут перевести себе все цифровые деньги, которые хранятся на кошельке. Но не имея закрытого ключа мошенник не сможет получить доступ к криптовалютным средствам пользователя, даже если перехватит его трафик.
Как выглядят закрытые и открытые ключи
Каждый из ключей имеет вид уникального набора символов, включающего буквы и цифры. Для примера можно взять ключи шифрования блокчейна bitcoin. Он работает на основе алгоритма шифрования SHA-256, генерирующего 256-битное число. Для более удобной работы с такими числами была создана комбинация, состоящая из 64 символов. Это и есть закрытый ключ.
В сети биткоина используются и другие форматы создания приватных ключей:
Приватный ключ Биткоин (в формате WIF): 51 символ base58, начинается с «5»: 5JPeWYZx922hXi49Lg2RIPWLIqcmDGS9YegMNgANvx8cJa6kNK8
Короткий (сжатый WIF): 52 символа base58, начинается с «К» или «L»: KykxZQLSNPYVtYCsoqFGFnEqpRar997zihJgvfrPo8LapFrAtaea
В НЕХ формате (64 символа [0-9А-F]): 4BBFF74CA25A2A00409DCB24EC0418E9A41F9B3B56216A183E0E9731F4589DC6
В Base64 формате (44 символа): S7/3TKJaKgBAncsk7AQY6aQfmztWIWoY Pg6XMFRYncY=
В большей части криптовалютных кошельков, работающих с ВТС, используется WIF-формат. Для обычных транзакций достаточно сжатого ключа, состоящего из 52 символов. В кошельках для хранения Ethereum чаще всего используется код из 64 символов.
Публичный ключ для работы с транзакциями биткоина тоже может иметь разное количество символов:
Адрес Биткоин кошелька: 1DcEeFRGc4mfRLXWiVZySpmmXk7SsVLfMG
Короткий адрес: 1BSUkuwtdM7gkdy6W4Q954gNKWBgy4A19Q
Публичный ключ (130 символов [0-9А-F]): 04D7AS1212E4EEFE40C72B201E74AA3S57DEFD940ACESC3E1C76B75S77CD45FF9626065170497984F81C23BC8CBEEE64DBD84C9FE113F4A78930A0DA7FA296B3F6D
Публичный ключ (короткий, 66 символов [0-9А-F]): 03D7A51212E4EEFE40C72B201E74AA3557DEFD940ACESC3E107687577CD45FF962
Самый распространенный вариант – это короткий адрес. Он может начинаться с единицы или тройки.
Методы шифрования в криптовалюте
Криптография – это наука о методах сохранения целостности данных и конфиденциальности, она появилась задолго до создания первой криптовалюты. Достижение целей криптографии включает в себя использование разных алгоритмов защиты информации.
Симметричное шифрование
Является самым популярным и простым способом кодирования данных транзакции. Сообщения шифруются и расшифровываются при помощи одного ключа. То есть выполняются симметричные действия.
Получателю сообщения передается ключ, при помощи которого он может раскодировать данные.
Асимметричное шифрование
При таком методе кодирования данных используются 2 ключа:
открытый — нужен для запуска операции;
закрытый – для расшифровки сообщения.
Приватный ключ позволяет ставить электронную подпись в транзакции, подтверждая тем самым ее подлинность. Когда валидаторы видят поступление транзакции с электронной подписью, они определяют эту операцию как действие законного владельца цифровых активов.
Логика здесь простая: закрытый ключ есть только у того, кто владеет средствами на отдельном кошельке. Значит, кроме этого пользователя электронную подпись поставить никто не может, ведь для этого необходимо наличие ключа.
Чтобы избежать потери приватного ключа, нужно записать секретную комбинацию символов в нескольких блокнотах, которые будут храниться в надежном месте, или сохранить ее на специальном устройстве. В этом случае даже при сбое системы или поломке электронных хранилищ пользователь не потеряет доступ к своим запасам криптовалюты.
Хеширование
Так называется еще один метод кодирования счетов пользователей, обеспечивающий надежное шифрование транзакций.
Суть метода сводится к преобразованию любой информации в уникальный набор символов. Он применяется для кодирования больших объемов данных. Расшифровать информацию можно при помощи специального хэш-значения или цифрового отпечатка.
Принцип работы
Публичный ключ используется как для обеспечения конфиденциальности, так и для идентификации пользователя в системе.
Схема применения имеет следующий вид:
Пользователь, которому нужно перевести деньги, дает свой публичный ключ.
Отправитель использует полученный набор символов для шифрования транзакции – ее запуска в безопасном режиме.
Выполняется перевод криптовалюты на указанный адрес криптовалютного кошелька.
Получив перевод, адресат использует приватный ключ для расшифровки транзакции. Секретный набор символов открывает доступ к записи в блокчейне, в которой содержится информация о смене владельца определенного количества криптосредств.
Для более наглядного примера можно представить следующую ситуацию:
Пользователь А хочет отправить 5 биткоинов пользователю Б.
Пользователь Б предоставляет публичный ключ пользователю А.
При помощи публичного ключа пользователь А создает транзакцию и шифрует ее при помощи приватного ключа.
Пользователь Б видит, что ему на кошелек поступили 5 ВТС. Чтобы получить доступ к этим деньгам, он использует приватный ключ своего кошелька, то есть расшифровывает транзакцию, и теперь может пользоваться монетами.
Без приватного ключа авторизовать перевод невозможно, поэтому доступ к полученным цифровым деньгам есть только у владельца секретного набора символов.
Отличия приватного и публичного ключей
Каждый ключ – это набор символов, который используется для проведения транзакции. Но их функции и характеристики имеют отличия.
Уровень доступа
Публичный ключ не является секретным, он доступен всем. Если сторонние пользователи узнают открытый набор символов криптовалютного кошелька, они не смогут установить его владельца. То есть ключ хоть и публичный, но содержит в себе минимум данных.
Приватный ключ должен быть доступен только владельцу кошелька. И его нельзя никому разглашать. Другими словами, тот, кому принадлежит приватный ключ, является владельцем средств на криптовалютном счету.
Процесс шифрования
Если публичный ключ шифрует сообщение, то приватный, наоборот, расшифровывает.
Эти два набора символов работают в паре друг с другом:
Без открытого ключа отправитель не сможет запустить транзакцию.
Без приватного ключа получатель не сможет авторизировать (расшифровать) перевод.
Только использование двух ключей при работе с транзакциями позволяет обеспечить высокий уровень защиты средств.
Изменение приватных ключей (свипинг)
Когда пользователь переходит на новый кошелек, он может перевести все средства со своего старого счета. Для проведения такой транзакции потребуется приватный ключ. Как только средства будут переведены, прежний закрытый набор символов перестает быть нужным. В новом кошельке генерируется его собственный закрытый ключ.
Такая зачистка получила название sweeping – подметание. Этот процесс напоминает перенос драгоценностей из одного сейфа в другой. При этом старый сейф утилизируется за ненадобностью.
Выполнение свипинга может быть полезно в следующих ситуациях:
Появился риск взлома. Например, на ПК установлен десктопный кошелек, и на этом же компьютере была запущена подозрительная программа. Чтобы избежать кражи закрытого ключа, стоит перевести все средства на другой кошелек.
Появилась необходимость ликвидации старого кошелька. При выходе более удобного приложения можно перевести на него средства, отказавшись от устаревшего варианта.
Ключ был потерян, но пользователь помнит мнемоническую фразу. Речь идет о специальном наборе слов, введя которые можно восстановить доступ к счетам. Эти слова формируются в процессе регистрации кошелька. Переводить все средства нужно по той причине, что утерянный закрытый ключ может быть кем-то найден. Теоретически в самый неожиданный момент криптовалюту могут украсть.
Если приходится пользоваться закрытым ключом, полученным от другого человека. Когда секретную комбинацию символов знает 2 пользователя, всегда есть риск кражи средств. Лучше сразу перевести монеты на другой кошелек, закрытый ключ которого не будет известен третьим лицам.
При работе с криптовалютой нужно всегда отслеживать текущий уровень защиты кошелька.
Импортирование ключей
Помимо свипинга, можно выполнить импорт приватных ключей. В этом случае в новый кошелек переносятся не сами монеты, а именно комбинации символов – закрытый ключ.
Импорт нужен, если пользователь регистрируется в новом приложении и не хочет отказываться от старого кошелька. Для транзакций в каждом из них будет использоваться один приватный ключ. Таким образом будет создано 2 работающих кошелька с одной комбинацией символов для расшифровки транзакций и создания цифровой подписи.
Например, у пользователя может быть биткоин счет, который его устраивает. Но ему также нужен мультивалютный кошелек , чтобы работать с разными блокчейнами и криптовалютами. Тогда пользователь может установить еще один кошелек и скопировать в него закрытый ключ своего десктопного кошелька.
При импорте важно уделить внимание защите приватного ключа на новом ПО.
Как правильно хранить закрытые ключи
Выбирая способ хранения, нужно ориентироваться на ключевую задачу: оставить как можно меньше возможностей для доступа к кошельку через сеть. Только после выполнения этого условия есть смысл обращать внимание на функционал кошелька.
Злоумышленники могут украсть криптовалюту, получив доступ к содержимому жесткого диска на ПК, а также взломав аккаунт на облачном сервисе или онлайн-платформе. Чтобы такого не случилось, нужно использовать самые надежные варианты защиты.
К ним относятся 3 способа хранения приватных ключей:
Аппаратные кошельки. Эти устройства считаются более безопасными, чем десктопные кошельки, мобильные приложения и онлайн-сервисы. Они имеют вид флешки и содержат механизмы защиты данных. Для осуществления перевода аппаратный кошелек подключается к ПК. С него отправляется транзакция и там же подписывается. После зашифрованное сообщение передается в сеть. Современные аппаратные кошельки устроены так, что даже при взломе ПК мошенники не смогут получить доступ к закрытому ключу подключенного к компьютеру кошелька.
Компьютер или смартфон. Для хранения значительной суммы в криптовалюте есть смысл использовать отдельное устройство. В целях безопасности оно должно быть постоянно отключено от сети, и его можно включать только для проведения транзакций.
Бумажные носители. Это может быть блокнот или ламинированный листок с записанным закрытым ключом. Можно сделать несколько копий, чтобы при потере одной из них сохранить доступ к цифровым деньгам.
При использовании криптокошельков нужно позаботиться о создании предельно надежного хранилища закрытого ключа.
Некоторые кошельки сами генерируют закрытый ключ, который потом нужно просто запомнить. Есть специальные сервисы, позволяющие создать собственный секретный набор случайных чисел и букв. Также они дают возможность придумать и seed-фразу, при помощи которой восстанавливается доступ к кошельку.
Chapter 4: ‘Keys, Addresses’
You may have heard that bitcoin is based on cryptography, which is a branch of mathematics used extensively in computer security. Cryptography means "secret writing" in Greek, but the science of cryptography encompasses more than just secret writing, which is referred to as encryption. Cryptography can also be used to prove knowledge of a secret without revealing that secret (digital signature), or prove the authenticity of data (digital fingerprint). These types of cryptographic proofs are the mathematical tools critical to bitcoin and used extensively in bitcoin applications. Ironically, encryption is not an important part of bitcoin, as its communications and transaction data are not encrypted and do not need to be encrypted to protect the funds. In this chapter we will introduce some of the cryptography used in bitcoin to control ownership of funds, in the form of keys, addresses, and wallets.
Introduction
Ownership of bitcoin is established through digital keys, bitcoin addresses, and digital signatures. The digital keys are not actually stored in the network, but are instead created and stored by users in a file, or simple database, called a wallet. The digital keys in a user’s wallet are completely independent of the bitcoin protocol and can be generated and managed by the user’s wallet software without reference to the blockchain or access to the internet. Keys enable many of the interesting properties of bitcoin, including decentralized trust and control, ownership attestation, and the cryptographic-proof security model.
Most bitcoin transactions require a valid digital signature to be included in the blockchain, which can only be generated with a secret key; therefore, anyone with a copy of that key has control of the bitcoin. The digital signature used to spend funds is also referred to as a witness, a term used in cryptography. The witness data in a bitcoin transaction testifies to the true ownership of the funds being spent.
Keys come in pairs consisting of a private (secret) key and a public key. Think of the public key as similar to a bank account number and the private key as similar to the secret PIN, or signature on a check, that provides control over the account. These digital keys are very rarely seen by the users of bitcoin. For the most part, they are stored inside the wallet file and managed by the bitcoin wallet software.
In the payment portion of a bitcoin transaction, the recipient’s public key is represented by its digital fingerprint, called a bitcoin address, which is used in the same way as the beneficiary name on a check (i.e., "Pay to the order of"). In most cases, a bitcoin address is generated from and corresponds to a public key. However, not all bitcoin addresses represent public keys; they can also represent other beneficiaries such as scripts, as we will see later in this chapter. This way, bitcoin addresses abstract the recipient of funds, making transaction destinations flexible, similar to paper checks: a single payment instrument that can be used to pay into people’s accounts, pay into company accounts, pay for bills, or pay to cash. The bitcoin address is the only representation of the keys that users will routinely see, because this is the part they need to share with the world.
First, we will introduce cryptography and explain the mathematics used in bitcoin. Next, we will look at how keys are generated, stored, and managed. We will review the various encoding formats used to represent private and public keys, addresses, and script addresses. Finally, we will look at advanced use of keys and addresses: vanity, multisignature, and script addresses and paper wallets.
Public Key Cryptography and Cryptocurrency
Public key cryptography was invented in the 1970s and is a mathematical foundation for computer and information security.
Since the invention of public key cryptography, several suitable mathematical functions, such as prime number exponentiation and elliptic curve multiplication, have been discovered. These mathematical functions are practically irreversible, meaning that they are easy to calculate in one direction and infeasible to calculate in the opposite direction. Based on these mathematical functions, cryptography enables the creation of digital secrets and unforgeable digital signatures. Bitcoin uses elliptic curve multiplication as the basis for its cryptography.
In bitcoin, we use public key cryptography to create a key pair that controls access to bitcoin. The key pair consists of a private key and—derived from it—a unique public key. The public key is used to receive funds, and the private key is used to sign transactions to spend the funds.
There is a mathematical relationship between the public and the private key that allows the private key to be used to generate signatures on messages. This signature can be validated against the public key without revealing the private key.
When spending bitcoin, the current bitcoin owner presents her public key and a signature (different each time, but created from the same private key) in a transaction to spend those bitcoin. Through the presentation of the public key and signature, everyone in the bitcoin network can verify and accept the transaction as valid, confirming that the person transferring the bitcoin owned them at the time of the transfer.
In most wallet implementations, the private and public keys are stored together as a key pair for convenience. However, the public key can be calculated from the private key, so storing only the private key is also possible.
Private and Public Keys
A bitcoin wallet contains a collection of key pairs, each consisting of a private key and a public key. The private key (k) is a number, usually picked at random. From the private key, we use elliptic curve multiplication, a one-way cryptographic function, to generate a public key (K). From the public key (K), we use a one-way cryptographic hash function to generate a bitcoin address (A). In this section, we will start with generating the private key, look at the elliptic curve math that is used to turn that into a public key, and finally, generate a bitcoin address from the public key. The relationship between private key, public key, and bitcoin address is shown in Private key, public key, and bitcoin address.
Why is asymmetric cryptography used in bitcoin? It’s not used to "encrypt" (make secret) the transactions. Rather, the useful property of asymmetric cryptography is the ability to generate digital signatures. A private key can be applied to the digital fingerprint of a transaction to produce a numerical signature. This signature can only be produced by someone with knowledge of the private key. However, anyone with access to the public key and the transaction fingerprint can use them to verify the signature. This useful property of asymmetric cryptography makes it possible for anyone to verify every signature on every transaction, while ensuring that only the owners of private keys can produce valid signatures.
Private Keys
A private key is simply a number, picked at random. Ownership and control over the private key is the root of user control over all funds associated with the corresponding bitcoin address. The private key is used to create signatures that are required to spend bitcoin by proving ownership of funds used in a transaction. The private key must remain secret at all times, because revealing it to third parties is equivalent to giving them control over the bitcoin secured by that key. The private key must also be backed up and protected from accidental loss, because if it’s lost it cannot be recovered and the funds secured by it are forever lost, too.
The bitcoin private key is just a number. You can pick your private keys randomly using just a coin, pencil, and paper: toss a coin 256 times and you have the binary digits of a random private key you can use in a bitcoin wallet. The public key can then be generated from the private key.
Generating a private key from a random number
The first and most important step in generating keys is to find a secure source of entropy, or randomness. Creating a bitcoin key is essentially the same as "Pick a number between 1 and 2 256 ." The exact method you use to pick that number does not matter as long as it is not predictable or repeatable. Bitcoin software uses the underlying operating system’s random number generators to produce 256 bits of entropy (randomness). Usually, the OS random number generator is initialized by a human source of randomness, which is why you may be asked to wiggle your mouse around for a few seconds.
More precisely, the private key can be any number between 0 and n — 1 inclusive, where n is a constant (n = 1.1578 * 10 77 , slightly less than 2 256 ) defined as the order of the elliptic curve used in bitcoin (see Elliptic Curve Cryptography Explained). To create such a key, we randomly pick a 256-bit number and check that it is less than n. In programming terms, this is usually achieved by feeding a larger string of random bits, collected from a cryptographically secure source of randomness, into the SHA256 hash algorithm, which will conveniently produce a 256-bit number. If the result is less than n, we have a suitable private key. Otherwise, we simply try again with another random number.
Do not write your own code to create a random number or use a "simple" random number generator offered by your programming language. Use a cryptographically secure pseudorandom number generator (CSPRNG) with a seed from a source of sufficient entropy. Study the documentation of the random number generator library you choose to make sure it is cryptographically secure. Correct implementation of the CSPRNG is critical to the security of the keys.
The following is a randomly generated private key (k) shown in hexadecimal format (256 bits shown as 64 hexadecimal digits, each 4 bits):
The size of bitcoin’s private key space, (2 256 ) is an unfathomably large number. It is approximately 10 77 in decimal. For comparison, the visible universe is estimated to contain 10 80 atoms.
To generate a new key with the Bitcoin Core client (see [ch03_bitcoin_client]), use the getnewaddress command. For security reasons it displays the public key only, not the private key. To ask bitcoind to expose the private key, use the dumpprivkey command. The dumpprivkey command shows the private key in a Base58 checksum-encoded format called the Wallet Import Format (WIF), which we will examine in more detail in Private key formats. Here’s an example of generating and displaying a private key using these two commands:
The dumpprivkey command opens the wallet and extracts the private key that was generated by the getnewaddress command. It is not possible for bitcoind to know the private key from the public key unless they are both stored in the wallet.
The dumpprivkey command does not generate a private key from a public key, as this is impossible. The command simply reveals the private key that is already known to the wallet and which was generated by the getnewaddress command.
You can also use the Bitcoin Explorer command-line tool (see [appdx_bx]) to generate and display private keys with the commands seed, ec-new, and ec-to-wif:
Public Keys
The public key is calculated from the private key using elliptic curve multiplication, which is irreversible: K = k * G, where k is the private key, G is a constant point called the generator point, and K is the resulting public key. The reverse operation, known as "finding the discrete logarithm"—calculating k if you know K—is as difficult as trying all possible values of k, i.e., a brute-force search. Before we demonstrate how to generate a public key from a private key, let’s look at elliptic curve cryptography in a bit more detail.
Elliptic curve multiplication is a type of function that cryptographers call a "trap door" function: it is easy to do in one direction (multiplication) and impossible to do in the reverse direction (division). The owner of the private key can easily create the public key and then share it with the world knowing that no one can reverse the function and calculate the private key from the public key. This mathematical trick becomes the basis for unforgeable and secure digital signatures that prove ownership of bitcoin funds.
Elliptic Curve Cryptography Explained
Elliptic curve cryptography is a type of asymmetric or public key cryptography based on the discrete logarithm problem as expressed by addition and multiplication on the points of an elliptic curve.
An elliptic curve is an example of an elliptic curve, similar to that used by bitcoin.
Bitcoin uses a specific elliptic curve and set of mathematical constants, as defined in a standard called secp256k1, established by the National Institute of Standards and Technology (NIST). The secp256k1 curve is defined by the following function, which produces an elliptic curve:
The mod p (modulo prime number p) indicates that this curve is over a finite field of prime order p, also written as \(\( \mathbb
Because this curve is defined over a finite field of prime order instead of over the real numbers, it looks like a pattern of dots scattered in two dimensions, which makes it difficult to visualize. However, the math is identical to that of an elliptic curve over real numbers. As an example, Elliptic curve cryptography: visualizing an elliptic curve over F(p), with p=17 shows the same elliptic curve over a much smaller finite field of prime order 17, showing a pattern of dots on a grid. The secp256k1 bitcoin elliptic curve can be thought of as a much more complex pattern of dots on a unfathomably large grid.
So, for example, the following is a point P with coordinates (x,y) that is a point on the secp256k1 curve:
In elliptic curve math, there is a point called the "point at infinity," which roughly corresponds to the role of zero in addition. On computers, it’s sometimes represented by x = y = 0 (which doesn’t satisfy the elliptic curve equation, but it’s an easy separate case that can be checked).
There is also a + operator, called "addition," which has some properties similar to the traditional addition of real numbers that gradeschool children learn. Given two points P1 and P2 on the elliptic curve, there is a third point P3 = P1 + P2, also on the elliptic curve.
Geometrically, this third point P3 is calculated by drawing a line between P1 and P2. This line will intersect the elliptic curve in exactly one additional place. Call this point P3' = (x, y). Then reflect in the x-axis to get P3 = (x, –y).
There are a couple of special cases that explain the need for the "point at infinity."
If P1 and P2 are the same point, the line "between" P1 and P2 should extend to be the tangent on the curve at this point P1. This tangent will intersect the curve in exactly one new point. You can use techniques from calculus to determine the slope of the tangent line. These techniques curiously work, even though we are restricting our interest to points on the curve with two integer coordinates!
In some cases (i.e., if P1 and P2 have the same x values but different y values), the tangent line will be exactly vertical, in which case P3 = "point at infinity."
If P1 is the "point at infinity," then P1 + P2 = P2. Similarly, if P2 is the point at infinity, then P1 + P2 = P1. This shows how the point at infinity plays the role of zero.
It turns out that + is associative, which means that (A + B) + C = A + (B + C). That means we can write A + B + C without parentheses and without ambiguity.
Now that we have defined addition, we can define multiplication in the standard way that extends addition. For a point P on the elliptic curve, if k is a whole number, then kP = P + P + P + … + P (k times). Note that k is sometimes confusingly called an "exponent" in this case.
Generating a Public Key
Starting with a private key in the form of a randomly generated number k, we multiply it by a predetermined point on the curve called the generator point G to produce another point somewhere else on the curve, which is the corresponding public key K. The generator point is specified as part of the secp256k1 standard and is always the same for all keys in bitcoin:
where k is the private key, G is the generator point, and K is the resulting public key, a point on the curve. Because the generator point is always the same for all bitcoin users, a private key k multiplied with G will always result in the same public key K. The relationship between k and K is fixed, but can only be calculated in one direction, from k to K. That’s why a bitcoin address (derived from K) can be shared with anyone and does not reveal the user’s private key (k).
A private key can be converted into a public key, but a public key cannot be converted back into a private key because the math only works one way.
Implementing the elliptic curve multiplication, we take the private key k generated previously and multiply it with the generator point G to find the public key K:
Public key K is defined as a point K = (x,y):
To visualize multiplication of a point with an integer, we will use the simpler elliptic curve over real numbers—remember, the math is the same. Our goal is to find the multiple kG of the generator point G, which is the same as adding G to itself, k times in a row. In elliptic curves, adding a point to itself is the equivalent of drawing a tangent line on the point and finding where it intersects the curve again, then reflecting that point on the x-axis.
Most bitcoin implementations use the OpenSSL cryptographic library to do the elliptic curve math. For example, to derive the public key, the function EC_POINT_mul() is used.
Bitcoin Addresses
A bitcoin address is a string of digits and characters that can be shared with anyone who wants to send you money. Addresses produced from public keys consist of a string of numbers and letters, beginning with the digit "1." Here’s an example of a bitcoin address:
The bitcoin address is what appears most commonly in a transaction as the "recipient" of the funds. If we compare a bitcoin transaction to a paper check, the bitcoin address is the beneficiary, which is what we write on the line after "Pay to the order of." On a paper check, that beneficiary can sometimes be the name of a bank account holder, but can also include corporations, institutions, or even cash. Because paper checks do not need to specify an account, but rather use an abstract name as the recipient of funds, they are very flexible payment instruments. Bitcoin transactions use a similar abstraction, the bitcoin address, to make them very flexible. A bitcoin address can represent the owner of a private/public key pair, or it can represent something else, such as a payment script, as we will see in [p2sh]. For now, let’s examine the simple case, a bitcoin address that represents, and is derived from, a public key.
The bitcoin address is derived from the public key through the use of one-way cryptographic hashing. A "hashing algorithm" or simply "hash algorithm" is a one-way function that produces a fingerprint or "hash" of an arbitrary-sized input. Cryptographic hash functions are used extensively in bitcoin: in bitcoin addresses, in script addresses, and in the mining Proof-of-Work algorithm. The algorithms used to make a bitcoin address from a public key are the Secure Hash Algorithm (SHA) and the RACE Integrity Primitives Evaluation Message Digest (RIPEMD), specifically SHA256 and RIPEMD160.
Starting with the public key K, we compute the SHA256 hash and then compute the RIPEMD160 hash of the result, producing a 160-bit (20-byte) number:
where K is the public key and A is the resulting bitcoin address.
A bitcoin address is not the same as a public key. Bitcoin addresses are derived from a public key using a one-way function.
Bitcoin addresses are almost always encoded as "Base58Check" (see Base58 and Base58Check Encoding), which uses 58 characters (a Base58 number system) and a checksum to help human readability, avoid ambiguity, and protect against errors in address transcription and entry. Base58Check is also used in many other ways in bitcoin, whenever there is a need for a user to read and correctly transcribe a number, such as a bitcoin address, a private key, an encrypted key, or a script hash. In the next section we will examine the mechanics of Base58Check encoding and decoding and the resulting representations. Public key to bitcoin address: conversion of a public key into a bitcoin address illustrates the conversion of a public key into a bitcoin address.
Base58 and Base58Check Encoding
In order to represent long numbers in a compact way, using fewer symbols, many computer systems use mixed-alphanumeric representations with a base (or radix) higher than 10. For example, whereas the traditional decimal system uses the 10 numerals 0 through 9, the hexadecimal system uses 16, with the letters A through F as the six additional symbols. A number represented in hexadecimal format is shorter than the equivalent decimal representation. Even more compact, Base64 representation uses 26 lowercase letters, 26 capital letters, 10 numerals, and 2 more characters such as “«” and "/" to transmit binary data over text-based media such as email. Base64 is most commonly used to add binary attachments to email. Base58 is a text-based binary-encoding format developed for use in bitcoin and used in many other cryptocurrencies. It offers a balance between compact representation, readability, and error detection and prevention. Base58 is a subset of Base64, using upper- and lowercase letters and numbers, but omitting some characters that are frequently mistaken for one another and can appear identical when displayed in certain fonts. Specifically, Base58 is Base64 without the 0 (number zero), O (capital o), l (lower L), I (capital i), and the symbols “«” and "/". Or, more simply, it is a set of lowercase and capital letters and numbers without the four (0, O, l, I) just mentioned. Bitcoin’s Base58 alphabet shows the full Base58 alphabet.
To add extra security against typos or transcription errors, Base58Check is a Base58 encoding format, frequently used in bitcoin, which has a built-in error-checking code. The checksum is an additional four bytes added to the end of the data that is being encoded. The checksum is derived from the hash of the encoded data and can therefore be used to detect and prevent transcription and typing errors. When presented with Base58Check code, the decoding software will calculate the checksum of the data and compare it to the checksum included in the code. If the two do not match, an error has been introduced and the Base58Check data is invalid. This prevents a mistyped bitcoin address from being accepted by the wallet software as a valid destination, an error that would otherwise result in loss of funds.
To convert data (a number) into a Base58Check format, we first add a prefix to the data, called the "version byte," which serves to easily identify the type of data that is encoded. For example, in the case of a bitcoin address the prefix is zero (0x00 in hex), whereas the prefix used when encoding a private key is 128 (0x80 in hex). A list of common version prefixes is shown in Base58Check version prefix and encoded result examples.
Next, we compute the "double-SHA" checksum, meaning we apply the SHA256 hash-algorithm twice on the previous result (prefix and data):
From the resulting 32-byte hash (hash-of-a-hash), we take only the first four bytes. These four bytes serve as the error-checking code, or checksum. The checksum is concatenated (appended) to the end.
The result is composed of three items: a prefix, the data, and a checksum. This result is encoded using the Base58 alphabet described previously. Base58Check encoding: a Base58, versioned, and checksummed format for unambiguously encoding bitcoin data illustrates the Base58Check encoding process.
In bitcoin, most of the data presented to the user is Base58Check-encoded to make it compact, easy to read, and easy to detect errors. The version prefix in Base58Check encoding is used to create easily distinguishable formats, which when encoded in Base58 contain specific characters at the beginning of the Base58Check-encoded payload. These characters make it easy for humans to identify the type of data that is encoded and how to use it. This is what differentiates, for example, a Base58Check-encoded bitcoin address that starts with a 1 from a Base58Check-encoded private key WIF that starts with a 5. Some example version prefixes and the resulting Base58 characters are shown in Base58Check version prefix and encoded result examples.
Bitcoin Testnet Address
Private Key WIF
BIP-38 Encrypted Private Key
BIP-32 Extended Public Key
Key Formats
Both private and public keys can be represented in a number of different formats. These representations all encode the same number, even though they look different. These formats are primarily used to make it easy for people to read and transcribe keys without introducing errors.
Private key formats
The private key can be represented in a number of different formats, all of which correspond to the same 256-bit number. Private key representations (encoding formats) shows three common formats used to represent private keys. Different formats are used in different circumstances. Hexadecimal and raw binary formats are used internally in software and rarely shown to users. The WIF is used for import/export of keys between wallets and often used in QR code (barcode) representations of private keys.
64 hexadecimal digits
Base58Check encoding: Base58 with version prefix of 128- and 32-bit checksum
As above, with added suffix 0x01 before encoding
Example: Same key, different formats shows the private key generated in these three formats.
All of these representations are different ways of showing the same number, the same private key. They look different, but any one format can easily be converted to any other format. Note that the "raw binary" is not shown in Example: Same key, different formats as any encoding for display here would, by definition, not be raw binary data.
We use the wif-to-ec command from Bitcoin Explorer (see [appdx_bx]) to show that both WIF keys represent the same private key:
Decode from Base58Check
The Bitcoin Explorer commands (see [appdx_bx]) make it easy to write shell scripts and command-line "pipes" that manipulate bitcoin keys, addresses, and transactions. You can use Bitcoin Explorer to decode the Base58Check format on the command line.
We use the base58check-decode command to decode the uncompressed key:
The result contains the key as payload, the WIF version prefix 128, and a checksum.
Notice that the "payload" of the compressed key is appended with the suffix 01, signalling that the derived public key is to be compressed:
Encode from hex to Base58Check
To encode into Base58Check (the opposite of the previous command), we use the base58check-encode command from Bitcoin Explorer (see [appdx_bx]) and provide the hex private key, followed by the WIF version prefix 128:
Encode from hex (compressed key) to Base58Check
To encode into Base58Check as a "compressed" private key (see Compressed private keys), we append the suffix 01 to the hex key and then encode as in the preceding section:
The resulting WIF-compressed format starts with a "K." This denotes that the private key within has a suffix of "01" and will be used to produce compressed public keys only (see Compressed public keys).
Public key formats
Public keys are also presented in different ways, usually as either compressed or uncompressed public keys.
As we saw previously, the public key is a point on the elliptic curve consisting of a pair of coordinates (x,y). It is usually presented with the prefix 04 followed by two 256-bit numbers: one for the x coordinate of the point, the other for the y coordinate. The prefix 04 is used to distinguish uncompressed public keys from compressed public keys that begin with a 02 or a 03.
Here’s the public key generated by the private key we created earlier, shown as the coordinates x and y:
Here’s the same public key shown as a 520-bit number (130 hex digits) with the prefix 04 followed by x and then y coordinates, as 04 x y:
Compressed public keys
Compressed public keys were introduced to bitcoin to reduce the size of transactions and conserve disk space on nodes that store the bitcoin blockchain database. Most transactions include the public key, which is required to validate the owner’s credentials and spend the bitcoin. Each public key requires 520 bits (prefix + x + y), which when multiplied by several hundred transactions per block, or tens of thousands of transactions per day, adds a significant amount of data to the blockchain.
As we saw in the section Public Keys, a public key is a point (x,y) on an elliptic curve. Because the curve expresses a mathematical function, a point on the curve represents a solution to the equation and, therefore, if we know the x coordinate we can calculate the y coordinate by solving the equation y 2 mod p = (x 3 + 7) mod p. That allows us to store only the x coordinate of the public key point, omitting the y coordinate and reducing the size of the key and the space required to store it by 256 bits. An almost 50% reduction in size in every transaction adds up to a lot of data saved over time!
Whereas uncompressed public keys have a prefix of 04, compressed public keys start with either a 02 or a 03 prefix. Let’s look at why there are two possible prefixes: because the left side of the equation is y 2 , the solution for y is a square root, which can have a positive or negative value. Visually, this means that the resulting y coordinate can be above or below the x-axis. As you can see from the graph of the elliptic curve in An elliptic curve, the curve is symmetric, meaning it is reflected like a mirror by the x-axis. So, while we can omit the y coordinate we have to store the sign of y (positive or negative); or in other words, we have to remember if it was above or below the x-axis because each of those options represents a different point and a different public key. When calculating the elliptic curve in binary arithmetic on the finite field of prime order p, the y coordinate is either even or odd, which corresponds to the positive/negative sign as explained earlier. Therefore, to distinguish between the two possible values of y, we store a compressed public key with the prefix 02 if the y is even, and 03 if it is odd, allowing the software to correctly deduce the y coordinate from the x coordinate and uncompress the public key to the full coordinates of the point. Public key compression is illustrated in Public key compression.
Here’s the same public key generated previously, shown as a compressed public key stored in 264 bits (66 hex digits) with the prefix 03 indicating the y coordinate is odd:
This compressed public key corresponds to the same private key, meaning it is generated from the same private key. However, it looks different from the uncompressed public key. More importantly, if we convert this compressed public key to a bitcoin address using the double-hash function (RIPEMD160(SHA256(K))) it will produce a different bitcoin address. This can be confusing, because it means that a single private key can produce a public key expressed in two different formats (compressed and uncompressed) that produce two different bitcoin addresses. However, the private key is identical for both bitcoin addresses.
Compressed public keys are gradually becoming the default across bitcoin clients, which is having a significant impact on reducing the size of transactions and therefore the blockchain. However, not all clients support compressed public keys yet. Newer clients that support compressed public keys have to account for transactions from older clients that do not support compressed public keys. This is especially important when a wallet application is importing private keys from another bitcoin wallet application, because the new wallet needs to scan the blockchain to find transactions corresponding to these imported keys. Which bitcoin addresses should the bitcoin wallet scan for? The bitcoin addresses produced by uncompressed public keys, or the bitcoin addresses produced by compressed public keys? Both are valid bitcoin addresses, and can be signed for by the private key, but they are different addresses!
To resolve this issue, when private keys are exported from a wallet, the WIF that is used to represent them is implemented differently in newer bitcoin wallets, to indicate that these private keys have been used to produce compressed public keys and therefore compressed bitcoin addresses. This allows the importing wallet to distinguish between private keys originating from older or newer wallets and search the blockchain for transactions with bitcoin addresses corresponding to the uncompressed, or the compressed, public keys, respectively. Let’s look at how this works in more detail, in the next section.
Compressed private keys
Ironically, the term "compressed private key" is a misnomer, because when a private key is exported as WIF-compressed it is actually one byte longer than an "uncompressed" private key. That is because the private key has an added one-byte suffix (shown as 01 in hex in Example: Same key, different formats), which signifies that the private key is from a newer wallet and should only be used to produce compressed public keys. Private keys are not themselves compressed and cannot be compressed. The term "compressed private key" really means "private key from which only compressed public keys should be derived," whereas "uncompressed private key" really means "private key from which only uncompressed public keys should be derived." You should only refer to the export format as "WIF-compressed" or "WIF" and not refer to the private key itself as "compressed" to avoid further confusion
Example: Same key, different formats shows the same key, encoded in WIF and WIF-compressed formats.
What is Master Key in Bitcoin? How to get a New Bitcoin Address?
We are creating a child address and our master address is always the same.
Greetings. The one question that always comes to our mind is that when we create an address it always gives a different address that is not matched with any other address that we created before. So how it is possible and how bitcoin wallet ensure that this address own by your wallet?
After reading the complete article you will be a master of the address process.
Before continuing I believe that you know about the bitcoin seed phrase and how it works. If you want to know then you can read the below article first.
How does the Bitcoin Seed Phrase Work?
The seed phrase is the key to the bitcoin wallet.
**Index**
- What is Master Key?
- What is HMAC-SHA512?
- What are Extended Private Key and Extended Public Key?
- Child Key Derivation
- Conclusion
** What is Master Key? **
- The master key is the hash that we get from PBKDF2 (Password-Based Key Derivation Function 2).
- It is unique for every seed phrase. It is also known as an extended key.
- It is used to create multiple child keys. we will understand later about the process.
** What is HMAC-SHA512? **
- HMAC (Hash-Based Message Authentication Code) is a function that has two parameters first is data and the second is key.
- This function produces 64 random bytes result with the process with an additional parameter as key.
The result is the combination of two things. For getting these things we split the result into 32–32 bytes.
- The left side result is called an extended key as a normal key.
- The right side result is called a chain code.
- Chain code help to create other child keys based on extended key.
** What is Extended Private Key and Extended Public Key? **
- Extended Private Key: In the HMAC-SHA512 function we pass in data parameter 512 bits of entropy (Seed) and key parameter a simple arbitrary string “Bitcoin Seed”.
- In the HMAC-SHA512 function, we pass in data parameter 512 bits of entropy (Seed) and key parameter a simple arbitrary string “Bitcoin Seed”.
As per HMAC function output, we split it into two parts
- Left side 32 bytes called Extended Private Key.
- Right side 32 bytes called Chain Code.
If you forget the chain code and remember the extended private key then you cannot derivate the child addresses.
Extended Public Key:
- It is a simple public key coupled with chain code.
- When we convert the private key into a public key using ECDSA (Elliptic Curve Digital Signature Algorithm) and add the chain code (32 bytes). We will get our extended public key.
Now we have both extended keys as it looks like the same public/private key and the interesting thing is how we can create the child keys.
** Child Key Derivation Process **
- When we request an address then the new address is generated from the master key.
We have two types of extended keys:
- Extended Private Key can generate Private key and public key.
- Extended Public Key can only generate the public key.
Each child has an index and it is up to 2**32 (4294967295). It means that we can generate 4294967295 new addresses from a single wallet.
We will understand the three derivation processes.
- Normal Child using Extended Private Key
- Hardened Child using Extended Private Key
- Normal Child using Extended Public Key
- Hardened Child using Extended Public Key is not possible.
Normal Child using Extended Private Key
- Normal child address has an index of only half of the total index (2**32) /2 means that it can be from 0 to 2147483647
- We will use the HMAC function and get the result.
- We get the result in 64 bytes and next we split it into two parts 32 bytes + 32 bytes.
- Right result is always a chain code.
- We add parent private key to leftResult and module of elliptic curve range just to be a valid range.
- That’s it. Now we will convert this childPrivateKey to HEX format whereas we can create the corresponding childPublicKey using ECDSA.
Now we will have the three things
- childPublicKey: is the public key of a child address.
- childPrivateKey: is the private key of a child address.
- newChainCode: is a random number that is used to create a new child address.
Hardened Child using Extended Private Key
- A hardened key is a secure way to generate the child address. It is used for an internal or secret purposes.
- The index number is the last split of possible children which is from 2147483648 to 4294967295.
- As Pieter: suggests it should be a default way of creating an address. because we can not do anything without a private key.
- The process is much similar to a normal child key. the fact is that there is no parent public key used.
If you lost your child address private key and you created a child’s key using a normal public key so it might change then someone will get your master private key using a reverse algorithm and break your wallet and steal all the bitcoins that you have in your child addresses. But in the Hardened child key, it is not possible to reach on your master key.
Normal Child using Extended Public Key
- We can only create the public child address using Extended Public Key.
- It is useless because there is nothing to use without a private key.
- The process for creating an address is much similar like rest two.
** Conclusion **
- Hardened Child Address is secure to do the bitcoin transaction.
- The public key is the point of the elliptic curve multiplied by a private key. If you increase the number of private key you will get the new private key.
- Don’t share your child’s address private key because if someone has extended the public key and private key of any normal child address then he can steal your bitcoins that exist in your other child address.
- We can use serialization to pass the extended key + chain code with some metadata.
- We can create limited child addresses because 4 bytes field of the child number (0xffffffff) that is in decimal 4294967295.
That’s it. I hope it helps you find out how a bitcoin address generates.
Stay tuned with me and join me to learn the bitcoin series on every Monday at 9 AM (GMT +5:30). You can share your thought as well. I am happy to read your words respectfully.