text:
///////////////////////////////////////////////////////////////////////////////
/// \file offset_runs.hpp
/// An index property map with an integer offset
//
//  Copyright 2006 Eric Niebler. 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_TIME_SERIES_DETAIL_OFFSET_RUNS_HPP_EAN_04_26_2006
#define BOOST_TIME_SERIES_DETAIL_OFFSET_RUNS_HPP_EAN_04_26_2006

#include <boost/time_series/time_series_fwd.hpp>

#include <boost/assert.hpp>
#include <boost/utility/result_of.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/range_run_storage/concepts.hpp>
#include <boost/range_run_storage/traits/is_dense_runs.hpp>

namespace boost { namespace time_series { namespace storage
{
    template<typename Runs>
    struct msvc_result_offset_runs
    {
        // For result_of support
        template<typename K>
        struct result;

        template<typename This, typename K>
        struct result<This(K)>
          : remove_reference<typename result_of<Runs(K)>::type>
        {};
    };

    // wraps a runs property map and
    // an offset.
    template<typename Runs, typename Offset>
    struct offset_runs
      : msvc_result_offset_runs<Runs>
    {
        offset_runs(Runs const &runs, Offset offset)
          : runs_(runs)
          , offset_(offset)
        {}

        // Readability : Key to index
        template<typename K>
        typename msvc_result_offset_runs<Runs>
            ::template result<offset_runs(K)>::type
        operator ()(K const &k) const
        {
            using range_run_storage::concepts::Run;
            typedef typename msvc_result_offset_runs<Runs>
                ::template result<offset_runs(K)>::type run_type;
            typedef typename Run<run_type>::is_unit_length is_unit_length;
            return this->call_(this->runs_(k), is_unit_length());
        }

    private:
        template<typename R>
        R call_(R const &r, mpl::true_) const
        {
            typedef typename range_run_storage::concepts::Run<R>::offset_type offset_type;
            offset_type offset = range_run_storage::offset(r);

            // With the InfiniteRangeRunStorage concept, infinite runs
            // can only be a pre_run or a post_run, never from the runs
            // property map
            BOOST_ASSERT(-inf != offset && inf != offset);
            return R(offset + this->offset_);
        }

        template<typename R>
        R call_(R const &r, mpl::false_) const
        {
            typedef typename range_run_storage::concepts::Run<R>::offset_type offset_type;
            offset_type offset = range_run_storage::offset(r);
            offset_type endoff = range_run_storage::end_offset(r);

            // With the InfiniteRangeRunStorage concept, infinite runs
            // can only be a pre_run or a post_run, never from the runs
            // property map
            BOOST_ASSERT(-inf != offset && inf != offset);
            BOOST_ASSERT(-inf != endoff && inf != endoff);
            return R(offset + this->offset_, endoff + this->offset_);
        }

        Runs runs_;
        Offset offset_;
    };

    template<typename Runs, typename Offset>
    inline offset_runs<Runs, Offset>
    make_offset_runs(Runs const &runs, Offset offset)
    {
        return offset_runs<Runs, Offset>(runs, offset);
    }

}}}

namespace boost { namespace range_run_storage { namespace traits
{
    template<typename Runs, typename Offset>
    struct is_dense_runs<time_series::storage::offset_runs<Runs, Offset> >
      : is_dense_runs<Runs>
    {};
}}}

#endif


text:
//
// request_parser.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//

#include "request_parser.hpp"
#include <boost/regex.hpp>

namespace my {
	namespace http {

		request_parser::request_parser()
			: state_(method_start)
		{
		}

		void request_parser::reset()
		{
			state_ = method_start;
		}

		boost::tribool request_parser::consume(request& req, char input)
		{
			switch (state_)
			{
			case method_start:
				if (!is_char(input) || is_ctl(input) || is_tspecial(input))
				{
					return false;
				}
				else
				{
					state_ = method;
					req.method.push_back(input);
					return boost::indeterminate;
				}
			case method:
				if (input == ' ')
				{
					state_ = uri;
					return boost::indeterminate;
				}
				else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
				{
					return false;
				}
				else
				{
					req.method.push_back(input);
					return boost::indeterminate;
				}
			case uri_start:
				if (is_ctl(input))
				{
					return false;
				}
				else
				{
					state_ = uri;
					req.uri.push_back(input);
					return boost::indeterminate;
				}
			case uri:
				if (input == ' ')
				{
					state_ = http_version_h;
					return boost::indeterminate;
				}
				else if (is_ctl(input))
				{
					return false;
				}
				else
				{
					req.uri.push_back(input);
					return boost::indeterminate;
				}
			case http_version_h:
				if (input == 'H')
				{
					state_ = http_version_t_1;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_t_1:
				if (input == 'T')
				{
					state_ = http_version_t_2;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_t_2:
				if (input == 'T')
				{
					state_ = http_version_p;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_p:
				if (input == 'P')
				{
					state_ = http_version_slash;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_slash:
				if (input == '/')
				{
					req.http_version_major = 0;
					req.http_version_minor = 0;
					state_ = http_version_major_start;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_major_start:
				if (is_digit(input))
				{
					req.http_version_major = req.http_version_major * 10 + input - '0';
					state_ = http_version_major;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_major:
				if (input == '.')
				{
					state_ = http_version_minor_start;
					return boost::indeterminate;
				}
				else if (is_digit(input))
				{
					req.http_version_major = req.http_version_major * 10 + input - '0';
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_minor_start:
				if (is_digit(input))
				{
					req.http_version_minor = req.http_version_minor * 10 + input - '0';
					state_ = http_version_minor;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case http_version_minor:
				if (input == '\r')
				{
					state_ = expecting_newline_1;
					return boost::indeterminate;
				}
				else if (is_digit(input))
				{
					req.http_version_minor = req.http_version_minor * 10 + input - '0';
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case expecting_newline_1:
				if (input == '\n')
				{
					state_ = header_line_start;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case header_line_start:
				if (input == '\r')
				{
					state_ = expecting_newline_3;
					return boost::indeterminate;
				}
				else if (!req.headers.empty() && (input == ' ' || input == '\t'))
				{
					state_ = header_lws;
					return boost::indeterminate;
				}
				else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
				{
					return false;
				}
				else
				{
					req.headers.push_back(header());
					req.headers.back().name.push_back(input);
					state_ = header_name;
					return boost::indeterminate;
				}
			case header_lws:
				if (input == '\r')
				{
					state_ = expecting_newline_2;
					return boost::indeterminate;
				}
				else if (input == ' ' || input == '\t')
				{
					return boost::indeterminate;
				}
				else if (is_ctl(input))
				{
					return false;
				}
				else
				{
					state_ = header_value;
					req.headers.back().value.push_back(input);
					return boost::indeterminate;
				}
			case header_name:
				if (input == ':')
				{
					state_ = space_before_header_value;
					return boost::indeterminate;
				}
				else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
				{
					return false;
				}
				else
				{
					req.headers.back().name.push_back(input);
					return boost::indeterminate;
				}
			case space_before_header_value:
				if (input == ' ')
				{
					state_ = header_value;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case header_value:
				if (input == '\r')
				{
					state_ = expecting_newline_2;
					return boost::indeterminate;
				}
				else if (is_ctl(input))
				{
					return false;
				}
				else
				{
					req.headers.back().value.push_back(input);
					return boost::indeterminate;
				}
			case expecting_newline_2:
				if (input == '\n')
				{
					state_ = header_line_start;
					return boost::indeterminate;
				}
				else
				{
					return false;
				}
			case expecting_newline_3:
				if (req.method == "GET")
				{
					return (input == '\n');
				}
				else
				{
					state_ = http_post_content;
					return boost::indeterminate;
				}
			case http_post_content:
				size_t cont_len;
				req.get_content_length(cont_len);
				if (req.content.length() < cont_len)
				{
					req.content.append(&input);
					if (req.content.length() == cont_len)
						return true;
					return boost::indeterminate;
				}
// 				if (req.content.length() == cont_len)
// 				{
// 					return true;
// 					if (input == '\r')
// 					{
// 						state_ = expecting_content_newline_1;
// 						return boost::indeterminate;
// 					}
// 					else
// 					{
// 						return false;
// 					}
//				}
			case expecting_content_newline_1:
				return (input == '\n');
			default:
				return false;
			}
		}

		bool request_parser::is_char(int c)
		{
			return c >= 0 && c <= 127;
		}

		bool request_parser::is_ctl(int c)
		{
			return (c >= 0 && c <= 31) || (c == 127);
		}

		bool request_parser::is_tspecial(int c)
		{
			switch (c)
			{
			case '(': case ')': case '<': case '>': case '@':
			case ',': case ';': case ':': case '\\': case '"':
			case '/': case '[': case ']': case '?': case '=':
			case '{': case '}': case ' ': case '\t':
				return true;
			default:
				return false;
			}
		}

		bool request_parser::is_digit(int c)
		{
			return c >= '0' && c <= '9';
		}

		inline bool boost_match(const char* pattern,const char* text,unsigned int flags=boost::regex::normal,boost::match_results<const char*>* result=NULL)
		{
			boost::basic_regex<char,boost::regex_traits<char>> expression(pattern,flags);
			if(NULL==result)
				return boost::regex_match(text,expression);
			return boost::regex_match(text,*result,expression);
		}

		inline bool boost_search(const char* pattern,const char* text,unsigned int flags=boost::regex::normal,boost::match_results<const char*>* result=NULL)
		{
			boost::basic_regex<char,boost::regex_traits<char>> expression(pattern,flags);
			if(NULL==result)
				return boost::regex_search(text,expression);
			return boost::regex_search(text,*result,expression);
		}

		void split_string(std::vector<std::string> &str_list, string o_str, string split_str)
		{
			int comma_n = 0;

			do
			{
				std::string tmp_s = "";
				comma_n = o_str.find(split_str);
				if( -1 == comma_n )
				{
					tmp_s = o_str.substr( 0, o_str.length() );
					str_list.push_back( tmp_s );
					break;
				}
				tmp_s = o_str.substr( 0, comma_n );
				o_str.erase( 0, comma_n+1 );
				str_list.push_back( tmp_s );
			}
			while(true);
		}

		void get_kv(map<string, string>& kv, string kv_str, string kv_sep)
		{
			int pos = kv_str.find(kv_sep);
			if (pos != string::npos)
			{
				kv[kv_str.substr(0, pos)] = kv_str.substr(pos+1, string::npos);
			}
		}

		int request_parser::parse_content( int type, std::string content, Json::Value& jreq )
		{
			string str_to_parse;
			if (type == GET_METHOD)
			{
				size_t qm_idx = content.find("?");
				if (qm_idx == std::string::npos)
					return -1;
				str_to_parse = content.substr(qm_idx+1);
			}
			else if (type == POST_METHOD)
			{
				str_to_parse = content;
			}

  			map <string, string> kv;
// 			string expr1 = "((\\w+)=(.+(?!&)))";
// 			string expr2 = "(\\w+)=(.+(?!&))";
// 			boost::regex expression(expr1,
// 				boost::regbase::normal | boost::regbase::icase);
// 			boost::sregex_token_iterator begin(str_to_parse.begin(), str_to_parse.end(), expression, 1);
// 			boost::sregex_token_iterator end;
// 			boost::cmatch what;
// 			while(begin != end)
// 			{
// 				string sValue = *begin++;
// 				boost_search(expr2.c_str(), sValue.c_str(), boost::regex::icase|boost::regex::perl, &what);
// 				kv[what[1].str()] = what[2].str();
// 				std::cout << "w1:" << what[1].str()<<endl;
// 				std::cout << "w2:" << what[2].str()<<endl;
// 			}
			vector<std::string> str_list;
			split_string(str_list, str_to_parse, "&");
			for (size_t list_idx = 0; list_idx < str_list.size(); list_idx++)
			{
				get_kv(kv, str_list[list_idx], "=");
			}

			map<string, string>::iterator it = kv.begin();
			while (it != kv.end())
			{
				jreq[it->first] = it->second;
				it++;
			}

// 			if (jreq["req_type"] == Json::Value::null)
// 			{
// 				return false;
// 			}
// 			else
// 			{
// 				req_type = boost::lexical_cast<int, string>(jreq["req_type"].asString());
// 			}
// 			if (jreq["player_id"] == Json::Value::null)
// 			{
// 				player_id = 0;
// 			}
// 			else
// 			{
// 				player_id = jreq["player_id"].asInt();
// 			}
// 			string s = "";
// 			if (jreq["content"] != Json::Value::null)
// 			{
// 				s = jreq["content"].asString();
// 			}
//
// 			scontent = s;
			return 0;
		}

	} // namespace http
} // namespace my

ext: cpp

max_stars_repo_name: elenno/MyServer

max_issues_repo_name: elenno/MyServer

max_forks_repo_name: elenno/MyServer


text:
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "../common/blake2.hpp"
#include "../common/checked_cast.hpp"
#include "blockchain.hpp"

using namespace epilog::common;

namespace epilog { namespace global {

blockchain::blockchain(const std::string &data_dir) :
    data_dir_(data_dir),
    db_meta_dir_((boost::filesystem::path(data_dir_) / "db" / "meta").string()),
    db_blocks_dir_((boost::filesystem::path(data_dir_) / "db" / "blocks").string()),
    db_heap_dir_((boost::filesystem::path(data_dir_) / "db" / "heap").string()),
    db_closure_dir_((boost::filesystem::path(data_dir_) / "db" / "closure").string()),
    db_symbols_dir_((boost::filesystem::path(data_dir_) / "db" / "symbols").string()),
    db_program_dir_((boost::filesystem::path(data_dir_) / "db" / "program").string()) {
   init();
}

void blockchain::update_meta_id()
{
    blake2b_state s;
    blake2b_init(&s, BLAKE2B_OUTBYTES);

    // Add previous id
    blake2b_update(&s, tip_.get_previous_id().hash(), meta_id::HASH_SIZE);

    auto &t = tip_;

    // Add the hash of the block that got us here
    // (If we add this, then we have the ability to falsify the whole
    //  meta-entry and mark it as invalid - otherwise we may attempt
    //  to infinitely look in vain for the proper version of its meta entry.)
    if (tip_.get_height() != 0) {
	auto *block = blocks_db().find(t.get_root_id_blocks(), tip_.get_height());
	assert(block != nullptr);
	blake2b_update(&s, block->hash(), block->hash_size());
    }

    // Hash all root hashes from state databases
    auto &h1 = heap_db().get_root_hash(t.get_root_id_heap());
    blake2b_update(&s, h1.hash(), h1.hash_size());
    auto &h2 = closure_db().get_root_hash(t.get_root_id_closure());
    blake2b_update(&s, h2.hash(), h2.hash_size());
    auto &h3 = symbols_db().get_root_hash(t.get_root_id_symbols());
    blake2b_update(&s, h3.hash(), h3.hash_size());
    auto &h4 = program_db().get_root_hash(t.get_root_id_program());
    blake2b_update(&s, h4.hash(), h4.hash_size());

    // Reuse this data buffer for everything.
    uint8_t data[1024];

    // Add number of entries in heap, closures, symbols and program.
    common::write_uint64(data, heap_db().num_entries(t.get_root_id_heap()));
    blake2b_update(&s, data, sizeof(uint64_t));
    common::write_uint64(data, closure_db().num_entries(t.get_root_id_closure()));
    blake2b_update(&s, data, sizeof(uint64_t));
    common::write_uint64(data, symbols_db().num_entries(t.get_root_id_symbols()));
    blake2b_update(&s, data, sizeof(uint64_t));
    common::write_uint64(data, program_db().num_entries(t.get_root_id_program()));
    blake2b_update(&s, data, sizeof(uint64_t));

    // Add version
    common::write_uint64(data, tip_.get_version());
    blake2b_update(&s, data, sizeof(uint64_t));

    // Add height
    common::write_uint32(data, tip_.get_height());
    blake2b_update(&s, data, sizeof(uint32_t));

    // Add timestamp
    auto &ts = tip_.get_timestamp();
    ts.write(data);
    blake2b_update(&s, data, ts.serialization_size());

    // Add pow difficulty
    tip_.get_pow_difficulty().write(data);
    blake2b_update(&s, data, tip_.get_pow_difficulty().serialization_size());

    memset(data, 0, sizeof(data));
    blake2b_final(&s, data, BLAKE2B_OUTBYTES);

    // The above hash can then be used as seed (and key) for
    // verifying the pow proof. Thus the pow proof itself is not part
    // of the hash.

    tip_.set_id(meta_id(data));
}

void blockchain::init()
{
    db_meta_ = nullptr;
    db_blocks_ = nullptr;
    db_heap_ = nullptr;
    db_closure_ = nullptr;
    db_symbols_ = nullptr;
    db_program_ = nullptr;

    tip_ = meta_entry();
    at_height_.clear();
    chains_.clear();

    // We let the tip be a simple txt file to make it easy to edit and check

    db_root_id tip_id;

    // Read in meta records
    meta_entry best;
    for (size_t height = 0;;height++) {
	auto &ids = meta_db().find_roots(height);
	if (ids.empty()) {
	    break;
	}
	for (auto &id : ids) {
	    auto stored = meta_db().find(id, height);
	    if (stored == nullptr) {
		continue;
	    }
	    auto custom_data = stored->custom_data();
	    auto custom_data_size = stored->custom_data_size();
	    meta_entry entry;
	    assert(custom_data_size == entry.serialization_size());
	    entry.read(custom_data);
	    entry.set_height(height);
	    entry.set_root_id_meta(id);
	    if (!entry.get_id().is_zero()) {
		chains_.insert(std::make_pair(entry.get_id(), entry));
		at_height_[entry.get_height()].insert(entry.get_id());
		if (!entry.is_partial()) {
		    // Check if DB is really available (integrity check)
		    if (dbs_available(entry)) {
			best = entry;
		    }
		}
	    }
	}
    }

    tip_ = best;

    auto tip_path = boost::filesystem::path(data_dir_) / "db" / "tip.txt";
    if (boost::filesystem::exists(tip_path)) {
	std::string line;
	std::ifstream fin = std::ifstream(tip_path.string());
	std::getline(fin, line);
	uint8_t id[meta_id::HASH_SIZE];
	if (line.length() != meta_id::HASH_SIZE) {
	    return;
	}
	hex::from_string(line, id, meta_id::HASH_SIZE);
	std::getline(fin, line);
	size_t height;
	std::istringstream iss(line);
	iss >> height;

	meta_id search_for(id);
	auto it = chains_.find(search_for);
	if (it != chains_.end()) {
	    tip_ = it->second;
	}
    }

    version_ = VERSION;
    time_ = utime();
}

static bool is_match(const meta_id &id, const uint8_t *prefix, size_t prefix_len) {
    if (prefix_len > id.hash_size()) {
	return false;
    }
    return memcmp(id.hash(), prefix, prefix_len) == 0;
}

std::set<meta_id> blockchain::find_entries(const uint8_t *prefix, size_t prefix_len) {
    uint8_t search[meta_id::HASH_SIZE];
    assert(prefix_len <= meta_id::HASH_SIZE);
    memset(&search[0], 0, meta_id::HASH_SIZE);
    memcpy(&search[0], prefix, prefix_len);
    meta_id search_id(search);
    std::set<meta_id> found;
    auto it = chains_.lower_bound(search_id);
    for (; it != chains_.end(); ++it) {
	auto &id = it->first;
	if (!is_match(id, prefix, prefix_len)) {
	    break;
	}
	found.insert(id);
    }
    return found;
}

std::set<meta_id> blockchain::find_entries(size_t height, const uint8_t *prefix, size_t prefix_len)
{
    std::set<meta_id> matched;
    size_t NONE = std::numeric_limits<size_t>::max();
    size_t h = height;
    if (h == NONE) {
	h = 0;
    }
    for (; !at_height_[h].empty(); h++) {
	auto &ids = at_height_[h];
	for (auto &id : ids) {
	    if (is_match(id, prefix, prefix_len)) {
		matched.insert(id);
	    }
	}
	if (height != NONE) {
	    break;
	}
    }
    return matched;
}

void blockchain::flush_db() {
    blocks_db().flush();
    heap_db().flush();
    closure_db().flush();
    symbols_db().flush();
    program_db().flush();
    meta_db().flush();
}

void blockchain::advance() {
    flush_db();

    db::root_id next_meta;
    db::root_id next_blocks;
    db::root_id next_heap;
    db::root_id next_closure;
    db::root_id next_symbols;
    db::root_id next_program;

    bool genesis = false;

    if (tip().get_root_id_meta().is_zero()) {
	next_meta = meta_db().new_root();
	next_blocks = blocks_db().new_root();
	next_heap = heap_db().new_root();
	next_closure = closure_db().new_root();
	next_symbols = symbols_db().new_root();
	next_program = program_db().new_root();
	genesis = true;
    } else {
	next_meta = meta_db().new_root(tip().get_root_id_meta());
	next_blocks = blocks_db().new_root(tip().get_root_id_blocks());
	next_heap = heap_db().new_root(tip().get_root_id_heap());
	next_closure = closure_db().new_root(tip().get_root_id_closure());
	next_symbols = symbols_db().new_root(tip().get_root_id_symbols());
	next_program = program_db().new_root(tip().get_root_id_program());
    }

    size_t new_height = genesis ? 0 : tip().get_height() + 1;

    meta_entry new_tip(tip());
    meta_id new_id;
    new_tip.set_id(new_id); // Will be recomputed, just setting it to zero
                            // to avoid confusion.
    new_tip.set_previous_id(tip().get_id());
    new_tip.set_version(version_);
    new_tip.set_timestamp(time_);
    new_tip.set_height(new_height);
    new_tip.set_root_id_meta(next_meta);
    new_tip.set_root_id_blocks(next_blocks);
    new_tip.set_root_id_heap(next_heap);
    new_tip.set_root_id_closure(next_closure);
    new_tip.set_root_id_symbols(next_symbols);
    new_tip.set_root_id_program(next_program);
    tip_ = new_tip;
}

void blockchain::add_meta_entry(meta_entry &e)
{
    if (e.get_previous_id().is_zero()) {
	e.set_root_id_meta(meta_db().new_root());
    } else {
	auto *prev_entry = get_meta_entry(e.get_previous_id());
	assert(prev_entry != nullptr);
	e.set_root_id_meta(meta_db().new_root(prev_entry->get_root_id_meta()));
    }
    update_meta_entry(e);
}

void blockchain::update_meta_entry(const meta_entry &e)
{
    const size_t data_size = meta_entry::serialization_size();
    uint8_t data[ data_size ];
    e.write(data);
    meta_db().update(e.get_root_id_meta(),
		     e.get_height(),
		     data, data_size);
    chains_[e.get_id()] = e;
    at_height_[e.get_height()].insert(e.get_id());
}

void blockchain::update_tip() {
    update_meta_id();

    auto find_it = chains_.find(tip().get_id());
    if (find_it != chains_.end()) {
	auto &existing_tip = find_it->second;
	if (tip_.get_id() == existing_tip.get_id()) {
	    existing_tip.set_root_id_heap(tip_.get_root_id_heap());
	    existing_tip.set_root_id_closure(tip_.get_root_id_closure());
	    existing_tip.set_root_id_symbols(tip_.get_root_id_symbols());
	    existing_tip.set_root_id_program(tip_.get_root_id_program());
	    existing_tip.set_root_id_blocks(tip_.get_root_id_blocks());
	}
	return;
    }

    add_meta_entry(tip());
}

size_t blockchain::depth(const meta_id &from_id, size_t max_depth)
{
    if (max_depth == 0) {
	return 0;
    }
    size_t d = 0;
    auto next_ids = follows(from_id);
    for (auto &next_id : next_ids) {
	auto next_depth = depth(next_id, max_depth - 1) + 1;
	if (next_depth > d) {
	    d = next_depth;
	}
    }
    return d;
}

// TODO: We should look at accumulated difficulty
meta_id blockchain::next(const meta_id &from_id, size_t max_lookahead) {
    if (max_lookahead == 0) {
	return from_id;
    }
    auto next_ids = follows(from_id);
    size_t best_depth = 0;
    meta_id best_id;
    for (auto &next_id : next_ids) {
	size_t d = depth(next_id, max_lookahead - 1);
	if (d > best_depth) {
	    best_depth = d;
	    best_id = next_id;
	}
    }
    return best_id;
}

meta_id blockchain::sync_point(int64_t height)
{
    if (at_height_.empty()) {
	return meta_id();
    }
    size_t abs_height = 0;
    if (height < 0) {
	size_t total_height = at_height_.rbegin()->first;
	if (static_cast<size_t>(-height) > total_height) {
	    abs_height = 0;
	} else {
	    abs_height = static_cast<size_t>(total_height - height);
	}
    } else {
	abs_height = static_cast<size_t>(height);
    }
    // If the chain at height abs_height is ambiguous, then go to
    // previous height until it isn't.
    while (abs_height > 0 && at_height_[abs_height].size() != 1) {
	abs_height--;
    }
    meta_id from_id = *(at_height_[abs_height].begin());
    // From this id we go forward and find the first branchpoint
    // that has two chains for which both are longer than 6.
    for (;;) {
	auto next_ids = follows(from_id);
	if (next_ids.size() == 0) {
	    break;
	}
	if (next_ids.size() == 1) {
	    from_id = *(next_ids.begin());
	    continue;
	}
	size_t found = 0;
	for (auto &next_id : next_ids) {
	    size_t d = depth(next_id, BRANCH_DEPTH);
	    if (d >= BRANCH_DEPTH) {
		found++;
	    }
	}
	if (found > 1) {
	    break;
	}
	from_id = next(from_id, BRANCH_DEPTH);
    }

    return from_id;
}

}}

max_stars_repo_name: datavetaren/epilog

max_issues_repo_name: datavetaren/epilog

max_forks_repo_name: datavetaren/epilog


text:
/*=============================================================================
    Copyright (c) 2015 Paul Fultz II
    alias.h
    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_HOF_GUARD_ALIAS_H
#define BOOST_HOF_GUARD_ALIAS_H

#include <boost/hof/returns.hpp>
#include <boost/hof/detail/delegate.hpp>
#include <boost/hof/detail/move.hpp>
#include <boost/hof/detail/holder.hpp>
#include <boost/hof/config.hpp>

/// alias
/// =====
///
/// Description
/// -----------
///
/// The `alias` class wraps a type with a new type that can be tagged by the
/// user. This allows defining extra attributes about the type outside of the
/// type itself. There are three different ways the value can be stored: as a
/// member variable, by inheritance, or as a static member variable. The value
/// can be retrieved uniformily using the `alias_value` function.
///
/// Synopsis
/// --------
///
///     // Alias the type using a member variable
///     template<class T, class Tag=void>
///     class alias;
///
///     // Alias the type by inheriting
///     template<class T, class Tag=void>
///     class alias_inherit;
///
///     // Alias the type using a static variable
///     template<class T, class Tag=void>
///     class alias_static;
///
///     // Retrieve tag from alias
///     template<class Alias>
///     class alias_tag;
///
///     // Check if type has a certian tag
///     template<class T, class Tag>
///     class has_tag;
///
///     // Retrieve value from alias
///     template<class Alias>
///     constexpr auto alias_value(Alias&&);
///

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4579)
#endif

namespace boost { namespace hof {

template<class T>
struct alias_tag;

template<class T, class Tag, class=void>
struct has_tag
: std::false_type
{};

template<class T, class Tag>
struct has_tag<T, Tag, typename detail::holder<
    typename alias_tag<T>::type
>::type>
: std::is_same<typename alias_tag<T>::type, Tag>
{};

namespace detail {

template<class T>
constexpr T& lvalue(T& x) noexcept
{
    return x;
}

template<class T>
constexpr const T& lvalue(const T& x) noexcept
{
    return x;
}

}

#define BOOST_HOF_UNARY_PERFECT_FOREACH(m) \
    m(const&, boost::hof::detail::lvalue) \
    m(&, boost::hof::detail::lvalue) \
    m(&&, boost::hof::move) \

template<class T, class Tag=void>
struct alias
{
    T value;
    BOOST_HOF_DELEGATE_CONSTRUCTOR(alias, T, value)
};

#define BOOST_HOF_DETAIL_ALIAS_GET_VALUE(ref, move) \
template<class Tag, class T, class... Ts> \
constexpr auto alias_value(alias<T, Tag> ref a, Ts&&...) BOOST_HOF_RETURNS(move(a.value))
BOOST_HOF_UNARY_PERFECT_FOREACH(BOOST_HOF_DETAIL_ALIAS_GET_VALUE)

template<class T, class Tag>
struct alias_tag<alias<T, Tag>>
{ typedef Tag type; };

template<class T, class Tag=void>
struct alias_inherit
#if (defined(__GNUC__) && !defined (__clang__))
: std::conditional<(std::is_class<T>::value), T, alias<T>>::type
#else
: T
#endif
{
    BOOST_HOF_INHERIT_CONSTRUCTOR(alias_inherit, T)
};

#define BOOST_HOF_DETAIL_ALIAS_INHERIT_GET_VALUE(ref, move) \
template<class Tag, class T, class... Ts, class=typename std::enable_if<(BOOST_HOF_IS_CLASS(T))>::type> \
constexpr T ref alias_value(alias_inherit<T, Tag> ref a, Ts&&...) BOOST_HOF_RETURNS_DEDUCE_NOEXCEPT(move(a)) \
{ \
    return move(a); \
}
BOOST_HOF_UNARY_PERFECT_FOREACH(BOOST_HOF_DETAIL_ALIAS_INHERIT_GET_VALUE)

template<class T, class Tag>
struct alias_tag<alias_inherit<T, Tag>>
{ typedef Tag type; };

namespace detail {

template<class T, class Tag>
struct alias_static_storage
{
#ifdef _MSC_VER
    // Since we disable the error for 4579 on MSVC, which leaves the static
    // member unitialized at runtime, it is, therefore, only safe to use this
    // class on types that are empty with constructors that have no possible
    // side effects.
    static_assert(BOOST_HOF_IS_EMPTY(T) &&
        BOOST_HOF_IS_LITERAL(T) &&
        BOOST_HOF_IS_DEFAULT_CONSTRUCTIBLE(T), "In-class initialization is not yet implemented on MSVC");
#endif
    static constexpr T value = T();
};

template<class T, class Tag>
constexpr T alias_static_storage<T, Tag>::value;

}

template<class T, class Tag=void>
struct alias_static
{
    template<class... Ts, BOOST_HOF_ENABLE_IF_CONSTRUCTIBLE(T, Ts...)>
    constexpr alias_static(Ts&&...) noexcept
    {}
};

template<class Tag, class T, class... Ts>
constexpr const T& alias_value(const alias_static<T, Tag>&, Ts&&...) noexcept
{
    return detail::alias_static_storage<T, Tag>::value;
}

template<class T, class Tag>
struct alias_tag<alias_static<T, Tag>>
{ typedef Tag type; };

namespace detail {

template<class T, class Tag>
struct alias_try_inherit
: std::conditional<(BOOST_HOF_IS_CLASS(T) && !BOOST_HOF_IS_FINAL(T) && !BOOST_HOF_IS_POLYMORPHIC(T)),
    alias_inherit<T, Tag>,
    alias<T, Tag>
>
{};

#if BOOST_HOF_HAS_EBO
template<class T, class Tag>
struct alias_empty
: std::conditional<(BOOST_HOF_IS_EMPTY(T)),
    typename alias_try_inherit<T, Tag>::type,
    alias<T, Tag>
>
{};
#else
template<class T, class Tag>
struct alias_empty
: std::conditional<
        BOOST_HOF_IS_EMPTY(T) &&
        BOOST_HOF_IS_LITERAL(T) &&
        BOOST_HOF_IS_DEFAULT_CONSTRUCTIBLE(T),
    alias_static<T, Tag>,
    alias<T, Tag>
>
{};
#endif

}

}} // namespace boost::hof

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#endif

ext: hpp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
//          Copyright Oliver Kowalke 2014.
// 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 MEMORIA_CONTEXT_DETAIL_EXCHANGE_H
#define MEMORIA_CONTEXT_DETAIL_EXCHANGE_H

#include <algorithm>
#include <utility>

#include <boost/config.hpp>

namespace memoria {
namespace context {
namespace detail {

template< typename T, typename U = T >
T exchange( T & t, U && nv) {
    T ov = std::move( t);
    t = std::forward< U >( nv);
    return ov;
}

}}}

#endif // MEMORIA_CONTEXT_DETAIL_EXCHANGE_H

max_stars_repo_name: victor-smirnov/memoria

max_issues_repo_name: victor-smirnov/memoria

max_forks_repo_name: victor-smirnov/memoria


text:
//  boost/system/windows_error.hpp  ------------------------------------------//

//  Copyright Beman Dawes 2007

//  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)

//  See library home page at http://www.boost.org/libs/system

#ifndef BOOST_SYSTEM_WINDOWS_ERROR_HPP
#define BOOST_SYSTEM_WINDOWS_ERROR_HPP

//  This header is effectively empty for compiles on operating systems where
//  it is not applicable.

#include <boost/system/config.hpp>

#ifdef BOOST_WINDOWS_API

#include <boost/system/error_code.hpp>

// Neither MinGW or Cygwin versions of winerror.h work if used alone, so on
// either of those platforms include the full windows.h

#if defined(__MINGW32__) || defined(__CYGWIN__)
#include <windows.h>
#else
#include <winerror.h>
#endif

namespace boost
{
  namespace system
  {

    //  Microsoft Windows  ---------------------------------------------------//

    //  To construct an error_code after a API error:
    //
    //      error_code( ::GetLastError(), system_category() )

    namespace windows_error
    {
      enum windows_error_code
      {
        success = 0,
        // These names and values are based on Windows winerror.h
        invalid_function = ERROR_INVALID_FUNCTION,
        file_not_found = ERROR_FILE_NOT_FOUND,
        path_not_found = ERROR_PATH_NOT_FOUND,
        too_many_open_files = ERROR_TOO_MANY_OPEN_FILES,
        access_denied = ERROR_ACCESS_DENIED,
        invalid_handle = ERROR_INVALID_HANDLE,
        arena_trashed = ERROR_ARENA_TRASHED,
        not_enough_memory = ERROR_NOT_ENOUGH_MEMORY,
        invalid_block = ERROR_INVALID_BLOCK,
        bad_environment = ERROR_BAD_ENVIRONMENT,
        bad_format = ERROR_BAD_FORMAT,
        invalid_access = ERROR_INVALID_ACCESS,
        outofmemory = ERROR_OUTOFMEMORY,
        invalid_drive = ERROR_INVALID_DRIVE,
        current_directory = ERROR_CURRENT_DIRECTORY,
        not_same_device = ERROR_NOT_SAME_DEVICE,
        no_more_files = ERROR_NO_MORE_FILES,
        write_protect = ERROR_WRITE_PROTECT,
        bad_unit = ERROR_BAD_UNIT,
        not_ready = ERROR_NOT_READY,
        bad_command = ERROR_BAD_COMMAND,
        crc = ERROR_CRC,
        bad_length = ERROR_BAD_LENGTH,
        seek = ERROR_SEEK,
        not_dos_disk = ERROR_NOT_DOS_DISK,
        sector_not_found = ERROR_SECTOR_NOT_FOUND,
        out_of_paper = ERROR_OUT_OF_PAPER,
        write_fault = ERROR_WRITE_FAULT,
        read_fault = ERROR_READ_FAULT,
        gen_failure = ERROR_GEN_FAILURE,
        sharing_violation = ERROR_SHARING_VIOLATION,
        lock_violation = ERROR_LOCK_VIOLATION,
        wrong_disk = ERROR_WRONG_DISK,
        sharing_buffer_exceeded = ERROR_SHARING_BUFFER_EXCEEDED,
        handle_eof = ERROR_HANDLE_EOF,
        handle_disk_full= ERROR_HANDLE_DISK_FULL,
        rem_not_list = ERROR_REM_NOT_LIST,
        dup_name = ERROR_DUP_NAME,
        bad_net_path = ERROR_BAD_NETPATH,
        network_busy = ERROR_NETWORK_BUSY,
        // ...
        file_exists = ERROR_FILE_EXISTS,
        cannot_make = ERROR_CANNOT_MAKE,
        // ...
        broken_pipe = ERROR_BROKEN_PIPE,
        open_failed = ERROR_OPEN_FAILED,
        buffer_overflow = ERROR_BUFFER_OVERFLOW,
        disk_full= ERROR_DISK_FULL,
        // ...
        lock_failed = ERROR_LOCK_FAILED,
        busy = ERROR_BUSY,
        cancel_violation = ERROR_CANCEL_VIOLATION,
        already_exists = ERROR_ALREADY_EXISTS
        // ...

        // TODO: add more Windows errors
      };

    }  // namespace windows

# ifndef BOOST_SYSTEM_NO_DEPRECATED
    namespace windows = windows_error;
# endif

    template<> struct is_error_code_enum<windows_error::windows_error_code>
      { static const bool value = true; };

    namespace windows_error
    {
      inline error_code make_error_code( windows_error_code e )
        { return error_code( e, system_category() ); }
    }

  }  // namespace system
}  // namespace boost

#endif  // BOOST_WINDOWS_API

#endif  // BOOST_SYSTEM_WINDOWS_ERROR_HPP


text:
#include "OT/Base/PvwBaseOT.h"
#include "OT/Base/Math/DMC.h"
#include "Crypto/PRNG.h"
#include "Crypto/sha1.h"
#include "Network/Channel.h"
#include "cryptopp/osrng.h"
#include "Common/Log.h"

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>

//#include <boost/thread/tss.hpp>
//void Cleanup_Miracl(Miracl* miracl)
//{
//	if (miracl)
//	{
//		bOPRF::Log::out << "deleting Miracle" << bOPRF::Log::endl;
//		delete miracl;
//	}
//}

using namespace std;
namespace bOPRF {

	const char* role_to_str(OTRole role)
	{
		if (role == Receiver)
			return "Receiver";
		if (role == Sender)
			return "Sender";
		return "Both";
	}

	OTRole INV_ROLE(OTRole role)
	{
		if (role == Receiver)
			return Sender;
		if (role == Sender)
			return Receiver;
		else
			return Both;
	}

	void send_if_ot_sender(Channel& channel, vector<ByteStream>& os, OTRole role)
	{

		if (role == Sender)
		{
			channel.asyncSendCopy(os[0].data(), os[0].size());
			//os[0].Send(channel);
		}
		else if (role == Receiver)
		{

			channel.recv(os[1]);
			//os[1].setp(0);
			//os[1].Receive(channel);
		}
		else
		{
			// both sender + receiver

			channel.asyncSendCopy(os[0]);
			channel.recv(os[1]);
			//os[0].Send(channel);
			//os[1].setp(0);
			//os[1].Receive(channel);
			//P->send_receive_player(os);
		}
	}

	void send_if_ot_receiver(Channel& channel, vector<ByteStream>& os, OTRole role)
	{
		if (role == Receiver)
		{
			channel.asyncSendCopy(os[0]);
		}
		else if (role == Sender)
		{
			channel.recv(os[1]);
			//P->receive(os[1]);
		}
		else
		{
			// both
			channel.asyncSendCopy(os[0]);
			channel.recv(os[1]);
			//P->send_receive_player(os);
		}
	}

	/*
	 * pack/unpack routines for Miracl data types
	 */

	void pack(ByteStream& s, const Big& z)
	{
		u8 data[50];
		i32 len = to_binary(z, 50, (char*)data, false);
		s.append((u8*)&len, sizeof(u32));
		s.append(data, len);
	}

	void unpack(Big& z, ByteStream& s)
	{
		u8 data[50];
		i32 len;
		s.consume((u8*)&len, sizeof(i32));
		s.consume(data, len);
		z = from_binary(len, (char*)data);
	}

	void pack(ByteStream& s, const ECn& P)
	{
		Big x, y;
		P.get(x, y);
		pack(s, x);
		pack(s, y);
	}

	void unpack(ECn& P, ByteStream& s)
	{
		Big x, y;
		unpack(x, s);
		unpack(y, s);
		P = ECn(x, y);
	}

	//#define BASEOT_DEBUG

		// Run the PVW OTs
	void Exec_OT(vector< vector<ECn> >& Miracl_Sender_Inputs,
		BitVector& OT_Receiver_Inputs,
		vector<ECn>& Miracl_Receiver_Outputs,
		const CRS& crs,
		csprng& Miracl_RNG,
		PRNG& G,
		Channel& channel,
		OTRole role)
	{
		u64 n = OT_Receiver_Inputs.size();
		//Log::out << Log::PvwBaseOT << "Starting base OTs as " << role_to_str(role) << ", n = " << n << Log::endl;
		vector<ByteStream> strm(2);

		Big z;
		vector<SK> sk(n);
		PK pk;
		if (role & Receiver)
		{
			// Generate my receiver inputs
			OT_Receiver_Inputs.randomize(G);
			for (u64 i = 0; i < n; i++)
			{
				// Generate public keys on my branch
				KeyGen(sk[i], pk, OT_Receiver_Inputs[i], crs, Miracl_RNG);

				pack(strm[0], pk.g);
				pack(strm[0], pk.h);
			}
		}
		strm[1].setp(0);

		// Send receiver's public keys over
		send_if_ot_receiver(channel, strm, role);

		ECn c0, c1;

		if (role & Sender)
		{
			strm[0].setp(0);
			for (u64 i = 0; i < n; i++)
			{
				// Generate sender inputs
				z = strong_rand(&Miracl_RNG, crs.bit_size(), 2);
				Miracl_Sender_Inputs[i][0] = z*crs.get_g(0);
				z = strong_rand(&Miracl_RNG, crs.bit_size(), 2);
				Miracl_Sender_Inputs[i][1] = z*crs.get_g(0);

				// Unpack public keys, encrypt my two messages on the correct
				// branch and send them back
				unpack(pk.g, strm[1]);
				unpack(pk.h, strm[1]);

				pk.Encrypt(c0, c1, Miracl_Sender_Inputs[i][0], 0, crs, Miracl_RNG);
				pack(strm[0], c0);
				pack(strm[0], c1);
#ifdef BASEOT_DEBUG
				//Log::out << "m[" << i << ", 0] = " << Miracl_Sender_Inputs[i][0] << Log::endl;
				pack(strm[0], Miracl_Sender_Inputs[i][0]);
#endif
				pk.Encrypt(c0, c1, Miracl_Sender_Inputs[i][1], 1, crs, Miracl_RNG);
				pack(strm[0], c0);
				pack(strm[0], c1);
#ifdef BASEOT_DEBUG
				//Log::out << "m[" << i << ", 1] = " << Miracl_Sender_Inputs[i][1] << Log::endl;
				pack(strm[0], Miracl_Sender_Inputs[i][1]);
#endif
			}
		}

		// Sender sends ciphertexts over
		strm[1].setp(0);
		send_if_ot_sender(channel, strm, role);

#ifdef BASEOT_DEBUG
		ECn m0, m1;
#endif

		if (role & Receiver)
		{
			// Now unpack the received ciphertexts, decrypt the one we want
			// and store it
			for (u64 i = 0; i < n; i++)
			{
				unpack(c0, strm[1]);
				unpack(c1, strm[1]);
#ifdef BASEOT_DEBUG
				unpack(m0, strm[1]);
#endif
				if (OT_Receiver_Inputs[i] == 0)
				{
					sk[i].Decrypt(Miracl_Receiver_Outputs[i], c0, c1);
#ifdef BASEOT_DEBUG
					if (Miracl_Receiver_Outputs[i] != m0)
					{
						Log::out << "Bad PvwBaseOT message received" << Log::endl;
						Log::out << "Received   " << Miracl_Receiver_Outputs[i] << Log::endl;
						Log::out << "wanted m0  " << m0 << Log::endl;
						throw std::runtime_error("rt error at " LOCATION);
					}
#endif
				}
				unpack(c0, strm[1]);
				unpack(c1, strm[1]);
#ifdef BASEOT_DEBUG
				unpack(m1, strm[1]);
#endif
				if (OT_Receiver_Inputs[i] == 1)
				{
					sk[i].Decrypt(Miracl_Receiver_Outputs[i], c0, c1);
#ifdef BASEOT_DEBUG
					if (Miracl_Receiver_Outputs[i] != m1)
					{
						Log::out << "Bad PvwBaseOT message " << i << " received" << Log::endl;
						Log::out << "Received   " << Miracl_Receiver_Outputs[i] << Log::endl;
						Log::out << "wanted m1  " << m1 << Log::endl;
						throw std::runtime_error("rt error at " LOCATION);
					}
#endif
				}

				//Log::out << Log::PvwBaseOT << "m"<< OT_Receiver_Inputs.get_bit(i) <<"[" << i << "] = " << Miracl_Receiver_Outputs[i] << Log::endl;

			}
		}
		//Log::out << Log::PvwBaseOT << "Exit base OT" << Log::endl;
	}

	void PvwBaseOT::exec_base(PRNG& G)
	{
		// Set up crs
	  CRS crs(&(*GetPrecision()));
		//Log::out << "check 0" << Log::endl;

		// Initialize a secure random number generator for Miracl
		csprng Miracl_RNG;
		u8 data[100];
		//Log::out << "check 1" << Log::endl;
		G.get_u8s(data, 100);
		//CryptoPP::OS_GenerateRandomBlock(false, data, sizeof(u8) * 100);

		strong_init(&Miracl_RNG, 100, (char*)data, 0L);
		///Log::out << "check 2" << Log::endl;

		vector< vector<ECn> > Miracl_Sender_Inputs(nOT, vector<ECn>(2));
		vector<ECn>           Miracl_Receiver_Outputs(nOT);

		Exec_OT(Miracl_Sender_Inputs, receiver_inputs, Miracl_Receiver_Outputs, crs, Miracl_RNG, G, mChannel, mOTRole);

		ByteStream s;
		u8 buff[SHA1::HashSize];
		//CBC_MAC cbc;
		SHA1 sha;
		// Hash PVW output into byte strings
		for (int i = 0; i < nOT; i++)
		{
			if (mOTRole & Sender)
			{
				s.setp(0);
				pack(s, Miracl_Sender_Inputs[i][0]);

				sha.Reset();
				sha.Update(s.data(), s.size());
				sha.Final(buff);
				sender_inputs[i][0] = *(block*)buff;

				//cbc.zero_key();
				//cbc.Update(s);
				//cbc.Finalize(sender_inputs[i][0]);
#ifdef BASEOT_DEBUG
				s.setp(0);
				pack(s, Miracl_Sender_Inputs[i][0]);
				Log::out << Log::PvwBaseOT << "m[" << i << ", 0] s = " << s << Log::endl;
				mChannel.Send(s);
				s.setp(0);
				s.append(sender_inputs[i][0]);
				mChannel.AsyncSendCopy(s);
				Log::out << Log::PvwBaseOT << "m[" << i << ", 0]   = " << sender_inputs[i][0] << Log::endl;
#endif
				s.setp(0);
				pack(s, Miracl_Sender_Inputs[i][1]);
				sha.Reset();
				sha.Update(s.data(), s.size());
				sha.Final(buff);

				//cbc.zero_key();
				//cbc.Update(s);
				//cbc.Finalize(sender_inputs[i][1]);
				sender_inputs[i][1] = *(block*)buff;
#ifdef BASEOT_DEBUG
				s.setp(0);
				pack(s, Miracl_Sender_Inputs[i][1]);
				mChannel.Send(s);
				Log::out << Log::PvwBaseOT << "m[" << i << ", 1] s = " << s << Log::endl;

				s.setp(0);
				s.append(sender_inputs[i][1]);
				mChannel.AsyncSendCopy(s);
				Log::out << Log::PvwBaseOT << "m[" << i << ", 1]   = " << sender_inputs[i][1] << Log::endl;
#endif
			}
			if (mOTRole & Receiver)
			{
				s.setp(0);
				pack(s, Miracl_Receiver_Outputs[i]);
				sha.Reset();
				sha.Update(s.data(), s.size());
				sha.Final(buff);

				receiver_outputs[i] = *(block*)buff;

				//cbc.zero_key();
				//cbc.Update(s);
				//cbc.Finalize(receiver_outputs[i]);

#ifdef BASEOT_DEBUG
				Log::out << Log::PvwBaseOT << "s " << s << Log::endl;
				ECn ecm0, ecm1;
				block m0, m1;

				s.setp(0);
				mChannel.recv(s);
				unpack(ecm0, s);
				s.setp(0);
				mChannel.recv(s);
				s.consume(m0);

				s.setp(0);
				mChannel.recv(s);
				unpack(ecm1, s);
				s.setp(0);
				mChannel.recv(s);
				s.consume(m1);

				if (receiver_inputs[i])
				{
					if (Miracl_Receiver_Outputs[i] != ecm1)
					{
						Log::out << "Bad PvwBaseOT Miracl message " << i << " received" << Log::endl;
						Log::out << "Received   " << Miracl_Receiver_Outputs[i] << Log::endl;
						Log::out << "wanted m1  " << ecm1 << Log::endl;
						throw std::runtime_error("rt error at " LOCATION);
					}

					if (receiver_outputs[i] != m1)
					{
						Log::out << "Bad PvwBaseOT message " << i << " received" << Log::endl;
						Log::out << "Received   " << receiver_outputs[i] << Log::endl;
						Log::out << "wanted m1  " << m1 << Log::endl;
						throw std::runtime_error("rt error at " LOCATION);
					}
				}
				else
				{

					if (Miracl_Receiver_Outputs[i] != ecm0)
					{
						Log::out << "Bad PvwBaseOT Miracl message " << i << " received" << Log::endl;
						Log::out << "Received   " << Miracl_Receiver_Outputs[i] << Log::endl;
						Log::out << "wanted m0  " << ecm0 << Log::endl;
						throw std::runtime_error("rt error at " LOCATION);
					}

					if (receiver_outputs[i] != m0)
					{
						Log::out << "Bad PvwBaseOT message " << i << " received" << Log::endl;
						Log::out << "Received   " << receiver_outputs[i] << Log::endl;
						Log::out << "wanted m0  " << m0 << Log::endl;
						throw std::runtime_error("rt error at " LOCATION);
					}
				}
#endif
			}

		}
		deletePercision();
		//delete GetPrecision();
		//Log::out << "base ots done" << Log::endl;
	}

	void PvwBaseOT::check()
	{
		ByteStream os;
		block tmp;

		for (int i = 0; i < nOT; i++)
		{
			if (mOTRole & Sender)
			{
				// send both inputs over
				os.append(sender_inputs[i][0]);
				os.append(sender_inputs[i][1]);

				if (eq(sender_inputs[i][0], sender_inputs[i][1]))
					throw std::runtime_error("rt error at " LOCATION);

				mChannel.asyncSendCopy(os);
			}

			if (mOTRole & Receiver)
			{
				mChannel.recv(os);

				os.consume((u8*)&tmp, sizeof(block));

				if (receiver_inputs[i] == 1)
				{
					os.consume((u8*)&tmp, sizeof(block));
				}

				if (neq(tmp, receiver_outputs[i]))
				{
					Log::out << "Base Incorrect OT" << Log::endl;
					Log::out << "I        have " << receiver_outputs[i] << Log::endl;
					Log::out << "but they have " << tmp << Log::endl;

					throw std::runtime_error("Exit");;
				}
			}
			os.setp(0);
		}
	}

}

max_stars_repo_name: keiyou/BaRK-OPRF

max_issues_repo_name: keiyou/BaRK-OPRF

max_forks_repo_name: keiyou/BaRK-OPRF


text:
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// Copyright (C) 2011 Vicente J. Botet Escriba
//
//  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)

// <boost/thread/future.hpp>

// class packaged_task<R(ArgTypes...)>

// template <class Callable, class Alloc>
//   struct uses_allocator<packaged_task<Callable>, Alloc>
//      : true_type { };

#define BOOST_THREAD_VERSION 3

#include <boost/thread/future.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/static_assert.hpp>

#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
#include <libs/thread/test/sync/futures/test_allocator.hpp>

int main()
{

  BOOST_STATIC_ASSERT_MSG((boost::uses_allocator<boost::packaged_task<double>, test_allocator<double> >::value), "");

  return boost::report_errors();
}

#else
int main()
{
  return boost::report_errors();
}
#endif

max_stars_repo_name: boostpro/boost-release

max_issues_repo_name: boostpro/boost-release

max_forks_repo_name: boostpro/boost-release