- Генерируем Bitcoin-адрес на Python
- Generator bitcoin address python
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Bitcoin address generation in pure python
- Step 1: Generate ECDSA Keypair
- Step 2: Calculate the public key
- Checksum
- Public key compression
- Step 4: Encode the private key in the WIF format
- Source code
- Bitcoin Address Generation on Python
Генерируем Bitcoin-адрес на Python
Тема криптовалют снова начинает будоражить интернет. Супер, что вам не надо идти в отделение банка с паспортом и выстаивать очередь, чтобы открыть счет. Сгенерировать кошелек Bitcoin — дело нескольких строк кода на Python.
Нам понадобятся библиотеки base58 и ecdsa. base58 – это кодирование бинарных данных 58-ю печатными символами (цифрами и латинскими буквами, кроме 0, O, I, l, которые похожи друг на друга). ecdsa – библиотека криптографии на эллиптических кривых.
Импортируем то, что нужно:
Нам нужен приватный ключ, из него мы вычислим публичный ключ, а из него – адрес кошелька Bitcoin. (Обратная процедура не возможна без полного перебора до конца времен). Приватный ключ – это 32 байта данных, которые мы получим из криптографически-надежного источника случайных чисел. Вообще можно придумать свой приватный ключ самостоятельно, если так хочется. Для генерации случайного приватного ключа мы воспользуемся библиотекой ecdsa:
Вычислим этой же библиотекой публичный ключ и добавим спереди байт 0x4 (это признак «несжатого» публичного ключа; есть и другие форматы).
Теперь нужно из публичного ключа сделать привычный число-буквенный адрес Bitcoin. Взглянем на схему:
Для получения адреса из публичного ключа вычисляем сначала RIPEMD160(SHA256(public-key)):
Дополняем его префиксом 0x0 (главная сеть Bitcoin):
Вычисляем контрольную сумму (нужна, чтобы наши денюжки не пропадали, если мы ошибемся в каком-то символе адреса). Контрольная сумма это первые 4 байта от SHA256(SHA256(r)):
Получаем адрес кошелька, закодировав в base58 сложенные r и checksum:
Генерация приватного ключа из своего источника случайностей, например, os.urandom:
Важно для конфиденциальных данных, вроде приватного ключа, использовать криптографически безопасный источник случайности. Об этом я писал в одной из недавних статей!
Полный пример кода генерации кошельков.
Проверить ключи и адрес можно здесь. (Нажимаем Skip, дальше Enter my own…)
Подробнее по теме можно почитать здесь.
Специально для канала @pyway. Подписывайтесь на мой канал в Телеграм @pyway 👈
Источник
Generator bitcoin address python
Minimal Bitcoin address generator in Python
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
addrgen — minimal Bitcoin address generator in Python
This script generates a single Bitcoin address using the compressed public key format and prints it with its private key.
For some reason, the script segfaults on OS X unless it’s run in in 32-bit mode. Instead, those on OS X should run:
Generating other types of addresses
Supply the version number for your desired address with the —otherversion switch. (supported by pywallet at least)
If you wish to generate addresses based on a passphrase, a given private key, or some other option look at the commented lines in the test() function.
Created and Licensed Public Domain by Joric/bitcoin-dev June 2012 with minor modifications by David Sterry.
About
Minimal Bitcoin address generator in Python
Источник
Bitcoin address generation in pure python
Bitcoin address generation can be split in 4 steps listed bellow:
- Generating a secure private key.
- Calculate the public key from the private key.
- Encode the public key as a bitcoin address.
- Encode the private key in the WIF format.
Step 1: Generate ECDSA Keypair
The very first step is to select a good and secure number, for this example we won’t use one, instead we will simply get the random from the system. An example why is important a good and secure random number is written in this post about cracking some bitcoin private keys, the bug isn’t located in the key generation, but in the random used to sign the transactions, but the point is the same, weak PRNG (Pseudo-random number generators) can put everything in risk.
Using this PRNG can be done with:
Step 2: Calculate the public key
Since bitcoin uses spec256k1 the only thing that we need to do is multiply it by the initial point in the curve by the private key to obtain the public key.
Next step is to convert the key to a byte array and hash it, first with SHA-256 then with RIPEMD-160. Then we prepend the hashed public key with 0x00 if the target network is the mainnet, if the address generated meant to be used in the testnet 0x6f must be prepended.
Checksum
Then the only thing left to add in the address it the checksum, it is appended to the address and is the last 4 bytes of the double SHA-256 of the address calculated above.
Then just encode the key bytes to base58 and you have your Bitcoin address !
Public key compression
When representing the public key as a number is possible to compress it considering that the key is $x$ and $y$ in the eliptic curve and since we have the equation, and given an $x$ value, there is only two values for $y$ possible. So to compress a public key, if $y$ is odd, 0x03 is appended to the $x$ value, else, 0x02 is appended.
Step 4: Encode the private key in the WIF format
To create a WIF () key from the private key bytes is far simples than the previous steps, first prepend the byte 0x80 to the wif, then append the private key bytes. After, append the checksum, that is the last 4 bytes of the double SHA-256 of the partial wif key that we already have calculated.
Source code
This is a reference script, it depends on Python 3 to run and is self contained, it means no external dependencies are required to run it. One example of its output:
Источник
Bitcoin Address Generation on Python
B itcoin is a digital currency created in January 2009. It follows the ideas set out in a whitepaper by the mysterious and pseudonymous developer Satoshi Nakamoto. A bitcoin address is a unique identifier that serves as a virtual location where the cryptocurrency can be sent or hold. Transactions provide to transfer assets between Bitcoin wallets that keep private key and bitcoin addresses. The private key ensures that the transaction comes from the owner of the wallet. Generating bitcoin address as offline is possible. This code explains how you can generate a bitcoin address step by step. As you see at the figure below, there are some operations while bitcoin address is generated.
Let’s start to examine how can we generate bitcoin address;
- Step 1: Elliptic Curve Digital Signature Algorithm is used to generate Private Key because Public Key Cryptography provides bitcoin’s signature principle.
- Step 2: Due to Public Key Cryptography, we need Public Key that depends on a Private Key. So we generate it with the Elliptic Curve Digital Signature Algorithm too.
- Step 3: We apply SHA256 to ECDSA Public Key that is created in Step 2.
- Step 4: We apply RIDEMP160 to value that is created in Step 3 and get value as 20 bytes.
- Step 5: We prepend 00 as Network Byte to value that is created in Step 4.
- Step 6: We apply double SHA256 to the value that is created in Step 5 to Checksum.
- Step 7: We get 4 bytes of value that is created in Step 6 as Checksum.
- Step 8: We append Checksum value that is created in Step 7 to value that is created at Step #5.
- Step 9: We applied Base58 Encoding to value that is created in Step 8. After Base58 Encoding, we get the value that is Bitcoin Address. (In Python, b58encode result should decode to utf-8 for showing)
Finally, the result is comprised and the source code is available here;
Источник