Line data Source code
1 : // Copyright (c) 2022 The PIVX Core developers 2 : // Distributed under the MIT software license, see the accompanying 3 : // file COPYING or https://www.opensource.org/licenses/mit-license.php. 4 : 5 : #include "bls/key_io.h" 6 : 7 : #include "chainparams.h" 8 : #include "bech32.h" 9 : #include "bls/bls_wrapper.h" 10 : 11 : namespace bls { 12 : 13 : template<typename BLSKey> 14 2401 : static std::string EncodeBLS(const CChainParams& params, 15 : const BLSKey& key, 16 : CChainParams::Bech32Type type) 17 : { 18 2401 : if (!key.IsValid()) return ""; 19 4749 : std::vector<unsigned char> vec{key.ToByteVector()}; 20 4696 : std::vector<unsigned char> data; 21 2348 : data.reserve((vec.size() * 8 + 4) / 5); 22 181394 : ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, vec.begin(), vec.end()); 23 4696 : auto res = bech32::Encode(params.Bech32HRP(type), data); 24 2348 : memory_cleanse(vec.data(), vec.size()); 25 2348 : memory_cleanse(data.data(), data.size()); 26 2348 : return res; 27 : } 28 : 29 : template<typename BLSKey> 30 136 : static Optional<BLSKey> DecodeBLS(const CChainParams& params, 31 : const std::string& keyStr, 32 : CChainParams::Bech32Type type, 33 : unsigned int keySize) 34 : { 35 136 : if (keyStr.empty()) return nullopt; 36 272 : auto bech = bech32::Decode(keyStr); 37 136 : if (bech.first == params.Bech32HRP(type) && bech.second.size() == keySize) { 38 132 : std::vector<unsigned char> data; 39 132 : data.reserve((bech.second.size() * 5) / 8); 40 5620 : if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, bech.second.begin(), bech.second.end())) { 41 132 : CDataStream ss(data, SER_NETWORK, PROTOCOL_VERSION); 42 132 : BLSKey key; 43 132 : ss >> key; 44 185 : if (key.IsValid()) return {key}; 45 : } 46 : } 47 4 : return nullopt; 48 : } 49 : 50 70 : std::string EncodeSecret(const CChainParams& params, const CBLSSecretKey& key) 51 : { 52 70 : return EncodeBLS<CBLSSecretKey>(params, key, CChainParams::BLS_SECRET_KEY); 53 : } 54 : 55 2331 : std::string EncodePublic(const CChainParams& params, const CBLSPublicKey& pk) 56 : { 57 2331 : return EncodeBLS<CBLSPublicKey>(params, pk, CChainParams::BLS_PUBLIC_KEY); 58 : } 59 : 60 : const size_t ConvertedBlsSkSize = (BLS_CURVE_SECKEY_SIZE * 8 + 4) / 5; 61 : const size_t ConvertedBlsPkSize = (BLS_CURVE_PUBKEY_SIZE * 8 + 4) / 5; 62 : 63 55 : Optional<CBLSSecretKey> DecodeSecret(const CChainParams& params, const std::string& keyStr) 64 : { 65 55 : return DecodeBLS<CBLSSecretKey>(params, keyStr, CChainParams::BLS_SECRET_KEY, ConvertedBlsSkSize); 66 : } 67 : 68 81 : Optional<CBLSPublicKey> DecodePublic(const CChainParams& params, const std::string& keyStr) 69 : { 70 81 : return DecodeBLS<CBLSPublicKey>(params, keyStr, CChainParams::BLS_PUBLIC_KEY, ConvertedBlsPkSize); 71 : } 72 : 73 : } // end bls namespace