Skip to content

Commit

Permalink
Add functions for decoding SP addresses
Browse files Browse the repository at this point in the history
Add a function for decoding the string address and a second
function for decoding the data part of the silent payment address.
  • Loading branch information
josibake committed Jul 21, 2023
1 parent 6d11e3c commit ae6019b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/key_io.cpp
Expand Up @@ -15,6 +15,8 @@
/// Maximum witness length for Bech32 addresses.
static constexpr std::size_t BECH32_WITNESS_PROG_MAX_LEN = 40;

/// Data size for decoded Bech32m silent payment addresses (33 byte pubkey + 33 byte pubkey)
static constexpr std::size_t SILENT_PAYMENT_V0_DATA_SIZE = 66;
namespace {
class DestinationEncoder
{
Expand Down Expand Up @@ -309,3 +311,33 @@ bool IsValidDestinationString(const std::string& str)
{
return IsValidDestinationString(str, Params());
}

std::pair<CPubKey, CPubKey> DecodeSilentData(const std::vector<unsigned char>& data)
{

std::vector<unsigned char> scan_pubkey_data(data.begin(), data.begin() + 33);
CPubKey scan_pubkey{scan_pubkey_data};

std::vector<unsigned char> spend_pubkey_data(data.begin() + 33, data.end());
CPubKey spend_pubkey{spend_pubkey_data};

return {scan_pubkey, spend_pubkey};
}

std::vector<unsigned char> DecodeSilentAddress(const std::string& str)
{
const auto& params{Params()};
const auto& silent_payment_hrp = params.SilentPaymentHRP();
const auto dec = bech32::Decode(str, /*silent=*/true);
if (dec.encoding != bech32::Encoding::BECH32M || dec.hrp != silent_payment_hrp) {
return {};
}
auto version = dec.data.front(); // retrieve the version
std::vector<unsigned char> silent_payment_data;
silent_payment_data.reserve(((dec.data.size() - 1) * 5) / 8);
if (!ConvertBits<5, 8, false>([&](unsigned char c) { silent_payment_data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {
return {};
}
if ((version == 0 && silent_payment_data.size() != SILENT_PAYMENT_V0_DATA_SIZE) || silent_payment_data.size() < SILENT_PAYMENT_V0_DATA_SIZE) return {};
return silent_payment_data;
}
4 changes: 4 additions & 0 deletions src/key_io.h
Expand Up @@ -24,6 +24,10 @@ std::string EncodeExtPubKey(const CExtPubKey& extpubkey);
std::string EncodeDestination(const CTxDestination& dest);
CTxDestination DecodeDestination(const std::string& str);
CTxDestination DecodeDestination(const std::string& str, std::string& error_msg, std::vector<int>* error_locations = nullptr);

std::pair<CPubKey, CPubKey> DecodeSilentData(const std::vector<unsigned char>& data);
std::vector<unsigned char> DecodeSilentAddress(const std::string& str);

bool IsValidDestinationString(const std::string& str);
bool IsValidDestinationString(const std::string& str, const CChainParams& params);

Expand Down

0 comments on commit ae6019b

Please sign in to comment.