text:
// Copyright (c) 2018-2019 The Unit-e developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <amount.h>
#include <blockchain/blockchain_behavior.h>
#include <chainparams.h>
#include <consensus/validation.h>
#include <esperanza/vote.h>
#include <esperanza/walletextension.h>
#include <key.h>
#include <key_io.h>
#include <keystore.h>
#include <primitives/transaction.h>
#include <primitives/txtype.h>
#include <proposer/block_builder.h>
#include <proposer/eligible_coin.h>
#include <script/script.h>
#include <staking/coin.h>
#include <test/esperanza/finalization_utils.h>
#include <txmempool.h>
#include <validation.h>

#include <test/test_unite.h>
#include <wallet/test/wallet_test_fixture.h>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(walletextension_tests)

BOOST_FIXTURE_TEST_CASE(vote_signature, ReducedTestingSetup) {

  CBasicKeyStore keystore;
  CKey k;
  InsecureNewKey(k, true);
  keystore.AddKey(k);

  CPubKey pk = k.GetPubKey();

  esperanza::Vote vote{pk.GetID(), GetRandHash(), 10, 100};
  std::vector<unsigned char> voteSig;
  BOOST_CHECK(CreateVoteSignature(&keystore, vote, voteSig));

  std::vector<unsigned char> expectedSig;
  k.Sign(vote.GetHash(), expectedSig);

  BOOST_CHECK_EQUAL(HexStr(expectedSig), HexStr(voteSig));
  BOOST_CHECK(CheckVoteSignature(pk, vote, voteSig));
}

BOOST_FIXTURE_TEST_CASE(vote_signature2, TestingSetup) {

  CBasicKeyStore keystore;

  auto params = CreateChainParams(CBaseChainParams::TESTNET);

  CTxDestination dest = DecodeDestination("muUx4dQ4bwssNQYpUqAJHSJCUonAZ4Ro2s");
  const CKeyID *keyID = boost::get<CKeyID>(&dest);

  esperanza::Vote vote{*keyID, uint256S("4e7eae1625c033a05e92cff8d1591e4c7511888c264dbc8917ef94c3e66f22ef"), 12, 13};

  std::string pkey = "cNJWVLVrfrxZT85cwYfHdbRKGi2FQjkKFBjocwwinNNix5tytG33";

  CKey key = DecodeSecret(pkey);
  keystore.AddKey(key);

  std::vector<unsigned char> voteSig;
  BOOST_CHECK(CreateVoteSignature(&keystore, vote, voteSig));
}

BOOST_FIXTURE_TEST_CASE(sign_coinbase_transaction, WalletTestingSetup) {

  const key::mnemonic::Seed seed("stizzoso atavico inodore srotolato birra stupendo velina incendio copione pietra alzare privato folata madama gemmato");
  const CExtKey &ext_key = seed.GetExtKey();

  const auto key = ext_key.key;
  const auto pubkey = key.GetPubKey();
  const auto pubkeydata = std::vector<unsigned char>(pubkey.begin(), pubkey.end());

  auto block_builder = proposer::BlockBuilder::New(&settings);

  {
    LOCK(m_wallet->cs_wallet);
    m_wallet->AddKeyPubKey(key, pubkey);
  }

  const auto destination = WitnessV0KeyHash(pubkey.GetID());

  CMutableTransaction tx1;
  tx1.vout.emplace_back(100, GetScriptForDestination(destination));

  CMutableTransaction tx2;
  tx2.vout.emplace_back(1250, GetScriptForDestination(destination));

  CMutableTransaction tx3;
  tx3.vout.emplace_back(125, GetScriptForDestination(destination));

  CTransactionRef tx1ref = MakeTransactionRef(tx1);
  CTransactionRef tx2ref = MakeTransactionRef(tx2);
  CTransactionRef tx3ref = MakeTransactionRef(tx3);

  {
    LOCK(m_wallet->cs_wallet);
    const CWallet *wallet = m_wallet.get();

    CWalletTx walletTx1(wallet, tx1ref);
    CWalletTx walletTx2(wallet, tx2ref);
    CWalletTx walletTx3(wallet, tx3ref);

    m_wallet->LoadToWallet(walletTx1);
    m_wallet->LoadToWallet(walletTx2);
    m_wallet->LoadToWallet(walletTx3);
  }

  const CBlockIndex block = [] {
    CBlockIndex index;
    index.nHeight = 230;
    return index;
  }();

  CScript prev_script_pubkey = CScript::CreateP2PKHScript(ToByteVector(pubkey.GetID()));
  staking::Coin coin1(&block, {tx1ref->GetHash(), 0}, {100, prev_script_pubkey});
  staking::Coin coin2(&block, {tx2ref->GetHash(), 0}, {1250, prev_script_pubkey});
  staking::Coin coin3(&block, {tx3ref->GetHash(), 0}, {125, prev_script_pubkey});
  proposer::EligibleCoin eligible_coin{
      coin2,       // coin used as stake
      uint256(),   // kernel hash
      5000,        // reward
      7251,        // target height
      1548255362,  // target time,
      0x1d00ffff   // difficulty = 1
  };

  staking::CoinSet coins;
  coins.insert(coin1);
  coins.insert(coin2);
  coins.insert(coin3);

  // BuildCoinbaseTransaction() will also sign it
  CTransactionRef coinbase_transaction =
      block_builder->BuildCoinbaseTransaction(uint256(), eligible_coin, coins, 700, boost::none, m_wallet->GetWalletExtension());

  // check that a coinbase transaction was built successfully
  BOOST_REQUIRE(static_cast<bool>(coinbase_transaction));

  // should contain:
  // - (0) meta input
  // - (1) coin2 (the stake, eligible_coin uses coin2)
  // - (2) coin1 (combined other coin)
  // - (3) coin3 (combined other coin)
  BOOST_REQUIRE_EQUAL(coinbase_transaction->vin.size(), 4);

  // (0) meta input need not be signed
  BOOST_CHECK(coinbase_transaction->vin[0].scriptWitness.IsNull());

  // (1, 2, 3) remaining pieces must be signed with pubkey
  for (int i = 1; i < 3; ++i) {
    auto &stack = coinbase_transaction->vin[1].scriptWitness.stack;
    BOOST_CHECK_EQUAL(stack.size(), 2);  // signature + public key
    auto &witness_pubkey = stack[1];
    BOOST_CHECK(witness_pubkey == pubkeydata);
  }

  // We should be able to spend all the outputs
  for (const auto &out : coinbase_transaction->vout) {
    BOOST_CHECK(::IsMine(*m_wallet, out.scriptPubKey) == ISMINE_SPENDABLE);
  }
}

BOOST_FIXTURE_TEST_CASE(get_remote_staking_balance, WalletTestingSetup) {
  auto pwallet = m_wallet.get();
  auto &wallet_ext = pwallet->GetWalletExtension();

  CKey our_key;
  our_key.MakeNewKey(/* compressed: */ true);
  CPubKey our_pubkey = our_key.GetPubKey();

  CKey their_key;
  their_key.MakeNewKey(true);
  CPubKey their_pubkey = their_key.GetPubKey();

  CKey random_key;
  random_key.MakeNewKey(true);
  CPubKey random_pubkey = random_key.GetPubKey();

  const auto our_script = CScript() << ToByteVector(our_pubkey) << OP_CHECKSIG;
  const auto our_script_hash = Sha256(our_script.begin(), our_script.end());

  const auto their_script = CScript() << ToByteVector(their_pubkey) << OP_CHECKSIG;
  const auto their_script_hash = Sha256(their_script.begin(), their_script.end());

  LOCK2(cs_main, m_wallet->cs_wallet);
  pwallet->AddKey(our_key);
  pwallet->AddCScript(our_script);

  // P2PKH transactions don't affect remote staking balance
  {
    CMutableTransaction tx;
    tx.vout.emplace_back(100, CScript::CreateP2PKHScript(ToByteVector(our_pubkey.GetID())));
    CWalletTx wtx(pwallet, MakeTransactionRef(tx));
    m_wallet->LoadToWallet(wtx);

    CAmount balance = wallet_ext.GetRemoteStakingBalance();
    BOOST_CHECK_EQUAL(balance, 0);
  }

  // ...neither do P2PK transactions
  {
    CMutableTransaction tx;
    tx.vout.emplace_back(100, CScript() << ToByteVector(our_pubkey) << OP_CHECKSIG);
    CWalletTx wtx(pwallet, MakeTransactionRef(tx));
    m_wallet->LoadToWallet(wtx);
    BOOST_CHECK_EQUAL(m_wallet->IsMine(tx.vout[0]), ISMINE_SPENDABLE);

    CAmount balance = wallet_ext.GetRemoteStakingBalance();
    BOOST_CHECK_EQUAL(balance, 0);
  }

  // ...neither do other people's remote staking transactions...
  {
    CMutableTransaction tx;
    tx.vout.emplace_back(100, CScript::CreateRemoteStakingKeyhashScript(
                                  ToByteVector(their_pubkey.GetID()),
                                  ToByteVector(random_pubkey.GetSha256())));
    CWalletTx wtx(pwallet, MakeTransactionRef(tx));
    m_wallet->LoadToWallet(wtx);

    CMutableTransaction tx2;
    tx2.vout.emplace_back(100, CScript::CreateRemoteStakingScripthashScript(
                                   ToByteVector(their_pubkey.GetID()),
                                   ToByteVector(their_script_hash)));
    CWalletTx wtx2(pwallet, MakeTransactionRef(tx2));
    m_wallet->LoadToWallet(wtx2);

    CAmount balance = wallet_ext.GetRemoteStakingBalance();
    BOOST_CHECK_EQUAL(balance, 0);
  }

  // ...or tranctions that other people are staking on this node
  {
    CMutableTransaction tx;
    tx.vout.emplace_back(100, CScript::CreateRemoteStakingKeyhashScript(
                                  ToByteVector(our_pubkey.GetID()),
                                  ToByteVector(their_pubkey.GetSha256())));
    CWalletTx wtx(pwallet, MakeTransactionRef(tx));
    m_wallet->LoadToWallet(wtx);

    CMutableTransaction tx2;
    tx2.vout.emplace_back(100, CScript::CreateRemoteStakingScripthashScript(
                                   ToByteVector(our_pubkey.GetID()),
                                   ToByteVector(their_script_hash)));
    CWalletTx wtx2(pwallet, MakeTransactionRef(tx2));
    m_wallet->LoadToWallet(wtx2);

    CAmount balance = wallet_ext.GetRemoteStakingBalance();
    BOOST_CHECK_EQUAL(balance, 0);
  }

  // ...we have to be able to spend it to count.
  {
    CMutableTransaction tx;
    tx.vout.emplace_back(100, CScript::CreateRemoteStakingKeyhashScript(
                                  ToByteVector(their_pubkey.GetID()),
                                  ToByteVector(our_pubkey.GetSha256())));
    CWalletTx wtx(pwallet, MakeTransactionRef(tx));
    m_wallet->LoadToWallet(wtx);

    CMutableTransaction tx2;
    tx2.vout.emplace_back(100, CScript::CreateRemoteStakingScripthashScript(
                                   ToByteVector(their_pubkey.GetID()),
                                   ToByteVector(our_script_hash)));
    CWalletTx wtx2(pwallet, MakeTransactionRef(tx2));
    m_wallet->LoadToWallet(wtx2);

    CAmount balance = wallet_ext.GetRemoteStakingBalance();
    BOOST_CHECK_EQUAL(balance, 200);
  }
}

BOOST_FIXTURE_TEST_CASE(get_stakeable_coins, TestChain100Setup) {

  const auto pwallet = m_wallet.get();
  const auto &wallet_ext = pwallet->GetWalletExtension();

  {
    LOCK2(cs_main, m_wallet->cs_wallet);
    BOOST_CHECK_EQUAL(wallet_ext.GetStakeableCoins().size(), 1);
  }

  // Make the first coinbase mature
  CScript coinbase_script = GetScriptForDestination(coinbaseKey.GetPubKey().GetID());
  bool processed;
  CreateAndProcessBlock({}, coinbase_script, boost::none, &processed);
  BOOST_CHECK(processed);

  CTransaction &stakeable = m_coinbase_txns.front();

  // Check that a coin can be selected
  {
    LOCK2(cs_main, m_wallet->cs_wallet);
    staking::CoinSet stakeable_coins = wallet_ext.GetStakeableCoins();
    BOOST_REQUIRE_EQUAL(stakeable_coins.size(), 2);  // The just created stakeable tx + initial reward

    bool found = false;
    for (const staking::Coin &coin : stakeable_coins) {
      if (stakeable.GetHash() == coin.GetTransactionId() && coin.GetOutputIndex() == 0) {
        found = true;
        break;
      }
    }
    BOOST_CHECK(found);
  }

  // Make sure locked coins are not selected
  {
    LOCK2(cs_main, m_wallet->cs_wallet);
    staking::CoinSet stakeable_coins = wallet_ext.GetStakeableCoins();
    BOOST_CHECK_EQUAL(stakeable_coins.size(), 2);  // The just created stakeable tx + initial reward

    pwallet->LockCoin(COutPoint(stakeable.GetHash(), 0));

    stakeable_coins = wallet_ext.GetStakeableCoins();
    BOOST_CHECK_EQUAL(stakeable_coins.size(), 1);

    // Make sure we select the other coin in the coinbase
    BOOST_CHECK(stakeable_coins.begin()->GetTransactionId() != stakeable.GetHash());
    BOOST_CHECK(stakeable_coins.begin()->GetOutputIndex() != 0);
  }
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: dtr-org/unit-e


text: #include <boost/smart_ptr/make_shared_object.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (c) 2014-2018 The Bitcoin Core developers
// Copyright (c) 2017-2020 The LitecoinZ Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <key_io.h>

#include <base58.h>
#include <bech32.h>
#include <script/script.h>
#include <util/strencodings.h>

#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>

#include <assert.h>
#include <string.h>
#include <algorithm>

namespace
{
class DestinationEncoder : public boost::static_visitor<std::string>
{
private:
    const CChainParams& m_params;

public:
    explicit DestinationEncoder(const CChainParams& params) : m_params(params) {}

    std::string operator()(const PKHash& id) const
    {
        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
        data.insert(data.end(), id.begin(), id.end());
        return EncodeBase58Check(data);
    }

    std::string operator()(const ScriptHash& id) const
    {
        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
        data.insert(data.end(), id.begin(), id.end());
        return EncodeBase58Check(data);
    }

    std::string operator()(const WitnessV0KeyHash& id) const
    {
        std::vector<unsigned char> data = {0};
        data.reserve(33);
        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
        return bech32::Encode(m_params.Bech32HRP(), data);
    }

    std::string operator()(const WitnessV0ScriptHash& id) const
    {
        std::vector<unsigned char> data = {0};
        data.reserve(53);
        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
        return bech32::Encode(m_params.Bech32HRP(), data);
    }

    std::string operator()(const WitnessUnknown& id) const
    {
        if (id.version < 1 || id.version > 16 || id.length < 2 || id.length > 40) {
            return {};
        }
        std::vector<unsigned char> data = {(unsigned char)id.version};
        data.reserve(1 + (id.length * 8 + 4) / 5);
        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.program, id.program + id.length);
        return bech32::Encode(m_params.Bech32HRP(), data);
    }

    std::string operator()(const CNoDestination& no) const { return {}; }
};

CTxDestination DecodeDestination(const std::string& str, const CChainParams& params)
{
    std::vector<unsigned char> data;
    uint160 hash;
    if (DecodeBase58Check(str, data)) {
        // base58-encoded Bitcoin addresses.
        // Public-key-hash-addresses have version 0 (or 111 testnet).
        // The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
        const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
        if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
            std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());
            return PKHash(hash);
        }
        // Script-hash-addresses have version 5 (or 196 testnet).
        // The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
        const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
        if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {
            std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());
            return ScriptHash(hash);
        }
    }
    data.clear();
    auto bech = bech32::Decode(str);
    if (bech.second.size() > 0 && bech.first == params.Bech32HRP()) {
        // Bech32 decoding
        int version = bech.second[0]; // The first 5 bit symbol is the witness version (0-16)
        // The rest of the symbols are converted witness program bytes.
        data.reserve(((bech.second.size() - 1) * 5) / 8);
        if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, bech.second.begin() + 1, bech.second.end())) {
            if (version == 0) {
                {
                    WitnessV0KeyHash keyid;
                    if (data.size() == keyid.size()) {
                        std::copy(data.begin(), data.end(), keyid.begin());
                        return keyid;
                    }
                }
                {
                    WitnessV0ScriptHash scriptid;
                    if (data.size() == scriptid.size()) {
                        std::copy(data.begin(), data.end(), scriptid.begin());
                        return scriptid;
                    }
                }
                return CNoDestination();
            }
            if (version > 16 || data.size() < 2 || data.size() > 40) {
                return CNoDestination();
            }
            WitnessUnknown unk;
            unk.version = version;
            std::copy(data.begin(), data.end(), unk.program);
            unk.length = data.size();
            return unk;
        }
    }
    return CNoDestination();
}

class PaymentAddressEncoder : public boost::static_visitor<std::string>
{
private:
    const CChainParams& m_params;

public:
    PaymentAddressEncoder(const CChainParams& params) : m_params(params) {}

    std::string operator()(const libzcash::SproutPaymentAddress& zaddr) const
    {
        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
        ss << zaddr;
        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SPROUT_PAYMENT_ADDRESS);
        data.insert(data.end(), ss.begin(), ss.end());
        return EncodeBase58Check(data);
    }

    std::string operator()(const libzcash::SaplingPaymentAddress& zaddr) const
    {
        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
        ss << zaddr;
        // ConvertBits requires unsigned char, but CDataStream uses char
        std::vector<unsigned char> seraddr(ss.begin(), ss.end());
        std::vector<unsigned char> data;
        // See calculation comment below
        data.reserve((seraddr.size() * 8 + 4) / 5);
        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, seraddr.begin(), seraddr.end());
        return bech32::Encode(m_params.Bech32HRP(CChainParams::SAPLING_PAYMENT_ADDRESS), data);
    }

    std::string operator()(const libzcash::InvalidEncoding& no) const { return {}; }
};

class ViewingKeyEncoder : public boost::static_visitor<std::string>
{
private:
    const CChainParams& m_params;

public:
    ViewingKeyEncoder(const CChainParams& params) : m_params(params) {}

    std::string operator()(const libzcash::SproutViewingKey& vk) const
    {
        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
        ss << vk;
        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SPROUT_VIEWING_KEY);
        data.insert(data.end(), ss.begin(), ss.end());
        std::string ret = EncodeBase58Check(data);
        memory_cleanse(data.data(), data.size());
        return ret;
    }

    std::string operator()(const libzcash::SaplingExtendedFullViewingKey& extfvk) const
    {
        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
        ss << extfvk;
        // ConvertBits requires unsigned char, but CDataStream uses char
        std::vector<unsigned char> serkey(ss.begin(), ss.end());
        std::vector<unsigned char> data;
        // See calculation comment below
        data.reserve((serkey.size() * 8 + 4) / 5);
        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, serkey.begin(), serkey.end());
        std::string ret = bech32::Encode(m_params.Bech32HRP(CChainParams::SAPLING_EXTENDED_FVK), data);
        memory_cleanse(serkey.data(), serkey.size());
        memory_cleanse(data.data(), data.size());
        return ret;
    }

    std::string operator()(const libzcash::InvalidEncoding& no) const { return {}; }
};

class SpendingKeyEncoder : public boost::static_visitor<std::string>
{
private:
    const CChainParams& m_params;

public:
    SpendingKeyEncoder(const CChainParams& params) : m_params(params) {}

    std::string operator()(const libzcash::SproutSpendingKey& zkey) const
    {
        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
        ss << zkey;
        std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SPROUT_SPENDING_KEY);
        data.insert(data.end(), ss.begin(), ss.end());
        std::string ret = EncodeBase58Check(data);
        memory_cleanse(data.data(), data.size());
        return ret;
    }

    std::string operator()(const libzcash::SaplingExtendedSpendingKey& zkey) const
    {
        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
        ss << zkey;
        // ConvertBits requires unsigned char, but CDataStream uses char
        std::vector<unsigned char> serkey(ss.begin(), ss.end());
        std::vector<unsigned char> data;
        // See calculation comment below
        data.reserve((serkey.size() * 8 + 4) / 5);
        ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, serkey.begin(), serkey.end());
        std::string ret = bech32::Encode(m_params.Bech32HRP(CChainParams::SAPLING_EXTENDED_SPEND_KEY), data);
        memory_cleanse(serkey.data(), serkey.size());
        memory_cleanse(data.data(), data.size());
        return ret;
    }

    std::string operator()(const libzcash::InvalidEncoding& no) const { return {}; }
};

// Sizes of SaplingPaymentAddress, SaplingExtendedFullViewingKey, and
// SaplingExtendedSpendingKey after ConvertBits<8, 5, true>(). The calculations
// below take the regular serialized size in bytes, convert to bits, and then
// perform ceiling division to get the number of 5-bit clusters.
const size_t ConvertedSaplingPaymentAddressSize = ((32 + 11) * 8 + 4) / 5;
const size_t ConvertedSaplingExtendedFullViewingKeySize = (ZIP32_XFVK_SIZE * 8 + 4) / 5;
const size_t ConvertedSaplingExtendedSpendingKeySize = (ZIP32_XSK_SIZE * 8 + 4) / 5;
} // namespace

CKey DecodeSecret(const std::string& str)
{
    CKey key;
    std::vector<unsigned char> data;
    if (DecodeBase58Check(str, data)) {
        const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
        if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
            std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
            bool compressed = data.size() == 33 + privkey_prefix.size();
            key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
        }
    }
    if (!data.empty()) {
        memory_cleanse(data.data(), data.size());
    }
    return key;
}

std::string EncodeSecret(const CKey& key)
{
    assert(key.IsValid());
    std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
    data.insert(data.end(), key.begin(), key.end());
    if (key.IsCompressed()) {
        data.push_back(1);
    }
    std::string ret = EncodeBase58Check(data);
    memory_cleanse(data.data(), data.size());
    return ret;
}

CExtPubKey DecodeExtPubKey(const std::string& str)
{
    CExtPubKey key;
    std::vector<unsigned char> data;
    if (DecodeBase58Check(str, data)) {
        const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
        if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
            key.Decode(data.data() + prefix.size());
        }
    }
    return key;
}

std::string EncodeExtPubKey(const CExtPubKey& key)
{
    std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
    size_t size = data.size();
    data.resize(size + BIP32_EXTKEY_SIZE);
    key.Encode(data.data() + size);
    std::string ret = EncodeBase58Check(data);
    return ret;
}

CExtKey DecodeExtKey(const std::string& str)
{
    CExtKey key;
    std::vector<unsigned char> data;
    if (DecodeBase58Check(str, data)) {
        const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
        if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
            key.Decode(data.data() + prefix.size());
        }
    }
    return key;
}

std::string EncodeExtKey(const CExtKey& key)
{
    std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
    size_t size = data.size();
    data.resize(size + BIP32_EXTKEY_SIZE);
    key.Encode(data.data() + size);
    std::string ret = EncodeBase58Check(data);
    memory_cleanse(data.data(), data.size());
    return ret;
}

std::string EncodeDestination(const CTxDestination& dest)
{
    return boost::apply_visitor(DestinationEncoder(Params()), dest);
}

CTxDestination DecodeDestination(const std::string& str)
{
    return DecodeDestination(str, Params());
}

bool IsValidDestinationString(const std::string& str, const CChainParams& params)
{
    return IsValidDestination(DecodeDestination(str, params));
}

bool IsValidDestinationString(const std::string& str)
{
    return IsValidDestinationString(str, Params());
}

std::string EncodePaymentAddress(const libzcash::PaymentAddress& address)
{
    return boost::apply_visitor(PaymentAddressEncoder(Params()), address);
}

template<typename T1, typename T2, typename T3>
T1 DecodeAny(
    const std::string& str,
    std::pair<CChainParams::Base58Type, size_t> sprout,
    std::pair<CChainParams::Bech32Type, size_t> sapling)
{
    std::vector<unsigned char> data;
    if (DecodeBase58Check(str, data)) {
        const std::vector<unsigned char>& prefix = Params().Base58Prefix(sprout.first);
        if ((data.size() == sprout.second + prefix.size()) &&
            std::equal(prefix.begin(), prefix.end(), data.begin())) {
            CSerializeData serialized(data.begin() + prefix.size(), data.end());
            CDataStream ss(serialized, SER_NETWORK, PROTOCOL_VERSION);
            T2 ret;
            ss >> ret;
            memory_cleanse(serialized.data(), serialized.size());
            memory_cleanse(data.data(), data.size());
            return ret;
        }
    }

    data.clear();
    auto bech = bech32::Decode(str, 1023);
    if (bech.first == Params().Bech32HRP(sapling.first) &&
        bech.second.size() == sapling.second) {
        // Bech32 decoding
        data.reserve((bech.second.size() * 5) / 8);
        if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, bech.second.begin(), bech.second.end())) {
            CDataStream ss(data, SER_NETWORK, PROTOCOL_VERSION);
            T3 ret;
            ss >> ret;
            memory_cleanse(data.data(), data.size());
            return ret;
        }
    }

    memory_cleanse(data.data(), data.size());
    return libzcash::InvalidEncoding();
}

libzcash::PaymentAddress DecodePaymentAddress(const std::string& str)
{
    return DecodeAny<libzcash::PaymentAddress,
        libzcash::SproutPaymentAddress,
        libzcash::SaplingPaymentAddress>(
            str,
            std::make_pair(CChainParams::SPROUT_PAYMENT_ADDRESS, libzcash::SerializedSproutPaymentAddressSize),
            std::make_pair(CChainParams::SAPLING_PAYMENT_ADDRESS, ConvertedSaplingPaymentAddressSize)
        );
}

bool IsValidPaymentAddressString(const std::string& str) {
    return IsValidPaymentAddress(DecodePaymentAddress(str));
}

std::string EncodeViewingKey(const libzcash::ViewingKey& vk)
{
    return boost::apply_visitor(ViewingKeyEncoder(Params()), vk);
}

libzcash::ViewingKey DecodeViewingKey(const std::string& str)
{
    return DecodeAny<libzcash::ViewingKey,
        libzcash::SproutViewingKey,
        libzcash::SaplingExtendedFullViewingKey>(
            str,
            std::make_pair(CChainParams::SPROUT_VIEWING_KEY, libzcash::SerializedSproutViewingKeySize),
            std::make_pair(CChainParams::SAPLING_EXTENDED_FVK, ConvertedSaplingExtendedFullViewingKeySize)
        );
}

std::string EncodeSpendingKey(const libzcash::SpendingKey& sk)
{
    return boost::apply_visitor(SpendingKeyEncoder(Params()), sk);
}

libzcash::SpendingKey DecodeSpendingKey(const std::string& str)
{
    return DecodeAny<libzcash::SpendingKey,
        libzcash::SproutSpendingKey,
        libzcash::SaplingExtendedSpendingKey>(
            str,
            std::make_pair(CChainParams::SPROUT_SPENDING_KEY, libzcash::SerializedSproutSpendingKeySize),
            std::make_pair(CChainParams::SAPLING_EXTENDED_SPEND_KEY, ConvertedSaplingExtendedSpendingKeySize)
        );
}

max_stars_repo_name: kaboela/litecoinz

max_issues_repo_name: kaboela/litecoinz

max_forks_repo_name: kaboela/litecoinz


text:
// Copyright Dean Michael Berris 2010
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_NETWORK_SUPPORT_STRING_CHECK_20100808
#define BOOST_NETWORK_SUPPORT_STRING_CHECK_20100808

#include <boost/network/tags.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost {
namespace network {

template <class Tag, class Enable = void>
struct is_default_string : mpl::false_ {};

template <class Tag>
struct is_default_string<
    Tag,
    typename enable_if<typename Tag::is_default_string>::type> : mpl::true_ {};

}  // namespace network

}  // namespace boost

#endif  // BOOST_NETWORK_SUPPORT_STRING_CHECK_20100808

max_stars_repo_name: ChadSki/Phasor


text:
/*
* TS Elements
* Copyright 2015-2018 M. Newhouse
* Released under the MIT license.
*/

#pragma once

#include "tiles.hpp"
#include "resource_library_interface.hpp"
#include "collision_shape.hpp"

#include <boost/iterator.hpp>
#include <boost/utility/string_ref.hpp>

#include <set>
#include <unordered_set>
#include <string>

namespace ts
{
  namespace resources
  {
    class TileLibrary;

    namespace detail
    {
      // These comparator objects allow for tile definitions can be compared to their
      // associated tile ids, allowing for convenient lookup in the exposed tile library interfaces.
      struct TileDefinitionComparator
      {
        using is_transparent = std::true_type;
        bool operator()(const TileDefinition& a, const TileDefinition& b) const;
        bool operator()(const TileDefinition& a, TileId tile_id) const;
        bool operator()(TileId tile_id, const TileDefinition& a) const;
      };

      struct TileGroupDefinitionComparator
      {
        using is_transparent = std::true_type;
        bool operator()(const TileGroupDefinition& a, const TileGroupDefinition& b) const;
        bool operator()(const TileGroupDefinition& a, TileId tile_id) const;
        bool operator()(TileId tile_id, const TileGroupDefinition& a) const;
      };
    }

    // The TileLibrary class exposes two types of resources. First we have tile definitions, which
    // define how a tile should be drawn and how it interacts with the game world. Additionally,
    // we have tile groups, which contain a set of placed sub-tiles.
    class TileLibrary
    {
    private:
      using tile_container_type = std::set<TileDefinition, detail::TileDefinitionComparator>;
      using tile_group_container_type = std::set<TileGroupDefinition, detail::TileGroupDefinitionComparator>;

    public:
      using tile_interface_type = ResourceLibraryInterface<tile_container_type, SetSearchPolicy>;
      using tile_group_interface_type = ResourceLibraryInterface<tile_group_container_type, SetSearchPolicy>;

      using tile_iterator = tile_interface_type::iterator;
      using tile_group_iterator = tile_group_interface_type::iterator;

      struct TileDefinitionInterface;

      // This function allows for efficiently defining larger sets of tiles, without making multiple copies
      // of the file name strings or other kinds of inefficiencies.
      TileDefinitionInterface define_tile_set(boost::string_ref pattern_file, boost::string_ref image_file);

      tile_group_iterator define_tile_group(const TileGroupDefinition& tile_group_def);

      void define_collision_shape(TileId tile_id, CollisionShape collision_shape);

      tile_interface_type tiles() const;
      tile_group_interface_type tile_groups() const;

    private:
      tile_iterator define_tile(const TileDefinition& tile_def);

      tile_container_type tile_definitions_;
      tile_group_container_type tile_group_definitions_;

      std::unordered_set<std::string> filename_strings_;
    };

    struct TileLibrary::TileDefinitionInterface
    {
      tile_iterator define_tile(TileId tile_id, IntRect pattern_rect, IntRect image_rect);

    private:
      friend TileLibrary;
      TileDefinitionInterface(TileLibrary* tile_library, boost::string_ref pattern_file, boost::string_ref image_file);

      TileLibrary* tile_library_;
      boost::string_ref pattern_file_;
      boost::string_ref image_file_;
    };
  }
}

max_stars_repo_name: mnewhouse/tselements

max_issues_repo_name: mnewhouse/tselements

max_forks_repo_name: mnewhouse/tselements


text:
#include <fstream>
#include <regex>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include "Guide.h"
#include "ParserException.h"

namespace ophidian::parser
{
    Guide::Guide(const std::string &guide_file):
        m_nets{}
    {
        read_file(guide_file);
    }

    void Guide::read_file(const std::string &guide_file)
    {
        auto line = std::string{};

        auto file = std::ifstream{guide_file};

        if (!file.is_open()){
            throw exceptions::InexistentFile{};
        }

        auto integer = std::regex{"(\\+|-)?[[:digit:]]+"};
        auto net = std::regex{"net[[:digit:]]+"};
        auto metal = std::regex{"Metal[[:digit:]]+"};

        auto words = std::vector<std::string>{};

        while (getline(file, line))
        {
            boost::split(words, line, [](char c){return c == ' ';});

            if(regex_match(words[0],net))
            {
                auto net_name = Guide::net_type::name_type{words[0]};

                getline(file, line); //get "("

                if(line.compare("(") != 0){
                    throw exceptions::GuideFileSyntaxError{};
                }

                words.clear();

                auto regions = Guide::net_type::region_container_type{};

                while (getline(file, line) && line.compare(")") != 0)
                {
                    //get the regions belonging to NET
                    boost::split(words, line, [](char c){return c == ' ';});

                    if(words.size() != 5){
                        throw exceptions::GuideFileSyntaxError{};
                    }

                    if(!(regex_match(words[0], integer) && regex_match(words[1], integer) &&
                         regex_match(words[2], integer) && regex_match(words[3], integer) &&
                         regex_match(words[4], metal))  )
                    {
                        throw exceptions::GuideFileSyntaxError{};
                    }

                    auto x1 = static_cast<double>(boost::lexical_cast<int>(words[0]));
                    auto y1 = static_cast<double>(boost::lexical_cast<int>(words[1]));
                    auto x2 = static_cast<double>(boost::lexical_cast<int>(words[2]));
                    auto y2 = static_cast<double>(boost::lexical_cast<int>(words[3]));

                    auto origin = Guide::database_unit_point_type{
                        database_unit_type{x1},
                        database_unit_type{y1}
                    };
                    auto upperRight = Guide::database_unit_point_type{
                        database_unit_type{x2},
                        database_unit_type{y2}
                    };

                    regions.emplace_back(
                        Guide::net_type::region_type::layer_name_type{words[4]},
                        Guide::net_type::region_type::geometry_type{origin, upperRight}
                    );
                }

                if(line.compare(")") != 0){ //get ")"
                    throw exceptions::GuideFileSyntaxError();
                }

                m_nets.emplace_back(
                    std::move(net_name),
                    std::move(regions)
                );
            }
        }

        file.close();
    }

    Guide::net_container_type& Guide::nets() noexcept
    {
        return m_nets;
    }

    const Guide::net_container_type& Guide::nets() const noexcept
    {
        return m_nets;
    }

    const Guide::Net::name_type& Guide::Net::name() const noexcept
    {
        return m_name;
    }

    Guide::Net::region_container_type& Guide::Net::regions() noexcept
    {
        return m_regions;
    }

    const Guide::Net::region_container_type& Guide::Net::regions() const noexcept
    {
        return m_regions;
    }

    const Guide::Region::layer_name_type& Guide::Region::metal_layer_name() const noexcept
    {
        return m_metal;
    }

    const Guide::Region::geometry_type& Guide::Region::geometry() const noexcept
    {
        return m_region;
    }
}

max_stars_repo_name: sheiny/ophidian

max_issues_repo_name: sheiny/ophidian

max_forks_repo_name: eclufsc/openeda