Angular, Blockchain, Science とか

Angular, Blockchain, Science全般 の情報を主に書いていきます。

Bitcoin Base58Checksum について

Mastering Bitcoin の Base58Checksum のコードにわかりやすくコメントを付けました。

#include <bitcoin/bitcoin.hpp>

int main()
{
    // Private secret key.
    bc::ec_secret secret;
    bool success = bc::decode_base16(secret,
        "038109007313a5807b2eccc082c8c3fbb988a973cacf1a7df9ce725c31b14776");
    assert(success);
    // Get public key.
    bc::ec_point public_key = bc::secret_to_public_key(secret);
    std::cout << "Public key: " << bc::encode_hex(public_key) << std::endl;
    
    // SHA256 + ripemd160
    const bc::short_hash hash = bc::bitcoin_short_hash(public_key);

    bc::data_chunk unencoded_address;
    // Reserve 25 bytes
    //   [ version:1バイト ]
    //   [ hash:20バイト = 160ビット(ripemd160) ]
    //   [ checksum:4バイト]
    unencoded_address.reserve(25);
    // Version byte, 0 is normal BTC address (P2PKH).
    unencoded_address.push_back(0);
    // Hash = ripemd160(sha256(public-key))
    bc::extend_data(unencoded_address, hash);
    // Checksum is computed by hashing data, and adding 4 bytes from hash.
    // Checksum sha256(sha256(unencoded_address)) の最初の4バイト
    bc::append_checksum(unencoded_address);
    // Finally we must encode the result in Bitcoin's base58 encoding
    assert(unencoded_address.size() == 25);
    const std::string address = bc::encode_base58(unencoded_address);

    std::cout << "Address: " << address << std::endl;
    return 0;
}

もっと頑張って勉強しないと。