M Baas
I am an E&E engineering PhD student at Stellenbosch University. I post about deep learning, electronics, and other things I find interesting.
Introduction to Bitcoin address formats
by Matthew Baas
An abridged taxonomy of the major bitcoin address formats and versions.
TL;DR: bitcoin (BTC) has been through several versions, and will doubtless go through more in the future. Different major bitcoin versions have different address formats. This post aims to document the common BTC address types encountered in common use as of Feb 2022, and is targeted at those who have a minimal understanding of bitcoin.
I will be assuming you have a basic idea of what bitcoin is, and just about nothing else :). For those already well experienced in BTC and its technical components, this might be of less use to you.
Update 2022-03-20: changed name of wrapped segwit to script hash addresses (BIP-13). This is done to better indicate that this address format can encode the hash of any arbitrary script, not just wrapping segregated witness.
1. Bitcoin overview
Before the taxonomy, a brief reminder of the key parts of bitcoin are appropriate.
The Bitcoin (BTC or just btc) blockchain is fundamentally a record of transactions between btc addresses. By looking at all transactions involving a given BTC address, we can determine the balance of that address. This means that an amount of bitcoin is owned by a BTC address on the BTC blockchain.
However, a single ‘wallet’ in common software wallets these days can correspond to many different addresses. The total value of that wallet is the sum of balances of all the addresses contained in that wallet (just like how in real life a single wallet can have multiple cards in it).
Changes to bitcoin: BIPs
The original version of the bitcoin protocol and software released over a decade ago has undergone significant upgrades and bug fixes. Upgrades, or improvements to bitcoin are formally proposed as Bitcoin Improvement Proposals (BIPs). They have a formal format, a formal lifecycle, and are typically reviewed many times by multiple people before miners consider adopting the BIP.
For example, BIP-32 is an upgrade for introducing a feature called Hierarchical Deterministic Wallets. Some BIPs are minor bugfixes and usability improvements, while others are fairly large updates which introduce swathes of new functionality. Each BIP is only ‘active’ (i.e. in effect on the main BTC blockchain) if the majority of miners agree to run software that implements that BIP. As of Jan 2022 there are 43 BIPs which are in effect – the ‘final’ state of an accepted BIP.
Unique to BTC: all BIPs should be backwards compatible. That is to say, the very first bitcoins should still be spendable using the original methods, and the main functionality that worked in previous versions must still work in the latest version.
Other cryptocurrencies often do not have this feature, where failing to update wallet software to the latest version of the cryptocurrency’s protocol will render your funds unusable. Such a design guideline has its benefits and drawbacks: you can always be confident that you can spend your funds, even if it is your own hand-written wallet software from a decade ago. However, this comes at the cost of major version bloat, where all future BIPs and wallet software code must have special hooks and workarounds to make sure both the latest and all previous versions work as intended.
The nature of BTC improvements
The major BIPs have changed the BTC blockchain so that the blockchain still contains a list of transactions, however nowadays the information that can be included in a transaction has expanded substantially.
Transactions can have many receiving and sending addresses within them along with other metadata. They can also require approval from owners of multiple BTC addresses, and various other functionality – e.g. only being spendable after a certain amount of time.
However, since all BIPs are backwards compatible, new addresses created using software implementing newer BIPs have different forms to let BTC nodes and miners know that the address and its format corresponds to the newer BTC protocol version. This is necessary so that old addresses are not handled as if they support newer features – part of ensuring backwards compatibility.
2. BTC address taxonomy
Note: the example addresses used below are just examples I grabbed of the internet, not mine and I don’t know where they come from. DO NOT SEND ANY FUNDS TO THESE EXAMPLE ADDRESSES.
Here is a list of the types of addresses you will commonly see while using bitcoin:
| Address version | Example | Description | Payment type |
|---|---|---|---|
| Legacy | 1 5e15hWo6CShMgbAfo8c2Ykj4C6BLq6Not | Oldest bitcoin version. Always start with a 1 . | P2PKH |
| Script hash addresses (BIP-13) | 3 5PBEaofpUeH8VnnNSorM1QZsadrZoQp4N | 2nd major address version. Always start with a 3 . | P2SH |
| Native Segwit | bc1q 42lja79elem0anu8q8s3h2n687re9jax556pcc | 3rd major address version. Always start with bc1q . Current standard. | P2WPKH |
| Lightning Network | lnbc 2500u1pvjluezsp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpu9qrsgquk0rl77nj30yxdy8j9vdx85fkpmdla2087ne0xh8nhedh8w27kyke0lp53ut353s06fv3qfegext0eh0ymjpf39tuven09sam30g4vgpfna3rh | BTC’s 2nd layer off-chain payment protocol. Always start with lnbc . | LN |
| Taproot (segwit v1) | bc1p mzfrwwndsqmk5yh69yjr5lfgfg4ev8c0tsc06e | 4th major address version. Always start with bc1p . Upcoming standard. | P2TR |
I will now give a brief overview of the different types of wallets associated with each major address version, except for lightning network, since that is not on the main btc blockchain and I don’t know enough about it. Also, what follows is my current best understanding of each address technology, and may not be fully correct from here onwards. For the best information on them, consult the source BIPs on the bitcoin github, and the bitcoin node software.
2.1 Legacy
The legacy address is made from a pair of (private key, public key) , and the address is simply a hash of the public key using the private key with some cryptography. The result of this hash is something like 1 5e15hWo6CShMgbAfo8c2Ykj4C6BLq6Not
This is why legacy payments are also referred to as Pay-to-Public-Key-Hash (P2PKH), as you are literally paying to a hash of the public key of the target wallet.
You can spend from the address so long as you can prove (using cryptography) that you have the private key corresponding to the address (hashed public key).
2.2 Script hash addresses (aka wrapped segwit)
Script hash addresses (defined in BIP-13), sometimes known as wrapped segwit addresses, are made, very roughly speaking, from a tuple (private key, public key, script) . The address is the hash of a script that involves certain spending conditions.
Such spending conditions can be simple: e.g. showing the private key associated with public key allows you to spend this bitcoin’
Or they can be complex: e.g. showing the private key associated with this public key allows you to spend this bitcoin after 27 days if you also reveal a predetermined secret number.
The script of these conditions is then hashed using the private key to obtain the address. e.g. 3 5PBEaofpUeH8VnnNSorM1QZsadrZoQp4N . And this is why script hash addresses (aka wrapped segwit) is known as Pay-to-Script-Hash (P2SH). To spend from an address you must have the private key, script, and satisfy the requirements of the script.
2.3 Native Segwit
Wallets in this version are defined, again very roughly speaking, by a pair (seed phrase, pass phrase, tree structure, script) . To get an address, we essentially compute a hash based on the seed phrase, pass phrase and a particular path within the tree structure, providing us with a hashed public key to send BTC to. When transactions are broadcast to the blockchain, a hash of the script is included in a separate part of the transaction called the ‘witness’. Spending from any segwit or newer addresses requires satisfying the script requirements specified by the witness.
Hence, we call it Pay-to-Witness-Public-Key-Hash (P2WPKH) because the address is a hash of the public key and witness pair. If a script is used (e.g. for multi-sig wallets) then it is also known as Pay-to-Witness-Script-Hash (P2WSH). The seed and pass phrase in the tuple above can also instead be specified by an extended public and extended private key, and internally the seed and pass phrase are used to generate the extended public and private keys in wallet software.
- Seed phrase: “wild quiz always market robust … twist divert margin route”
- Pass phrase: “” (blank is default)
- Path within tree structure: “m/0/0/2’” ; the path is often in format of “m/
’/ ’/ ’”, but can be somewhat arbitrary. Each directory name is an integer (i.e account can be ‘0124’, but not ‘abcd’)
Then the derived address will be some series of cryptographic functions that takes these items as input, yielding an address like bc1q 42lja79elem0anu8q8s3h2n687re9jax556pcc
2.4 Taproot
With taproot, a now released but not yet widely used version of the BTC protocol, addresses can be formulated in significantly more ways. Concretely, like native segwit, a wallet can consists of a seed phrase and a pass phrase. These are used to generate an extended public and private key, which are used to derive the addresses at arbitrary paths in a hierarchically deterministic wallet.
However, now with taproot, there is one more thing that can be added to generate an address – taptweak s. A taptweak – fundamentally a natural number – is added at an intermediary step to the native segwit tuple to yield a new public key and thus address. Arbitrary bitcoin scripts can then be encoded into a taptweak and thus into an address. This, combined with the script and metadata added to the ‘witness’ part of the address in any transaction, provides the necessary functionality for various new taproot features.
These taptweak s have some special mathematical properties that allow for various interesting functionality, such as having a binary tree of different scripts committed to the same address, allowing one to spend from that address if they can satisfy a script at some path in the tree. Taproot also introduced musig , which allows for multi-sig wallets to be constructed with what is essentially a taptweak , thereby making multi-sig wallets indistinguishable from regular wallets on the blockchain.
Example
Let us look at a single example of a transaction I found from browsing blockchain.com. Below is an example of an actual address clearly used by some whale or exchange:

We can see that the address – from its format – is a native segwit (segwit v0) address using a non-trivial script in the witness (P2WSH). Recalling that BTC is fundamentally owned by an address and not a wallet, we can also observe the whale nature of the address: tallying all its transactions yields the final balance belonging to this address at over 2930 BTC!

Next lets look at a transaction it is in:
In this example transaction, the segwit address above is sending funds to six output BTC addresses from various versions. I have highlighted the version of each address with colors as used in the table earlier for clarity. Such a transaction highlights how backwards compatible and interoperable BTC is – a single transaction can involve inputs and outputs from differing versions of the BTC protocol, all without problem.
Summary
I hope you found this post valuable, and as always, if you spot things I am mistaken on, please get in contact with me via the About page. I will continue to update the list above if/when new major BTC versions and address formats are released.
Simple explanations of how bitcoin works
People like me often confuse blockchains with cryptocurrencies. Blockchain is digitally distributed, decentralized that exists across a network. In simple words, the blockchain is a shared, immutable, public ledger that tracks the history of transactions and assets. Indeed, blockchain development is one of many tremendous technologies that catch many’s eyes as the modern cryptocurrency system is built on top of it, Bitcoin, etc.
According to my personal experience, as a beginner, I feel it’s overwhelming to start my first blockchain ticket because there are many essential concepts you need to get a hang of before you start a new line in the code source. I noticed most of the tutorials or the guidelines about the blockchain are too sophisticated for newcomers. These articles usually do not explain the concepts in deep because the authors assume the audience has already understood all of them.
Thankfully, searching for a beginner’s guide leads me to https://learnmeabitcoin.com/[1] which is an amazing source for grabbing the Bitcoin essentials. The author explains the concepts in simple words and illustrates the difficult ones with GIFs.
Node and Memory Pool
Every computer that runs the Bitcoin program is a node. These connected computers as a whole create the network. A node is set to follow some rules so that only valid transactions made by users will be relayed to the network. The node will share the newly created(fresh) and confirmed transactions with peer nodes. Each node also keeps blocks of confirmed transactions. These are held together in a file called the blockchain.
A node has a limited size of the memory pool. When a fresh transaction is received by a node, it will hold it in its memory pool with all the other latest transactions it has received. The node keeps receiving the transactions in the queue until its memory pool gets full. From here the transaction will be competing to get selected for inclusion. The more network fee (metric is fee-per-byte) you would be willing to pay for, the more likely you would be preferred by the other nodes, the faster your transaction would be confirmed. Once the memory pool is full, the node needs to drop transactions from the queue to clear space for the next transaction.
Mining
Each node has the option to try and mine the transactions n their memory pool into a file (blockchain, explained below). In short, imagine all the transactions in your memory pool can be condensed into a string of numbers and letters. You need to hash it by another string so that this new string begins with a certain number of zeros. If you are the first one to find this number, you will get a reward for your effort.
However, to add transactions from the memory pool to the blockchain, a node has to use a lot of computer processing power. The difficulty t regulates how long it takes for miners to add new blocks of transactions to the blockchain.
You must be curious why is mining necessary?
Because mining allows the entire Bitcoin Network to agree on which transactions get “archived”, and this is how you prevent fraud in a digital currency.
- Depending on the number of participants, the difficulty adjusts every 2016 blocks to make sure the next 2016 blocks would be mined within 2 weeks.
Blockchain
The blockchain is actually a file of transactions that holds the transaction data over the network. New transactions are added to the file in blocks, and these blocks are built on top of one another to create a chain of blocks. Hence, blockchain.
The current size of the blockchain is approximately 417.07GB and increases on a daily basis. A simple alternative is to install a trusted Bitcoin wallet. A bitcoin wallet manages your keys and addresses so that you can send and receive bitcoins and save you from holding a copy of the blockchain on your local disk.
Bitcoin is a shared network, and a rule called Longest Chain is introduced to ensure the validity of the blockchain.
The rule that nodes adopt the longest chain of blocks allows every node on the network to agree on what the blockchain looks like, and therefore agree on the same transaction history.
Blocker
The blocker header is a summary of data in the block. For blocker 123456, the data looks like:
The data includes 6 fields:
Version (4 bytes): The version of the block.
Previous Block Hash (32 bytes): The block hash of the block that this block is being built on top of. This is what “chains” the blocks together.
Merkle Root(32 bytes): All of the transactions in this block, hashed together. Basically provides a single-line summary of all the transactions in this block.
Time: (4 bytes)When a miner is trying to mine this block, the Unix time at which this block header is being hashed is noted within the block header itself.
Bits(4 bytes): A shortened version of the Target.
Nonce (4 bytes): The field that miners change in order to try and get a hash of the block header (a Block Hash) that is below the Target.
Hash function
Most of the intermediate data during the data processing is sensitive, we want to scramble the data before saving them. There are two hash functions commonly used in Bitcoin: HASH160 and HASH256.
HASH256 involves putting data through the SHA-256 hash function, then putting the result through the SHA-256 hash function another time. This is the most common method for hashing data in Bitcoin. It’s used when hashing transaction data to create TXIDs, and when hashing block headers during mining.
HASH160 involves putting data through the SHA-256 hash function, then putting the result through the RIPEMD-160 hash function next. It is only used when shortening public keys and scripts in creating legacy addresses. It has not been used in any recent developments that require hashing of data in Bitcoin.
RIPEMD160 produces a 160 bit (20 byte) digest and will contain fewer characters.
HMAC-SHA512 allows you to pass data along with in an additional secret key to produce a new set of random bytes.
BIP (Bitcoin Improvement Proposal)
A Bitcoin Improvement Proposal (BIP) is a formal proposal to change Bitcoin. As a piece of software, Bitcoin is always undergoing upgrades — bugs need to be fixed, algorithms can be made more efficient, code can be simplified, compatibility with other software must be maintained, and new features can be added.
You can find a list of existing BIPs and their current status on https://github.com/bitcoin/bips.
Base58
Base58 is commonly used in Bitcoin development. It is a set of characters you can use to represent big numbers in a shorter and more user-friendly format without all the easily mistakable characters like 0 , O , l and I .
Base58 has two advantages:
- It gives you a large set of characters, so you can represent large numbers in a shorter format.
- It leaves out awkward characters, to save you from making mistakes when transcribing.
Transaction
Transaction ID (txid): is basically an identification number for a bitcoin transaction. You can get the transaction ID by applying the HASH256 algorithm to transaction data.
Transaction Data: A bitcoin transaction is just a bunch of data that describes the movement of bitcoins (from inputs to outputs); A bitcoin address is like an account number that holds bitcoins. So when you want to send bitcoins to someone else, you grab whole amounts that you have already received and use them to send a new amount to a new address. If the amount of your Bitcoin is greater than the number of Bitcoin you intend to save, these unspent coins will be sent to another address called change address. Every output has a lock on the top of it to prevent others from spending your Bitcoin.
Weight is a metric for measuring the size of a transaction. For transaction c586389e5e4b3acb9d6c8be1c19ae8ab2795397633176f5a6442a261bbdefc3a, the weight is
Bitcoin script
Bitcoin uses a mini programming language called Script for the locking mechanism.
For creating your own script, you can install btcdeb aka Bitcoin Script Debugger and write in CLI. For the input btcdeb ['OP_20 OP_10 OP_SUB'],
Inputs and outputs are the batches of data that will be created and generated in every transaction. The locking script is placed on every output and the unlocking script must be provided for unlocking the scripts.
For locking and unlocking the script to complete the transaction, you need to run the Script script. Script underlies a stack-based structure and runs from left to right.
There are various types of standard scripts:
- P2PKH (Pay To Pubkey Hash) most common
- P2MS (Pay To Multisig)
- P2SH (Pay To Script Hash)
- P2PK (Pay To Pubkey)
A private key is a 256-bit number, Bitcoin performs elliptic curve multiplication(https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication) on the private key to generate the public key.
This is a simple example of generating a Bitcoin private key and a public address in Javascript.
The private key can be converted into a “Wallet Import Format” (WIF), which basically makes it easier to copy and move around. A WIF private key is a standard private key, but with a few added extras: Version Byte prefix — Indicates which network the private key is to be used on; Compression Byte suffix (optional) — Indicates if the private key is used to create a compressed public key; Checksum — Useful for detecting errors/typos when you type out your private key.
The public key is just the mapping point of the private key on the curve. The public key hash is a hashed version of your public key. It’s the version of your public key that you give to other people so that they can send you bitcoins. It’s shorter than the original public key, and it may provide an extra layer of security for your bitcoins compared to giving out your public key directly.
The received outputs usually will be locked to a P2PKH script. When you want to unlock these bitcoins (to send them to someone in a new transaction), you put your original public key along with a digital signature in to the input’s unlocking code.
Digital signature are used to prove ownership of specific coins and to authorize their transfer to a new owner.The address is an easy format of a locking script. Instead of sending the complete lock script like 76a914662ad25db00e7bb38bc04831ae48b4b446d1269888ac # P2PKH script , we can send something like 1AKDDsfTh8uY4X3ppy1m7jw1fVMBSMkzjP.
Bitcoin, addresses include checksums so they can be checked to see if they have been typed in correctly. Checksums are created by applying HASH256 and taking the first 4 bytes of the result.
HD (hierarchical deterministic) Wallet
Hierarchical means the keys and addresses can be organized in to a tree.
Deterministic means the keys and addresses are always generated in the same way every time.
- Mnemonic seed
BIP39 introduces the mnemonic seed which encodes a random number into readable words and uses them to create a seed. A mnemonic seed is usually between 12 and 24 words.
Do not trust seeds generated on websites. When creating a wallet you should generate your own seed privately on your own computer.
2. Extended keys
BIP32 introduces the extended keys. An extended key is a private key or public key that you can use to derive new keys in a HD wallet. Therefore, you can have a single extended private key, and use it as the source for all the child private keys and public keys in your wallet. In addition, a corresponding extended public key will generate the same child public keys.
To get a master public and private key, you put the seed through the HMAC-SHA512 hash function. The HMAC function returns 64 bytes of data. We split this in to two halves to create our master extended private key: The left half will be the private key, which is just like any other private key. The right half will be the chain code, which is just an extra 32 bytes of random data.
All extended keys can derive child extended keys:
- Extended private keys can generate child keys with new private keys and public keys.
- Extended public keys can generate child keys with new public keys only.
There are two types of children from an extended private key: Normal and Hardened.
- Normal: The extended private key and extended public key can generate the same public key. Indexes 0 to 2147483647 (the first half of all possible children)
- Hardened: Only the extended private key can generate the public key. Indexes 2147483648 to 4294967295 (the last half of all possible children).
There are 3 methods for deriving child keys:
(a) Normal Child extended private key
(b) Hardened Child extended private key
(c) Normal Child extended public key
(d) Hardened Child extended public key — Not possbile
3. Derivation Paths
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.
BIP44 introduces a wallet structure for consistency concern:
m / purpose' / coin_type' / account' / change / index
The slashes / indicate a new level in the tree (a new child). The numbers (e.g. 0 ) indicate the child number from the parent. A ' or h indicates a hardened child extended private key.
Conclusion
In my opinion, Bitcoin is trending and will be in the next few decades still. Blockchain development is evolving and the community encourages the developers to start their own journey by introducing more convenient tools. Understanding how Bitcoin works is essential and will benefit you in comprehending the other advanced topics.
Адреса кошельков P2PKH, P2SH и SegWit – что это?
Адреса кошельков P2PKH, P2SH и SegWit – что это? Как это виляет на выбор криптовалютных кошельков? Какова скорость транзакций? Все это и многое другое чуть ниже.
При попытке разобраться в принципах работы различных криптовалют многие сталкиваются с большим количеством криптографических терминов, англоязычных аббревиатур и всякого рода названий. И если про хеширование в общих чертах кто-то что-то слышал, то Segregated Witness, Lightning network, P2SH, P2PKH – это для большинства нечто непереводимое, причем очень тесно связанное между собой, и где точка входа в это тайное знание – не понятно. В этой статье мы попробуем хотя бы немного разомкнуть этот круг и простыми словами рассказать, чем отличаются типы кошельков P2PKH, P2SH и SegWit.
В начале были P2PKH-адреса
И придумал их сам Накамото. Именного тогда в архитектуру первой криптовалюты были заложены фундаментальные особенности, которые, в своем большинстве, остаются актуальными и сегодня. Адрес-кошелька в таком формате – это результат кодирования по алгоритму Base58 строки, содержащей три фрагмента:
- Идентификатор сети (с ним всё просто, это шестнадцатеричное значение 0х00 для биткоин).
- Открытый ключ (но не простой, а после поочередного хеширования сначала по алгоритму SHA-256, затем по алгоритму RIPEMD-160).
- Фрагмент контрольной суммы от предыдущего фрагмента (а это ещё пара последовательных хеширований по алгоритму SHA-256).
Алгоритм кодирования Base58 – одно из полезнейших изобретений, которое позволяет преобразовывать строку из любых символов в любой кодировке в строку, содержащую только однозначно понимаемые человеком. Уверены, вы сталкивались с ситуацией, когда цифра 0 и буква О не отличаются от друг от друга. Аналогичная ситуация с буквами I (заглавная буква i) и l (строчная буква L). Так вот Base58 решает эту проблему, такие «неоднозначные» символы просто не используются. Такой подход находит свое применение не только при формировании адресов кошельков, но и, например, в сервисах сокращения ссылок.
Платой за удобство является чувствительно к регистру, то есть буквы F и f – это разные буквы по версии Base58. Это несущественный недостаток, но об этом нельзя забывать. P2PKH-Адрес биткоин-кошелька имеет вид:
1Kb3Sx1hiXQnXZoJJUWXH3tvbdqjmhyFir
Есть буквы верхнего и нижнего регистра, цифры, все символы понятны, а начинается всегда с единицы. Почему так получается? Идентификатор сети стоял в начале строки. Он рамен нулю, поэтому после преобразования в начале строки всегда оказывается единица. Никакого противоречия, адгоритм Base58 превращает шестнадцатеричный 0 (идентификатор сети) в символ 1 (первый символ адреса кошелька).
P2SH-адреса
В 2012 году в использование были введены новые P2SH-адреса. Обновление касается, прежде всего, механизма обработки платежей, а не самих адресов. Появилась возможность создания кошельков с мультиподписью (чтобы отправить средства требуется подтверждение от нескольких владельцев ключей), снизилась комиссия за перевод для отправителя платежа.
Эти весьма актуальные нововведения не повлияли на структуру адреса кошелька, но требовалось различать кошельки с их поддержкой, и без них (так называемые «старые» P2PKH-адреса). Для этого разработчиками было принято решение на этапе генерация адреса использовать другой идентификатор сети не 0х00, а 0х05. После кодирования в Base58 идентификатор превратится в 3, поэтому все P2SH-адреса начинаются с тройки. Пример такого адреса:
3QVgQ7JNEkxrabfe9ZQBtS36sGEG58DmLt
Адрес всё также содержит цифры, почти все буквы латинского алфавита и всё также чувствителен к регистру.
SegWit-адреса
Еще более масштабное обновление – SegWit , которое заработало в 2017 году. Оно вызывало бурный общественный резонанс, был риск разделения биткоина на две равнозначные криптовалюты, непредсказуемых потрясений стоимости и прочего. В итоге все прошло благополучно, а обновление хорошо повлияло на безопасность системы, снизило размеры комиссии, скорость обработки транзакций, а также добавило возможность проведения дальнейших серьезных изменений. Но изменения коснулись и формата записи адресов. Теперь вместо Base58 при генерации используется алгоритм Bech32, который еще больше ограничивает количество допустимых для использования символов (и в данном случае это хорошо). Все символы теперь в одном регистре, а цифра 1 – служебный разделитель.
Если сильно упростить, то SegWit-адрес включает в себя три фрагмента:
- Идентификатор сети (bc1 в дальнейшем уже не подвергается преобразованию).
- Адрес кошелька.
- Цифра 1, которая служит разделителем между вторым и четвертым фрагментом.
- Контрольная сумма.
Фрагменты 2, 3 и 4 подвергаются кодированию по алгоритму Bech32, а идентификатор добавляется без изменения, то есть адрес в итоге содержит одну единицу, доставшуюся от идентификатора. Пример SegWit-адреса:
bc1rt6rnd3w2uu82wzkl3fhqq263ch37w6lq5sue7
Основной недостаток такие адресов – это отсутствие их поддержки со стороны некоторых сервисов – старых кошельков, некоторых бирж и т.д.
Транзакции между различными типами кошельков как правило проходят благополучно, но создать себе SegWit-адрес можно не в каждом сервисе.
Какой кошелек в итоге выбрать?
Команда разработчиков EMCD.io рекомендует использовать SegWit-кошельки.
Во-первых, это безопаснее — такие кошельки устойчивее сразу к нескольким типам атак.
Во-вторых, это дешевле — стоимость транзакции ниже, по сравнению с другими типами кошельков.
В-третьих, это быстрее — транзакции обрабатывается быстрее, так как их размер меньше.
В-четвертых, SegWit-кошельки совместимы со всеми остальными и вы можете отправлять из них средства на любые другие.
И, наконец, SegWit — это реальность сегодняшнего и даже завтрашнего дня, это прогресс и вклад в развитие сети биткоина. Именно такие кошельки смогут получить преимущества от всех последующих обновлений.
Формы биткоин-адресов: различия, преимущества и недостатки

На сегодняшний день существует несколько форм биткоин-адресов, имеющих отличительные характеристики. Несмотря на разнообразие, все они используются одинаково активно. Каждая новая версия имеет как преимущества так и недостатки, о них вы и узнаете из этой статьи.
Форматы биткоин-адресов:
- Legacy был предложен Сатоши Накамото;
- P2SH (Pay-To-Script Hash) – разработка от Гэвина Андресена;
- SegWit (P2WPKH – Pay-To-Witness Public Key Hash) был создан Питером Велле и Грегом Максвеллом.
Что исзвестно о биткоин-адресе формата Legacy?
Сатоши Накамото был предложен стандартный 26-35-символьный биткоин-адрес. В его структуре:
- префикс (в виде цифры 1);
- публичный ключ (сгенерированный алгоритмами RIPEMD и SHA256, применимыми к приватному ключу);
- контрольная сумма транзакции.
Данный формат был изначально достаточно эффективен и удобен, поскольку способствовал уменьшению рисков отправить средства на некорректно заданный адрес.
Другое название формы Legacy – Pay-To-Public Key Hash (P2PKH). Он требует подпись от получателя, которая взимается из приватного ключа, а также публичный ключ для проведения транзакции. Данный формат биткоин-адреса довольно емкий, обладает низкой скоростью хэширования, высокой чувствительностью к регистру и высокими комиссиями за выполнение операций. Но его неоспоримым плюсом остается низкая вероятность приема системой неверно указанного адреса.
Шифрование частей Legacy-адреса
Для шифрования частей биткоин-адреса формата P2PKH используется система кодировки Base58Check. В ее основе – символы латинского алфавита, а главная задача – защита адреса от опечаток. В данной системе присутствуют лишь 58 символов, которые невозможно перепутать ни между собой, ни с какими-то другими. Отсутствуют математические “+” и “-”, косые черты, а также ноль и некоторые другие прописные и строчные символы.
Какие особенности у P2SH-адресов?
В начале 2012 года главным научным сотрудником Bitcoin Foundation Гэвином Андресеном в обновлении BIP-0016 был предложен улучшенный формат биткоин-адреса. Префикс для такого адреса уже не 1, а 3. Он получил название Pay-To-Script Hash, поскольку при транзакции средств подразумевает наличие скрипта у получателя, который совпадает со скриптом хеша.
Эта особенность позволила снизить комиссии за перевод средств, перекладывать их на получателя, а также создавать адресные строки с мультиподписью. Еще одна особенность формата P2SH – разрешение на операции со средствами на одном криптокошельке для всех пользователей с ключом доступа, или же их полный запрет.
SegWit – новое поколение адресов для транзакций с биткоином?
В обновлении для биткоина BIP-0173 был предложен совершенно новый формат адресов под названием Bech32 (альтернативное название – SegWit или P2WPKH). Протокол подразумевает сокращение блока в размерах за счет удаления из него ключа-подписи. Формат начал активно использоваться еще в 2017 году.
В таком адресе используются лишь 32 символа, сама строка может вмещать от 40 до 90 символов. В структуре адреса:
- часть bc1;
- данные о получателе;
- контрольная сумма перевода.
Формат Bech32 допускает до 4-х ошибок в записи, которые автоматически исправляются кодом Боуза-Чоудхури-Хоквингема (или коротко – БЧХ-код).
SegWit значительно сократили длинну QR-кодов, что сделало запись адреса криптокошелька задачей попроще. Возросла защита от ошибок при написании, снизились комиссии за транзакцию, а скорость последних наоборот – повысилась.
Одним из главным минусов данного формата есть то, что он не поддерживается некоторыми сервисами и криптокошельками. Но в этом случае можно использовать формат P2SH. Перевод “золотой монеты” с Legacy на SegWit возможен и ничем не затруднен. В блокчейне эти адреса не имеют существенной разницы.
Вывод
Технологии не стоят на месте, о чем говорит смена тяжелых и дорогостоящих биткоин-адресов криптокошельков на более легкие и дешевые версии. При этом защита транзакций не пострадала, а возросла вместе со скоростью их проведения. Форки не исключили “старую” Legacy, поэтому, при необходимости, способны к взаимодействию.