btcsuite / btcutil

Provides bitcoin-specific convenience functions and types
480 stars 410 forks source link

bech32: add new EncodeM and DecodeGeneric functions for bech32 #202

Closed Roasbeef closed 3 years ago

Roasbeef commented 3 years ago

In this commit, we add two new package level functions: EncodeM, and DecodeGeneric. The new encode method is intended to allow callers to specify that they want to use the new bech32m checksum. This should be used when encoding segwit addresses with version 1 and beyond. The new DecodeGeneric function allows a caller to decode a bech32 and bech32m string with a single function. A new return value is added which is the version of the returned bech32 string, which allows callers to perform additional segwit addr validation (v1+ should use bech32m etc).

We opted to add new functions rather than modifying the existing functions to not cause a breaking API change, as most uses in the wild can just use the existing functions, and only taproot related logic/code needs to worry about the new methods.

A series of tests have been added to ensure that DecodeGeneric extracts the proper bech version, and we've also adopted the bech32m tests from BIP 350.

Fixes part of https://github.com/btcsuite/btcd/issues/1735.

Fixes https://github.com/btcsuite/btcutil/issues/195

onyb commented 3 years ago

Mentioning here so we don't forget - we should probably update the relevant Bitcoin wiki article: https://en.bitcoin.it/wiki/Bech32_adoption#Libraries

Roasbeef commented 3 years ago

Fixed typos, fixed linter error.

Roasbeef commented 3 years ago

So we'd even be able to decode segwit v0 addresses that use bech32m (even if probably no wallet will ever create those).

Yeah exactly, the idea is that say in lnd, we can detect that case and reject the send w/ a detailed error message.

gitteri commented 3 years ago

Looks like someone sent btc to the test vector mentioned above... most block explorers are unable to parse bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0. Can we get this in soon? https://chain.so/address/BTC/bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0

Roasbeef commented 3 years ago

I've added all the additional test vectors. Note that this PR doesn't implement new versions of btcuil.Address for the new script versions, so some of the vectors don't apply as directly. I'll add them in the follow up PR that creates new btcutil.Address implementations for taproot addresses.