text:
#include <game/move.h>

#include <base58.h>
#include <consensus/validation.h>
#include <game/db.h>
#include <game/map.h>
#include <game/state.h>
#include <key_io.h>
#include <names/common.h>
#include <names/main.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/names.h>
#include <script/standard.h>
#include <util.h>
#include <utilstrencodings.h>
#include <validation.h>

#include <boost/foreach.hpp>
#include <boost/xpressive/xpressive_dynamic.hpp>

/* Maximum number of waypoints per character.  */
static const int MAX_WAYPOINTS = 100;

/* Number of colours in the game.  */
static const int NUM_TEAM_COLORS = 4;

/* ************************************************************************** */
/* Move.  */

bool Move::IsValid(const GameState &state) const
{
  PlayerStateMap::const_iterator mi = state.players.find (player);

  CAmount oldLocked;
  if (mi == state.players.end ())
    {
      if (!IsSpawn ())
        return false;
      oldLocked = 0;
    }
  else
    {
      if (IsSpawn ())
        return false;
      oldLocked = mi->second.lockedCoins;
    }

  assert (oldLocked >= 0 && newLocked >= 0);
  const CAmount gameFee = newLocked - oldLocked;
  const CAmount required = MinimumGameFee (*state.param, state.nHeight + 1);
  assert (required >= 0);
  if (gameFee < required)
    return error ("%s: too little game fee attached, got %lld, required %lld",
                  __func__, gameFee, required);

  return true;
}

bool ParseWaypoints(UniValue& obj, std::vector<Coord>& result, bool& bWaypoints)
{
    bWaypoints = false;
    result.clear();
    UniValue v;
    if (!obj.extractField("wp", v))
        return true;
    if (!v.isArray())
        return false;
    if (v.size() % 2)
        return false;
    int n = v.size() / 2;
    if (n > MAX_WAYPOINTS)
        return false;
    result.resize(n);
    for (int i = 0; i < n; i++)
    {
        int x = v[2 * i].get_int();
        int y = v[2 * i + 1].get_int();
        if (!IsInsideMap(x, y))
            return false;
        // Waypoints are reversed for easier deletion of current waypoint from the end of the vector
        result[n - 1 - i] = Coord(x, y);
        if (i && result[n - 1 - i] == result[n - i])
            return false; // Forbid duplicates
    }
    bWaypoints = true;
    return true;
}

bool ParseDestruct(UniValue& obj, bool& result)
{
    result = false;
    UniValue v;
    if (!obj.extractField("destruct", v))
        return true;
    result = v.get_bool();
    return true;
}

static bool
IsValidReceiveAddress (const std::string& str)
{
  /* TODO: Allow P2SH addresses at some point in the future.  For now,
     we have to disable support to stay consensus-compatible with
     the existing client.  */

  const CTxDestination dest = DecodeDestination (str);
  return IsKeyDestination (dest);
}

bool Move::Parse(const PlayerID &p, const std::string &json)
{
    try
    {

    if (!IsValidPlayerName(p))
        return false;

    UniValue obj;
    if (!obj.read(json, false) || !obj.isObject())
        return false;

    UniValue v;
    if (obj.extractField ("msg", v))
        message = v.get_str();
    if (obj.extractField("address", v))
    {
        const std::string &addr = v.get_str();
        if (!addr.empty() && !IsValidReceiveAddress(addr))
            return false;
        address = addr;
    }
    if (obj.extractField("addressLock", v))
    {
        const std::string &addr = v.get_str();
        if (!addr.empty() && !IsValidReceiveAddress(addr))
            return false;
        addressLock = addr;
    }

    if (obj.extractField("color", v))
    {
        color = v.get_int();
        if (color >= NUM_TEAM_COLORS)
            return false;
        if (!obj.empty()) // Extra fields are not allowed in JSON string
            return false;
        player = p;
        return true;
    }

    const std::vector<std::string> keys = obj.getKeys ();
    std::set<int> character_indices;
    for (const auto& key : keys)
    {
        const int i = atoi(key.c_str());
        if (i < 0 || strprintf("%d", i) != key)
            return false;               // Number formatting must be strict
        if (character_indices.count(i))
            return false;               // Cannot contain duplicate character indices
        character_indices.insert(i);
        v = obj[key];
        if (!v.isObject ())
            return false;
        bool bWaypoints = false;
        std::vector<Coord> wp;
        if (!ParseWaypoints(v, wp, bWaypoints))
            return false;
        bool bDestruct;
        if (!ParseDestruct(v, bDestruct))
            return false;

        if (bDestruct)
            destruct.insert(i);
        if (bWaypoints)
            waypoints.insert(std::make_pair(i, wp));

        if (!v.empty())      // Extra fields are not allowed in JSON string
            return false;
    }

    player = p;
    return true;

    } catch (const std::runtime_error& exc)
    {
        /* This happens when some JSON value has a wrong type.  */
        return false;
    }
}

void Move::ApplyCommon(GameState &state) const
{
    std::map<PlayerID, PlayerState>::iterator mi = state.players.find(player);

    if (mi == state.players.end())
    {
        if (message)
        {
            PlayerState &pl = state.dead_players_chat[player];
            pl.message = *message;
            pl.message_block = state.nHeight;
        }
        return;
    }

    PlayerState &pl = mi->second;
    if (message)
    {
        pl.message = *message;
        pl.message_block = state.nHeight;
    }
    if (address)
        pl.address = *address;
    if (addressLock)
        pl.addressLock = *addressLock;
}

std::string Move::AddressOperationPermission(const GameState &state) const
{
    if (!address && !addressLock)
        return std::string();      // No address operation requested - allow

    PlayerStateMap::const_iterator mi = state.players.find(player);
    if (mi == state.players.end())
        return std::string();      // Spawn move - allow any address operation

    return mi->second.addressLock;
}

void
Move::ApplySpawn (GameState &state, RandomGenerator &rnd) const
{
  assert (state.players.count (player) == 0);

  PlayerState pl;
  assert (pl.next_character_index == 0);
  pl.color = color;

  /* This is a fresh player and name.  Set its value to the height's
     name coin amount and put the remainder in the game fee.  This prevents
     people from "overpaying" on purpose in order to get beefed-up players.
     This rule, however, is only active after the life-steal fork.  Before
     that, overpaying did, indeed, allow to set the hunter value
     arbitrarily high.  */
  if (state.ForkInEffect (FORK_LIFESTEAL))
    {
      const CAmount coinAmount = GetNameCoinAmount (*state.param, state.nHeight);
      assert (pl.lockedCoins == 0 && pl.value == -1);
      assert (newLocked >= coinAmount);
      pl.value = coinAmount;
      pl.lockedCoins = newLocked;
      state.gameFund += newLocked - coinAmount;
    }
  else
    {
      pl.value = newLocked;
      pl.lockedCoins = newLocked;
    }

  const unsigned limit = state.GetNumInitialCharacters ();
  for (unsigned i = 0; i < limit; i++)
    pl.SpawnCharacter (state, rnd);

  state.players.insert (std::make_pair (player, pl));
}

void Move::ApplyWaypoints(GameState &state) const
{
    std::map<PlayerID, PlayerState>::iterator pl;
    pl = state.players.find (player);
    if (pl == state.players.end ())
      return;

    for (const auto& p : waypoints)
    {
        std::map<int, CharacterState>::iterator mi;
        mi = pl->second.characters.find(p.first);
        if (mi == pl->second.characters.end())
            continue;
        CharacterState &ch = mi->second;
        const std::vector<Coord> &wp = p.second;

        if (ch.waypoints.empty() || wp.empty() || ch.waypoints.back() != wp.back())
            ch.from = ch.coord;
        ch.waypoints = wp;
    }
}

CAmount
Move::MinimumGameFee (const Consensus::Params& param, unsigned nHeight) const
{
  if (IsSpawn ())
    {
      const CAmount coinAmount = GetNameCoinAmount (param, nHeight);

      // fee for new hunter is 1 HUC
      if (param.rules->ForkInEffect (FORK_TIMESAVE, nHeight))
        return coinAmount + COIN;

      if (param.rules->ForkInEffect (FORK_LIFESTEAL, nHeight))
        return coinAmount + 5 * COIN;

      return coinAmount;
    }

  // destruct fee is 1 HUC
  if (param.rules->ForkInEffect (FORK_TIMESAVE, nHeight))
    return COIN * destruct.size ();

  if (param.rules->ForkInEffect (FORK_LIFESTEAL, nHeight))
    return 20 * COIN * destruct.size ();

  return 0;
}

bool
Move::IsValidPlayerName (const std::string& player)
{
  if (player.size() > MAX_NAME_LENGTH)
    return false;

  // Check player name validity
  // Can contain letters, digits, underscore, hyphen and whitespace
  // Cannot contain double whitespaces or start/end with whitespace
  using namespace boost::xpressive;
  static sregex regex = sregex::compile("^([a-zA-Z0-9_-]+ )*[a-zA-Z0-9_-]+$");
  smatch match;
  return regex_search(player, match, regex);
}

/* ************************************************************************** */
/* StepData.  */

StepData::StepData (const GameState& s)
  : state(s), dup(), nTreasureAmount(-1), newHash(), vMoves()
{
  const CAmount nSubsidy = GetBlockSubsidy (state.nHeight + 1, *state.param);
  // Miner subsidy is 10%, thus game treasure is 9 times the subsidy
  nTreasureAmount = nSubsidy * 9;
}

bool
StepData::addTransaction (const CTransaction& tx, const CCoinsView* pview,
                          CValidationState& res)
{
  if (!tx.IsNamecoin ())
    return true;

  /* Keep the moves to add to the step data here first.  This is necessary
     to prevent a situation where some moves are added already but the
     function fails later with an error.  */
  std::vector<Move> newMoves;

  for (const auto& txo : tx.vout)
    {
      const CNameScript nameOp(txo.scriptPubKey);
      if (!nameOp.isNameOp () || !nameOp.isAnyUpdate ())
        continue;

      const std::string strName = ValtypeToString (nameOp.getOpName ());
      const std::string strValue = ValtypeToString (nameOp.getOpValue ());

      if (dup.count (strName))
        return res.Invalid (error ("%s: duplicate name '%s' in block",
                                   __func__, strName.c_str ()));
      dup.insert (strName);

      Move m;
      m.newLocked = txo.nValue;

      if (!m.Parse (strName, strValue))
        return res.Invalid (error ("%s: cannot parse move %s",
                                   __func__, strValue.c_str ()));
      if (!m.IsValid (state))
        return res.Invalid (error ("%s: invalid move for player %s",
                                   __func__, strName.c_str ()));

      if (m.IsSpawn ())
        {
          if (nameOp.getNameOp () != OP_NAME_FIRSTUPDATE)
            return res.Invalid (error ("%s: spawn is not firstupdate",
                                       __func__));
        }
      else if (nameOp.getNameOp () != OP_NAME_UPDATE)
        return res.Invalid (error ("%s: firstupdate is not spawn"));

      const std::string addressLock = m.AddressOperationPermission (state);
      if (pview && !addressLock.empty ())
        {
          /* If one of inputs has address equal to addressLock, then that input
             has been signed by the address owner and thus authorizes the
             address change operation.  */
          bool found = false;
          for (const auto& txi : tx.vin)
            {
              const COutPoint prevout = txi.prevout;
              Coin coin;

              if (!pview->GetCoin (prevout, coin))
                continue;

              CTxDestination dest;
              if (ExtractDestination (coin.out.scriptPubKey, dest)
                    && EncodeDestination (dest) == addressLock)
                {
                  found = true;
                  break;
                }
            }
          if (!found)
            return res.Invalid (error ("%s: address operation denied",
                                       __func__));
        }

      newMoves.push_back (m);
    }

  vMoves.insert (vMoves.end (), newMoves.begin (), newMoves.end ());
  return true;
}

/* ************************************************************************** */

bool
PerformStep (const CBlock& block, const GameState& stateIn,
             const CCoinsView* pview, CValidationState& valid,
             StepResult& res, GameState& stateOut)
{
  StepData step(stateIn);
  for (const auto& tx : block.vtx)
    if (!step.addTransaction (*tx, pview, valid))
      return error ("%s: tx %s not accepted",
                    __func__, tx->GetHash ().GetHex ().c_str());
  step.newHash = block.GetHash ();

  if (!PerformStep (stateIn, step, stateOut, res))
    return error ("%s: game engine failed to perform step", __func__);

  return true;
}

max_stars_repo_name: chronokings/huntercore


text:
#pragma once

#include <bunsan/lazy_ptr.hpp>

#include <boost/noncopyable.hpp>

#include <functional>
#include <memory>
#include <vector>

namespace bunsan {
namespace application {

class global_state : private boost::noncopyable {
 public:
  virtual ~global_state();

 protected:
  global_state();
};

template <typename T>
class global_state_any : public global_state {
 public:
  explicit global_state_any(T state) : m_state(std::move(state)) {}

  ~global_state_any() override {}

 private:
  T m_state;
};

using global_state_ptr = std::unique_ptr<global_state>;
using global_state_factory = std::function<global_state_ptr()>;

template <typename T>
global_state_ptr make_global_any_state(T state) {
  return std::make_unique<global_state_any<T>>(std::move(state));
}

template <typename T>
global_state_ptr make_global_unique_state() {
  return make_global_any_state(std::make_unique<T>());
}

class global_registry : private boost::noncopyable {
 public:
  using global_registry_ptr = std::shared_ptr<global_registry>;

 public:
  ~global_registry();

 public:
  /*!
   * Locks state, lifetime is supported by external pointers.
   * Once all pointers are destroyed registry is removed
   * and next call will create it from scratch.
   */
  static global_registry_ptr lock();

  /// \returns true
  static bool register_state_factory(const global_state_factory &factory);

  template <typename T>
  static bool register_unique_state_factory() {
    return register_state_factory(&make_global_unique_state<T>);
  }

 private:
  global_registry();

 private:
  std::vector<global_state_ptr> m_states;

 private:
  using state_factory_list = std::vector<global_state_factory>;

  struct global_instance_storage {
    std::mutex lock;
    state_factory_list factories;
    std::weak_ptr<global_registry> instance;
  };

  static global_lazy_ptr<global_instance_storage> global_instance;
};

using global_registry_ptr = global_registry::global_registry_ptr;

}  // namespace application
}  // namespace bunsan

ext: hpp


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file    DoglegOptimizer.cpp
 * @brief
 * @author  Richard Roberts
 * @date 	Feb 26, 2012
 */

#include <gtsam/nonlinear/DoglegOptimizer.h>

#include <gtsam/inference/EliminationTree.h>
#include <gtsam/linear/GaussianJunctionTree.h>
#include <gtsam/nonlinear/DoglegOptimizerImpl.h>

#include <boost/algorithm/string.hpp>

using namespace std;

namespace gtsam {

/* ************************************************************************* */
DoglegParams::VerbosityDL DoglegParams::verbosityDLTranslator(const std::string &verbosityDL) const {
	std::string s = verbosityDL;  boost::algorithm::to_upper(s);
	if (s == "SILENT") return DoglegParams::SILENT;
	if (s == "VERBOSE") return DoglegParams::VERBOSE;

	/* default is silent */
	return DoglegParams::SILENT;
}

/* ************************************************************************* */
std::string DoglegParams::verbosityDLTranslator(VerbosityDL verbosityDL) const {
	std::string s;
	switch (verbosityDL) {
	case DoglegParams::SILENT:  s = "SILENT"; break;
	case DoglegParams::VERBOSE: s = "VERBOSE"; break;
	default:                    s = "UNDEFINED"; break;
	}
	return s;
}

/* ************************************************************************* */
void DoglegOptimizer::iterate(void) {

  // Linearize graph
  const Ordering& ordering = *params_.ordering;
  GaussianFactorGraph::shared_ptr linear = graph_.linearize(state_.values, ordering);

  // Pull out parameters we'll use
  const bool dlVerbose = (params_.verbosityDL > DoglegParams::SILENT);

  // Do Dogleg iteration with either Multifrontal or Sequential elimination
  DoglegOptimizerImpl::IterationResult result;

  if ( params_.isMultifrontal() ) {
    GaussianBayesTree bt;
    bt.insert(GaussianJunctionTree(*linear).eliminate(params_.getEliminationFunction()));
    result = DoglegOptimizerImpl::Iterate(state_.Delta, DoglegOptimizerImpl::ONE_STEP_PER_ITERATION, bt, graph_, state_.values, ordering, state_.error, dlVerbose);
  }
  else if ( params_.isSequential() ) {
    GaussianBayesNet::shared_ptr bn = EliminationTree<GaussianFactor>::Create(*linear)->eliminate(params_.getEliminationFunction());
    result = DoglegOptimizerImpl::Iterate(state_.Delta, DoglegOptimizerImpl::ONE_STEP_PER_ITERATION, *bn, graph_, state_.values, ordering, state_.error, dlVerbose);
  }
  else if ( params_.isCG() ) {
    throw runtime_error("todo: ");
  }
  else {
    throw runtime_error("Optimization parameter is invalid: DoglegParams::elimination");
  }

  // Maybe show output
  if(params_.verbosity >= NonlinearOptimizerParams::DELTA) result.dx_d.print("delta");

  // Create new state with new values and new error
  state_.values = state_.values.retract(result.dx_d, ordering);
  state_.error = result.f_error;
  state_.Delta = result.Delta;
  ++state_.iterations;
}

} /* namespace gtsam */

ext: cpp


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Htcoin Developers
// Copyright (c) 2013 Htcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "irc.h"
#include "util.h"
#include "timedata.h"

#include "net.h"
#include <string>
#include <stdarg.h>

#include <boost/thread.hpp>

using namespace std;
using namespace boost;

int nGotIRCAddresses = 0;
bool fShutdown = false;

void ThreadIRCSeed2(void* parg);

std::string real_strprintf(const std::string &format, int dummy, ...);
#define strprintf2(format, ...) real_strprintf(format, 0, __VA_ARGS__)

#define loop                for (;;)

#ifndef HAVE_STRLCAT
/*
 * '_cups_strlcat()' - Safely concatenate two strings.
 */

size_t                  /* O - Length of string */
strlcat(char       *dst,        /* O - Destination string */
              const char *src,      /* I - Source string */
          size_t     size)      /* I - Size of destination string buffer */
{
  size_t    srclen;         /* Length of source string */
  size_t    dstlen;         /* Length of destination string */

 /*
  * Figure out how much room is left...
  */

  dstlen = strlen(dst);
  size   -= dstlen + 1;

  if (!size)
    return (dstlen);        /* No room, return immediately... */

 /*
  * Figure out how much room is needed...
  */

  srclen = strlen(src);

 /*
  * Copy the appropriate amount...
  */

  if (srclen > size)
    srclen = size;

  memcpy(dst + dstlen, src, srclen);
  dst[dstlen + srclen] = '\0';

  return (dstlen + srclen);
}
#endif /* !HAVE_STRLCAT */

#ifndef HAVE_STRLCPY
/*
 * '_cups_strlcpy()' - Safely copy two strings.
 */

size_t                  /* O - Length of string */
strlcpy(char       *dst,        /* O - Destination string */
              const char *src,      /* I - Source string */
          size_t      size)     /* I - Size of destination string buffer */
{
  size_t    srclen;         /* Length of source string */

 /*
  * Figure out how much room is needed...
  */

  size --;

  srclen = strlen(src);

 /*
  * Copy the appropriate amount...
  */

  if (srclen > size)
    srclen = size;

  memcpy(dst, src, srclen);
  dst[srclen] = '\0';

  return (srclen);
}
#endif /* !HAVE_STRLCPY */

#pragma pack(push, 1)
struct ircaddr
{
    struct in_addr ip;
    short port;
};
#pragma pack(pop)

void ParseString(const string& str, char c, vector<string>& v)
{
    if (str.empty())
        return;
    string::size_type i1 = 0;
    string::size_type i2;
    loop
    {
        i2 = str.find(c, i1);
        if (i2 == str.npos)
        {
            v.push_back(str.substr(i1));
            return;
        }
        v.push_back(str.substr(i1, i2-i1));
        i1 = i2+1;
    }
}

inline void Sleep2(int64_t n)
{
    /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
	 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
    boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
}

/*
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
    // Only the first 15 characters are used (16 - NUL terminator)
    ::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
    // TODO: This is currently disabled because it needs to be verified to work
    //       on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
    //       removed.
    pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX)
    pthread_setname_np(name);
#else
    // Prevent warnings for unused parameters...
    (void)name;
#endif
}
*/

/*
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
    char pszModule[MAX_PATH] = "";
    GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
    const char* pszModule = "Htcoin";
#endif
    if (pex)
        return strprintf2(
						 "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
    else
        return strprintf2(
						 "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
}

 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
    std::string message = FormatException(pex, pszThread);
    printf("\n\n************************\n%s\n", message.c_str());
    fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
    //strMiscWarning = message;
}

static int64_t nMockTime = 0;  // For unit testing

int64_t GetTime()
{
    if (nMockTime) return nMockTime;

    return time(NULL);
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime = nMockTimeIn;
}

static int64_t nTimeOffset = 0;

int64_t GetAdjustedTime()
{
    return GetTime() + nTimeOffset;
}
*/

string vstrprintf(const char *format, va_list ap)
{
    char buffer[50000];
    char* p = buffer;
    int limit = sizeof(buffer);
    int ret;
    loop
    {
        va_list arg_ptr;
        va_copy(arg_ptr, ap);
#ifdef WIN32
        ret = _vsnprintf(p, limit, format, arg_ptr);
#else
        ret = vsnprintf(p, limit, format, arg_ptr);
#endif
        va_end(arg_ptr);
        if (ret >= 0 && ret < limit)
            break;
        if (p != buffer)
            delete[] p;
        limit *= 2;
        p = new char[limit];
        if (p == NULL)
            throw std::bad_alloc();
    }
    string str(p, p+ret);
    if (p != buffer)
        delete[] p;
    return str;
}

string real_strprintf(const char *format, int dummy, ...)
{
    va_list arg_ptr;
    va_start(arg_ptr, dummy);
    string str = vstrprintf(format, arg_ptr);
    va_end(arg_ptr);
    return str;
}

string real_strprintf(const std::string &format, int dummy, ...)
{
    va_list arg_ptr;
    va_start(arg_ptr, dummy);
    string str = vstrprintf(format.c_str(), arg_ptr);
    va_end(arg_ptr);
    return str;
}

///

string EncodeAddress(const CService& addr)
{
    struct ircaddr tmp;
    if (addr.GetInAddr(&tmp.ip))
    {
        tmp.port = htons(addr.GetPort());

        vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
        return string("u") + EncodeBase58Check(vch);
    }
    return "";
}

bool DecodeAddress(string str, CService& addr)
{
    vector<unsigned char> vch;
    if (!DecodeBase58Check(str.substr(1), vch))
        return false;

    struct ircaddr tmp;
    if (vch.size() != sizeof(tmp))
        return false;
    memcpy(&tmp, &vch[0], sizeof(tmp));

    addr = CService(tmp.ip, ntohs(tmp.port));
    return true;
}

static bool Send(SOCKET hSocket, const char* pszSend)
{
    if (strstr(pszSend, "PONG") != pszSend)
        printf("IRC SENDING: %s\n", pszSend);
    const char* psz = pszSend;
    const char* pszEnd = psz + strlen(psz);
    while (psz < pszEnd)
    {
        int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
        if (ret < 0)
            return false;
        psz += ret;
    }
    return true;
}

bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
    loop
    {
        bool fRet = RecvLine(hSocket, strLine);
        if (fRet)
        {
            if (fShutdown)
                return false;
            boost::this_thread::interruption_point();

            vector<string> vWords;
            ParseString(strLine, ' ', vWords);
            if (vWords.size() >= 1 && vWords[0] == "PING")
            {
                strLine[1] = 'O';
                strLine += '\r';
                Send(hSocket, strLine.c_str());
                continue;
            }
        }
        return fRet;
    }
}

int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
    loop
    {
        string strLine;
        strLine.reserve(10000);
        if (!RecvLineIRC(hSocket, strLine))
            return 0;
        printf("IRC %s\n", strLine.c_str());
        if (psz1 && strLine.find(psz1) != string::npos)
            return 1;
        if (psz2 && strLine.find(psz2) != string::npos)
            return 2;
        if (psz3 && strLine.find(psz3) != string::npos)
            return 3;
        if (psz4 && strLine.find(psz4) != string::npos)
            return 4;
    }
}

bool Wait(int nSeconds)
{
    if (fShutdown)
        return false;
    boost::this_thread::interruption_point();
    printf("IRC waiting %d seconds to reconnect\n", nSeconds);
    for (int i = 0; i < nSeconds; i++)
    {
       if (fShutdown)
            return false;
        boost::this_thread::interruption_point();
        Sleep2(1000);
    }
    return true;
}

bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
    strRet.clear();
    loop
    {
        string strLine;
        if (!RecvLineIRC(hSocket, strLine))
            return false;

        vector<string> vWords;
        ParseString(strLine, ' ', vWords);
        if (vWords.size() < 2)
            continue;

        if (vWords[1] == psz1)
        {
            printf("IRC %s\n", strLine.c_str());
            strRet = strLine;
            return true;
        }
    }
}

bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
    Send(hSocket, strprintf2("USERHOST %s\r", strMyName.c_str()).c_str());

    string strLine;
    if (!RecvCodeLine(hSocket, "302", strLine))
        return false;

    vector<string> vWords;
    ParseString(strLine, ' ', vWords);
    if (vWords.size() < 4)
        return false;

    string str = vWords[3];
    if (str.rfind("@") == string::npos)
        return false;
    string strHost = str.substr(str.rfind("@")+1);

    // Hybrid IRC used by lfnet always returns IP when you userhost yourself,
    // but in case another IRC is ever used this should work.
    printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
    CNetAddr addr(strHost, true);
    if (!addr.IsValid())
        return false;
    ipRet = addr;

    return true;
}

void ThreadIRCSeed3()
{

    try
    {
        ThreadIRCSeed2(NULL);
    }
    catch (std::exception& e) {
        fShutdown=true;
        //PrintExceptionContinue(&e, "ThreadIRCSeed3()");
    } catch (...) {
        fShutdown=true;
        //PrintExceptionContinue(NULL, "ThreadIRCSeed3()");
    }
    printf("ThreadIRCSeed exited\n");
}

void ThreadIRCSeed(void* parg)
{
    //IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));

    // Make this thread recognisable as the IRC seeding thread
    RenameThread("bitcoin-ircseed");

    try
    {
        ThreadIRCSeed2(parg);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "ThreadIRCSeed()");
    } catch (...) {
        PrintExceptionContinue(NULL, "ThreadIRCSeed()");
    }
    printf("ThreadIRCSeed exited\n");
}

void ThreadIRCSeed2(void* parg)
{
  /*
	// Dont advertise on IRC if we don't allow incoming connections *
    if (mapArgs.count("-connect") || fNoListen)
        return;

    if (GetBoolArg("-irc", false))
        return;
*/
    printf("ThreadIRCSeed started\n");
    int nErrorWait = 10;
    int nRetryWait = 10;

    loop
    {
        CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org

        CService addrIRC("irc.lfnet.org", 6667, true);
        if (addrIRC.IsValid())
            addrConnect = addrIRC;

        SOCKET hSocket;
        if (!ConnectSocket(addrConnect, hSocket, 2000))
        {
            printf("IRC connect failed\n");
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }

        if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
        {
            CloseSocket(hSocket);
            hSocket = INVALID_SOCKET;
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }

        CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
        CService addrLocal;
        string strMyName;
        if (GetLocal(addrLocal, &addrIPv4))
            strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
        if (strMyName == "")
            strMyName = strprintf2("x%u", GetRand(1000000000));

        Send(hSocket, strprintf2("NICK %s\r", strMyName.c_str()).c_str());
        Send(hSocket, strprintf2("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());

        int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
        if (nRet != 1)
        {
            CloseSocket(hSocket);
            hSocket = INVALID_SOCKET;
            if (nRet == 2)
            {
                printf("IRC name already in use\n");
                Wait(10);
                continue;
            }
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }
        Sleep2(500);

        // Get our external IP from the IRC server and re-nick before joining the channel
        CNetAddr addrFromIRC;
        if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
        {
            printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
            if (addrFromIRC.IsRoutable())
            {
                // IRC lets you to re-nick
                AddLocal(addrFromIRC, LOCAL_UPNP);
                strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
                Send(hSocket, strprintf2("NICK %s\r", strMyName.c_str()).c_str());
            }
        }

		/*
        if (fTestNet) {
            Send(hSocket, "JOIN #HtcoinTEST3\r");
            Send(hSocket, "WHO #HtcoinTEST3\r");
        } else { */
            // randomly join #Htcoin00-#Htcoin99
            int channel_number = GetRandInt(100);
            channel_number = 0; // Htcoin: for now, just use one channel
            Send(hSocket, strprintf2("JOIN #Htcoin%02d\r", channel_number).c_str());
            Send(hSocket, strprintf2("WHO #Htcoin%02d\r", channel_number).c_str());
       // }

        int64_t nStart = GetTime();
        string strLine;
        strLine.reserve(10000);
        while (RecvLineIRC(hSocket, strLine))
        {
            boost::this_thread::interruption_point();
            if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
                continue;

            vector<string> vWords;
            ParseString(strLine, ' ', vWords);
            if (vWords.size() < 2)
                continue;

            char pszName[10000];
            pszName[0] = '\0';

            if (vWords[1] == "352" && vWords.size() >= 8)
            {
                // index 7 is limited to 16 characters
                // could get full length name at index 10, but would be different from join messages
                strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
                printf("IRC got who\n");
            }

            if (vWords[1] == "JOIN" && vWords[0].size() > 1)
            {
                // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
                strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
                if (strchr(pszName, '!'))
                    *strchr(pszName, '!') = '\0';
                printf("IRC got join\n");
            }

            if (pszName[0] == 'u')
            {
                CAddress addr;
                if (DecodeAddress(pszName, addr))
                {
                    addr.nTime = GetAdjustedTime();
                    //if (addrman.Add(addr, addrConnect, 51 * 60))
                    //    printf("IRC got new address: %s\n", addr.ToString().c_str());
                    nGotIRCAddresses++;
                }
                else
                {
                    printf("IRC decode failed\n");
                }
            }
        }
        CloseSocket(hSocket);
        hSocket = INVALID_SOCKET;

        if (GetTime() - nStart > 20 * 60)
        {
            nErrorWait /= 3;
            nRetryWait /= 3;
        }

        nRetryWait = nRetryWait * 11 / 10;
        if (!Wait(nRetryWait += 60))
            return;
    }
}

#ifdef TEST
int main(int argc, char *argv[])
{
    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
    {
        printf("Error at WSAStartup()\n");
        return false;
    }

    ThreadIRCSeed(NULL);

    WSACleanup();
    return 0;
}
#endif

max_stars_repo_name: HTCCORE/HTCCORE

max_issues_repo_name: HTCCORE/HTCCORE

max_forks_repo_name: HTCCORE/HTCCORE


text:
// This file is part of the URDF PLUGIN for V-REP
//
// Copyright 2006-2015 Coppelia Robotics GmbH. All rights reserved.
// marc@coppeliarobotics.com
// www.coppeliarobotics.com
//
// A big thanks to Ignacio Tartavull and Martin Pecka for their precious help!
//
// The URDF PLUGIN is licensed under the terms of GNU GPL:
//
// -------------------------------------------------------------------
// The URDF PLUGIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// THE URDF PLUGIN IS DISTRIBUTED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTY. THE USER WILL USE IT AT HIS/HER OWN RISK. THE ORIGINAL
// AUTHORS AND COPPELIA ROBOTICS GMBH WILL NOT BE LIABLE FOR DATA LOSS,
// DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR
// MISUSING THIS SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the URDF PLUGIN.  If not, see <http://www.gnu.org/licenses/>.
// -------------------------------------------------------------------

//
// This file was automatically created for V-REP release V3.2.3 rev4 on December 21st 2015

// The URDF plugin is courtesy of Ignacio Tartavull and Martin Pecka.

#include "v_repExtUrdf.h"
#include "v_repLib.h"
#include <iostream>
#include <vector>
#include <bitset>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include <math.h>
#include "urdfdialog.h"
#include "robot.h"

#ifdef _WIN32
	#include <direct.h>
#endif /* _WIN32 */

#if defined (__linux) || defined (__APPLE__)
	#include <string.h>
	#define _stricmp(x,y) strcasecmp(x,y)
#endif

#define PLUGIN_VERSION 8	// 1 until 20/1/2013 (1 was a very early beta)
							// 2 until 10/1/2014 (V-REP3.0.5)
							// 3: new lock
							// 4: since V-REP 3.1.2
							// 5: since after V-REP 3.1.3
							// 6: since V-REP 3.2.2
							// 7: since V-REP 3.2.2 rev2
							// 8: since V-REP 3.3.0 (headless mode detect)

LIBRARY vrepLib;
CUrdfDialog* urdfDialog=NULL;

// This is the plugin start routine (called just once, just after the plugin was loaded):
VREP_DLLEXPORT unsigned char v_repStart(void* reservedPointer,int reservedInt)
{
	// Dynamically load and bind V-REP functions:
	 // ******************************************
	 // 1. Figure out this plugin's directory:
	 char curDirAndFile[1024];
 #ifdef _WIN32
	 _getcwd(curDirAndFile, sizeof(curDirAndFile));
 #elif defined (__linux) || defined (__APPLE__)
	 getcwd(curDirAndFile, sizeof(curDirAndFile));
 #endif
	 std::string currentDirAndPath(curDirAndFile);
	 // 2. Append the V-REP library's name:
	 std::string temp(currentDirAndPath);
 #ifdef _WIN32
	 temp+="/v_rep.dll";
 #elif defined (__linux)
	 temp+="/libv_rep.so";
 #elif defined (__APPLE__)
	 temp+="/libv_rep.dylib";
 #endif /* __linux || __APPLE__ */
	// 3. Load the V-REP library:
	vrepLib=loadVrepLibrary(temp.c_str());
	if (vrepLib==NULL)
	{
		std::cout << "Error, could not find or correctly load the V-REP library. Cannot start 'Urdf' plugin.\n";
		return(0); // Means error, V-REP will unload this plugin
	}
	if (getVrepProcAddresses(vrepLib)==0)
	{
		std::cout << "Error, could not find all required functions in the V-REP library. Cannot start 'Urdf' plugin.\n";
		unloadVrepLibrary(vrepLib);
		return(0); // Means error, V-REP will unload this plugin
	}
	// ******************************************

	// Check the version of V-REP:
	// ******************************************
	int vrepVer;
	simGetIntegerParameter(sim_intparam_program_version,&vrepVer);
	if (vrepVer<30001) // if V-REP version is smaller than 3.00.01
	{
		std::cout << "Sorry, your V-REP copy is somewhat old. Cannot start 'Urdf' plugin.\n";
		unloadVrepLibrary(vrepLib);
		return(0); // Means error, V-REP will unload this plugin
	}
	// ******************************************

	// Check if V-REP runs in headless mode:
	// ******************************************
	if (simGetBooleanParameter(sim_boolparam_headless)>0)
	{
		std::cout << "V-REP runs in headless mode. Cannot start 'Urdf' plugin.\n";
		unloadVrepLibrary(vrepLib);
		return(0); // Means error, V-REP will unload this plugin
	}
	// ******************************************

	QWidget* pMainWindow = (QWidget*)simGetMainWindow(1);
	urdfDialog=new CUrdfDialog(pMainWindow); // The plugin dialog
	simAddModuleMenuEntry("",1,&urdfDialog->dialogMenuItemHandle);
	simSetModuleMenuItemState(urdfDialog->dialogMenuItemHandle,1,"URDF import...");

    int inputArgsTypes[] = {
        10,
        sim_lua_arg_string, // URDF contents
        sim_lua_arg_bool, // assign collision links to layer 9
        sim_lua_arg_bool, // assign joints to layer 10
        sim_lua_arg_bool, // convex decompose
        sim_lua_arg_bool, // create visual links if none
        sim_lua_arg_bool, // show convex decomposition dialog
        sim_lua_arg_bool, // center model above ground
        sim_lua_arg_bool, // prepare model definition if feasible
        sim_lua_arg_bool, // alternate local respondable masks
        sim_lua_arg_bool  // enable position control for revolute and prismatic joints
    };

    simRegisterCustomLuaFunction("simExtImportUrdf",
        "string robot_name=simExtImportUrdf("
         "string urdf,"
         "bool hideCollisionLinks,"
         "bool hideJoints,"
         "bool convexDecomposeNonConvexCollidables,"
         "bool createVisualIfNone,"
         "bool showConvexDecompositionDlg,"
         "bool centerAboveGround,"
         "bool makeModel,"
         "bool noSelfCollision,"
         "bool positionCtrl"
        ")",
        inputArgsTypes, v_repImportUrdfCallback);

    int inputArgsTypesFile[] = {
        10,
        sim_lua_arg_string, // filenameAndPath
        sim_lua_arg_bool, // assign collision links to layer 9
        sim_lua_arg_bool, // assign joints to layer 10
        sim_lua_arg_bool, // convex decompose
        sim_lua_arg_bool, // create visual links if none
        sim_lua_arg_bool, // show convex decomposition dialog
        sim_lua_arg_bool, // center model above ground
        sim_lua_arg_bool, // prepare model definition if feasible
        sim_lua_arg_bool, // alternate local respondable masks
        sim_lua_arg_bool  // enable position control for revolute and prismatic joints
    };

    simRegisterCustomLuaFunction("simExtImportUrdfFile",
         "string robot_name=simExtImportUrdf("
          "string fileAndPath,"
          "bool hideCollisionLinks,"
          "bool hideJoints,"
          "bool convexDecomposeNonConvexCollidables,"
          "bool createVisualIfNone,"
          "bool showConvexDecompositionDlg,"
          "bool centerAboveGround,"
          "bool makeModel,"
          "bool noSelfCollision,"
          "bool positionCtrl"
         ")",
         inputArgsTypesFile, v_repImportUrdfCallback);

	return(PLUGIN_VERSION); // initialization went fine, we return the version number of this plugin (can be queried with simGetModuleName)
}

// This is the plugin end routine (called just once, when V-REP is ending, i.e. releasing this plugin):
VREP_DLLEXPORT void v_repEnd()
{
	// Here you could handle various clean-up tasks
	delete urdfDialog;
	unloadVrepLibrary(vrepLib); // release the library
}

// This is the plugin messaging routine (i.e. V-REP calls this function very often, with various messages):
VREP_DLLEXPORT void* v_repMessage(int message,int* auxiliaryData,void* customData,int* replyData)
{ // This is called quite often. Just watch out for messages/events you want to handle
	// Keep following 6 lines at the beginning and unchanged:
	static bool refreshDlgFlag=true;
	int errorModeSaved;
	simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
	simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);
	void* retVal=NULL;

	// Here we can intercept many messages from V-REP (actually callbacks).
	// For a complete list of messages that you can intercept/react with, search for "sim_message_eventcallback"-type constants
	// in the V-REP user manual.

	if (message==sim_message_eventcallback_refreshdialogs)
		refreshDlgFlag=true; // V-REP dialogs were refreshed. Maybe a good idea to refresh this plugin's dialog too

	if (message==sim_message_eventcallback_menuitemselected)
	{ // A custom menu bar entry was selected..
		if (auxiliaryData[0]==urdfDialog->dialogMenuItemHandle)
			urdfDialog->makeVisible(!urdfDialog->getVisible()); // Toggle visibility of the dialog
	}

	if (message==sim_message_eventcallback_instancepass)
	{ // It is important to always correctly react to events in V-REP. This message is the most convenient way to do so:
		urdfDialog->handleCommands();
		urdfDialog->setSimulationStopped(simGetSimulationState()==sim_simulation_stopped);

		int flags=auxiliaryData[0];
		bool sceneContentChanged=((flags&(1+2+4+8+16+32+64+256))!=0); // object erased, created, model or scene loaded, und/redo called, instance switched, or object scaled since last sim_message_eventcallback_instancepass message
		bool instanceSwitched=((flags&64)!=0);

		if (instanceSwitched)
		{
			// React to an instance switch here!!
		}

		if (sceneContentChanged)
		{
			refreshDlgFlag=true;
		}
	}
	if ((message==sim_message_eventcallback_guipass)&&refreshDlgFlag)
	{ // handle refresh of the plugin's dialog:
		urdfDialog->refresh(); // Refresh the dialog
		refreshDlgFlag=false;
	}

	// Keep following unchanged:
	simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings
	return(retVal);
}

VREP_DLLEXPORT simChar* v_repImportUrdf(simChar* filenameOrUrdf, simBool hideCollisionLinks, simBool hideJoints, simBool convexDecomposeNonConvexCollidables, simBool createVisualIfNone, simBool showConvexDecompositionDlg, simBool centerAboveGround, simBool makeModel, simBool noSelfCollision, simBool positionCtrl) {

    robot Robot(filenameOrUrdf, hideCollisionLinks, hideJoints, convexDecomposeNonConvexCollidables, createVisualIfNone, showConvexDecompositionDlg, centerAboveGround, makeModel, noSelfCollision, positionCtrl);

    simChar* result = (simChar*)simCreateBuffer(Robot.name.length()+1);
    memcpy((void*) result, (void*) Robot.name.c_str(), Robot.name.length()+1);

    return result;
}

void v_repImportUrdfCallback(SLuaCallBack* p)
{
    if (p->inputArgCount == 10) {
        simChar* name = v_repImportUrdf(p->inputChar,p->inputBool[0],p->inputBool[1],p->inputBool[2],p->inputBool[3],
                    p->inputBool[4],p->inputBool[5],p->inputBool[6],p->inputBool[7],p->inputBool[8]);

        p->outputArgCount = 1;

        p->outputArgTypeAndSize = (simInt*)simCreateBuffer(p->outputArgCount*2*sizeof(simInt));
        p->outputArgTypeAndSize[0] = sim_lua_arg_string;
        p->outputArgTypeAndSize[1] = 1;

        p->outputChar = (simChar*)simCreateBuffer(strlen(name)+1);
        memcpy((void*)p->outputChar, (void*)name, strlen(name)+1);

    } else {
        simSetLastError("simExtImportUrdfCallback","Wrong number of arguments.");
        p->outputArgCount = 0;
    }
}


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "consensus/babe/impl/babe_lottery_impl.hpp"

#include <unordered_set>

#include <boost/assert.hpp>
#include "common/buffer.hpp"
#include "common/mp_utils.hpp"
#include "consensus/validation/prepare_transcript.hpp"

namespace kagome::consensus {
  using common::Buffer;
  namespace vrf_constants = crypto::constants::sr25519::vrf;

  BabeLotteryImpl::BabeLotteryImpl(
      std::shared_ptr<crypto::VRFProvider> vrf_provider,
      std::shared_ptr<primitives::BabeConfiguration> configuration,
      std::shared_ptr<crypto::Hasher> hasher)
      : vrf_provider_{std::move(vrf_provider)},
        hasher_{std::move(hasher)},
        logger_{common::createLogger("BabeLottery")} {
    BOOST_ASSERT(vrf_provider_);
    BOOST_ASSERT(hasher_);
    BOOST_ASSERT(logger_);
    BOOST_ASSERT(configuration);
    epoch_length_ = configuration->epoch_length;
  }

  BabeLottery::SlotsLeadership BabeLotteryImpl::slotsLeadership(
      const EpochDescriptor &epoch,
      const Randomness &randomness,
      const Threshold &threshold,
      const crypto::Sr25519Keypair &keypair) const {
    BabeLottery::SlotsLeadership result;
    result.reserve(epoch_length_);

    for (BabeSlotNumber i = epoch.start_slot;
         i < epoch.start_slot + epoch_length_;
         ++i) {
      primitives::Transcript transcript;
      prepareTranscript(transcript, randomness, i, epoch.epoch_number);
      logger_->trace(
          "prepareTranscript (leadership): randomness {}, slot {}, epoch {}",
          randomness,
          i,
          epoch.epoch_number);

      auto sign_opt =
          vrf_provider_->signTranscript(transcript, keypair, threshold);

      result.push_back(sign_opt);
    }

    return result;
  }

  Randomness BabeLotteryImpl::computeRandomness(
      const Randomness &last_epoch_randomness, EpochNumber last_epoch_number) {
    static std::unordered_set<EpochNumber> computed_epochs_randomnesses{};

    // the function must never be called twice for the same epoch
    BOOST_ASSERT(computed_epochs_randomnesses.insert(last_epoch_number).second);

    // randomness || epoch_number || rho
    Buffer new_randomness(
        vrf_constants::OUTPUT_SIZE + 8 + last_epoch_vrf_values_.size() * 32, 0);

    std::copy(last_epoch_randomness.begin(),
              last_epoch_randomness.end(),
              new_randomness.begin());

    auto epoch_number_bytes = common::uint64_t_to_bytes(last_epoch_number);
    std::copy(epoch_number_bytes.begin(),
              epoch_number_bytes.end(),
              new_randomness.begin() + vrf_constants::OUTPUT_SIZE);

    auto new_vrf_value_begin =
        new_randomness.begin() + vrf_constants::OUTPUT_SIZE + 8;
    // NOLINTNEXTLINE
    for (size_t i = 0; i < last_epoch_vrf_values_.size(); ++i) {
      auto const &value_bytes = last_epoch_vrf_values_[i];
      std::copy(value_bytes.begin(), value_bytes.end(), new_vrf_value_begin);
      new_vrf_value_begin += 32;
    }
    last_epoch_vrf_values_.clear();

    return hasher_->blake2b_256(new_randomness);
  }

  void BabeLotteryImpl::submitVRFValue(const crypto::VRFPreOutput &value) {
    last_epoch_vrf_values_.push_back(value);
  }
}  // namespace kagome::consensus

max_stars_repo_name: Harrm/kagome

max_issues_repo_name: Harrm/kagome

max_forks_repo_name: Harrm/kagome